OAuth1 or OAuth2 for a non SSL website?

Question: I want to implement OAuth server on my PHP server, which dosent have a SSL connection. There's no decent OAuth 2 framework for PHP-codeigniter yet. So which one should I use OAuth1 or OAuth2 ?
Answer: The short answer is: you should consider using OAuth 1.0a [1] rather than OAuth 2.0
The long answer is below:
OAuth 2.0 by default requires the use of SSL/TLS for transport layer security. Therefore, when implementing an OAuth 2.0 compliant Authorization Server, you need to allow client applications to connect to the Authorization Endpoint as well as Token Endpoint over a secure channel. See the following sections in the OAuth 2.0 specification [2]:
3.1 (Authorization Endpoint)
"[...] the authorization server MUST require the use of TLS as described in Section 1.6 when sending requests to the authorization endpoint."
3.2 (Token Endpoint)
"[...] the authorization server MUST require the use of TLS as described in Section 1.6 when sending requests to the token endpoint."
In your case, when you do not have an SSL connection, you can still possibly consider using OAuth 2.0 and the MAC Access Authentication [3], which specifies how to make OAuth 2.0 requests by issuing MAC-type access tokens. Such tokens are cryptographically signed with a shared symmetric key (key is shared between the client application and the server).
IMPORTANT NOTE: In such setup, however, you will still need to provide a mechanism for clients to be able to establish a shared secret with your OAuth 2.0 server in a secure way (how this is done is up to you - can be over some SSL channel or out-of-band, depending on your exact use cases). This is a strict requirement to allow clients to securely access protected resources!
"The MAC scheme requires the establishment of a shared symmetric key
between the client and the server.  This specification offers one
such method for issuing a set of MAC credentials to the client using
OAuth 2.0 in the form of a MAC-type access token.
The primary design goal of this mechanism is to simplify and improve
HTTP authentication for services that are unwilling or unable to
employ TLS for every request.  In particular, this mechanism leverage
an initial TLS setup phase to establish a shared secret between the
client and the server.  The shared secret is then used over an
insecure channel to provide protection against a passive network
attacker."
Based on the above explanation, I would consider using OAuth 1.0a [3], which does not require the use of a transport-level security for communication between the client and Authorization Server (OAuth 1.0a uses the term "Service Provider", btw). Instead, it relies on messages being signed using a shared symmetric key (or an RSA key). However. please note that unless you use signatures using HMAC-SHA1 or RSA-SHA1 (i.e. you decide to use the PlAINTEXT signature type), you will need to use SSL/TLS anyway.
[1] https://www.rfc-editor.org/rfc/rfc5849
[2] https://www.rfc-editor.org/rfc/rfc6749
[3] https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-http-mac-01
Comment: what about the client apps. Required to have SSL connections, or just for resource & authorization servers enough?
Answer: From a client's perspective, OAuth 2 is easier to integrate into applications, among other benfits: How is OAuth 2 different from OAuth 1?
Just integrate any external Oauth2 library with Codeigniter. Here is one: https://github.com/bshaffer/oauth2-server-php
Answer: I am using OAuth2 for 2 years, and I highly recommend using it since it is very reliable.
Relating to SSL, as far as I know, OAuth should be utilizing SSL to gain proper implementation, avoiding this will simply not adopting OAuth protocol.

OAuth1 or OAuth2 for a non SSL website?


How do I disassociate a filetype and mode?

Question: I think the Change Log mode in emacs (spacemacs) acts crazily and I want to turn it off when editing my CHANGELOG. How do I do that for good?
Comment: FYI, I've updated my sample code, in case you copied it verbatim.  I saw you already accepted the answer...
Answer: The change-log-mode exists to help with viewing and editing Change Log files like the one Emacs itself uses.  You might consider simply modifying the mode's settings so it behaves like you want instead of "throwing the baby out with the bath water" so to speak. :)
Since that wasn't the specific question you asked, you can use a different mode by modifying auto-mode-alist.  This variable tells Emacs what mode to load based on a regex matching of the file being loaded.  For Change Logs, by default, it shows this:
'(("[cC]hange\\.?[lL]og?\\'" . change-log-mode)
  ("[cC]hange[lL]og[-.][0-9]+\\'" . change-log-mode)
  ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
  ("[cC]hange[lL]og[-.][-0-9a-z]+\\'" . change-log-mode))

You can simply get rid of it like this:
(setq auto-mode-alist (rassq-delete-all 'change-log-mode auto-mode-alist))

You shouldn't need to do that, though, as adding to the list overrides settings.  So you can just replace it like this:
(setq auto-mode-alist
      (append '(("[cC]hange\\.?[lL]og?\\'" . text-mode)
                ("[cC]hange[lL]og[-.][0-9]+\\'" . text-mode)
                ("\\$CHANGE_LOG\\$\\.TXT" . text-mode)
                ("[cC]hange[lL]og[-.][-0-9a-z]+\\'" . text-mode))
              auto-mode-alist))

Comment: You don't need the `setq auto-mode-alist` bit there, `add-to-list` modifies the list in-place.
Comment: Hmm, you seem to have omitted quoting for your string literals.  That doesn't actually work, does it? Also see `rassq-delete-all`.
Comment: @rpluim ah right.  I shouldn't type so fast. :)
Comment: @npostavs Thanks for the correction.  What happened was I did `(print "%s" auto-mode-alist)` and copied the result, which stripped the quotes out.  I've fixed up the examples.
Answer: How about:
(defalias 'change-log-mode #'text-mode)

This suggestion has (not unreasonably) garnered some down-votes.  I'm not deleting it, but it needs some extra notes:

cyberbisson's answer is the correct solution to the question in the title: "How do I disassociate a filetype and mode?".  In general, that's the sensible approach to take (and is of course completely fine in this case).
My suggestion was 100% aimed at the specific use-case of eradicating change-log-mode.  I'm mostly sure this mode has a sufficiently-limited set of uses that in practice clobbering the mode function is going to be fine.  Assuming that is indeed the case, this is just a very very easy approach.
I'm not recommending this approach as a general solution (although it would undoubtedly also work fine in practice in numerous other cases).  DoMiNeLa10 commented that it might break things, and that's definitely possible for arbitrary uses of defalias to clobber modes, but (I suspect) not likely to be a problem for this example.
This approach has one advantage (or disadvantage) over the auto-mode-alist approach in that it also prevents change-log-mode from being triggered in any other way.  This is probably not relevant, but worth pointing out.
M-x load-library RET add-log RET would redefine change-log-mode to its normal value, if you wanted to do that.
Comment: I am not the DV, but I wonder why this got downvoted. Perhaps there is a more idiomatic way?
Comment: I didn't DV (and I won't, because this solution will work), but that's an awfully big hammer for this nail.  You won't be able to even manually use the mode of you do it this way.
Comment: The issue was "Change Log mode ... acts crazily" and they didn't want to use it, so it didn't seem entirely unreasonable to suggest a way in which nothing would ever cause it to be used.  (My first inclination was updating `auto-mode-alist`, but I went with this approach on purpose, as big a hammer as it is.)
Comment: @phils this solution is bad, because overriding `change-log-mode` could lead to unexpected breakage.
Comment: I can come up with some scenarios, but honestly, I think it would be fine in practice for this particular case.  cyberbisson's answer certainly matches the question title better, though.


What do I do with this short story?

Question: I wrote a really, really, good short story recently, with an amazing main character. I want to use her again, but it doesn't feel right to put a character from a short story into a long series! should I write a series of short stories about her?
Comment: If you care for the character and you can imagine a longer plot, why not go for it? If the inspiration and ideas are there, nothing should hold you back. Worst case, you try and realize that it doesn't make sense - for some reason YOU believe. I say do it. Write a bigger work with the character and see what she can do - she might just surprise you.
Comment: Writing Excuses has a podcast where they discuss the length of stories in word-count, and a formula to estimate how much story content each contains.
https://writingexcuses.com/2017/07/02/12-27-choosing-a-length/
Answer: If you're wanting to go with a longer story like a novel, I'd suggest either making your short story in the past (of the longer story) or announce that the short story isn't canon (doesn't effect or make anything different for the main story).
A series of short stories would also be cool, but that decision is entirely up to you! :)
Answer: The problem with short stories as compared to novels is that they usually just show an aspect of a person's life, without digging too deep into the backstory of the character.
While it is absolutely possible to convert a character from a short story to a novel form, I do believe that it might be necessary to provide more backstory.
Thus it would probably change the way we experience it. It will be a more episodic story telling which might not go hand in hand with the (traditional) understanding of short stories.
(Of course, anything that one can think of is possible, do not let traditions stand in your way of your creativity, enjoy the process and have fun with it.)
Answer: Many short stories have been turned into novels
Flowers for Algernon by Daniel Keyes was a short story that was then adapted into a full novel.  M. R. Carey turned Iphigenia In Aulis into The Girl with All the Gifts.  Dragonflight, the first book of Anne McCaffery's Dragonriders of Pern began life as two novellas, Weyr Search and Dragonrider.
In all of these cases and more, the longer novel stands adjacent to the original stories.  The story told in the short story is repeated in the novels, although sometimes with details changed to better fit the longer form story being told.
A second form of adaptation can be seen in Seanan McGuire's novella Rolling in the Deep, which was followed by the novel Into the Drowning Deep, and Mary Robinette Kowal's The Lady Astronaut of Mars, which served as foundation for The Calculating Stars and The Fated Sky.  This sounds a bit more like what you're interested in.  The original story is part of the canon of the world, and the novels are additional stories in that world.  Kowal's series even features the same character!
And there are also many novels that began life as short story collections.  Callahan's Crosstime Saloon by Spider Robinson was a series of short stories collected together, as was I, Robot by Issac Asimov, and Sparrow Hill Road by Seanan McGuire.  Collecting stories together like this does leave a mark, though.  It is usually fairly easy to tell when a story began life as a short story collection.  (In particular it is educational to look at Sparrow Hill Road, which began as a short story collection, and its sequel The Girl in the Green Silk Gown, which did not).  That is not necessarily a bad thing.  Many people enjoy the episodic feel of a novel made of short stories, and some stories are best told in that manner.  It's like writing a TV show instead of a movie.  Both are excellent storytelling mediums, but they are also different storytelling mediums.
The path you choose is up to you.  All paths are equally valid, but the considerations you need to make for each one are different.

What do I do with this short story?


Adding a Maven project to Eclipse compiled project

