How to programmatically send SMS on the iPhone?

Question: Does anybody know if it's possible, and how, to programmatically send a SMS from the iPhone, with the official SDK / Cocoa Touch?
Comment: in Ios 4 You can send sms with code but problem is your application will be closed
Comment: If using the official SDK is not a requirement for others, I wrote this post to show how to do this using Twilio: https://www.twilio.com/blog/2016/11/how-to-send-an-sms-from-ios-in-swift.html
Comment: you can create a google spreadsheet off of your gmail, make the fields you want, then do `tools->script editor` and in a POST request use `MailApp.sendEmail` api to send email to a phone number. att's is firstname.lastname@example.com, tmobile's is email@example.com I think (ALL FREE)
Answer: Restrictions
If you could send an SMS within a program on the iPhone, you'll be able to write games that spam people in the background.  I'm sure you really want to have spams from your friends, "Try out this new game!  It roxxers my boxxers, and yours will be too! roxxersboxxers.com!!!! If you sign up now you'll get 3,200 RB points!!"
Apple has restrictions for automated (or even partially automated) SMS and dialing operations.  (Imagine if the game instead dialed 911 at a particular time of day)
Your best bet is to set up an intermediate server on the internet that uses an online SMS sending service and send the SMS via that route if you need complete automation.  (ie, your program on the iPhone sends a UDP packet to your server, which sends the real SMS)
iOS 4 Update
iOS 4, however, now provides a viewController you can import into your application.  You prepopulate the SMS fields, then the user can initiate the SMS send within the controller.  Unlike using the "SMS:..." url format, this allows your application to stay open, and allows you to populate both the to and the body fields.  You can even specify multiple recipients.
This prevents applications from sending automated SMS without the user explicitly aware of it.  You still cannot send fully automated SMS from the iPhone itself, it requires some user interaction.  But this at least allows you to populate everything, and avoids closing the application.
The MFMessageComposeViewController class is well documented, and tutorials show how easy it is to implement.
iOS 5 Update
iOS 5 includes messaging for iPod touch and iPad devices, so while I've not yet tested this myself, it may be that all iOS devices will be able to send SMS via MFMessageComposeViewController.  If this is the case, then Apple is running an SMS server that sends messages on behalf of devices that don't have a cellular modem.
iOS 6 Update
No changes to this class.
iOS 7 Update
You can now check to see if the message medium you are using will accept a subject or attachments, and what kind of attachments it will accept.  You can edit the subject and add attachments to the message, where the medium allows it.
iOS 8 Update
No changes to this class.
iOS 9 Update
No changes to this class.
iOS 10 Update
No changes to this class.
iOS 11 Update
No significant changes to this class
Limitations to this class
Keep in mind that this won't work on phones without iOS 4, and it won't work on the iPod touch or the iPad, except, perhaps, under iOS 5.  You must either detect the device and iOS limitations prior to using this controller, or risk restricting your app to recently upgraded 3G, 3GS, and 4 iPhones.
However, an intermediate server that sends SMS will allow any and all of these iOS devices to send SMS as long as they have internet access, so it may still be a better solution for many applications.  Alternately, use both, and only fall back to an online SMS service when the device doesn't support it.
Comment: I think it's ironic that somebody flagged this post as spam. Read between the lines, peoples!
Comment: I really appreciate that you keep this post updated for new iOS versions. :)
Comment: And if you purchase that domain I will never be able to look at you the same way again.
Comment: @Frank - Updated my writeup to reflect the new iOS 4 features.  Removed wishy-washy wording.
Comment: -1 because this reads as speculation. Also, see Jus' Wondrin''s and rydgaze's answers on how to send in-app SMSes.
Comment: I know this is very late but is it possible to send a message with a photo as an attachment?
Comment: Added to this could be, that in iOS5 Apple don't send SMS as Adam is speculating, they use iMessage with devices that is not inherently a phone.
Comment: @edhedges, yours should be a new question, not a comment.
Comment: I need to send an sms to a specific number but with predefined (prefill) body text. Thos body text should be the manual selection from 4 possible options. E.g. The app opens and pop-ups "select reason". Then 4 options are available. Next the user selects one of these 4 options and then an automatic SMS is sent having as body text the choice of the user. Any tip?
Answer: Here is a tutorial which does exactly what you are looking for: the MFMessageComposeViewController.
http://blog.mugunthkumar.com/coding/iphone-tutorial-how-to-send-in-app-sms/
Essentially:
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
    controller.body = @"SMS message here";
    controller.recipients = [NSArray arrayWithObjects:@"1(234)567-8910", nil];
    controller.messageComposeDelegate = self;
    [self presentModalViewController:controller animated:YES];
}

And a link to the docs.
https://developer.apple.com/documentation/messageui/mfmessagecomposeviewcontroller
Comment: You can certainly send SMS in the background using a service such as Twilio, but if you want to send it from the user's phone number, they have to approve the message via the above method.
Comment: anyone using the above code may wish to consider putting the `MFMessageComposeViewController *controller = ...` inside the if block. (the class method does not need to have an instance to do the test)
Comment: still, the SMS form has to pop up. Any way to send in background?
Comment: The link `http://blog.mugunthkumar.com/coding/iphone-tutorial-how-to-send-in-app-sms/` says "502 Bad Gateway" on my laptop. Maybe the link is broken.
Answer:
You must add the MessageUI.framework to your Xcode project
Include an #import <MessageUI/MessageUI.h> in your header file
Add these delegates to your header file MFMessageComposeViewControllerDelegate  & UINavigationControllerDelegate
In your IBAction method declare instance of MFMessageComposeViewController say messageInstance
To check whether your device can send text use [MFMessageComposeViewController canSendText] in an if condition, it'll return Yes/No
In the if condition do these:

First set body for your messageInstance as:
messageInstance.body = @"Hello from Shah";

Then decide the recipients for the message as:
messageInstance.recipients = [NSArray arrayWithObjects:@"12345678", @"87654321",         nil];

Set a delegate to your messageInstance as:
messageInstance.messageComposeDelegate = self;

In the last line do this:
[self presentModalViewController:messageInstance animated:YES];