Question: I am trying to add java code from a Maven project (called docx4java) which I checked out from svn to an existing Eclipse project (called DocumentManager). I have tried the normal way, that I thought would work, i.e.:
Right Click on eclipse project>Properties>Java Build Paths> Projects > Add (here I add the Maven project) and >Libraries (here I specify Native Library location e.g. docx4/trunk/docx4/src/) but I still can't get the 'Maven' classes to be recognised in eclipse. I get the message
import docx4j.src.main.java.org.docx4j.convert.out.flatOpcXml.FlatOpcXmlCreator cannot be resolved

I have tried adding a test project that was compiled in Eclipse and that works fine, Eclipse seems to recognise it i.e. import org.me.TestProject works fine.
How can I get the code from the Maven project docx4java to work in the Eclipse compiled project DocumentManager?
Answer: You can generate eclipse poject files (which you can just import into your Workspace) using the maven eclipse plugin
Take a look at these ecplise plugins for a more direct integration of maven into eclipse
Answer: You should create a eclipse project for docx4java as @Attila has commented. Once that is done, you should have two projects on your workspace: docx4java and DocumentManager. At this point, what you are doing now (adding a project reference to the Java Build Paths) should work.
Answer: It seems that the source path is not configured correctly, this is why the compiler cannot find your "Maven classes".

docx4java.src.main.java...

Maven has a different directory structure and you have to tell Eclipse where to find your sources.
For a "vanilla" eclipse project, remove the standard eclipse build path src and add the maven source path src/main/java (or whereever you added the code), the compiler should correctly pick up your sources.
Note that you still have to add all jars mentioned in the dependencies section of the maven pom.xml file. Otherwise it won't compile, even if it finds your added java classes.
(Addendum: I would recommend to use maven in your existing project as well.)


Preventing SQL Injection In Ibatis

Question: Is there anything built into Ibatis that helps prevent SQL Injection attacks? I'm not looking for a list of ways outside of Ibatis to do this, and am just wondering if Ibatis has anything to prevent SQL Injection.
Answer: IBatis uses JDBC prepared statements under the hood and is therefore safe. However this only applies if your use the # notation. It's also possible to concat variables directly into your query using the $ notation which is not safe (unless you escape them). See this article for background info.
Answer: I'd guess iBatis is using prepared statements, and parameter binding, so it's safe.
Comment: -1 - guessing for something as sensitive as a SQL Injection entry point
Comment: It's not safe when using $ notation

Preventing SQL Injection In Ibatis


I charge my iPad mini and I start to turn it on showing a screen that my iPad is charging but it turn off

Question: My iPad mini went dead because I didn't charge it while I'm playing with only 2 percent. I started to charge it and for a few hours I start to turn it on. The screen shows that my iPad is charging but the battery doesn't change it just it starts at the beginning (I don't know how to describe this). Then it turn off I noticed that when it turn off the screen would flash a white screen quickly with a black line in the middle of my iPad horizontally. I have been charging it for a few hours maybe between 6 - 7 hours and it was still doing the same thing. I need my iPad for school and my mom would beat my butt if she knews. Can you help me please? Thank you
Answer: Are you using an Apple original or MFi certified charger and cable? The charging circuits built into Apple iDevices can be damaged by cheap chargers. They will give the appearance of charging, what we call "fake charging" but not really charging at all. This usually requires a logic board level repair.
However in your case, it may just be a dead battery as the iPad mini is an old device and the battery may have just up and died after you let it deplete down to near 0%. You shouldn't worry about getting your butt kicked...these things happen. You should tell them the battery appears to be dead and if they never had it replaced, they should consider bringing it into a repair shop for a battery replacement.
Comment: It was a mini iPad 4 by the way and it's ok now my problem all along was a low voltage. I was charging on a wire and then 1 day passed I decided to charge on the wall socket then it appears it was charging. So I'm gonna delete my question


Is there an idiom that refers to the money paid to get a killer to kill someone?

Question: Is there an idiom that refers to the money paid to get a killer to kill someone? I thought blood money was that expression, but it doesn't seem like there's an idiom that refers to it and blood money seems to be more general. I think dirty money refers to money that comes from any crime though.
Comment: "Blood money" is money that a killer pays to the family of the victim, in some cultures.
Answer: A more general term we could consider is bounty.

A bounty is money that is offered as a reward for doing something, especially for finding or killing a particular person.
A bounty of $50,000 was put on Dr. Alvarez's head.
Answer: The usual phrase is a price on his/her head, an amount of money that will be paid for the capture or death of the individual concerned.
https://idioms.thefreedictionary.com/a+price+on+his+head
Answer: There does not seem to be a specific word for the money paid in a contract killing (one in which a person hires an assassin or hitman) as distinct from a "bounty" (money which is offered for the capture or killing of a person by anyone, with no contract).  You should not say "He offered a bounty of $1000 to the hitman to murder his wife."
In contracts generally, the money that is paid is called the "consideration".
"money etc given to the party in exchange for contractual promises"
If you are describing a highly professional killer, and want to use legal terms, perhaps in order to make it appear "respectable" you could say.

"He offered a consideration of $10,000 for the killing of his erstwhile business partner."

However, there is something ironic about using legal terminology to describe elements of an illegal agreement.
Otherwise simply "payment" or "money", or no word but implied through the mention of dollars etc.

The hitman was paid $1500 in advance and was promised a share of the $100 000 life insurance.

"Blood money" is money that a killer (but usually not a murderer) pays to the family of the victim, in some cultures.
Answer: Hit money
If you hire someone to kill someone else, that person is called a hitman, and you have placed a "hit" on the intended victim. You can refer to the payment as hit money.
I guess technically you could say "hitwoman" if the person is female, but I have never heard of this situation occurring and don't think I have ever heard this term actually used. It may have happened at some point, but I don't remember any incidents of it.


Are the two op-amp terminals at equal bias for positive feedback?

Question: For negative feedback op-amp circuits, we know that V+ = V-. However, does that also hold for positive feedback circuits? According to my simplistic SPICE simulations, this seems to be the case, but I want to confirm.
Comment: In any op-amp circuit if V+ doesn't approximately equal V- then the OP amp is maxed out positive or negative. Therefore for any desired output voltage between those extremes v+ must equal v-.
Comment: +ve feedback causes hysteresis since the output has limited
Comment: whenever the differential inputs are NOT near zero, the output will be saturated at one rail according the the polarity and Vcm input requirements. we call this non-linear mode , and with positive feedback ratio x Output swing = input Hysteresis
Answer: No: even though the op amp input terminal \$V_{IN-}\$ is driven to nearly the same voltage as \$V_{IN+}\$ when configured for negative feedback, when configured for positive feedback \$V_{IN+}\$ is not driven to the same voltage as \$V_{IN-}\$, and in fact it's driven away from the \$V_{IN-}\$ voltage.
Negative Feedback Configuration is Convergent
In negative feedback configuration, \$V_{IN+}\$ is the reference, and the feedback network drives \$V_{IN-}\$ such that \$V_{IN-} = V_{IN+} - (V_{OUT} / A_{v})\$, where \$A_{v}\$ is open-loop gain. If the output \$V_{OUT}\$ is "too big" compared to the target reference value, then the feedback \$V_{IN-}\$ is also "too big", and since \$V_{IN-}\$ > \$V_{IN+}\$ then \$V_{OUT}\$ is driven to a lower voltage, until \$V_{IN-}\$ reaches nearly the same voltage as \$V_{IN+}\$. Also, \$V_{OUT}\$ will be driven to whatever value the feedback network requires it to be to make \$V_{IN-}\$ match the reference \$V_{IN+}\$.
Positive Feedback Configuration is Divergent
In positive feedback configuration, \$V_{IN-}\$ is the reference, and the feedback network drives \$V_{IN+}\$ such that \$V_{IN+} = (V_{OUT} / A_{v}) + V_{IN-}\$, where \$A_{v}\$ is open-loop gain. If the output \$V_{OUT}\$ is "too big" compared to the target reference value, then the feedback \$V_{IN+}\$ is also "too big", and since \$V_{IN+}\$ > \$V_{IN-}\$ then \$V_{OUT}\$ is driven to an even higher voltage, until \$V_{OUT}\$ reaches the practical limit of how close the output can get to the power supply voltage.
Positive feedback can be useful when designing a memory cell, or when using hysteresis to help a comparator avoid responding to certain types of noise sources. But for DC amplifiers this effect is unwanted.
Comment: Positive feedback (frequency-dependent) is widely used in active filter circuits and is always present in oscillating circuits.
Answer: Your simulation program and the result is corrrect - there is no error.
However: The result is heavily unrealistic. What does this mean?

Under IDEAL conditions (ideal opamp and no power switch-on transient) the simulator can find a fixed DC bias point and, hence, can multiply the input signal with a gain factor - determined by the positive feedback path. This situation can be compared with two balls riding on each other. This would also be possible, when there is absolutely no disturbing effect (which in reality, however, never will happen)

But the simulation result will be realistic (Vin- NOT equal to Vin+) when you either will use a real opamp model (with signal delay) or when you are switching-on (at least) one of the two supply voltage sources at t=0 (simulation start). In this case, the simulation result will be the same as in practice: Positive feedback causes instability - and the output will be latched at one of the supply voltages.

Summary: The simulator did not make any errror - however, the user should know if the simulation set-up is a realistic one. In most (if not in all) cases, the mistake is on the users side (misinterpretation)
Answer: The simple answer is "no." In general when an op-amp has positive feedback only, the inverting and non-inverting inputs cannot be assumed to be the same. That assumption is only valid when there is negative feedback.
Probably what is happening in your simulation is that you have a condition occurring that is not possible in the real world, but only possible in the noise-free realm of the simulator. Try applying a tiny signal to one of the input terminals of the op-amp and see what happens.
Positive feedback is sometimes useful for a variety of purposes. But the assumption that V- = V+ is only valid when you have negative feedback.
Answer:
For negative feedback op-amp circuits, we know that V+ = V-. However, does that also hold for positive feedback circuits?

Yes, it is possible if only the input voltage (V2) is zero... the op-amp is ideal... and there are no other disturbances. In this situation, the output voltage (VOUT) will be zero... and the voltage of the non-inverting input (V+) will be zero as well... so all voltages will be zero...
If some input voltage (disturbance) is applied, it will affect V(-)... that will be amplified... and VOUT will affect V(-) even more through the positive feedback network (R1-R2). Now there are two possible situations.
If the loop gain <= 1 (this will be the case if your op-amp had a fixed gain of 7 or less), the circuit will still reach a equilibrium. But if the loop gain > 1, the amp will reinforce itself finally reaching the supply rail. This arrangement is used in latches and Schmitt triggers.
It is interesting that even in the latter situation, there is a (short) time interval when V(-) = V(+). This is because, when the circuit changes its state, the input and output voltage "move" against each other... and at some point they "meet" (become equal) for a while.
Finally, there are circuits with positive feedback where V(-) = V(+)... but they have also an additional negative feedback that dominates over the positive feedback. Such circuits are, for example, negative impedance converters (NIC).


Should I reinstall Ubuntu?

Question: Almost everyone knows that Ubuntu 9.10 is coming. So I have a question: is it safe to upgrade my current Ubuntu up to version 9.10 via apt-get or it is better to reinstall it from scratch? As I know for Windows it is always better to reinstall from scratch than upgrade it to higher version and get unstable system.
Answer: I have been updating Ubuntu ever since 6.04. There was always a little bug that got introduced, but it was always possible to find a workaround or a fix.
However:

Don't use apt-get. Use the update manger as recommended.
Don't upgrade as soon as possible. Wait a couple of days (or better yet, weeks) until others have stumbled across the obvious bugs.
Comment: Absolutely, wait a few days / weeks before you upgrade. I upgraded this morning, and due to a graphics issue on 9.10, that wasn't in 9.04, I'm moving back for now. Will try upgrade again in a few weeks when more people have done it... :)
Answer: Updating Ubuntu is perfectly fine.
The only somewhat important feature you might lose out on is EXT4. If your current file systems are EXT3, you can convert them to EXT4, but those will not gain some of the benefits (extents as I recall) of a freshly created EXT4 fs. You'll still be able to create new EXT4 fs with all the features of EXT4.
If you've installed horrendous numbers of third party packages from external repositories or .debs or source, you might have issues with those packages, but the main system should still be fine. This is, really, the only scenario what should preclude using the upgrade option.
While it's mostly a requirement to do a fresh install with windows and even some linux distributions, Ubuntu is not one of them.
And, yes, use the update manager as recommended.
And, yes, wait a few days or a week or two before the update. While this has been in beta for a while, and lots fo bugs are worked out, there'll be more right after mass adoption begins.
Answer: I don't see what you have to lose from the upgrade. If it doesn't work out well you end up reinstalling, so why not give the upgrade a try?
I will say that I've never had to reinstall a *nix. I haven't tried a major Ubuntu upgrade but every other *nix seems to upgrade in-place just fine. I'm running Ubuntu right now and it seems as good as the others...
Answer:
is it safe to update my current Ubuntu up to version 9.10 via apt-get

Probably, but as usual you should back your documents up first. Better: docs and home directory on a separate partition.
The reliability of dist-upgrade has improved since the bad old days, but I still lost a virtual machine upgraded from Intrepid to Jaunty.

or it is better to reinstall it from scratch?

Yes. It is always best to install any OS from scratch, Windows or otherwise. Again, with your stuff on a separate partition, an OS change is a cinch.
Apart from the usual stability worries of an upgraded OS, some features of Karmic won't get installed by default on an upgrade, in particular GRUB 2. (You can install it later manually.)
Comment: So, I will not get all new stuff/features during upgrade or it is relate only to incompatible features such as GRUB 2 ?
Comment: Well the ext4 driver and grub2 software are *present*, its just your existing filesystem isn't changed to use them.
Answer: I tried upgrading and I can tell you - don't do it if you are doing it from a laptop.
Forums are full with people that have problems one way or another.
Answer: Simple; don't use 9.10 at all on any notebook.
Example: Fresh installs on Acer, HP, and Clevo.
Weak and intermittent sound.
Restricted driver issues.
Boot problems galore. Black screen of death on new Clevo.
Kiba-Dock_0.1-1.2_i386.deb works fine with all other previous releases but karmic turns it to mush.
Video grainy and cuts stream off.
Go back to Jaunty, Ibex, or Hardy.
DO NOT USE THIS JUNK!

Should I reinstall Ubuntu?


What's the best approach to handle errors and ensure software robustness?

Question: I am developing a new desktop application from scratch using C#, before opening the visual studio and start typing in the keyboard I want to prepare a solid design for my software. The main challenge for me is how to handle errors and exceptions. I know that .Net Framework provide a good error handling but in addition to that I need to increase my software robustness. So i want to know is there any best practices to avoid Software crashing, hanging or freezing ?
If I need to develop a separate tool that diagnostic my software what should it be and what should it do ?
Comment: This is too broad.  Narrow your question down to a *specific,* software design-related problem you are having.
Comment: Are you asking about how to test software?
Comment: If we limit the question to handle errors it's fine, how to ensure software robustness is too broad however.
Answer:
handle errors and exceptions

Handle the exceptions you can recover from. Send up the ones you can't.
A file not being found is a problem but does it need to destroy all the work the user has done? Just tell them they couldn't load what they were trying to load. On the other hand if an exception leaves the system in some weird state don't make things worse by catching it and pretending things are fine when they aren't. If you can't predict what happens next roll over and die.

best practices to avoid Software crashing, hanging or freezing

Do not leak memory.
What makes server software developers so amazing is their ability to create software that can run for months without needing a restart. What makes linux systems so amazing is their ability to run for months without needing a restart.
If you leak memory your software is not amazing. It will need a restart. Even in c# this can happen. Sure it's got a garbage collector but all you have to do is hold a reference to something for longer than you need and it's a leak. The garbage collector won't help you here. If this thing is created "as needed" you're in big trouble because you're going to keep making more of it and never throw the old crap out.
The stupid easy way to detect some of these leaks is to watch your app run in the task manager. What does it's memory usage do over time?

If I need to develop a separate tool that diagnostic my software what should it be and what should it do

Test.
Automated tests. Unit tests, integration tests, end-to-end tests. Manual tests. Just test. Testing is a very intimate thing so don't expect anything you buy to just magically solve this problem for you. This is work. It's just as much work, if not more, as making the application itself. But it pays off.
Answer: Look at exceptions.
A general strategy would be

when an error occurs log it; write it to a file or error database. This is useful for monitoring your application and diagnosing faults
if it is recoverable; then recover. Ensure your system is in a sane state and continue. This may involve discarding some transaction or packet. If it might be a problem log it.
if it isn't recoverable; allow the user to save his work and do a clean shutdown

Carrying on after the system is broken only compounds the problem.
There is no "error handling strategy" that enables recovery from bugs. Your developement process should have elimated them before the user got near your system.
There are static analysis tools and testing tools to help you find problems in your code.


Using eclipse comparator from command line

Question: Can Eclipse Compare tool be called from command line? I just want to use it as a merge tool from an external tool.
Answer: I'm not aware that you can do this out of the box. But you can download the RCP SDK and create a really stripped down version of Eclipse which contains just the compare plugin. That will also help greatly with the startup time.
Comment: Unluckly looks that this is true.
Answer: Any reason you insist on Eclipse for that? I've used WinMerge for exactly the same purpose (external diff tool). It has built in ability to be called from command-line.
Other options:
https://stackoverflow.com/questions/792910/best-graphical-source-code-diff-viewer-editor-for-code-comparison-and-merging
Comment: Even if we are getting offtopic: If you seriously want to compare stuff (and are on Windows), nothing beats BeyondCompare.
Comment: I just wanted to use the comparator I was used to. Anyway I've looked into alternatives. Thanks both.
Comment: I like and use others, but cross platform is a big win, as well as not  losing focus. I'm launching from unit test triggered from inside of eclipse.
Answer: I wanted the same thing so I wrote it: https://github.com/kgilmer/steb
From a shell, the following line will open a compare editor comparing f1.txt and f2.txt:
steb -c f1.txt f2.txt


Is it possible to securely combine multiple hashes without hashing them?