Comment: Version note: `presentModalViewController:animated:` is deprecated; use `presentViewController:animated:completion:` instead. Also, remember to define the delegate method `- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result` if you want to know the results.
Comment: Please put the code for test. @Najeebullah Shah here or in github.
Answer: You can use a sms:[target phone number] URL to open the SMS application, but there are no indications on how to prefill a SMS body with text.
Comment: react-native-communications uses the &body= parameter to prefill the text when opening the sms:targetphonenumber&body=textyouwanttoprefillwith for iOS
Comment: I just tried this on my iphone 8, and it worked great... thanks!
Comment: I need to send an sms to a specific number but with predefined (prefill) body text. Thos body text should be the manual selection from 4 possible options. E.g. The app opens and pop-ups "select reason". Then 4 options are available. Next the user selects one of these 4 options and then an automatic SMS is sent having as body text the choice of the user. any tip?
Answer: One of the systems of inter-process communication in MacOS is XPC. This system layer has been developed for inter-process communication based on the transfer of plist structures using libSystem and launchd. In fact, it is an interface that allows managing processes via the exchange of such structures as dictionaries. Due to heredity, iOS 5 possesses this mechanism as well.
You might already understand what I mean by this introduction. Yep, there are system services in iOS that include tools for XPC communication. And I want to exemplify the work with a daemon for SMS sending. However, it should be mentioned that this ability is fixed in iOS 6, but is relevant for iOS 5.0—5.1.1. Jailbreak, Private Framework, and other illegal tools are not required for its exploitation. Only the set of header files from the directory /usr/include/xpc/* are needed.
One of the elements for SMS sending in iOS is the system service com.apple.chatkit, the tasks of which include generation, management, and sending of short text messages. For the ease of control, it has the publicly available communication port com.apple.chatkit.clientcomposeserver.xpc. Using the XPC subsystem, you can generate and send messages without user's approval.
Well, let's try to create a connection.
xpc_connection_t myConnection;

dispatch_queue_t queue = dispatch_queue_create("com.apple.chatkit.clientcomposeserver.xpc", DISPATCH_QUEUE_CONCURRENT);

myConnection = xpc_connection_create_mach_service("com.apple.chatkit.clientcomposeserver.xpc", queue, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED);

Now we have the XPC connection myConnection set to the service of SMS sending. However, XPC configuration provides for creation of suspended connections —we need to take one more step for the activation.
xpc_connection_set_event_handler(myConnection, ^(xpc_object_t event){
xpc_type_t xtype = xpc_get_type(event);
if(XPC_TYPE_ERROR == xtype)
{
NSLog(@"XPC sandbox connection error: %s\n", xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION));
}
// Always set an event handler. More on this later.

NSLog(@"Received a message event!");

});

xpc_connection_resume(myConnection);

The connection is activated. Right at this moment iOS 6 will display a message in the telephone log that this type of communication is forbidden. Now we need to generate a dictionary similar to xpc_dictionary with the data required for the message sending.
NSArray *recipient = [NSArray arrayWithObjects:@"+7 (90*) 000-00-00", nil];

NSData *ser_rec = [NSPropertyListSerialization dataWithPropertyList:recipient format:200 options:0 error:NULL];

xpc_object_t mydict = xpc_dictionary_create(0, 0, 0);
xpc_dictionary_set_int64(mydict, "message-type", 0);
xpc_dictionary_set_data(mydict, "recipients", [ser_rec bytes], [ser_rec length]);
xpc_dictionary_set_string(mydict, "text", "hello from your application!");

Little is left: send the message to the XPC port and make sure it is delivered.
xpc_connection_send_message(myConnection, mydict);
xpc_connection_send_barrier(myConnection, ^{
NSLog(@"The message has been successfully delivered");
});

That's all. SMS sent.
Comment: You shouldn't use XPC to send SMS. The App produced won't be approved by Apple. Use MessageUI Framework  instead
Comment: If you are using this techinique for app that you use for your organisation, and app is not going through app store, you have no worries.
Comment: Getting "XPC sandbox connection error: Connection invalid" on iOS 12
Answer: Add the MessageUI.Framework and use the following code
#import <MessageUI/MessageUI.h>

And then:
if ([MFMessageComposeViewController canSendText]) {
  MFMessageComposeViewController *messageComposer =
  [[MFMessageComposeViewController alloc] init];
  NSString *message = @"Your Message here";
  [messageComposer setBody:message];
  messageComposer.messageComposeDelegate = self;
  [self presentViewController:messageComposer animated:YES completion:nil];
}

and the delegate method -
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
             didFinishWithResult:(MessageComposeResult)result {
      [self dismissViewControllerAnimated:YES completion:nil];
 }

Comment: Apple will not allow you to send message without users approval. He has to send message/mail by manually pressing the button. Alternatively, you can use a custom service by sending emails/numbers to your backend and then sending. Though you cannot do this directly on iPhone
Comment: hey thats great , but can we do this functionality from background?
Answer: You can use this approach:
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"sms:MobileNumber"]]

iOS will automatically navigate from your app to the messages app's message composing page. Since the URL's scheme starts with sms:, this is identified as a type that is recognized by the messages app and launches it.
Answer: Follow this procedures
1 .Add MessageUI.Framework to project
2 . Import #import <MessageUI/MessageUI.h> in .h file.
3 . Copy this code for sending message
 if ([MFMessageComposeViewController canSendText]) {
    MFMessageComposeViewController *messageComposer =
    [[MFMessageComposeViewController alloc] init];
    NSString *message = @"Message!!!";
    [messageComposer setBody:message];
    messageComposer.messageComposeDelegate = self;
    [self presentViewController:messageComposer animated:YES completion:nil];
}

4 . Implement delegate method if you want to.
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{

   ///your stuff here

    [self dismissViewControllerAnimated:YES completion:nil];
}

Run And GO!
Comment: worth mentioning that you'll probably want to run `[self dismissViewControllerAnimated:YES completion:nil];` inside `messageComposeViewController: didFinishWithResult:` callback method. Else it will just hang there.
Answer: //Add the Framework in .h file

#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>

//Set the delegate methods

UIViewController<UINavigationControllerDelegate,MFMessageComposeViewControllerDelegate>

//add the below code in .m file

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    MFMessageComposeViewController *controller =
    [[[MFMessageComposeViewController alloc] init] autorelease];

    if([MFMessageComposeViewController canSendText])
    {
        NSString *str= @"Hello";
        controller.body = str;
        controller.recipients = [NSArray arrayWithObjects:
                                 @"", nil];
        controller.delegate = self;
        [self presentModalViewController:controller animated:YES];
    }

}

- (void)messageComposeViewController:
(MFMessageComposeViewController *)controller
                 didFinishWithResult:(MessageComposeResult)result
{
    switch (result)
    {
        case MessageComposeResultCancelled:
            NSLog(@"Cancelled");
            break;
        case MessageComposeResultFailed:
            NSLog(@"Failed");
            break;
        case MessageComposeResultSent:
            break;
        default:
            break;
    }
    [self dismissModalViewControllerAnimated:YES];
}

Comment: you should see this link:  http://blog.mugunthkumar.com/coding/iphone-tutorial-how-to-send-in-app-sms/      it will help you
Answer: Here is the Swift version of code to send SMS in iOS. Please noted that it only works in real devices. Code tested in iOS 7+. You can read more here.
1) Create a new Class which inherits MFMessageComposeViewControllerDelegate and NSObject:
import Foundation
import MessageUI

class MessageComposer: NSObject, MFMessageComposeViewControllerDelegate {
    // A wrapper function to indicate whether or not a text message can be sent from the user's device
    func canSendText() -> Bool {
        return MFMessageComposeViewController.canSendText()
    }

    // Configures and returns a MFMessageComposeViewController instance
    func configuredMessageComposeViewController(textMessageRecipients:[String] ,textBody body:String) -> MFMessageComposeViewController {
        let messageComposeVC = MFMessageComposeViewController()
        messageComposeVC.messageComposeDelegate = self  //  Make sure to set this property to self, so that the controller can be dismissed!
        messageComposeVC.recipients = textMessageRecipients
        messageComposeVC.body = body
        return messageComposeVC
    }

    // MFMessageComposeViewControllerDelegate callback - dismisses the view controller when the user is finished with it
    func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
        controller.dismissViewControllerAnimated(true, completion: nil)
        }
}

2) How to use this class:
func openMessageComposerHelper(sender:AnyObject ,withIndexPath indexPath: NSIndexPath) {
    var recipients = [String]()

    //modify your recipients here

    if (messageComposer.canSendText()) {
        println("can send text")
        // Obtain a configured MFMessageComposeViewController
        let body = Utility.createInvitationMessageText()

        let messageComposeVC = messageComposer.configuredMessageComposeViewController(recipients, textBody: body)

        // Present the configured MFMessageComposeViewController instance
        // Note that the dismissal of the VC will be handled by the messageComposer instance,
        // since it implements the appropriate delegate call-back
        presentViewController(messageComposeVC, animated: true, completion: nil)
    } else {
        // Let the user know if his/her device isn't able to send text messages
        self.displayAlerViewWithTitle("Cannot Send Text Message", andMessage: "Your device is not able to send text messages.")
    }
}

Answer: There is a class in iOS 4 which supports sending messages with body and recipents from your application. It works the same as sending mail. You can find the documentation here: link text
Answer: - (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    UIImage *ui =resultimg.image;
    pasteboard.image = ui;
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:"]];
}

Comment: how useful are your parameters ?
Comment: [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:"]];
Answer: //call method with name and number.
-(void)openMessageViewWithName:(NSString*)contactName withPhone:(NSString *)phone{

CTTelephonyNetworkInfo *networkInfo=[[CTTelephonyNetworkInfo alloc]init];

CTCarrier *carrier=networkInfo.subscriberCellularProvider;

NSString *Countrycode = carrier.isoCountryCode;

if ([Countrycode length]>0)     //Check If Sim Inserted
{

    [self sendSMS:msg recipientList:[NSMutableArray arrayWithObject:phone]];
}
else
{

    [AlertHelper showAlert:@"Message" withMessage:@"No sim card inserted"];
}

}
//Method for sending message
- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSMutableArray *)recipients{
 MFMessageComposeViewController *controller1 = [[MFMessageComposeViewController alloc] init] ;
 controller1 = [[MFMessageComposeViewController alloc] init] ;
 if([MFMessageComposeViewController canSendText])
{
    controller1.body = bodyOfMessage;
    controller1.recipients = recipients;
    controller1.messageComposeDelegate = self;
    [self presentViewController:controller1 animated:YES completion:Nil];
 }
}

Answer: If you want, you can use the private framework CoreTelephony which called CTMessageCenter class. There are a few methods to send sms.
Comment: He specifically asked if this were possible using the official SDK.
Comment: Can you provide more information about the private api? I have no problem to use private framework because I don't need to publish it to App Store.
Answer: Use this:
- (void)showSMSPicker
{
    Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));

    if (messageClass != nil) {
        // Check whether the current device is configured for sending SMS messages
        if ([messageClass canSendText]) {
           [self displaySMSComposerSheet];
        }
    }
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    //feedbackMsg.hidden = NO;
    // Notifies users about errors associated with the interface
    switch (result)
    {
        case MessageComposeResultCancelled:
        {
            UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"Message" message:@"SMS sending canceled!!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert1 show];
            [alert1 release];
        }

        // feedbackMsg.text = @"Result: SMS sending canceled";
        break;

        case MessageComposeResultSent:
        {
            UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"Message" message:@"SMS sent!!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert2 show];
            [alert2 release];
        }

        // feedbackMsg.text = @"Result: SMS sent";
        break;

        case MessageComposeResultFailed:
        {
            UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:@"Message" message:@"SMS sending failed!!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert3 show];
            [alert3 release];
        }

        // feedbackMsg.text = @"Result: SMS sending failed";
        break;

        default:
        {
            UIAlertView *alert4 = [[UIAlertView alloc] initWithTitle:@"Message" message:@"SMS not sent!!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert4 show];
            [alert4 release];
        }

        // feedbackMsg.text = @"Result: SMS not sent";
        break;
    }

    [self dismissModalViewControllerAnimated: YES];
}

Answer: [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"sms:number"]]

This would be the best and short way to do it.
Answer: You can present MFMessageComposeViewController, which can send SMS, but with user prompt(he taps send button). No way to do that without user permission. On iOS 11, you can make extension, that can be like filter for incoming messages , telling iOS either its spam or not. Nothing more with SMS cannot be done
Answer: You need to use the MFMessageComposeViewController if you want to show creating and sending the message in your own app.
Otherwise, you can use the sharedApplication method.


Weighted Monte Carlo Integration

Question: I have a function $F(x)$ which drops exponentially (like differential QCD cross section vs. Invariant mass). I want to perform Monte-Carlo integration. The problem is that only small $x$'s which have large $F(x)$ are accounted. I mean if the range of $x$ is $[1, 8]$ TeV, the maximum value of $F$ is $F(1)$ and the minimum value of $F$ is $F(8)$ which differ by 8 orders of magnitude. Thus, only random generated $x$'s which are close to 1 are accepted. How can I generate large $x$? Thanks
Comment: Why would you want to do that? The reason why large $x$ are not generated is because $F(x)$ does not contribute to the integral in a noticeable way for large $x$.
Comment: Actually, the underlying problem is related to physics. At some large $x$ I have a bump in the curve which comes from the theory. That bump should be seen by the Monte Carlo Generator, although with a small probability.
Comment: Is there a way to flatten the function? I saw this way of dealing with these kinds of curves (for example differential QCD cross-section ) in the ATLAS papers but don't know a starting point to learn it.
Comment: Can you post a picture of $F(x)$?
Comment: Do you want to integrate $F$ over the interval $[1,8]$?
Comment: The shape is like the red line in the following page :
https://www.researchgate.net/figure/The-NLO-QCD-pAccX-differential-cross-section-as-a-function-of-Feynman-xF-for-PRS-14_fig3_1734350
Comment: Yes I want to integrate it using Monte-Carlo method.
Comment: Do you use Markov chain rejection sampling? If not, could you specify what you are doing?
Answer: What about dividing the interval $[0,0.6]$ in sub-intervals $[x_i,x_{i-1}]$ so that in each one the function value has the same order of magnitude?
For example you could choose $x_0 =0$, $x_{m}=0.6$
$$
x_i \;|\; 0<i<m \; \wedge \;F(x_i) = 10^i
$$
Then you can integrate in each one and sum the partial results to get the total integral.
I have never done this, but it is what I would try first. The contributions at the extreme right of each interval will probably be underestimated, but at least this effect is reduced.
Be also sure to properly consider errors (they depend on your specific method): if the bump gives a contribution which is smaller than the uncertainty, either you have to reduce the error (which I suppose is your case, since you are interested in the bump) or you can ignore the bump.
If you try this, let me know if it works!
Detailed implementation
(pseudo-code)
<code>hit = 0
miss = 0
x = generate_random(x_interval)
y = generate_random([0,max_of_function])
if(F(x)>y) hit++
else if(F(x)<y) miss++
percentage_hits = hit/(hit+miss)
total_area = (x_interval*max_of_function)
function_area = percentage_hits * total_area
</code>
Now you have the area in the x_interval selected. Compute the same for each interval, then sum all the partial areas.
Comment: Thanks for the answer. Actually, it works. Assume we take $x$ as a property of an event. So by Monte-Carlo we mean generating random events which have the property $x$, according to a distribution function $F(x)$. Let's say I have generated a million event out of the method you just mentioned. Assuming I have 20 intervals. In each interval I have around 50000 events. Then if I histogram the events, I can't see anything useful since there are equal number of events in each interval.
Comment: Sorry, I think I don't understand your question: the basic idea with MC integration is to generate an uniform distribution of points, then see how much percentage of them is "under" the function and relate this to the fraction of the total area in which they are generated. I think you are using a more enveloped method, so if you will explain it or link some resource, then I hopefully can better understand. I'll try now to add some details to my answer.
Comment: In fact, it is related to physics and how events are generated theoretically and compared to experimental results to evaluate the theory. The problem is that whatever I find on-line has complicated mathematics and there is nothing that clearly explains the procedure.
Comment: But you are integrating the function, right? If this is your need, the pseudo-code I wrote should fit. Otherwise can you link some reference, even if it is compolicated, so that is clear what you need?
Comment: At some point I have to integrate it which is simple. I just use the built-in functions of python to do it. Sure, I will send post some references as soon as possible. Thanks

Weighted Monte Carlo Integration


Why won't water freeze if you put ice in it, despite ice being frozen?

Question: Just now I got some room temperature water and added some ice to cool it, and it just came to me, like the scientist I wish I was ... why doesn't frozen (freezing point) ice added to higher temperature liquid compound force the water molecules to solidify?
Answer: Why won't water freeze if you put ice in it?
It will, even at room temperature. You just need a big enough, cold enough ice cube.
Don't believe it? Add a few drops of water to an ice cube in an ice cube tray (which is the same as adding an ice cube to a few drop of water). Wait a few seconds, turn the tray upside down. No water will fall, presumably because it has frozen. Repeat, but immediately turn the tray upside down. You'll get a wet floor. You can conclude that, given enough time, the water will be frozen by the ice. To the whys and hows:
From the second law of thermodynamics we know that:

An isolated system, if not already in its state of thermodynamic equilibrium, spontaneously evolves towards it.

And

Heat cannot spontaneously flow from a colder location to a hotter location.

So if you put ice and water together in a cup, heat will flow from the water to the ice until they reach thermal equilibrium, which will be a temperature between the water's initial temperature and the ice's initial temperature. If the temperature of the ice was low enough or if there was enough ice for the water to keep giving away heat, then the water will freeze. That's considering our cup is an isolated system.
Why don't you usually see that happening? Well, regular ice cubes are probably around −5 °C, and there usually is more water than ice in a cup, so before the water has a chance to reach 0 °C all the ice has already melted. Besides that, the ice is receiving heat from the room, unless you're in a place where's below 0 °C. In that case, the water WILL eventually freeze, but mostly because of the environment.
Answer: Water, like most substances, requires more energy gain or loss to undergo a state change (from solid to liquid, liquid to gas) than to be warmed or cooled by a degree of temperature without changing state. Liquid water requires about 4.2 Joules per milliliter per degree Celsius to raise or lower its temperature. However, the Latent Heat of Fusion (Lf) of water (the energy that must be added to ice to melt it or removed from water to solidify it at the freezing point) is 334 Joules per milliliter.
Therefore, for ice to freeze the surrounding water, the ice must be cold enough that it can afford to gain enough energy to invoke this state change, without melting itself. Now, solid ice has a lower volumetric heat capacity; it only takes about 1.9 J/(mL * K) to change its temperature. So, for an ice cube, let's say 10mL in volume, to freeze 1mL of the surrounding water (at 0°C) without melting itself, the ice must be able to absorb 334J of energy without melting. That means the ice must be -16.7°C, or about 2°F.
That's well within the range of your average freezer (which in the US is normally kept around 0°F to ensure everything stays good and frozen), but that back-of-the-envelope calculation assumes the energy is gained evenly throughout the entire ice cube. This doesn't happen; it's common knowledge that ice melts from the outside in, and that's because it's a relatively poor conductor of heat compared to substances like metals, which sometimes seem to instantly liquefy when they reach their melting point. For the ice to be able to cool that kind of water volume without melting, therefore, it must be much colder; cold enough that the ice can afford to gain enough heat just in a few millimeters of its outer surface layer to freeze the water.
Regardless of this, if you have a fridge with in-door ice and water, and you fill a cup with the ice and then pour the water over it, the ice will clump; the combination of two cubes in close proximity, a small volume of already-cold liquid water in a thin layer between them, and the ice being colder than freezing, results in the ice freezing the water, joining the two cubes. This happens throughout the ice. If you go with crushed ice, which has smaller pieces but more surface area and a larger volume of frozen water to total water, the effect is even more pronounced. But, eventually, the overall thermal energy of the room adds more energy into the glass of water than the ice can absorb without melting. So, it melts.
Comment: The latent heat of vaporization (now normally referred to as the enthalpy of vaporization) and the latent heat of fusion (enthalpy of fusion) are different. The former is boiling, the latter is melting. For water, the enthalpy of vaporization (boiling) is 40.7 kJ/mol (2300 J/mL) whereas the enthalpy of fusion (melting) is 6.01 kJ/mol (334 J/mL) - but aside from the "typo", good points.
Comment: @R.M. Thanks for the comment. The edited answer fixes the "typo".
Answer: At room temperature, water is a liquid. So the ice will gradually turn into liquid.
You may ask your question in a different way:  if you add water to ice, why doesn't the ice turn into liquid?  It does, at room temperature.
If you add water to ice, at freezing temperature (Antarctica), the water turns to ice.
I think it is mostly due to the surrounding air temperature.
Comment: Well, yes and no. Ice will freeze cold water in a glass sitting on a table, as the colder ice and warmer water exchange energy to reach a rough equilibrium. But, the overall equilibrium of the larger system, at room temperature, eventually adds more energy than the ice can absorb without melting, so it does.
Comment: The question did not specify what the ambient temperature is (it said room temperature water, not system at room temperature). It might be best to first look at the question for an insulated system (no heat transfer), and then perhaps say what happens if you allow heat transfer.
Answer: Now if we have a look on values of sp heats of ice and water.
L(ice)=334 kJoule per kg
C(water)=4200 Joule per kg per degree Celsius
C(ice)=2100 Joule per kg per degree celsius
If we want 1 kg of water at 1 degree celsius to first reach zero degree Celsius and then be converted to ice the amount of heat released will be greater than 4200 joules
On the other hand,  If we want 1 kg of ice at minus one degree celsius to first reach zero degree Celsius and then be converted to water the amount of heat required will be around 2100 joules
Therefore in general if we want water to be converted to ice the ratio of ice to water should be more than 2 isto 1.
(Assuming temp of both are at same distance from 0degree celsius)


Does this look like asbestos insulation?

Question: Found some spare bits of it in the attic, was curious what it is. Fibre glass?
Comment: Looks like fiberglass to me too, but could be mineral/rock wool. Either way, not asbestos.
Comment: You wouldn't get to sleep the next day, though. Fiberglass is itchy, just with a delayed effect... ...... and all of them, the microfibers are also cancer vectors like asbestos, just not as aggressive or nearly as famous.  If you work with any of them occupationally, use PPE.
Comment: Definitely rockwool.
Comment: When it comes to fiberglass vs rock wool, you can tell the difference by feeling it.  Fiberglass is reasonably soft, but rock wool is stiff and scratchy.  You wouldn't be advised to sleep on either, but you might actually get to sleep on fiberglass, while rock wool would be poking you too much with straw-like needles of slag, so you'd never be able to relax.
Answer: No, that is fiberglass.  When it comes to asbestos insulation, it is found only in loose fill types, and in a solid board configuration.  Asbestos was never used in a batt form of insulation which is what your picture is of.
https://www.thespruce.com/how-to-identify-dangerous-asbestos-insulation-4119906
Comment: it's still not something you want to work with without protective gear.
Comment: Absolutely - gloves, glasses, mask, and wear long sleeves and legs and ideally tape the ends to your gloves and socks.  If you're working with it - but the question asked was about what it was, not how to work with it :)
Comment: https://en.wikipedia.org/wiki/Mineral_wool.
Answer: Asbestos did come in a board configuration for use in furnaces and combustion chambers. But that is not asbestos. It is probably Kaowool or a similar product
Comment: The picture is of batt insulation not board :)
Comment: Johns Manville makes a [mineral wool insulation](http://www.jm.com/en/building-insulation/residential/mineral-wool/) that also looks similar
Comment: Not kaowool - 99% it's Roxul.
Answer: The typically greenish colour and the smaller gaps between the fibres suggest to me that it's mineral wool (aka "rockwool", although that's technically a brand name) rather than fibreglass.  The two have pretty similar properties, but mineral wool is generally slightly more irritating to handle ... I'll handle fibreglass without gloves if I have to, but I won't go near mineral wool without good protective equipment because I'll be itching for days if I do.
Answer: Either fiberglass or rockwool. Take a small piece outside and apply flame to it. Fiberglass will melt, rockwood won't.
Comment: That must be a hot flame.  Common fiberglass melts at 1700 F.  Butane torches are 1400~.
Answer: Dang, that's tough. I want to say it's mineral wool but the sides are more puffed out than they should be from the factory, but that happens as soon as it rubs against something.  99.99% sure it's mineral wool. I've worked with that stuff for two house builds.  The part that tells me it's mineral wool is the stamp pattern on the face (left side in photo). That's the same stamp that is used once it's super heated (* not actual term) and compressed into a batt.  It's excellent (and itchy) stuff. I don't care who you are, it's not "fun" to work with as they market it.  Cut into it, and try installing it in the house without a mask. Guaranteed problems that evening and you will hack up black crap.  It's very good stuff, just wear proper gear.  I learned the first time around and invested in a suit and proper mask.


GameRanger interface not usable in Wine 1.6

Question: I recently moved from a Windows 7 to Ubuntu 12.04, and I play Warcraft III a lot with my friends using GameRanger. So I moved my WC3 to the Wine disk and managed to install GameRanger (after a whole day fighting with winetricks for mfc42.dll). Although some people report not being able to login, it worked perfectly for me. However, when the game and friends list shows up, I am not able to click on anything (in fact, the windows even go out of focus). I can press alt to bring up the toolbar menus, but I cant navigate with keyboard nor mouse. Any ideas how this can be fixed?
Answer: Well, my solution was simple but overkill: I copied my whole Windows installation over to wine's virtual drive, and it worked.


Is there any synchronized software update mechanism in Bitcoin-Blockchain?

Question: My question is regarding the update of Bitcoin software. Is there any mechanism for a synchronized software update in the Bitcoin network?
Answer: No there is not. Bitcoin is a protocol, and there are many different implementations of the protocol developed by many different people and groups. It would not make sense to distribute "new software" to all the different implementations.
Answer: Assuming you're talking about the specific software project Bitcoin Core, there is not, and this is very intentional. Core's developers (disclaimer: that includes myself) shouldn't have the power to force new  software onto the network.
Comment: Then how does a change in consensus rules or any of the software module is updated on all the Bitcoin nodes?
Comment: There isn't. People must choose to run new software of they want new rules.


Standard install procedure for PHP 5.3 without Suhosin?

Question: Is there a standard way to install PHP 5.3 without Suhosin?
How would doing so affect tracking of routine updates for precise?
If it's going to make life complicated now or in future then I might just leave it there.
Answer: Probably not. Suhosin is considered standard for PHP 5.3.
Using 5.3 without a hardening patch isn't recommended at all, and Suhosin is considered the de facto standard due to its binary compatibility.
Additionally, Precise is the last version running 5.3, so any version you upgrade to will have a fairly major future version of PHP. Since it sounds like you're on LTS releases, this may not be an issue for another year, but it will inevitably come into play.
If you still want to have 5.3 without Suhosin, you're very likely going to need to compile it yourself. It is possible to set it up so that apt/dpkg track dependencies (see this question for more details), but if apt sees you're running an older version of PHP than it has in the repos, it may try to update you, which will include Suhosin.
Alternatively, you could upgrade to 5.4, which has at least upstream standard repos without Suhosin. I think Ubuntu's repos have done the same and released 5.4 without Suhosin. At the very least, the Debian and Arch teams have declared Suhosin "upstream dead," so even if Ubuntu still has it, you should be able to pull straight from Debian, or possibly port the Arch one.
Comment: BTW there's Debian packager's (me) PPA with latest PHP 5.4 available for all supported Ubuntu releases.  And Ubuntu PHP 5.4 has dropped Suhosin as well, because there's no suhosin patch for PHP 5.4 at the moment of writing this comment.


Skyrim Followers

Question: Okay, this time, I want another follower besides Faendal who can teach me archery. I was wondering if it is possible to have Aela as a follower after the werewolf mission.
Answer: Werewolf "mission" (correctly called a quest) is a vague term to use, but it depends which quest in the quest line you are referring to. If you are referring to the start of the companions quest line then no. Aela only becomes a follower after completion of the entire companions quest line.
Answer: Yes, you can. Additionally you can also marry her, but that's not what you're asking.
I'm not sure what the requirements are to get her as a follower - whether you can get her straight after the first werewolf mission, or if you have to finish the entire Companions questline.
Comment: ok thx but im marrid to camilla tho
Answer: Yes, you can absolutely have Aela as a follower.
But word of advice, she isn't very good at fighting. She will not die but her life drains away very quickly in a combat thus all enemies will be focussed on you.

Skyrim Followers


Connection string works for Entity framework but fails on bulk

Question: The problem I am having is that in the Web.Config, I have a connection string which db.database is using, this works fine, I am able to retrieve data from the database no problem, however the problem I am having is when I try to use SqlBulkCopy:
using (SqlBulkCopy bulk = new SqlBulkCopy(db.Database.Connection.ConnectionString))
{
    bulk.DestinationTableName = datatable.TableName;
    bulk.WriteToServer(datatable);
}

I am using the exact same connection that the entity framework is using but it is failing and I get the error message
Login failed for user 'DatabaseName'.

I can't seem to figure out why it's failing, I Googled around and it says it's an authentication issue on the server / database side, but why would it work for db.database and not when using SqlBulkCopy?
Comment: Do you use ObjectContext or DbContext?
Answer: Please find the below it should help you:
try using a connection directly rather then entify framework.
string csDestination = "put here connection string to database";
using (SqlConnection destinationConnection = new SqlConnection(csDestination))
using (SqlBulkCopy bulk = new SqlBulkCopy(destinationConnection))
{
     bulk.DestinationTableName = datatable.TableName;
    bulk.WriteToServer(datatable);
}


For an arbitrary time signature, where do the beats go?

Question: 4/4 gets 1 and 3 as strong. 3/4 gets 1. 6/8 gets 1, and 4 is strong but less so. I don't know what 7/4 is supposed to be, but 1, 2, and 5 sounds good. 9/8 and 12/8 are really just 3 and 4 triplets, respectively, so they get 1, 4, and 7 and 1 and 7 respectively. I am also aware that beyond some number relative to the denominator (I think it's 9 for */4), you just subdivide into smaller units.
What's the general way to find where beats should be emphasized for a given time signature?
Answer: You're right with the more common ones, and 12/8 works rather like 4/4 with triplets.
Odd ones, like 5/4, usually work in twos and threes. 5/4 in 'Take Five' is 3+2. 7/4 is often 2+2+3, but if the writer wished, could be 2+3+2, or 3+2+2. Get onto something like 13/4 - I used to work with a Greek band - and it was 3+3+3+4.
So, generally speaking it's up to the writer, who may give a clue at the beginning, or beam appropriately - difficult with no quavers - but 3s and 4s (and 2s) are the order of the day.The ony general way is to listen and count. If sight-reading, look out for what could be the more emphasised notes, such as 1s, 3s and 5s of the underlying harmony. Those are often naturally emphasised in 4/4, so why shouldn't the odd ones follow suite?
Comment: And composers have enjoyed playing with the placement of beats in unusual meters for centuries, from the Renaissance Hemiola pattern to modern jazz. One of my favorite recent(ish) examples is Dave Brubeck's Blue Rondo A La Turk, which has some sections in 9/8 that jump between 2+2+2+3 and 3+3+3 in the Head.
Answer: Much depends on the composer's intent. For example 7/4 may be broken down into 4/4+3/4 (sometimes written 4+3/4) which is fairly easy to read. It could be 3/4+4/4 or 2+2+3/4 or 2+3+2/4 or the like.
In some cases, beaming is helpful. Alternating 6/8 as 3/8+3/8 and 3/4 ("America" from "West Side Story") could be shown by beaming the 6/8 measures as 3/8 by 3/8 and the others as 3/4.
There's no obvious way for things like 55/64 or the like. The composer has to give a hint (or several hints.)
Answer: 9/8 commonly gets the three pairs and a triplet treatment out here. That piece usually goes with •·•·•·•·· and then occasionally throws in a •·•·•··•· for syncopation
Technically, the time signature implies nothing about where the beats go, but there are common patterns that come with specific genres.
PS. Hoping my just-invented beat notation is readable…
Comment: @Tim's answer refers to "Take Five".  Off the same album, "Blue Rondo a la Turk" is 9/8 in 2+2+2+3.  Given your example, looks like Dave got it right!
Comment: What I'm saying is that there's no "right" for this. There are common and uncommon patterns. All are "right"
Comment: Ah, apologies, that was not the intent of the comment.  I took "there is no right way" as given. Just with your example being turkish, and seeing "Take Five" used as an example in the other answer...
Answer: As the other answers say, there is no rule that is inherent in the piece itself - the same time signature can be subdivided in different ways.
However, you can get very strong hints from the history of the piece. Before the 20th century, you will typically find uneven metrums in the folk music of countries with Turkish cultural influence. Within these countries, the metrums tend to cluster in different regions. So a folk dance in 9/8 from Southwestern Bulgaria is almost certain to be 2+2+2+3, while a folk dance in 9/8 from Northwestern Bulgaria may well be 2+3+2+2 (note, local performers are unlikely to know the formal name/division of the time signature, but they will readily recognize names for them, usually the name of a popular dance with that time signature).
In a sense, this is no different for the even metrums you mention. There is no unbreakable rule that 1 and 3 are the on-beats in a 4/4 signature, it's just that this is the common way to do it for music written in our own modern Western culture.
Answer: The standard numerators are 2, 3, and 4 for simple meters (beats subdivided into two parts) and 6, 9, and 12 for compound meters (primary beats subdivided into three parts).  For quadruple meters (four primary beats per bar, i.e., numerator of 4 or 12), the third primary beat has secondary stress in each measure.
For all other numerators, the patterns can vary, as other answers have already detailed.  But generally beats tend to be grouped into 2s and 3s.
One thing I'd add to other answers is that it's most typical for a piece to adopt a particular subdivision throughout (like 5/4 may be a 3+2 or a 2+3 and it's consistent), but there are pieces where this is not true.  Some music will explicitly indicate this in a time signature (e.g., (3+2)/5), but in many cases you just have to figure it out based on rhythmic patterns or style/genre.  I've seen several pieces where bars alternate in a 5 pattern with 3+2 one measure and 2+3 the next.  And sometimes the pattern gets altered just for a single bar somewhere, creating a sort of "syncopated" feel.  (This happens in other more standard meters too: for example, a piece in 6/8 might just throw in a single bar that feels more like 3/4 sometimes to change up the pattern.)


ERC223 and ERC827 can receive erc20 tokens and call a function immediately?

Question: As the title says, is that possible? For example on my ico contract, I accept  USDT erc20 token and when I receive each transaction, call a function for that   and send that address my tokens or eth.
Answer: With ERC20 you would use the two-step approve() and transferFrom() process. A front-end can coordinate the process such that:
Step 1: User approves a certain contract can take a certain amount of tokens.
Step 2: User invokes a function in that contract, and that contract attempts to take the tokens.
A known weakness of this approach is that it only deals with tokens that are expected and does not do anything with tokens that are simply sent to a receiving contract.
ERC223 proposes to address that with tokenFallback() functions in the receiving contract. So, nothing happens if the receiver is a wallet. If the receiver is a contract, the token contract itself will invoke tokenFallback() passing through the origin of the tokens.
This enables a receiving contract to kick off a process when tokens are received.
This sample from the github page shows how it would check for contract bytecode and then try to run tokenFallback()
  function transfer(address to, uint value, bytes data) {
        uint codeLength;
        assembly {
            codeLength := extcodesize(_to)
        }
        balances[msg.sender] = balances[msg.sender].sub(_value);
        balances[_to] = balances[_to].add(_value);
        if(codeLength>0) {
            // Require proper transaction handling.
            ERC223Receiver receiver = ERC223Receiver(_to);
            receiver.tokenFallback(msg.sender, _value, _data);
        }
    }

So, your contract might do something like this:
function tokenFallback(address sender, _value, bytes _data) public onlyTokenContract returns(bool success) {

  // process received tokens
  ...

The suggested onlyTokenContract is merely a suggestion. Intuitively, this seems like something intended for the token contract itself and probably no one else should be able to run it. You would have to code it with something like:
modifier onlyTokenContract() {
  require(msg.sender == address(ERC223token); // where ERC223 was initialized elsewhere
}

ERC827 is similar.
It is less opinionated in that it doesn't impose a named function like tokenFallback() and, instead, allows the sender to pass in bytes for an arbitrary .call() to the receiver. This can help in situations where tokenFallback() is too restrictive.
It does not implement the function calling in regular transfer() transactions. Instead, it depends on the sender using transferAndCall(). In practice, this may not accomplish the main goal and seems to imply a dependency on cooperation from exchanges and wallets that might not be there.
Usual caveats apply: Only use the code if you have studied it carefully, understand how it works and have received the comments and open issues.
Importantly, ERC223, and ERC827 do not change the character of existing tokens. So, if you want to create your own token, then you can choose the standard you want to use. For existing tokens such as USDT, the standard is already chosen. It is on you to review those token contracts, understand how they work and then determine the best design for your receiving contract. In other words, unless you create the token, you can't change the nature of tokens you receive - only how your system responds.
Hope it helps.


how to protect php page used by jquery ajax call

Question: I just finished coding my first jquery ajax call page. It calls a php page every 1 or 2 seconds and returns json data.
The page basically displays posts of the message board the user is viewing. There are multiple message boards and some users should not be able to view certain boards, however the same php page is used for the call. It pics out the message using $id that is sent by the ajax script.
My question is how would I protect the php page from being manipulated and opened directly? The user can easily change the board id by opening the file directly and changing the URL. Not to mention the other ways.
If there is no easy way, then I guess I'd have to duplicate the majority of the main page to check if the user has necessary permissions. That would mean more server load since the page is updated every second.
Answer: Ajax calls are treated by server in the same way as normal page requests. All the authentication and authorization mechanisms are called before serving the page. To make sure just log off and try to get stuff from your page using AJAX. It should not work if your page requires you to log into the site.
Answer: In ajax script you can use <code>$_SESSION</code> too - you can check if current user has privilages to specified ID - if not - just deny access.
Answer: Save the permissions in a session and check if that certain flag is present?
Answer: If an AJAX call can open the page, so can the user, you cannot rely on definitive technique to protect a page. Rest you can follow what @TheVillageIdiot has said in his answer.


How do I set up a private ethereum network?

Question: I'd like to set up a local (private) blockchain that isn't connected to the wider internet so that I can deploy some test contracts. How do I go about doing that?
Comment: Hi all - the top answers below are out of date these days (July/Aug 2017). Specifically, --dev (DevMode) is probably not what you want to use to run a private blockchain. See, e.g. https://ethereum.stackexchange.com/questions/23468/how-to-use-a-customised-data-directory-in-dev-modeprivate-blockchain/23492#23492 for more discussion on the topic.
Answer: Creating a private testnet for Ethereum is actually pretty easy. In recent versions of geth, you don't even need to create your own genesis block, or any other complicated steps (many of the online tutorials are out of date).
First, make sure you have geth installed. On OSX, you would do this by first installing Homebrew, then running:
$ brew tap ethereum/ethereum
$ brew install ethereum

For other platforms, check out the geth installation instructions.
You can test that it's working by checking the version:
$ geth version
Geth
Version: 1.3.6
Git Commit: 9e323d65b20c32ab1db40e8dde7172826e0e9c45
Protocol Versions: [63 62 61]
Network Id: 1
Go Version: go1.6
OS: darwin
GOPATH=/Users/adrian/go
GOROOT=/usr/local/Cellar/go/1.6/libexec

Now, you can start a private blockchain by running geth with the --dev option:
$ get --dev --ipcpath ~/Library/Ethereum/geth.ipc

This does the following things to make development easy (source):

Sets --vmdebug (Virtual Machine debug output)
Sets --maxpeers 0 (Networking disabled)
Sets --gasprice 0 (Make your contracts affordable)
Sets --port 0 (Listen on a random port)
Sets --shh (Whisper protocol enabled)
Sets --datadir to a temporary directory on your hard drive
Enables "dev mode", which causes geth to automatically generate a new genesis block the first time you run it.
Sets --ipcpath to the standard IPC path so other commands e.g. geth attach, works without additional parameters

Now, you can probably connect to your private network already, either by running geth --dev attach in another terminal window, or by starting up Mist Wallet. But before you can do anything, you probably want to create an account, and mine a few coins so that you can spend them.
Leave your original terminal window running, and in another window type:
$ geth --dev attach

This will give you a JavaScript console. You can run the following commands to create your first account:
> personal.newAccount('choose-a-password')
"0x48517108e6368f2b4da71816f9929e89c3e19ae5"

Now, you want to mine some coins:
> miner.start()
true

In the first window, you will see mining messages start to scroll by:
I0401 12:41:03.318046   83003 worker.go:348]   Mined block (#1 / fb68b6aa). Wait 5 blocks for confirmation
I0401 12:41:03.318486   83003 worker.go:569] commit new work on block 2 with 0 txs & 0 uncles. Took 399.006µs

Once you have about 10 blocks mined, go back to the JavaScript console, and stop it:
> miner.stop()
true

That's it! Now you have your own private testnet.
Finally, a quick shameless plug: I wrote gethdev, a simple wrapper around geth, which will simplify this process of creating your own private testnet, by automatically creating your first account, starting and stopping the mining process when there are pending transactions, and providing an environment variable to remember common arguments you always end up passing to geth. Feedback welcome!
Comment: thanks for answer! by the way, geth --dev attach won't start, if you didn't specify ipc path, so this what worked for me:
geth attach ipc://%your_temp_dev_path%/ethereum_dev_mode/geth.ipc
Comment: `geth --dev` works great, as does the gethdev project Adrian discussed.

To prevent having to use the custom ipc flag to attach to the dev server, consider running like this:

`get --dev --ipcpath ~/Library/Ethereum/geth.ipc`

This has the added benefit of allowing the Ethereum Mist wallet to work with your local ethereum testnet.
Comment: when we start mining in dev/private net what exactly is being mined? where do the blocks come from ?  In main or testnet we are connected to a global network . how is it in the case of dev? . I am just starting up on ethereum block chain . excuse for any obvious wrong questions.
Comment: Very good/detailed answer. +1
Comment: You should also add a command to show the balance after miner stop.
Comment: Noob here. I think there's a typo and the intended command is `geth --dev --ipcpath ~/Library/Ethereum/geth.ipc`. For me (Linux), this reports `IPC endpoint opened: ${HOME}/Library/Ethereum/geth.ipc` and I think requires `geth attach ipc://${HOME}/Library/Ethereum/geth.ipc`.
Answer: Some of the main steps involve specifying a networkId, and creating a genesis file (you can give your account a lot of ether!).
Rather than repeat what's been written, there are guides here and here.
Comment: This is no longer necessary. See Adrian Macneil's answer.
Answer: If you are just testing contracts I would recommend using a lightweight Ethereum node like https://github.com/trufflesuite/ganache-cli. This way getting your network set up is as simple as running:
npm install -g ganache-cli

Once it is installed, you can start the testnet with:
ganache-cli

This Ethereum Node simulator will have a few accounts which are prefilled with a bunch of ETH. Not only is using a simulator easier to setup, but boot-time and transactions are much quicker. However, it isn't a fully featured Ethereum node, so it's only good for early stage development.
I just wrote a blog post called An Introduction to Ethereum Testnets which you may find helpful. You can find it here: https://karl.tech/intro-guide-to-ethereum-testnets/
Answer: Using the scripts below (from From geth --dev exposes live net accounts. Is it safe?) will ensure that your --dev keystore is separated from your Mainnet keystore, reducing your risk of exposing your Mainnet account passwords.
Here is my Dev startup script:
#!/bin/sh

geth --datadir ~/EtherDev/data --dev --nodiscover    \
  --mine --minerthreads 1 --maxpeers 0 --verbosity 3 \
  --unlock 0 --password ~/EtherDev/etc/passwordfile  \
  --rpc console

And here is the Dev script I use to create my passwords:
#!/bin/sh

mkdir ~/EtherDev/data
geth --datadir ~/EtherDev/data           \
  --password ~/EtherDev/etc/passwordfile \
  account new

And I just use a simple password in ~/EtherDev/etc/passwordfile.
Answer: I faced some issues, while I was setting up private net using geth. Here are the steps I noted and I believe it can be helpful for you -
Note: I'm assuming you have installed geth and go on your machine.
$ mkdir pnet
$ geth --datadir pnet/ account new

# This command will prompt you to enter password, type the password and remember it.
# Once you enter the password, account will be created and account address(hash) will appear, don't miss saving it.
# Sample output - Address: {93044af5bc90b1dda0668ae3e171ce746c320d06}
# Note, multiple accounts can be created
# Note, you must append "0x" to the address in the allocate section i.e your address becomes {0x93044af5bc90b1dda0668ae3e171ce746c320d06}
$ vim genesis.json

# Sample Gensis file given below. In alloc attribute,
# Mention created account address and assign some balance as shown in sample file.
# {
#    "config": {
#        "chainId": 15,
#        "homesteadBlock": 0,
#        "eip155Block": 0,
#        "eip158Block": 0
#    },
#     "gasLimit": "0x8000000",
#     "difficulty": "0x400",
#     "alloc": {"0x93044af5bc90b1dda0668ae3e171ce746c320d06":
#                  {"balance":"200000000000000000000000"}
#             }
# }

# run below command to instantiate genesis block
$ geth --datadir pnet init genesis.json

# run following to start geth private node
$ geth --rpc --rpcport "8545" --rpcaddr "127.0.0.1" --rpccorsdomain "*" --datadir pnet/ --port "30303" --rpcapi "personal,db,eth,net,web3" --mine
# rpcaddr in above command will be the IP of the instance where you plan to run your geth node

# once geth node starts copy the geth.ipc path to attach a geth console in another terminal using below command
$ geth attach ipc://path_to_ipc_file/geth.ipc

# After opening geth console, try unlocking the first account created above, using below command
# personal.unlockAccount("hash of the account in quotes or eth.coinbase", "password in quotes", 0)

$ personal.unlockAccount('93044af5bc90b1dda0668ae3e171ce746c320d06', 'password', 0)

Now you can start using the geth private node.
Comment: what is  geth attach ipc://path_to_ipc_file/geth.ipc means ?     I curious that the path you said .
Comment: In order to attach another terminal window with your geth node you would have to use geth attach command and give the IPC file path. So here is my example you will need to change "path_to_ipc_file/geth.ipc" this to the actual ipc file path.
Comment: How do I know the path?
Comment: You can find it when you run your geth console, you will find it in logs. See the screenshot for reference(the second last line)

http://i.imgur.com/IOSjodm.png
Answer: As an additional information to the previous answers:
if your goal is to write and test contracts/Dapps you could use blockapps,  it helps you to setup easily a local private blockchain you could also look at testRpc .
Comment: Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Answer: This guy is awesome, get through all parts starting from 1 ending with 5:
https://hackernoon.com/heres-how-i-built-a-private-blockchain-network-and-you-can-too-62ca7db556c0
EDIT:
Just to summarize what is there on the link (using Mac):
First you need to download geth, the go etherum platform.

Create a folder and create a genesis file inside that folder, call it customGenesis.json, which contains your blockchain details. Make it similar to the following, just change the chain ID:
{
 "config": {
    "chainId": 2017,
    "homesteadBlock": 0,
    "eip155Block": 0,
    "eip158Block": 0
},
"alloc"      : {},
"coinbase"   : "0x0000000000000000000000000000000000000000",
"difficulty" : "0x400",
"extraData"  : "0x",
"gasLimit"   : "0x8000000",
"nonce"      : "0x0000000000000042",
"mixhash"    : "0x0000000000000000000000000000000000012345678765545432233567778987",
"parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp"  : "0x00"
}

Create another folder which will hold the node information, (folder_of_your_first_node)
Open the Terminal to create the first node using the blockchain genesis file:
geth --datadir (folder_of_your_first_node) init (folder_of_your_genesis_file)/customGenesis.json

Start the network using the first blockchain node, for the networkid select any unique number, make it big:
geth --datadir (folder_of_your_first_node) --networkid 77665533

Now the blockchain is ready and up and running, start a new Terminal window to access your node:
geth attach (folder_of_your_first_node)/geth.ipc

Now you are inside the node of the blockchain, create an account:
personal.newAccount()
Passphrase:(select a password)
Repeat passphrase: (repeat the password)
(you should see the address of your account here)

You can start mining for ethers, which you will need to deploy the contract:
miner.start(1)

Wait for some time, a minute, then stop mining:
miner.stop()

End of Article
Now I avoided what has been mentioned in the article to deploy contracts, where you can download the default Mist and start it using your private network, this will make deploying your contracts easier (using third new Terminal:
open -a /Applications/Mist.app --args --rpc  (folder_of_your_first_node)/geth.ipc

You should see your first account full of ethers :). Enjoy!
Another thing worth to mention her, after you deploy your first contract using Mist, you need to go back to your second Terminal (where you are inside the node) and start mining again, otherwise, your contact deployment transaction will not be processed:
miner.start(1)

Check the Mist, and make sure that the transaction at the bottom of the screen already processed, then you can go back and stop mining:
miner.stop()

Comment: Hi there. Link-only answers are discouraged because the link could go dead or be moved at any time, making your answer obsolete. Can you edit your answer to summarise the steps from the link?
Comment: @RichardHorrocks with my pleasure :)
Answer: I followed this documentation and had a private chain running in minutes.
http://www.ethdocs.org/en/latest/network/test-networks.html#id3
Comment: You cannot get a better description than I followed the documentation exactly as it is written.  There is no need to elaborate any further as it is explained in great detail step by step at the link provided.
Comment: Please give a better description of how you achieved it. Providing links without much context doesn't help many users.
Comment: Whilst this may theoretically answer the question, [it would be preferable to include the essential parts of the answer here](https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers/8259#8259), and provide the link for reference.
Comment: It does not "theoretically answer the question", it answers the question and provides a link to the steps I followed to get the result that this question poster is seeking.  "Preferable to include the essentials parts of the answer",  "I followed this documentation", that is the essential part of the answer.  Answers should be about quality not the quantity of the text in your answer.  If someone can achieve the exact result as me by following the documentation at the link provided why make it anymore complex with more subjective interpretation of a clear set of steps already verified to work,
Comment: Trying to give you advice that the community agrees with, if I don't others will. Take it or leave it.
Answer: Just to update with new tools this thread. There is a nice tool to help building private testnet for tests! uppeth: https://blog.ethereum.org/2017/04/14/geth-1-6-puppeth-master/

Geth 1.6 ships a new tool called puppeth, which aims to solve this particular pain point. Puppeth is a CLI wizard that aids in creating a new Ethereum network down to the genesis, bootnodes, signers, ethstats, faucet, dashboard and more, without the hassle that it would normally take to configure all these services one by one.

Here you get a live demo during Devcon3: https://www.youtube.com/watch?v=T5RcjYPTG9g&list=PLaM7G4Llrb7xnKb_SeaKZ27opvaIjlBv5&index=1
Answer: Create a folder and create a genesis file inside that folder, call it genesis.json
{
    "nonce"     : "0x0000000000000055",
    "mixHash"   : "0x0000000000000000000000000000000000000000000000000000000000000000",
    "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
    "difficulty": "0x20000",
    "gasLimit"  : "0x800000",
    "timestamp" : "0x0",
    "extraData" : "",
    "coinbase"  : "0x0000000000000000000000000000000000000000",
    "alloc"     : {},
    "config"    : {
        "chainId": 100,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    }
}

then genesis.json init commend run and genesis inti commend:
geth --datadir "D:\bolckchain\chaindata" init "c\genesis.json"

D:\bolckchain\chaindata meanies all data store this directory and c\genesis.json meanies this directory genesis file .
Then Private Network create commend run  :
geth --networkid 13 --port 30303 --datadir "D:\bolckchain\chaindata" console

Then this commend run and private network create : this network check :
$ admin

then networkid = 13 .
This port 30303 port changeable  example : 60606 this port o use
thanks try it and private network create then mist or ethereum wallet run
thanks
Answer: If you wanna setup a proof-of-authority private network, I've published a detailed step by step guide on medium.
https://medium.com/@ethervolution/setup-your-own-private-proof-of-authority-ethereum-network-with-geth-9a0a3750cda8
in a nutshell, you need at least 2 nodes for PoA clique consensus engine
create a workspace
$ mkdir devnet
$ cd devnet
devnet$ mkdir node1 node2

create 1 account per node
devnet$ geth --datadir node1/ account new
devnet$ geth --datadir node2/ account new

create a genesis file with puppeth
$ puppeth

initialize your nodes
devnet$ geth --datadir node1/ init genesis.json
devnet$ geth --datadir node2/ init genesis.json

create a bootnode
devnet$ bootnode -genkey boot.key

start your bootnode
devnet$ bootnode -nodekey boot.key -verbosity 9 -addr :30310

start node 1:
devnet$ geth --datadir node1/ --syncmode 'full' --port 30311 --rpc --rpcaddr 'localhost' --rpcport 8501 --rpcapi 'personal,db,eth,net,web3,txpool,miner' --bootnodes 'enode://email@example.com:30310' --networkid 1515 --gasprice '1' -unlock '0x87366ef81db496edd0ea2055ca605e8686eec1e6' --password node1/password.txt --mine

start node 2:
geth --datadir node2/ --syncmode 'full' --port 30312 --rpc --rpcaddr 'localhost' --rpcport 8502 --rpcapi 'personal,db,eth,net,web3,txpool,miner' --bootnodes 'enode://email@example.com:30310' --networkid 1515 --gasprice '0' --unlock '0x08a58f09194e403d02a1928a7bf78646cfc260b0' --password node2/password.txt --mine

open a javascript console to node 1:
devnet$ geth attach node1/geth.ipc

connect Mist to node 1:
devnet$ mist --rpc node1/geth.ipc

use a python or javascript web3 libraries to make JSON-RPC calls to your blockchain.
I hope this helps. Enjoy :)
Answer: I just wrote an article that goes over how to create a private ethereum blockchain using geth and go-ethereum. Let me know if you have any questions.
http://mlgblockchain.com/ethereum-private-network.html
Comment: Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Answer: You can use parity for a development network
Install Parity
bash <(curl https://get.parity.io -kL)

Start your private ethereum network
parity --chain dev

Browse at localhost:8180. There you can start developmenrt of smart contracts.
For further configuring the network
You can have a look at wiki if you want to further add any customisations to the network.


Is it me or someone else paying karma for my sins?

Question: According to Buddhism, is it me who is getting punished or rewarded in next life for my deeds in this life?
Comment: It works exactly like today, you may be paying for something you (your mindstream) did in a previous life. If you don't like it, don't do bad things
Comment: But it's not really exactly like today at all, is it. If I, today, suffer the negative consequences of an action I performed last month, then today's "I" feels like the same thing as last month's "I" (whether they *are* the same is irrelevant -- they *feel* the same). By contrast, if I, today, suffer the negative consequences of an action I performed in a past life, then the action and consequence do not even feel like the same thing. So much so that it is reasonable to ask if the "I" in the past life *is* the same thing as the current "I". I think that's what the OP is asking about.
Answer: Neither You nor Anyone else.
It is not you, because you are dying and reborning with very very short time period all the time we live in Sansara. It is not anyone else because the result taker is a anyway a  part of the series of dying and reborning cycle.
To understand this you have to understand components of a creature.
maximum number of components that a creature can have are two. They are body and mind.
minimum number of components that a creature can have is one. That is mind.(Aruupa Brahmas)
(So now at that moment you must realize that there is no soul to a creature.)
In descriptive Abhidhamma, mind is categorized to 4 components as  Vedanā,  Saṃjñā, Saṅkhāra,  Vijñāna.

This image shows the components of the creature without considering time.

Mind is continues flow of born, existence, dying of Naama (Mindlet). mindlet or Naama is the smallest sub component of the mind. 17 mindlets make a mindlet group called Ruupa.

This image shows how Naamas are born, exist and die with transmitting energy to the next Naama.

This image shows the time intervals of one Naama. Naama's born time=exist time= dying time= t1.
 Time interval between Dead Naama and Born start of Naama = t2. So at that very little time there is no visible mind. At that moment only body is exist. This is the thing called as anathma/anatta.

There can be one mindlet in the mind at once.
For a time of blink, trillions of mindlets born, exist and die (So one Naama exist less than nanoseconds).
If creature consists of body and mind combination, it must be considered both to call that as a creature. (At creatures point of view I, my point of view me).
If creature consists of only mind , it must be considered mind to call that as a creature. (At creatures point of view I, my point of view me).
When consider a wheel, engine, chase individually cannot be called as CAR. Likewise, body or mind (When both are there) individually cannot be called as me or I.
This rapid born, existance and deth of Naama can be seen in high meditation levels of vidhardhana meditation.
Now you realize there is no soul or thing that can be called as me because even before a person say me or I there are trillions of born, existence, dying of Naama.
When someone do a Karma, karma is completed in one Ruupa (consecutive 17 Naamas).
After doing the karma that Ruupa is dead. but energy transmitted to next Ruupas.
If creature made karma those Ruupas are dead at 17 Naama's time. So the creature did the karma is dead with Ruupa (But Body didn't dead so actual dead is not visible).
When Karma get punished at proper time the creature's body also can be dead.
When body dies we call it as real death.
When Karma get punished the Ruupas did the karma is dead and body also can be dead.
Karma is also get punished to Ruupas. Ruupas feels the senses according to the Karma.
When Karma is get punished, punished Ruupas are not the Ruupas that done the Karma but Those Ruupas are generated from the same stream of Naama cycle. So Load Buddha have said that the Punished person is Neither You nor Anyone else.
Comment: I haven't copied this from anywhere else my friend.  I have created all these images by my self and wrote this answer by my self. It took 5 hours to put this answer with creating images with graphing tools.
Comment: Thank you, for adding all that extra detail! If you copied that from one or sources, would you please say where you copied it from? Partly because it's polite (or perhaps 'fair use') to attribute the source, and partly so that people who are interested can read more from that source.
Comment: Yes; well done! I went looking for more background information on the technical terms you used. I think it's Wedhana = [Vedanā](http://en.wikipedia.org/wiki/Vedan%C4%81) ... Sanskara = [Saṅkhāra](http://en.wikipedia.org/wiki/Sa%E1%B9%85kh%C4%81ra) ... Wignnana = [Vijñāna](http://en.wikipedia.org/wiki/Vij%C3%B1%C4%81na) ... and Saggna = [Saṃjñā](http://en.wikipedia.org/wiki/Sa%E1%B9%83j%C3%B1%C4%81) ... i.e. these are four of [The five skandhas](http://en.wikipedia.org/wiki/Skandha#The_five_skandhas).
Comment: I'm impressed about your enthusiasm towards the Buddhism Chris. The article for five skandas will be very helpful to people who are looking for more information. Thank u so much.
Comment: :-) I have improved the article and Images with adding your valuable information.
Comment: Thank you. Also "descriptive abidhamma" is maybe the [Abhidhamma Pitaka](http://en.wikipedia.org/wiki/Abhidhamma_Pitaka) ... naama and ruupa are [Namarupa](http://en.wikipedia.org/wiki/Namarupa) (although I don't know why you say "17" ... maybe it's because "17" is what it says in the Abhidhamma Pitaka) ... and "vidhardhana meditation" is probably [vidarshana meditation](https://www.google.com/search?q=vidarshana+meditation).
Comment: Ah. It's interesting that time t2 is what you identify as anatta/anatman as described [here](http://en.wikipedia.org/wiki/Anatman_%28Hinduism%29#Buddhist_concept_of_Anatman_or_Anatta) and [here](http://en.wikipedia.org/wiki/Anatta).
Comment: Thanks for the detailed response. I will let the community decide the proper answer to the question as I am not sure.
Comment: @jorel This [Preface to the Abhidhamma](http://www.palikanon.com/english/sangaha/sangaha.htm#PREFACE) says, "That consciousness flows like a stream ... becomes extremely clear to one who understands the Abhidhamma. It must be added that an Abhidhamma student can fully comprehend the Anattā (No-soul) doctrine, the crux of Buddhism, which is important both from a philosophical and an ethical standpoint.

The advent of death, process of rebirth in various planes without anything to pass from one life to another, the evidently verifiable doctrine of Kamma and Rebirth are fully explained."
Comment: @Chris Descriptive Abhidhamma is Helping books written to describe Abhidhamma. In Sri Lanka there are books in Sinhalese as Abidharma sangrahaya, atuwa and Tiika. They are not available in any other languages.
Naama and Ruupa are two different names. But sometimes they take together to describe other terms. Then they called as NaamaRuupa.
When Naama is creating Ruupa, 17 Naama is capable of perform lest simple task in mind. That's why they are seperated and Named as Ruupa.
Answer: Yes.
And No.
Yes as it affects what you then will perceive as 'I'.[1]
No in the sense that a 'you' or 'I' never really existed. [2]
And No in the sense that you are not punished or rewarded. [3]
Answer:
'I am the owner of my actions, heir to my actions, born of my actions, related through my actions, and have my actions as my arbitrator. Whatever I do, for good or for evil, to that will I fall heir.' -- AN 5.57

Yes, according to Buddhism, it's you.
Answer: The answer comes in the Acela Sutta (although this quote comes from here). Basically we cannot say that you are paying for your sins, nor that nobody is paying for the sins, as both views take the extreme ends of annihilationism and eternalism. Instead, we should approach it from the perspective of dependent origination.

Again, when the Buddha was asked by the naked ascetic Kassapa whether
  suffering was of one's own making or of another's or both or neither,
  the Buddha replied "Do not put it like that." When asked whether there
  was no suffering or whether the Buddha neither knew nor saw it, the
  Buddha replied that there was, and that he both knew and saw it. He
  then said "Kassapa, if one asserts that 'He who makes (it) feels (it):
  being one existent from the beginning, his suffering is of his own
  making,' then one arrives at eternalism. But if one asserts that one
  makes (it), another feels (it); being one existent crushed out by
  feeling, his suffering is of another's making,' then one arrives at
  annihilationism. Instead of resorting to either extreme a Tathaagata
  teaches the Dhamma by the middle way (by dependent origination)"
  (S. XII, 17/vol. ii, 20).
Answer: so many make it seem like some moral judgment ... and it's not.
karma is NOT some cosmic sense of moral retribution. it is merely the effects of cosmic momentum amidst the gazillions of intertwined cogs and wheels and gears. you do something with negative consequences then gear 2 goes CW driving shaft 4 parallel to cog 3 which turns CCW which affects 1,204,302,750 other cogs to turn CW and 2,340,369 gears to turn CW at 45 degrees et al. THAT is karma.
Answer: The Buddha did not teach what the questioner is inferring.
The Buddha kept mundane dhamma & supramundane dhamma distinctly separate, as explained in MN 117 about the two sorts of right view.
The ideas in the question are ideas created by others at later time.
In other words, what is 'reborn' is a 'self' rather than something 'not-self' ('anatta').
'Rebirth' means the re-arising of self-view.
Therefore, what is re-born is always the idea of 'self'.
Please read the suttas, accurately. The suttas always state 'a being' ('satta') or person ('puriso') is subject to rebirth due to their own kamma.

This noble disciple reflects thus: 'I am (ahaṃ) not the only one who is the owner of one's kamma, the heir of one's kamma; who has kamma as one's
  origin, kamma as one's relative, kamma as one's resort; who will be
  the heir of whatever kamma, good or bad, that one does. All beings (sattā)
  that come and go, that pass away and undergo rebirth, are owners of
  their kamma, heirs of their kamma; all have kamma as their origin,
  kamma as their relative, kamma as their resort; all will be heirs of
  whatever kamma, good or bad, that they do.'
Upajjhatthana Sutta


Why does MS SQL Server Management Studio almost freeze up my computer while it restores?

Question: Why does MS SQL Server Management Studio almost freeze up my computer while it restores?  It makes it so when I click on the clock it takes seconds for the calendar to open.   I don't see why this should be since I have 4 gigs of ram and a dual core CPU.
Answer: I used to see this behaviour a lot too.
For me I believe it was because I was I/O bound on my system drive. I moved the .mdfs and .ldfs off my system drive onto a secondary drive and this stopped the machine freezing up during restores.
Answer: Are you restoring to a database on your computer? Perhaps you are I/O bound.
Before starting the restore fire up Task Manager and keep an eye on Memory and Proc usage. If running Vista or Windows 7 start up the Resource Monitor instead. That will easily tell you where the bottleneck is when a restore is running.
Answer: This is an educated guess but I would expect the Management Studio is trying to reconnect to your database or databases as it thinks that there has been an interruption in the connection, you could try shutting down the Management Studio and then hibernating the computer to see whether this is definitely the problem?


Can you store energy in an inductor and use it later?

Question: My company uses supercaps to power the device if power is cut. I was wondering if you could do the same thing with an inductor. If you can't, why not?
Comment: What's your definition of "later"?
Comment: More than a second.
Answer: The magnetic field which stores the energy is a function of the current through the inductor: no current, no field, no energy. You'll need an active circuit to keep that current flowing, once you cut the current the inductor will release the magnetic field's energy also as a current, and the inductor becomes a current source (whereas its dual, the capacitor is a voltage source).
Aspects of the capacitor-inductor duality in energy storage terms:
\begin{array}{ll}
\mbox{Capacitor} & \mbox{Inductor} \\
\mbox{* stores energy in electric field} & \mbox{* stores energy in magnetic field} \\
\mbox{* must be open loop (infinite resistance) } & \mbox{* must be closed loop (zero resistance)} \\
\mbox{* loses energy through parallel resistance} & \mbox{* loses energy through series resistance} \end{array}
A superconductor can sustain a magnetic field in a zero resistance current loop, however.

Unfortunately you'll always see the fumes of water vapor caused by the liquid nitrogen in pictures like this, which means temperatures below -183 °C.
Comment: Quibble; what you're seeing there is water condensing out of the air because it's been cooled sufficiently that the relative humidity is above 100%.  N2 gas iteself is invisible.
Comment: A nice analogy of an inductor looped in such a fashion would be a flywheel. And those are actually used sometimes in practice to store energy.
Answer: Problem is that energy in an inductor is due to current, and most all practical conductors have some resistance; this means that energy is continuously drained into heating the coil itself though I^2R loss. This can be overcome by using superconductors, which have no resistance at all, but the problem there is that all presently known superconductors have to be cooled to cryogenic temperatures. Also, while an ideal superconductor would remain superconducting at any arbitrary current, all know superconductors (afaik) have some upper limit to the current density they can support before the effect collapses.
Answer: \$\begin{array}{lcl}
\textbf{Capacitive Storage} & & \textbf{Inductive Storage} \\
\mbox{Must have infinite internal resistance} & | & \mbox{Must have zero internal resistance} \\
\mbox{Voltage must stay in it forever} & | & \mbox{Current must flow through it forever} \\
\mbox{You deal with voltage} & | & \mbox{You deal with current} \\
\mbox{Self discharge may take years} & | & \mbox{Self discharges in very short time} \\
\mbox{Electric field doesn't leak outside much} & | & \mbox{Magnetic field may interfere other components} \\
\mbox{Lighter} & | & \mbox{Very heavy (iron, copper, etc)} \\
\mbox{May be cheaper} & | & \mbox{Fe and Cu may be very expensive in some countries} \\
\end{array}\$
Answer: Yes, people can and do store energy in an inductor and use it later.
People have built a few superconducting magnetic energy storage units that store a megajoule of energy for a day or so at pretty high efficiency, in an inductor formed from superconducting "wire".
I've been told that several electric utilities have bought a few such units and use them to improve power quality.
Most people in the US have dozens of switching voltage converters.
Most of those switching voltage converters gradually store up energy at one voltage in an inductor or transformer, then "later" gradually draw that energy out of the inductor or transformer at a more desirable voltage, over and over, often 40,000 or a million times a second.
Many popular electronic parts suppliers allow you to sort inductors by their Q factor.
The Q factor rates how well an inductor or a capacitor stores energy.
In switching voltage regulators and other energy storage apps, bigger Q is better.
The best off-the-shelf inductors (all non-superconducting) at popular suppliers have a Q factor of 150 @ 25KHz.
Most capacitors have an order of magnitude better energy storage (higher Q) than that.
People can and do store some energy in inductors for use later.
But in nearly all energy-storage situations we use something else,
because that something else either (a) has lower up-front costs or (b) is more efficient or (c) requires less space or (d) some combination of the above.
Comment: A megajoule is not *that* much: a car battery stores about twice that. And I'm not sure about the scalability of it; people don't always realize that zero resistance doesn't mean that infinite current density should be possible. I also think "later" is meant to be further in the future than 1 microsecond :-).


(Neis) Miracle of Sarah giving birth at 90

Question: We all know how in Parshas Vayeira the miracle of Sarah giving birth @ 90 takes place. In Mitzrayim Yocheved gave birth @ 130 yet there is no mention of this. Was it not a bigger miracle? Then why is it not mentioned?
Comment: "In Mitzrayim Yocheved gave birth @ 130" Source?
Comment: IIRC correctly, Ralbag says that the only reason that Chazal made up the Midrash about Yocheved eing born on the way down to Egypt, was that the implication would be that she had Moshe at 130, and they wanted to give people _chizzuk_ in miracles...
Comment: All of the pashtanim, including Rav Saadya Gaon reject that Midrash.
Answer: Indeed, because of this Ibn Ezra (to Gen. 46:27) argues that Yocheved was not in fact born when they entered Egypt, but some time later, so that she bore Moshe at a normal age.
However, Ramban (ibid. v. 15) sharply disagrees with him (he goes so far as to use the semi-derogatory expression יוצק זהב רותח בפי החכם הזה!), and points out that since (a) Yocheved was the literal daughter of Levi (as per Num. 26:59), (b) 130 years passed from when they came to Egypt until Moshe was born, and (c) Levi was a grown man (in his forties) when they came down to Egypt - then there had to have been some kind of miracle here: either Levi fathered Yocheved, or Yocheved bore Moshe, at a very advanced age.
So he goes on to distinguish between miracles that Hashem performs (as sort of "standard operating procedure") to help righteous people or to destroy the wicked, which are not generally described explicitly in Tanach, versus those that are foretold by a prophet or an angel sent by G-d. Sarah's being able to bear children at 90 - and this, after decades of infertility - is a miracle of the latter type; Yocheved's bearing Moshe at 130 is of the former, and so it needn't be described in the Torah.
Comment: Won't work. Num. 26:59 clearly identifies Yocheved the daughter of Levi as the mother of Moshe, Aharon, and Miriam.
Comment: (a) He doesn't talk about Miriam (or Aharon - they were both definitely older than Moshe), but I guess the same logic would apply. (b) Not sure what you mean about reusing names. Do you mean that when the Torah says יוכבד... אשר ילדה אותה ללוי, it might be a later Levi, descendant of the first one? Interesting possibility, although לא בא הכתוב לסתום אלא לפרש - if that were the case there'd be no reason to mention that she was born to Levi. Plus, the fact is that we don't find any other person in Tanach with this name. (There are indeed other names that were reused, e.g., יוסף in Num. 13:7.)
Comment: Wait, so you are saying the Ramban held that Miriam was not Yocheved's first child? The Ramban held that names could not be reused before Yetzias Mitzrayim?
Giving birth after 130 seems to me to a mircale extrodinaire and worthy of mention regardless if predicted.
Guess I'm firmly in the Ibn Ezra's camp on this one :)
Comment: Not a different Levi, a different Yocheved!
Answer: When Yocheved gave birth at 130, it was an et ratzon (time of favor) for such childbearing from Hashem. Women around Yocheved were giving birth to children at a rate of 6 at a time (according to one midrash, 60 or more at a time according to others). And there's another midrash about how the women gave birth in the fields, and the children were swallowed up in the ground to protect them from the Egyptians (who then tried to plow the soil to kill them), and finally they sprouted like grass and returned home when they had grown up.
If you take all of these midrashim literally, then Moshe's birth at 130 was not unusual compared to the other miracles going on at the same time.
Comment: You have only compounded the question! Why aren't those miracles mentioned either!
Answer: A bit ago I gave a talk about this issue.  I also addressed two additional questions.  I think they are related to this issue.  Please excuse the format I don't have time right now to change it to be more of a written voice.  The following are the questions I raised:
1)  What is the function of the count found in Vayigash, 46;8?
2)  Why is it that the deceased sons of Yehudah (Er and Onan), although not counted as part of the seventy, are included in the list of people going down to Egypt and furthermore not only are they included but informs us that they died in Canaan? Is this not a list of the 70 that went down to Egypt?
3)  There is also much discussion about the final count, the Torah says that 70 people went down to Egypt…yet it only list 69 people. No problem, chazal pull one out of the hat and say that the mysterious 70th person was Yocheved, whom was in the womb.  Many Rishonim have difficulty with this, one reason is because she would then have been 130 when Moshe was born and this is a miraculous event that the Torah should have mentioned, like by Sara conceiving to Yitzchak.
Either way, why was chazal so hard pressed to choose this approach…why Yocheved?  Why didn't the Torah just say it openly?
Possible approach:
From the fact that Er and Onan were mentioned, and we were informed that they were killed,  perhaps we can deduce some things.  Er and Onan were unfortunately not on a high level, they had some issues for which they were punished, it always struck me as strange why they were killed for what they did.  Perhaps the reason they were killed was the very point of the list, Hashem saw fit that they should not be part of the group going down to Egypt.  There could not be people of lower standards, only high level individuals were part of the group.  All 70 were people of great stature.  (See Seforno in Shemot)
Perhaps the reason is that Hashem orchestrated that the children of Israel should have the highest level individuals as role models and leaders for the succeeding generations.  Hashem provided them with the greatest opportunity and the best situation for them to follow in the ways of there forefathers and not to be corrupted by the ways of the Egyptians.   Hashem was through providence ensuring that the children of Israel have a real Bechirah choice to follow in the ways of their impeccable leaders or follow in the ways of the Egyptians.  I believe this is the reason for the listing of all 70 to show the caliber of each and every one who went down.
The last question we asked regarding why chazal force the pshat of Yocheved being the 70th unmentioned member of the group, perhaps is because just like through providence hashem set into motion a way for the Children of Israel to take the high road, he also set into motion  a plan if the Children of Israel take the low road.  Yocheved was the mother of Moshe Rabeinu our leader who took the Jews out of Egypt.  Hashem set into motion already from the time of their descent how they would be redeemed if they opted to take the low road and deviate from the ways of their parents and grandparents.
I don't know that you need to take it literally that Yocheved was actually born then in order to convey the message that Hashem set into motion the patterns of providence.  It was Chazal's way of pointing to the idea.
Just some thoughts to consider.
Comment: This looks good at first run through. A couple of notes: not so much that Yocheved would be 130 when Moshe born but over 120 when Miriam (who is supposedly the first born) is born! And when you type this up nicely, clarify that Er and Onan are not included in the 70 count.
And a point which might help strengthen your idea - if Yocheved is counted as part of the 70, then Yaakov is not.
Comment: Yochved would be pointing to the possibilities of the future, Yaakov a place holder for the past.
oh, and hopefully it was a typo but Yehudas oldest are -not- counted.
Comment: Thank you for your feedback.  I stuck with Yocheved being 130 when Moshe is born because that is the way the Ibn Ezra raises the question. Thank you for the clarification regarding Er and Onan being included in the 70 count. How does the exclusion of Yaakov strengthen the point?
Answer: Torah makes a deal only from a miracles we should learn something from. There are huge number of miracles that has no any hint in Torah.
I don't know what specifically we should learn from the miracle of Sarah.
For example the Torah also doesn't tells us about the miracle of Avraam in Ur Kasdim, but Daniel book describes in details the miracle of Hannan'ya Mishael and Azar'ya, despite the fact that the miracle of Avraam was a "bigger" one. Because we shouldn't learn from the behavior of Avraam but we should do learn from the behavior of  Hannan'ya Mishael and Azar'ya
Comment: Maybe reason that the Torah does not mention them is that they did not happen...
Answer: One was predicted. One was not. The Torah only makes a big deal about predicted miracles.