Question: Let's say we have 1000 files and 1000 already computed cryptographic hashes for those files. Now we want to derive a single hash that authenticates all of them. Is there a more efficient way to do this than just hashing the concatenation of all those hashes (and thereby presumably calling the hash round function about 1000 times), without sacrificing security? What about also verifying the sequence?
Comment: If the files are in defined order, we can hash the concatenation of their hashes, in that defined order; otherwise we should sort the hashes (e.g. by increasing value) before computing the final hash, which adds to the cost. For many common hashes, the number of hash round functions required is significantly less than the number of files, since blocks are larger than hashes by a factor of 2 (SHA-256, SHA-512) or more, e.g. 3.2 (SHA-1), 4 (SHA-512/256), ≈4.57 (SHA-512/224).
Comment: @fgrieu Even if the block size is larger than the hash, the point is to have a method where the number of calls to the round function doesn't depend on the number of hashes you need to combine, maybe I should have clarified that in the question.
Answer: What you're looking for is called a Merkle tree. BLAKE2b, a modern hash and an evolution of one of the SHA-3 finalists (BLAKE), supports tree hashing natively.
Edit: This may or may not actually be what you're looking for. Initially hashing the tree will take more work ($\mathcal{O}(n\log(n))$ operations) than just hashing the set of hashes, but subsequent partial updates will take less work ($\mathcal{O}(\log(n))$ operations). If you're ever updating the list, a Merkle tree is probably more efficient.
Comment: A Merkle tree requires *more* work than hashing the concatenated list, however.
Comment: Please note well: BLAKE2 _was not_ running for SHA-3. It was BLAKE which was running there.
Comment: Ah yes, good point. Only for the first time, though. After that, subsequent updates to part of the tree can be computed with $\mathcal{ O}(\log(n))$ hashes.
Comment: Also note that, in practice, hashing a single block of sequential data tends to be more efficient than hashing multiple separate strings, since the latter has more overhead from repeated hash function calls, and also accesses memory in a less efficient pattern. This means that optimal performance (even for single-leaf access / update) is generally achieved with a $k$-ary hash tree, where $k \gg 2$ (and, on a modern CPU, I wouldn't be surprised if $k > 1000$).
Comment: I hope that's not what I'm looking for considering it's slower than just hashing the list. ;)
Comment: Updated the answer to reflect points made in the comments.
Answer: If the number of files is fixed, then concatenating the hashes (in a well-defined order) constitutes a hash function. Inverting it requires inverting the hash of one of the files, so if the per-file hash function is a cryptographic hash, then so is that 1000-file hash.
If the number of files is variable, then the natural way to combine the hashes would be to hash them. That's a very cheap operation, and I don't understand why you hope to find something cheaper. You do have to process all of the hashes after all, it's an $\Omega(k)$ operation where $k$ is the number of files.
Comment: I'm interested in not hashing them because I want to know if it would be possible, given a suitable round-function, to design a CTR-like hash function that'd be perfectly parallelizable for most of the work, which would imply you ending up with a lot of "sub-hashes" that'd need to get efficiently combined. Apparently this isn't possible, or at least there doesn't seem to be a well known method to set this up even with a suitable round-function.
Comment: @cooky451 You can parallelize by doing exactly what you're doing: compute the hashes of the files in parallel, and finally compute the hash of the list which is very quick.


Acceleration due to central forces in the Lagrangian

Question: On Wikiversity it states that for central forces:
Wouldn't $\ddot{\vec{r}}_1$ be the same as $\vec{g}$?
Answer: No. For some reason this article is including two different forces: (1) an attractive or repulsive central force between the two masses, described by the potential energy function $V(r)$, and (2) a uniform external gravitational field acting on each mass, described by the acceleration $\vec{g}$.
The acceleration $\ddot{\vec{r}}_1$ of $m_1$ is due to both of these forces, amd will not be equal to $\vec{g}$.
Answer: I'm a bit confused here, but as far I'm understanding that there are 2 particles whose Position is described as two position vectors, $\vec r_1$ and $\vec r_2$.
So, $$K_1 = \dfrac 12 m_1 \vec r_1^2$$
and silmilarly for $K_2$ of particle 2.
$$K_2 = \dfrac 12 m_2 \vec r_2^2$$
We'll write Potential energy here too which are there dependent on two forces of interaction, first Gravitational force and other as Force between them.
So, $$V_1 = m_1\vec g.\vec r_1 $$
$$V_2 = m_2 \vec g. \vec r_2$$
Now, the last function which is same for particle 1 and 2 which will be added once (You may add it twice to both particles, but that depends on the type of Force and it's nature of definition!)
We get Lagrangian as:
$$L = \dfrac 1 2 (m_1\vec r_1^2 + m_2 \vec r_2^2) - V(\vec r) + m_1 \vec g . \vec r_1 + m_2 \vec g. \vec r_2 \blacksquare$$
Here $\vec g$ is opposite to the direction of gravitational forces
Comment: Your kinetic energy should have a dot for the time derivative. Your $V_1$ and $V_2$ have the wrong sign. And you did not answer the OP's question.


How does this circuit output 25kHz?

Question: This circuit doesn't use a gate drive, so I am trying to understand how it can output 25kHz. A friend of mine told me that it does so with the use of LC resonance; the capacitor and inductor next to F1 and F2 achieve resonance as per the formula $$f = \frac{1}{2\pi \sqrt{LC}}$$ but I still have my doubts...
Comment: Have you tried to simulate it?
Comment: not yet. PSIM isn't working at my college PCs at the moment.
Comment: You can use the built in tool right here on EE.SE if you edit your question and press the schematics symbol. Installing LTspice is also an option.
Answer: This can be simulated online using Falstad's circuit simulator.  If you know the primary inductance, turns ratio and Mutual Coupling ratio (<1) then the impedance ratios are computed for each resulting inductance and referred nonlinear load impedance.. Although not easy, you must know all the RLC values of each trace, capacitor and choke, as well create a model of the trifilar center tapped transformer using two transformers with some awareness on transformer theory.
Transistors are simple with only hFE, FETS are simple with only Vt, gm or inverse RdsOn for the models. Stray inductance and capacitance as well as DCR and ESR must be estimated and added. Diodes are based on physics with Vf@ 1A may not be a perfect model unless you add Rs bulk resistance based on inverse Pd rating or datasheet curvesfor saturated series R slopes.
 Caps are always ideal so ESR MUST be added.
Same for chokes with DCR. and even better with PCB trace inductance if significant.
The series cap and diode clamps the AC to -Vf thus resulting in a AC voltage ratio and positive feedback loop to satisfy the Barkhausen Criteria for oscillation based on your formula above for effective L and effective C which is connected a certain percentage of the time  when the base emitter junction is conducting in series..
There is also an LC resonance with the AC bridge side load as well as the ferrite core stray capacitance and its own self resonant frequency chosen with winding patterns to be sufficiently high.
Comment: If you search some of my Falstad answer applications you can appreaciate the scope features, realtime slow speed interactive mouse features for component values etc. There is more than you can imagine but it is simple physics not COMSOL.

How does this circuit output 25kHz?


Number Series - 1,20,171

Question: $1,20,171,?,9625,57756,288775$
Please find the missing number in the series.
I have already tried with squares, cubes and progressions but couldn't find the problem.
Answer: Starting with $1$, you proceed as follows:

 Add $1$, and multiply the result by $10$.

This gives you $20$.

 Subtract $1$, and multiply the result by $9$.

This gives you $171$.

 Add $1$, and multiply the result by $8$.

This gives you $1376$.

 Subtract $1$, and multiply by $7$.

This gives you $9625$. Etc.

How do you get to this result?
Look at the last three numbers given. If you take the ratio of the last two values ($288775/57756$), you get a result very close to $5$. If you take the ratio $57756/9625$ You get a result very close to $6$. From there on it's just some fiddling...
Comment: Awesome!!....missed taking the ratios!
Answer: Partial Answer:
Let

 $1=a_1$, $20=a_2$, etc $\ldots$

then

 it seems like for some number $n$ that belongs to the group of numbers $\{1,2,3,\ldots\}$  (i.e. a natural number),

we have that

 $a_{n+1}-a_n$ is prime!

 $$a_2-a_1=20-1=19\tag{$n=1$}$$ $$a_3-a_2=171-20=151\tag{$n=2$}$$ Skipping $n=3$ because of that unknown number, $$a_4-a_3=57756-9625=48131\tag{$n=4$}$$ $$a_5-a_4=288775-57756=231019\tag{$n=5$}$$

Let

 the $m^\text{th}$ prime number be denoted as $p_m$,

then we have

 a pattern! $$19,151,(a_3-a_2), 48131, 231019$$ $$\Downarrow$$ $$p_8, p_{36}, (a_3-a_2), p_{4957}, p_{20524}$$ And now the pattern becomes $$8, 36, ?, 4957, 20524$$

But I can't find a pattern. One thing I noticed is that

 $$4957=\left(44-3^3\right)^3+44$$ and the close similarity, $$36 = \left(29-3^3\right)^3+29-1$$ (and, something pretty cool: $37^2=\left(38-3^3\right)^3+38$).

But, although similar, they do not match quite enough for me to say they belong to a kind of pattern. Overall, however, it is remarkably interesting :P
Comment: hmm...nice try!

Number Series - 1,20,171


"Visit Meta" section

Question: I'm curious about the "Visit Meta" section on the main page. What are the criteria for a question landing there? Many of the questions (at least as far as I can tell) are older.
Answer: One of the criteria is that if the question is tagged <code>[featured]</code> then it will appear.
There are others, but I can't find the original MSO post that explains them right now, but they are related to the activity on the question.
Comment: Can anyone tag a question [featured]?
Comment: @Michael - only moderators (those with the ♦ after their name) can use the red tags.
Answer: It's built based on "hot" meta question lists, plus the [featured] tag.
Click here to see what it uses:
https://softwareengineering.meta.stackexchange.com/?tab=week
https://softwareengineering.meta.stackexchange.com/?tab=hot
... in that order
The featured tag is problematic because users tend to leave the featured tag on.. forever. Which I disagree with, so we'll be pushing some changes on that soon.

"Visit Meta" section


VDC for little centrifugal pump. How much tolerance?

Question: Can I run a little 7 VDC (1.2 watts) pump with a 9 VDC/0.5 Amp power supply?  (The pump is for a drip to attract birds.)
Answer: You mustn't run a 7V rated device from a 9V power supply. It will probably work, but it will have a much reduced life time.
Cheapest solution that is somewhat reliable is to connect 3 diodes (1N4001 - 1N4007 will do fine) in series with the pump. These will always drop about 2V, in contrast to a resistor that drops voltage depending actual current.

simulate this circuit – Schematic created using CircuitLab
With a resistor, when the pump runs dry, current will probably drop and voltage on the pump will increase and the pump may get damaged.
Best solution from efficiency point of view is to find a power supply that outputs 7V regulated or add a step down converter. Something like this:

which usually sells for couple dollars/Euro.
Answer: Unless stated otherwise on the pump manual/datasheet, you will need to decrease the voltage from your power supply to fit in your pump requeriments, if not you may damage your pump. I suggest a resistor based voltage divider if you want to stay cheap (keep an eye on the resistor watts, use at least 2w resistors).
You can find more info and a handy calculator about the voltage divider here.


I cannot log into the Minecraft launcher

Question: I can't log into the Minecraft launcher, because it tells me that the username or passowrd is incorrect. I have tried resetting my password and have even given the account to my freidn and he was able to sign in perfectly, i cannot. If I try to login in through the official website the login button just doesn't simply doesn't work. I have even tried waiting to login in later, restarting my computer, but it hasn't worked. I have used my email and username to login. I have contacted Minecraft support via email and it told me that it is currently reviewing cases for the 30th of April, so I'd  rather try to fix the issue here. Thanks for your help!
Answer: Just for completions sake. Press the Minecraft authenticator button as you did


month of the date in Italian

Question: Use the module date-7.x-2.6, to insert a date dd / mm / yyyy in my content type. My problem is that when I view it, would that be translated into Italian for example "22 Settembre 1009" and now appears so: "22 Sep 1009". Thanks!
Answer: On the "Manage Display" page for your content type (under admin/structure/types), you can adjust the format to use to display the date.
To adjust the formats, you can configure the date and time settings (admin/config/regional/date-time).
Comment: hello, under Administration> Configuration> Regional and language, I have the ability to bind 3 different formats 3 different types of data, but any format I choose the month is always written in English   ("September")   and not in Italian   ("Settembre").    That to me is a problem, but the default language is set to Italian.

month of the date in Italian


Is it some bevel or emboss job?

Question:
How do I make the picture of right hand side from left hand side. I'm using Photoshop CS4. I tried some bevel and emboss but couldn't get the exact effect. Could someone assist me ?
Answer: This is really basic stuff and you should be able to Google these things instead of asking SE. Please do so in the future.

However, to answer your question, you have to first recognize that they are two different layers, one for the background, and one for the arrow. I quickly made them in photoshop.
For the background, do Emboss with the direction downwards (assuming light is in the top left corner). Change settings to mimic the original.
For the arrow, it's an Outer Bevel, again play with the settings. I also added a colour overlay to change the arrow colour.

Is it some bevel or emboss job?


What is continuous integration?

Question: What is continuous integration and what are its benefits?
Answer: This is by far the best explanation I have read so far.
Comment: Fowler almost always has the best explanations =)
Comment: I am simply amazed by the way he thinks about things ! CLEAR
Comment: No need write on other's words are great
Answer: At its simplest, it is simply a mechanism that rebuilds your project whenever a check in is made into some revision control system (CVS etc). This can be extended though to include running tests, all the way through to generating a CD image, mounting it within VMs, installing the product and running full tests on it.
It has the simple advantage of highlighting when code changes break the system as early as possible. Not only does it detect breaks in the code, it highlights who caused the break. This psychological effect is very effective in encouraging good testing prior to check in!
Answer: It is the practice of ensuring that all aspects of your software development process are lined up to permit the daily creation of a working version of your product.  It is best known as part of Extreme Programming.
This involves things as far afield as build automation, automated testing, daily check-ins, using a source code repository, etc.  But the ultimate goal is to help the entire project run according to core Agile Principles so that you deliver early and often.  This, in turn, helps you leverage feedback from your users, etc.
Answer: +1 for the link to Fowler's page.
Personally, I just found it "nice" to know whenever something didn't compile because we had the poor practice of having a single build (yes, we developed on the production build; we were awesome).  We hadn't got the integrated testing phase before I left.
After a while, it did, however, lessen the amount of massive coding changes (compared to the "check in and pray my changes don't conflict" that was rampant).  Eventually, most developers started making small changes frequently just to get confirmation from the CC.Net tray icon.
Overall, I found it very comforting to know that we could send out a build immediately if we had to.  Had we had just a few smoke tests integrated, I think the stress-level would have been substantially lower.
Comment: I just like the last sentence! It is a gold!
Answer: Just to refresh. At this point there is a huge difference between Continuous Integration (CI) and Continuous Delivery (CD). While most of posts above described CD I'll try to show how CI extends now CD definition. Having all the tools needed to build a package and deploy new version of app automatically is a crucial part of CD. Adding to that test automation (based on three level verification: General Health-check, Detailed Statistics and Historical entries) and a proper governance you're creating a really good piece of CI. Only because of such an extended definition building extraordinary cloud tools is possible. Think about muleESB or esbeetle.com. For both of them CI is something natural although only the second one is supporting both ESB and ETL components.
I hope that it was helpful.

What is continuous integration?


Electronic items limit to India

Question: If I take one brand new laptop and a brand new ipad to India, will I be subject to any duties?
Answer: I have traveled with two laptops before several times.
I carry one laptop in my carry-on luggage and another in my checked bags.
It was fine. Nobody asked me anything through immigration check or security check.
It is very common these days for one person to carry couple of gadgets with them while travelling due to work or other reasons.
If asked in the declaration form to declare electronics, than declare both items.

Electronic items limit to India


Upgrading from 4.1.5 database to 4.6.2 failing with constraint violation

Question: Trying to upgrade a 4.1.5 database to 4.2.6. I am getting a constraint violation. See the screenshot.
Answer: I recommend you take smaller steps, starting with 4.2. You can download the latest version of 4.2 from sourceforge (the latest in that series is currently 4.2.20).
If that upgrade goes ok, then you could proceed to 4.4 (the current LTS) and then up to 4.6.
Remember to backup your database before upgrading, and if the upgrade fails, restore from the backup before trying again.
Comment: I have treid to update to 4.2.20. from 4.1.5. I immediately get an error that a table exits. I've attached the screen shot to the original question
Comment: Are you sure you are starting with a 4.1 db that hasn't already been partially upgraded?
Comment: That should not be the case. It is a mysqldump of the current production database.
Answer: You may not care to keep all the log info in your live database so long as you have a backup. If so, run
<code>TRUNCATE civicrm_log;
</code>
on your sql db before running the upgrade.


Sotah in third temple?

Question: Putting the possibility of building a third temple aside, (this is a theoretical question), if the third temple was rebuilt, would the sotah ritual still apply like it did during the second temple period? Or would the takkanah against the ritual (see https://www.sefaria.org/Mishnah_Sotah.9.9) still apply in the third temple era?
Comment: What has changed since the day before the Temple was destroyed that would make you suspect the rule tomorrow might be different?
Comment: That was just me guessing. Anyone can guess. What are you looking for here in an answer?
Comment: Say a Halacha or responsa brought down on an issue in a source like the shulchan aruch or some other code of Jewish law @DoubleAA
Answer: The Torah teaches that in the future, G-d will "circumcise our hearts"

And the L-rd, your G-d, will circumcise your heart and the heart of your offspring (Devarim 30:6)

The Ramban (ad loc.) teaches that this means that the "physical lust" part of our being will be removed by G-d. Our Yetzer Hara will be removed and thus we have no more physical lusts anymore.
To extrapolate this, maybe we can say that the Sotah-process is not needed anymore, since there won't be any lusts anymore.
I have searched many places for מֵי הַמָּרִים בֵּית הַמִּקְדָּשׁ הַשְּׁלִישִׁי but it does not show up any source-based explanations.
In my answer here I quoted the Malbim on Zecharya where it explains that after Moshiach comes, every form and trace of idolatry will be removed from us.
Comment: Are you saying that the Sotah mitzvah will probably become kinda sorta dormant kinda like " א֛וֹב א֥וֹ יִדְּעֹנִ֖י"?
Comment: Maybe, I don't know. I do know that there are prophecies that tell us we will not have an yetzer hara anymore.
Answer: During the Second Temple period, there were a lot of philanderers; the Sotah process was intended for when adultery was a rare and shocking event, so it stopped working; eventually the rabbis stopped doing it.
By that logic, whether to use it in the next Temple will depend, simply enough, on whether there will be a lot of philanderers. And whether that will happen ... gets to the question of expectations about the Third Temple.
Comment: Thanks, so in that case the takkanah is not forever binding but conditional on similar circumstances. Appreciated, do you have a source for that assertion, however? @shalom
Comment: @KirkBellard This answer provided no source for such an assertion.
Comment: On the flip side, it might also depend on whether there are _any_ philanderers. Which makes this question more philosophical if so
Comment: The Tosefta says *because the procedure is for a safek, and this is a vadai.* The pasuk of *le efkod* was an asmachta. Therefore, I would read the current psak as: "do it, unless there are lots of philanderers."

Sotah in third temple?


How can I make a calendar appointment reminder remind me "5 minutes later" on iPhone like BlackBerry?

Question: Confession, I have just converted from BlackBerry to iPhone. On BlackBerry, if I had an event in my calendar with a reminder set for 15 minutes before the event, it have the option of dismissing the reminder or let it remind again in 5 minutes. I have been unable to find anything similar on the iPhone?
Answer: Unfortunately, iOS does not have a directly equivalent option. There are some workarounds and apps given here: Is there any way to change the snooze time for alarms on the iPhone?
Answer: There is a Snooze option on the lock screen in iOS 7 - the snooze time is 10 min.
Answer: Launch the Calendar app from the Home screen of your iPhone or iPad.
Tap on the name of the event you'd like to change the default alert for (or add an alert if you have default alerts disabled).
Tap on the Edit button in the upper right hand corner.
Tap on Alert.
Choose the alert time you'd like the Calendar to remind you at and then tap on Done in the upper right hand corner.


Indistinguishability game hop

Question: I am trying to prove that changing an input in a security game from a randomly permuted set to a set that is permuted using a pseudorandom permutation (PRP) results in a negligible distinguishing advantage between the two games. Does anyone know of any good examples in the literature of this kind of game hop. I have already read through the Shoup 2006 paper on games.
Comment: The Shoup paper is probably the best reference I can think of. Otherwise I would just recommend reading proofs that uses this technique, to get a feel of it. It is very commonly used and often called a "hybrid argument".
Comment: What do you mean by "changing an input"?
Comment: Oh, i realise this is not clear now! I meant changing an adversaries input so if you have Game 1 that uses a random permutation in Game 2 this input is changed and the game is given a PRP instead. An adversary has to try and distinguish between outputs from each of these games.
Comment: i just edited the question, hopefully this makes more sense
Comment: As to your proof, as I recall it is a matter of definition that any PRP seeded with randomness of length proportional to the security parameter should be at least computationally indistinguishable from from a true random permutation. So this should be a pretty easy proof (however, please check the definitions yourself, dont just take my word for it).
Answer: While I cannot point you to a specific paper that works as a great example for this technique, the idea is quite simple.
Assume two distributions $X,Y$ which have the same support, so random variables distributed according to one of these distributions are drawn from the same set.
Now assume you got a probabilistic adversary $A$ that takes as input $misc$ and a value $x$ that drawn according to $X$ and tries to solve some problem. Here $misc$ covers any additional inputs. As $X$ and $Y$ have the same support, we might also chose $x$ from $Y$ -- $A$ should at least accept such $x$ as input.
Let's switch to the games. Assume you got two games. In both you generate $misc$ the same way. But the games differ in how $x$ is chosen. In game 1 you chose $x$ according to $X$, in game 2 you chose $x$ according to $Y$. You might already see that if the success probability of $A$ differs, depending on if he plays in game 1 or in game 2, we can use this to distinguish the two cases, i.e. we can use this to decide from which distribution $x$ was chosen.
Say $A$ wins in game 1 with higher success probability than in game 2. Then we can built a distinguisher $D$ that takes a value $x$ and outputs 1 if $x$ was chosen from $X$ and $0$ if it was chosen from $Y$. $D$ simply runs $A(misc,x)$ and outputs 1 if $A$ succeeds. $D$ will distinguish the two cases exactly with $A$'s difference in success probability depending on which game he plays.
Hence, we can argue that if $X$ cannot be distinguished from $Y$ with probability greater $\epsilon$, the difference in $A$'s success probability between game 1 and game 2 must be limited by $\epsilon$.
That's how one game hop works. You can extend this arbitrarily. The important thing is that between two consecutive games you must only change the distribution of one of $A$'s inputs.
Comment: This is great, thank you for making it clear and simple :)
Answer: There is a similar approach to prove the semantic security of real world one time pad, using a pseudorandom generator. Basically the idea is to correlate the success probabilities of an alleged hard problem with the success probabilities of an attacker for your scheme. In the case of RWOTP once the simulator chooses a pseudorandom generator to pick up its key in order to reply to encryption queries by the attacker ($Pr[\mathcal{A}^{PRG}]$) and in the other case it chooses a uniform key($Pr[\mathcal{A}^{r\gets R}]$). The distinguishing probabilities of those two by definition of PRG is negligible: $Pr[\mathcal{A}^{PRG}]$ - $Pr[\mathcal{A}^{r\gets R}]=\epsilon$. But $Pr[\mathcal{A}^{r\gets R}]=\frac{1}{2}$ since $r$ is uniformly random. As such $Pr[\mathcal{A}^{PRG}]=\frac{1}{2}+\epsilon$.  But $Pr[\mathcal{A}^{PRG}]$ equals the success probabilities of $\mathcal{A}$ which tries to break RWOTP.
Similar answer here

Indistinguishability game hop


Does dark energy have gravity?

Question: So I keep running into this idea on the Internet that only mass has gravity, but isn't mass simply contained energy?
Energy bounces around, or travels at the speed of light, because it is not in the form of an atom, it is in the form of light, photons, quarks, neutrinos, and things we haven't discovered yet.
Wouldn't it make sense to say that if mass can warp space by its existence, then everything that exists must also have that effect as well, but to a much smaller degree, a square of the speed of light smaller, and we could only detect that gravity it had, if it wasn't flying around at the speed of light?
The reason this is important is that light cannot escape a black hole, and I believe that nothing can escape a black hole over time, whether it be light, dark energy, photons, neutrinos, or anything that exists at all, meaning that the fate of the universe changes.
If dark energy gets sucked into black holes because it has gravity by its existence, then the pushing effect it has turns into a pulling effect over time, and then the only logical conclusion is the universe is eternal, moving in an endless cycle of big bang, big crunch, big bang, which also explains why the Big Bang happened, and continues to happen, forever.
If you say that dark energy remains at constant density despite the expansion of the universe, explain why it does this, and why you think that, and why it doesn't have gravity. When was this proven, and what caused the Big Bang?
Comment: "The reason this is important is that light cannot escape a black hole, and I believe that nothing can escape a black hole over time, whether it be light, dark energy, photons, neutrinos, or anything that exists at all, meaning that the fate of the universe changes." : Hawking radiation?
Comment: So you're saying that Hawking Radiation is a false concept?
Comment: OK, when was it ever proven that energy doesn't have gravity, and that only mass does? I don't believe that you could ever prove that, except by looking at light from distant stars, which are affected by gravity. Doesn't that prove that since light is energy, that energy has gravity? If it has gravity because all things that exist bend space to some degree, then everything that exists including dark energy will get sucked into black holes and cause the big crunch.
Comment: The difference is, energy curves space time a square of the speed of light less than mass, and it's very hard to measure or prove that.
Comment: Yeah, Hawking radiation doesn't happen, because it can't, because all energy has gravity.
Comment: You really need to clarify your question though, it's all over the place at the moment.
Comment: Yes, Hawking radiation in terms of the big freeze theory where in the end only photons are flying around for all eternity is wrong.
Comment: No it doesn't. Light is a form of energy - correct. But why does it have gravity? Due to the lack of mass of photon's they are unable to cause a curvature in the space-time fabric; which according to Einstein is gravity.
Comment: That's not needed to curve the space time, it is simply the existence of anything that curves space time. Anything that exists has volume.
Comment: Photons are what build up light, do you agree? Photons do not display locality, hence they cannot have a gravitational influence
Comment: I'm not sure what you mean by display locality, I'll admit I didn't go to university, but I have been learning online for many years.
Comment: No problem, however, always remember that the internet is a dangerous place filled with excellent information. Photons show dual behavior, they can be both wave and particle at the same time. A single photon can never be measured accurately. A single photon can exist everywhere in the universe simultaneously. This is what it means to not display locality.
Comment: OK, but you're saying that it can't be measured accurately, to the point that it could be everywhere, so how does that mean you can tell anything about it at all? I really don't think that's true by the way, that it exists everywhere at once, unless there is an interconnectedness of all energy.
Comment: That is quantum mechanics. Difficult concept to grasp, but till now it explains the universe in the best way.
Comment: Yeah, I've read that in experiments, they say they can see subatomic particles appearing out of nowhere, but doesn't that just mean that they formed particle pairs and popped up where we can see them, and then went back to a place we couldn't see them? In some forms, energy can't be seen by humans, that doesn't mean it is everywhere at once. Does it?
Comment: Isn't the theory that there are strings of energy, which are way too small to see, but they are individual particles, similar to atoms in a way?
Comment: http://simple.wikipedia.org/wiki/Higgs_field This is the simple version of the Wikipedia entry that explains the Higgs field, which apparently explains why mass has gravity and energy doesn't, and it's apparently been proven to exist, but isn't it the case that still nobody can explain why gravity works at all?
Answer: Forgive me in advance, this may get overcomplicated. I am going to give you the facts as scaled down as I can but still sufficiently detailed. I think providing you with what we have and allowing you to infer from it is the best way to avoid misrepresenting the answer.
Here is the General Relativity equation that describes how gravity interacts with everything else:
$$R_{\mu\nu}-\frac{1}{2}g_{\mu\nu}R=8\pi G_NT_{\mu\nu}$$
On the left side is gravity; it is described by terms that have to do with how space curves, expands, and contracts. On the right side is matter, radiation, etc. Pretty much all forms of energy.
It was determined through observation that the universe as we know it is expanding and that the rate of expansion is accelerating. To account for the acceleration of the expansion, the best-fitting theory includes a constant term:
$$R_{\mu\nu}-\frac{1}{2}g_{\mu\nu}(R-2\Lambda)=8\pi G_NT_{\mu\nu}$$
Alternatively, one could choose to express that constant term on the right side of the equation. It makes no physical difference. Accordingly, you can interpret this term as a modification to how gravity affects spacetime (if added to the LHS) or as an additional energy term with a negative pressure (if added to the RHS).
Now, as per original GR, we have equations describing the expansion of the universe:
$$\frac{\ddot a}{a}=-\frac{4\pi G_N}{3}\sum_i(\rho_i+3p_i)$$
$a$ represents how much the universe has expanded, $\ddot a$ is the acceleration of the expansion, and $\rho_i$ and $p_i$ are the energy density and the pressure for the $i$th form of energy (the rest are constants). We put in matter, dark matter, radiation, and we even treat the background curvature of the universe as a form of energy here. What we find is that when we treat dark energy as an energy and set its pressure to be equal to negative of its energy density, our equations very closely match the observations. That is sufficient reason to like doing that. However, we also find (via a separate equation) that the energy density of something whose pressure equals the negative of the energy density remains constant for all time. This is unavoidable, it is one of the best fitting models so far.
Furthermore, the constant energy density presents other effects. The energy density of matter or radiation decreases with time. For instance, and this should be intuitive, the energy density of matter decreases like $a^{-3}$. That is, it drops like the cube of the expansion of the universe. And why not? as the universe expands, the volume increases like the expansion cubed; energy density is energy over volume, so it decreases like expansion cubed. Radiation goes like $a^{-4}$, and other energies decrease at varying rates. A constant density means that after a long time, it becomes the dominant term in the above equation. Effectively, after a long time:
$$\frac{\ddot a}{a}=\frac{8\pi G_N}{3}\rho_{DE}$$
This barrage of equations might mean nothing at all to you. That is fine. This is an answer to what dark energy is, why it has a constant energy density, and whether it has gravity.
As for whether or not dark energy can fall into a black hole, that is more complicated. From the point of view of modifying gravity, dark energy is not something that can fall into a black hole. However, from the point of view of being an additional energy term, one might think it must be able to fall into a black hole. Truthfully, I don't know that answer but I know it makes an insignificant difference. Dark energy is too weak to have an effect on the scale of black holes. Even the small gravity of the Sun is enough to negate the effect of dark energy throughout the solar system and probably a bit further. As you can see from the last equation, at late times the acceleration of the expansion is positive. Dark energy never brings the universe to a Big Crunch. For matter, radiation, etc, the acceleration terms at late times all are negative. Dark energy is preventing a Big Crunch.
In response to your last questions. This was never "proven". It was postulated decades ago and has been confirmed by many experiments but none that prove it beyond a doubt. As for what caused the Big Bang. The Big Bang was not an event, it was a moment of time. The Big Bang represents the point in time where the equation for $a$ (remember that's the term that represents how much the universe has expanded) goes to zero. That's it. It has no more need for a cause than has any moment of time after it.
Comment: Just a few comments. The "rate of expansion of the universe" is a term strictly used for $H={\dot a}/a$ and it is observed to be roughly constant. However, a given patch of the universe now grows approximately as $\sim a^3\sim e^{3 H({\rm now}) t} $ - so the growth is accelerating, the rate (as given oppositely in your answer) is not. Negative pressure is only a [confusing analogy](http://www.preposterousuniverse.com/blog/2013/11/16/why-does-dark-energy-make-the-universe-accelerate/). In any relevant sense, we do not actually presume dark energy to be a perfect fluid.
Comment: My last comment did not fit in the limit. Your last equation is not correct, it should be $({\dot a}/a)^2 = 8 \pi G \rho_{DM}/3$. Only then it all makes sense.
Comment: @Void when dark energy dominates, $(\dot a/a)^2=\ddot a/a$
Comment: Okay, that's true, ma' bad.
Answer: I am going to answer the following questions:
1) Does dark energy have gravity?
2) Why does dark energy have constant density during the expansion of the universe?
First about the term of dark energy - it is more of a label for many attempts of a solution to the problem of an accelerated expansion of the universe. One of the most promising (or say "mainstream") solutions is that of the cosmological constant or vacuum energy. Both of these concepts play an identical role in the equations of standard cosmology but their origin is either from a modified theory of relativity (the cosmological constant $\Lambda$) or particle physics (the vacuum energy). Now to the questions.
1) If we say accelerated expansion of the universe is due to a fundamental constant of the theory of gravity $\Lambda$, Dark energy indeed does not "have" gravity, because it is not really energy, it is just gravitation behaving slightly differently from what we thought on large scales.
If we say accelerated expansion is due to vacuum energy or some other "non-mainstream" energy, we are sure by observation that we do not feel it's "local" gravitational effect, that is lumps of dark energy pulling on objects in space. This means this energy must very homogeneous, ideally constant throughout the whole space. Why? Because if the distribution is completely homogeneous, there isn't any larger lump of dark energy we would be attracted to rather than anywhere else - the gravity just cancels out locally because it is equal in all directions but has an effect on cosmic scales.
2) If we consider vacuum energy, it is an energy inherent per unit volume of space even if it is completely empty (vacuous). So as the volume of a patch of the universe grows (as there is "more space"), there is always a constant energy per volume. (Notice that the overall energy of the universe grows, this is a well known result of standard cosmology.) This can be traced back to a basically postulated property of vacuum in quantum field theory and quantum field theory on curved background.
In the case of the cosmological constant, we don't need any argumentation of this sort, the constant is a property of gravitation.

Does dark energy have gravity?


Correct swiss pairings for a group of 4 players

Question: Say we have a situation that's not super uncommon in swiss tournaments. There are four people currently tied with the most points, where #1 and #3 have just played White (for example), while #2 and #4 have just played Black. Everything else being equal, do FIDE rules say anything about what the pairings should be here? Information about any rules from individual federations is also welcome.
Answer:
There are four people currently tied with the most points, where #1 and #3 have just played White (for example), while #2 and #4 have just played Black.

All else being equal, the pairings would likely be 1 vs 4 and 2 vs 3. This is, however, not guaranteed.
The pairing rules for the commonly used Dutch system are here. Let's walk through rule B (Pairing Process for a bracket) to see what happens.
Rule B.2 says:

To make the pairing, each bracket will be usually divided into two subgroups, called S1 and S2.
S1 initially contains the highest N1 players (sorted according to A.2), where N1 is either M1 (in a heterogeneous bracket) or MaxPairs (otherwise).
S2 initially contains all the remaining resident players.

This is a fancy way of saying that the group is split into an upper and lower half. In your scenario, #1 and #2 would be in the first half while #3 and and #4 would be in the second half.
Then, rule B.3 says:

S1 players are tentatively paired with S2 players, the first one from S1 with the first one from S2, the second one from S1 with the second one from S2 and so on.

So the tentative parings would be 1 vs 3 and 2 vs 4.
Rule B.4 says we should then evaluate how this tentative pairing complies with the various criteria in rule C. When we do so, we find that this pairing violates the quality criteria C.10 "minimize the number of players who do not get their colour preference." Since the candidate is not perfect, rule B.4 says we should apply rule B.5. Rule B.5 in turn says to apply rule B.6. (This is a homogeneous bracket, since everyone has the same score.)
Rule B.6 says we should first try a transposition. A transposition means the order of the players in the second half are changed. Since there are only two players in the second half, only one transposition is possible and we can pretty much skip the rules saying which transpositions should be considered first. So the new tentative pairing is 1 vs 4 and 2 vs 3.
As it turns out, this transposition results in a perfect candidate. So we stop there. The pairings would be 1 vs 4 and 2 vs 3.
But there are several reasons why the pairings might not go this way:

The players might have played each other in an earlier round. It is prohibited for players to play the same opponent twice in the same Swiss, so some other pairing would have to be generated.
A player who played Black last round might actually be due Black again due to playing White twice in a row earlier (or vice versa.) Having a different color preference could result in different pairings.
A problem with pairing the lower score groups could mean that the top group must be collapsed into the lower groups to be able to generate legal pairings. The group would then be entirely re-paired, which would almost certainly result in different pairings.
Some other system besides the Dutch system is being used. In this case you'd obviously have to read the rules for that system instead.
Comment: Well documented and clearly written! It's important to note however, that whilest it is to be prevented, it is not forbidden (and near impossible to prevent that) a player has the same colour twice in a row.
This is explained in `A.6`: the colour difference (e.g. 3 white plays and 4 black plays = +1) must vary between -1 and +1.
So you could imagine a 4B-3W=+1 : white paring is possible >which creates> 4B-4W=0: white pairing is possible >which creates> 4B-5W=-1 : an extra white paring would make -2, so a black pairing is now required.
Comment: Could you explain this E.2:
"E.2 Grant the stronger colour preference. If both are absolute (topscorers, see A.7) grant the wider colour difference (see A.6)." I can understand A.7 and A.6, and colour difference but what is "grant the wider colour difference" exactly?
Comment: I am also thinking if this is the last round, it is better to pair #1B vs #2W, because they have the same score and color preferences are meet and the most important is to match the top players based from initial ranking or seeding.
Comment: @ferdy A player with XWBB has an absolute preference for White since he's just played Black twice in a row. A player with BBWB also has an absolute preference for White. But the first player has a difference of 1 while the second has a difference of 2, so player 2 would get their preference if they had to play each other.
Comment: @ferdy As for pairing #1 and #2 in the last round, that's an opinion the Dutch system doesn't share. If there's a winner in both games there will be a tie for first no matter how you pair them anyway; is it really better for that tie to be between #1 and #3 instead of #1 and #2?
Comment: @DM On "But the first player has a difference of 1 while the second has a difference of 2", that is technically wrong. The second player BBWB has a colour difference of -2, the formula to get the colour difference is `white - black`. `W=1, B=3`, `1 - 3 is -2`. What is `XWBB`?
Comment: OK, fine, -2. "X" is an unplayed game, such as a bye or forfeit win.
Answer: The FIDE algorithm (I assume the standard is used) can be read online. It is deterministic. I can think only of one worst case: No initial ranking can be done as the players have same name and same rating :-)
Considering the second part of your question, note that other Swiss variants exist.
Answer: In this situation, assuming the pairings are possible, #1 would play Black against #4 while #2 would play White against #3.
Comment: Yes, but I think perhaps you should say why?


Document set Library issue

Question: I have created a document set library. By the time any of users create an item they can not view the documents as they should. I can see the documents, as site owner but not other users.
Could anyone advice what could be causing it?
Thanks for the time.
James
Comment: Have you looked at their permissions to the Document Library that the document set is in? It should be inheriting from that
Comment: Based on policy they have been assigned as contributors with no delete.
Comment: Is it possible that Item Level Permissions has been turned on for the document library? If they have contribute access it could block viewing of some items, but they should be able to see their own. there is no GUI method of turning on Item Level Permissions, however can be done programmatically, so could be part of it?
Answer: Make sure that other users have permissions to the documents sets in the library.

If you have enabled Content Approval in this library, make sure files are approved  or check the draft item security setting:
Comment: Hi BeerusDev, the permission level as I'd stated is steel contributed. I think I should change that to members for this lib.
Comment: Hi Hartraf, I'm not sure what you meant by programmatically, since it should not occurred from the very first place. Document set is there to be used by any users and visitors to the SharePoint site. Maybe it all about the level of permission that I have set up. I'm planning to change it to members to see the differences. Thanks. James

Document set Library issue


migrate timer job from sharepoint 2007 to 2010

Question: is it possible to migrate a custom timer job from SharePoint 2007 to 2010? is so,please let me know what points should i keep in mind before & after proceeding.
Answer: You should consider the following during the move:

You may only need WSP which contains timer job logic that can be deployed to 2010 platform.
You have to perform IISReset and restart timer job service to have full impact in 2010 version.
If you want to improve the timer job for 2010 (for whatever reasons) source code must be kept alive and you should be able to build/deploy updated WSPs.


Volume of a sphere using cartesian coordinates

Question: I'm preparing my calculus exam and I'm in doubt about how to generally compute triple integrals.
I know that the cartesian equation of a sphere is
$B_R=\{(x, y, z)|x^2+y^2+z^2=R^2\}$,
so (if I didn't want to use spherical coordinates, wich I'm aware is the best way and I already did that)
it's volume would just be $\iiint_S \mathrm{d}x\mathrm{d}y\mathrm{d}z$,
but what would the extremes be?
I know $-R \leq z \leq R$ and $-\sqrt{R^2-y^2-z^2} \leq x \leq\sqrt{R^2-y^2-z^2} $,
but what are the extremes for $y$?
I can't describe it in terms of $x$, so I have
$$\text{Vol}(B_R) = \int_{-R}^{R} \int_?^?\int_{-\sqrt{R^2-y^2-z^2}}^\sqrt{R^2-y^2-z^2} \mathrm{d}x\mathrm{d}y\mathrm{d}z.$$
What should be there instead of the '?'
Comment: The limits are $\pm\sqrt{R^2-z^2}$, because that is the maximum/minimum that $y$ is allowed to take knowing $z$ only.
Comment: So i have to compute the maximum/minimum of the function and substitute its $x$ coordinate in the extremes?
Comment: I don't know what "function" you are talking about.  Also, sphere is 2-dimensional, so doesn't have "volume".  You want the *ball* $B_R=\{x^2+y^2+z^2\leq R^2\}$ instead.
Comment: A sphere is a 3-dimensional object. The 2-dimensional analogue of a sphere is a circle.
Answer: It should be
\begin{equation}
\text{vol}(B_R) = \int_{-R}^{R} \int_{-\sqrt{R^2-z^2}}^{\sqrt{R^2-z^2}} \int_{-\sqrt{R^2-z^2-y^2}}^{\sqrt{R^2-z^2-y^2}} \, dx \, dy \, dz
\end{equation}
The way to think about this is to successively "fix" each variable as follows: pick a variable, for example $z$. Clearly, its bounds are $-R \leq z \leq R$. Then, for a fixed $z$, we have
\begin{equation}
0 \leq x^2 + y^2 \leq R^2 - z^2.
\end{equation}
Now, pick your next variable, say $y$. From the above inequality, it follows that $y$ must satisfy $- \sqrt{R^2 - z^2} \leq y \leq \sqrt{R^2 - z^2}$ (if it was outside this interval, the inequality above would be violated). Now, keep $y$ fixed. Then, we get
\begin{equation}
0 \leq x^2 \leq R^2 - z^2 - y^2
\end{equation}
which implies $-\sqrt{R^2 - z^2 - y^2} \leq x \leq \sqrt{R^2 - z^2 - y^2}$.

So, what you're doing is you look at the constraint all $3$ variables satisfy. Then, you choose one of them (for example $z$) and ask yourself what are the bounds it can take (in this case it was obvious). Then, you think of $z$ as fixed, and ask yourself what constraint do the remaining two variables satisfy (in this case $x,y$). Then you pick one of them (for example $y$) and ask what values can it take. Now, think of $y$ as fixed ax well, so that you end up with a constraint on $x$. This is a step-by-step reduction process which should be helpful; to really solidify your understanding you should see what each step is doing geometrically as well.
Answer: After doing away with the integral over $x$ it remains to be integrated over $y$ and $z$, as you already know. The domain of the remaining double integral is a circle on the $YZ$ plane. So, its limits are $-\sqrt{R^2 - z^2}$ (lower) and $\sqrt{R^2 - z^2}$ (upper).
If you want to see it geometrically, think of your 2-dimensional sphere of radius $R$ in the 3-dimensional Cartesian space. Project everything onto the $YZ$ plane to get a flat 2-dimensional circle of radius $R$. You can see that circle as the union of infinitely many half-circumferences of radius $R$, for $R$ ranging from $0$ to $R$.
Comment: Yes, but let me elaborate a bit on that. By integrating on a variable (say $x$) with those limits, you are passing the domain's information onto the integrand. When integrating a definite integral over $x$ your result cannot depend on $x$. With iterated integrals we follow this process with the hopes of obtaining a real number, which is the area or volume of a geometric object.
Comment: So in general when computing multiple integrals, after being done with one variable, i should "forget it" and think the space as losing one dimension (the direction of the variable i already integrated)?


Writing a Basic Shell

Question: For my class I have to create a basic shell similar to bash that will allow the user to call commands like ls, sleep, etc.
I am looking for resources on how to do this: tutorials, help text, sample code or even just some general information on how to get started.
Does anyone have an links or info to help me out?
Comment: At a high level, the idea is to read the input string and do a fork/exec.  For piping processes together, combine the fork/exec idiom with dup2 and close to connect the pipes.
Comment: Do you need it to parse shell scripts (or the arbitrary command line calls like `for x in \`seq 0 10\`; do something; done`?
Comment: No shell scripts, just executing built in linux commands and doing some file structure manipulation
Answer: It really depends on how simple your shell has to be.  If you don't need job control (i.e. backgrounding) or pipes then it is very simple.  Here is an example:
#include <stdio.h>
#include <stdlib.h>

#define MAX_LENGTH 1024

int main(int argc, char *argv[]) {
  char line[MAX_LENGTH];

  while (1) {
    printf("$ ");
    if (!fgets(line, MAX_LENGTH, stdin)) break;
    system(line);
  }

  return 0;
}

You can exit from the above example with CTRL-D.  To add built-in commands like exit or cd you would have to tokenize the line using strtok() and look at the first token.  Here is a more complicated example with those commands added:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#ifdef _WIN32
#include <windows.h>
#define chdir _chdir

#else
#include <unistd.h>
#endif

#define MAX_LENGTH 1024
#define DELIMS " \t\r\n"

int main(int argc, char *argv[]) {
  char *cmd;
  char line[MAX_LENGTH];

  while (1) {
    printf("$ ");
    if (!fgets(line, MAX_LENGTH, stdin)) break;

    // Parse and execute command
    if ((cmd = strtok(line, DELIMS))) {
      // Clear errors
      errno = 0;

      if (strcmp(cmd, "cd") == 0) {
        char *arg = strtok(0, DELIMS);

        if (!arg) fprintf(stderr, "cd missing argument.\n");
        else chdir(arg);

      } else if (strcmp(cmd, "exit") == 0) {
        break;

      } else system(line);

      if (errno) perror("Command failed");
    }
  }

  return 0;
}

You could extend this by adding more build-in commands or by supporting things like cd with out arguments to change to your home directory.  You could also improve the command prompt by adding information such as the current directory.
As a side note, an easy way to add a command history and line editing features is to use the GNU readline library.
Comment: @AliShakiba ``strtok`` keeps a context.  Passing zero causes it to continue parsing where it left off.  You should read the ``strtok`` man page.
Answer: I wrote a very basic shell for the HelenOS project. It has the following features:

Line editing / history
Buit in commands / loadable commands
Search path to find external commands
EXTREMELY basic scripting
Dumbed down implementations of most of the GNU core utilities (done from scratch) as built in functions.

Most of it is implemented on a very simple re-usable framework built around function pointers. At the minimum, you'll need a built in 'exit' or 'quit' so someone can actually get out of the shell, plus 'cd' and 'pwd'. An 'export' / 'declare' built in would also make sense.
You can look at the code (BSD) licensed here. Or download the repo, it's in uspace/app/bdsh. I can probably dig up the last working Linux version, prior to when I ported it if you need it. The biggest difference is the HelenOS version uses a home grown line editor, task_spawn() instead of execve() / posix_spawn(), etc. The rest is portable. It was originally designed just to make testing of features easy and interactive. I didn't implement job control, as it wasn't needed. That could be achieved trivially, however.
If you want to study a 'real' shell, I highly recommend looking at dash, you'll find it much simpler to grasp than diving straight into the code of bash.
Anecdotally, 'bdsh' stands for 'brain dead shell'.
Answer: You could look at BusyBox for some very small shell implementations.
Answer: If you are starting , try http://stephen-brennan.com/2015/01/16/write-a-shell-in-c/ and further for detailed knowledge http://www.gnu.org/software/libc/manual/html_node/Data-Structures.html#Data-Structures .
Also , while learning how to program a shell using C/C++ make a habit to refer man pages of commands.
Answer: Bash provides very few commands on its own: cd, pushd, popd, the variable handling routines (set and $x), and all of the control flow items like loops and conditionals. Almost all other commands are found in the $PATH.
Unless the assignment states otherwise, ignore variables and control flow. Just provide a REPL that looks in $PATH and executes whatever the user enters (presumably through posix_spawn()) and pass along the command-line arguments.
Answer: Lowball answer:
If the program is very simple, then simple system calls can be implemented script-like with the command "system("putdesiredcommandhere");"
When you install "printf" in a program, you are doing a simple system call, with the help of stdio.h.
Small code sample follows.
#include <stdio.h>
#include <stdlib.h>
main ()
{
    system ("clear");
    system ("echo this is an example of a basic system call");
    printf ("just as you've always done.\n");

    return 0;
}

Using that method, you could transcribe bash or csh scripts into a c program.  It would require using a system call for each line in the script.

Writing a Basic Shell


What's the difference between SHA and AES encryption?

Question: What's the difference between SHA and AES encryption?
Comment: Better for http://security.stackexchange.com/.
Answer: SHA isn't encryption, it's a one-way hash function. AES (Advanced_Encryption_Standard) is a symmetric encryption standard.
AES Reference
Answer: TL;DR; each of SHA algorithm family is a one-way hashing feature and/or function,
while AES is intended to allow both encryption and decryption.

SHA is a family of "Secure Hash Algorithms" that have been developed by the National Security Agency. There is currently a competition among dozens of options for who will become SHA-3, the new hash algorithm for 2012+.
You use SHA functions to take a large document and compute a "digest" (also called "hash") of the input. It's important to realize that this is a one-way process. You can't take a digest and recover the original document.
AES, the Advanced Encryption Standard is a symmetric block algorithm. This means that it takes 16 byte blocks and encrypts them. It is "symmetric" because the key allows for both encryption and decryption.
UPDATE: Keccak was named the SHA-3 winner on October 2, 2012.
Answer: SHA and AES serve different purposes.  SHA is used to generate a hash of data and AES is used to encrypt data.
Here's an example of when an SHA hash is useful to you.  Say you wanted to download a DVD ISO image of some Linux distro.  This is a large file and sometimes things go wrong - so you want to validate that what you downloaded is correct.  What you would do is go to a trusted source (such as the offical distro download point) and they typically have the SHA hash for the ISO image available.  You can now generated the comparable SHA hash (using any number of open tools) for your downloaded data.  You can now compare the two hashs to make sure they match - which would validate that the image you downloaded is correct.  This is especially important if you get the ISO image from an untrusted source (such as a torrent) or if you are having trouble using the ISO and want to check if the image is corrupted.
As you can see in this case the SHA has was used to validate data that was not corrupted.  You have every right to see the data in the ISO.
AES, on the other hand, is used to encrypt data, or prevent people from viewing that data with knowing some secret.
AES uses a shared key which means that the same key (or a related key) is used to encrypted the data as is used to decrypt the data.  For example if I encrypted an email using AES and I sent that email to you then you and I would both need to know the shared key used to encrypt and decrypt the email.  This is different than algorithms that use a public key such PGP or SSL.
If you wanted to put them together you could encrypt a message using AES and then send along an SHA1 hash of the unencrypted message so that when the message was decrypted they were able to validate the data.  This is a somewhat contrived example.
If you want to know more about these some Wikipedia search terms (beyond AES and SHA) you want want to try include:
Symmetric-key algorithm  (for AES)
Cryptographic hash function  (for SHA)
Public-key cryptography (for PGP and SSL)
Answer: SHA is a hash function and AES is an encryption standard. Given an input you can use SHA to produce an output which is very unlikely to be produced from any other input. Also, some information is lost while applying the function so even if you knew how to produce an input yielding the same output, that input wouldn't likely be the same one used in the first place.
On the other hand AES is meant to protect from disclosure to third parties any data sent between two parties sharing the same encryption key. This means that once you know the encryption key and the output (and the IV...) you can seamlessly get back to the original input.
Please notice that SHA doesn't require anything but an input to be applied, while AES requires at least 3 thins: what you're encrypting/decrypting, an encryption key and the initialization vector (IV).
Answer: SHA stands for Secure Hash Algorithm while AES stands for Advanced Encryption Standard. So SHA is a suite of hashing algorithms. AES on the other hand is a cipher which is used to encrypt. SHA algorithms (SHA-1, SHA-256 etc...) will take an input and produce a digest (hash), this is typically used in a digital signing process (produce a hash of some bytes and sign with a private key).
Answer: SHA doesn't require anything but an input to be applied, while AES requires at least 3 things - what you're encrypting/decrypting, an encryption key, and the initialization vector.
Comment: [This was flagged as a "late answer to an old question, provided by a new user. My comment is in that context.] This doesn't appear to add any info over what's already provided in other answers to this question.
Comment: That is wrong. You don't need a initialization vector (IV) to use AES.  Some modes of operations for AES require an IV (which is totally different).


temporary queues for msmq

Question: In the JMS world there is this concept called temporary destinations which is very heplful for request/response scenarios. The sender makes request on some destination and  creates a temporary destination (which  exists only as long as the session it is created in is stil there)for receving the responses.
Is there such a thing for msmq?
Answer: No there isn't. Its seems to me that this concept ( of sessions ) is strange in a queuing scenario.

temporary queues for msmq


Is quantum query complexity equivalent to the total number of calls to the quantum computer for any given algorithm?

Question: In other words, if an algorithm requires N total calls to the quantum computer to find the solution (of any given problem), would N be equivalent to its query complexity?
Answer: The query complexity is usually spoken about with respect to an oracle or black-box function. It is the numbers of times you make use of that oracle in your algorithm (each time you use it, you are said to be "querying it", hence the terminology "query complexity"). It might be that you use the oracle many times in a single run of the algorithm on the quantum computer (such as in Grover's search).


corr() is giving an error. please help out of this problem and tell me what is this error about

Question:
when I am trying to run sns.heatmap(df.corr(),annot=True) this code in my jupyter notebook. this error is occuring. I cannot understand this problem. please help me.
Answer: For df.corr() you would have to pass float/integer instead of string.
You can check this answer on stack overflow as well - https://stackoverflow.com/questions/51241575/calculate-correlation-between-columns-of-strings.
To convert the strings to the integers/floats you can use feature extraction techniques used in NLP like CountVectorizer, TfidifVectorizer, Word Embedding. You can refer this documentation - https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html
Answer: Use this:
my_df = df.select_dtypes(exclude=[object])

This will select only the integer and float columns from your dataframe.
After this you can use:
my_df.corr()

Hope it will work.