PHP reading a cookie file

Question: Are there any helper libs to read a cookie file in php. I have a cookie file on my local disk and I would like a better way of reading it. I am currently just reading to file like by line and parsing out the values.
Answer: This is pretty simple if you aim to read Netscape's format (e.g. curl saves cookies in COOKIEJAR in this format).
First an example (pipes and line numbers are added here and do not occur in real file):
01 | # Netscape HTTP Cookie File
02 | # http://curl.haxx.se/rfc/cookie_spec.html
03 | # This file was generated by libcurl! Edit at your own risk.
04 |
05 | .google.com    TRUE    /   FALSE   1305843382  cookiename  the value
06 | .yahoo.com TRUE    /   FALSE   1305843382  another_cookie  it's value
07 |

As you can see:

We might have comment lines denoted with # as the first character.
We might have blank lines

And then, the beefy lines each have 7 tokens separated with a tab character (\t).
These are defined here:

domain - The domain that created AND that can read the variable.
flag - A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for domain.
path - The path within the domain that the variable is valid for.
secure - A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
expiration - The UNIX time that the variable will expire on. UNIX time is defined as the number of seconds since Jan 1, 1970 00:00:00 GMT.
name - The name of the variable.
value - The value of the variable.

So, now let's make our cookie-file parser.
// read the file
$lines = file('path/to/cookies.txt');

// var to hold output
$trows = '';

// iterate over lines
foreach($lines as $line) {

  // we only care for valid cookie def lines
  if($line[0] != '#' && substr_count($line, "\t") == 6) {

    // get tokens in an array
    $tokens = explode("\t", $line);

    // trim the tokens
    $tokens = array_map('trim', $tokens);

    // let's convert the expiration to something readable
    $tokens[4] = date('Y-m-d h:i:s', $tokens[4]);

    // we can do different things with the tokens, here we build a table row
    $trows .= '
	' . implode('	', $tokens) . '
' . PHP_EOL;

    // another option, make arrays to do things with later,
    // we'd have to define the arrays beforehand to use this
    // $domains[] = $tokens[0];
    // flags[] = $tokens[1];
    // and so on, and so forth

  }

}

// complete table and send output
// not very useful as it is almost like the original data, but then ...
echo '
'.PHP_EOL.'
'.PHP_EOL.$trows.'
'.PHP_EOL.'
';

Finally, here is a demo.
Comment: Note, that `$tokens[4]` could be `0`, if expires = session.
Comment: @OlegPopov you are more than welcome; this is all SO is about!
Answer: I could not find a code to cater for HttpOnly cookie records which is quite popular now - for example used in http://www.google.com/. An HttpOnly cookie is ONLY readable by browser and will remain hidden from all client side scripts like java scripts. You can find more details about HttpOnly cookies here.
Ignoring the format of these cookies in Netscape cookie files, will result in incorrect parsing. These records are prefixed with a "#HttpOnly_" string.
We should also "urldecode" parameter names and their values for almost all applications.
The following function is a combined and updated version of sample codes of Majid Fouladpour and Philip Norton which considers HttpOnly cookies and returns all cookies with their attributes in an array:
/**
 * Extract any cookies found from the cookie file. This function expects to get
 * a string containing the contents of the cookie file which it will then
 * attempt to extract and return any cookies found within.
 *
 * @param string $string The contents of the cookie file.
 *
 * @return array The array of cookies as extracted from the string.
 *
 */
function extractCookies($string) {

    $lines = explode(PHP_EOL, $string);

    foreach ($lines as $line) {

        $cookie = array();

        // detect httponly cookies and remove #HttpOnly prefix
        if (substr($line, 0, 10) == '#HttpOnly_') {
            $line = substr($line, 10);
            $cookie['httponly'] = true;
        } else {
            $cookie['httponly'] = false;
        }

        // we only care for valid cookie def lines
        if( strlen( $line ) > 0 && $line[0] != '#' && substr_count($line, "\t") == 6) {

            // get tokens in an array
            $tokens = explode("\t", $line);

            // trim the tokens
            $tokens = array_map('trim', $tokens);

            // Extract the data
            $cookie['domain'] = $tokens[0]; // The domain that created AND can read the variable.
            $cookie['flag'] = $tokens[1];   // A TRUE/FALSE value indicating if all machines within a given domain can access the variable.
            $cookie['path'] = $tokens[2];   // The path within the domain that the variable is valid for.
            $cookie['secure'] = $tokens[3]; // A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.

            $cookie['expiration-epoch'] = $tokens[4];  // The UNIX time that the variable will expire on.
            $cookie['name'] = urldecode($tokens[5]);   // The name of the variable.
            $cookie['value'] = urldecode($tokens[6]);  // The value of the variable.

            // Convert date to a readable format
            $cookie['expiration'] = date('Y-m-d h:i:s', $tokens[4]);

            // Record the cookie.
            $cookies[] = $cookie;
        }
    }

    return $cookies;
}

And this is a demonstration of the function.
Answer: This library allows you to manipulate (add, delete, update,...) Netscape Cookie File (eg. Cookies generated by CURL) :
https://github.com/kegi/netscape-cookie-file-handler
Simple example of reading + writing cookies:
/*Open and parse the cookie file*/

$configuration = (new Configuration())->setCookieDir('cookies/');
$cookieJar = (new CookieFileHandler($configuration))->parseFile('my_cookie_file');

/*Add (and save) a cookie*/

$cookieJar->add(
    (new Cookie())
        ->setHttpOnly(true)
        ->setPath('/foo')
        ->setSecure(true)
        ->setExpire(new DateTime('2020-02-20 20:20:02'))
        ->setName('foo')
        ->setValue('bar')
)->persist();

P.S. This project is great, But I do not know why at this moment, its stars are so low! ;-)
Comment: Thanks for promoting my lib ! ;)
Comment: @KevinGilbert Oh! What a small world. :-D
Answer: I think $_COOKIE is what your looking for.
This superglobal can be used to read cookie data... to set it you need to use setcookie() More can be found on the PHP website under $_COOKIE superglobal
Answer: I'm not sure I understand you correctly as it's normally pretty straightforward to set (using setcookie) and read a cookie in PHP from your scripts:
$value = $_COOKIE['mycookie'];

If you are looking for a way of reading a raw cookie directly from your filesystem, without going through a browser, you'll need to specify what format/browser they were written in. The values could have been serialized from a lot of different languages and the end-result of the file might differ from browser to browser.
// Edit:
More on the browser differences: for example, Mozilla has a format like that and IE something more like that.
Answer: Quick way to display:
 cat sess_qe3qq1164dnggru0m1j7fpbr23 | tr ';' '\n'

Answer: If you are using sessions in PHP, and you are in fact trying to parse the session data on disk, you can use the unserialize() function on the contents of that file.

PHP reading a cookie file


Why cant I get my sound to work on new Win7 installation?

Question: Sound wont work after installing new windows.
I got a new HD and installed windows on it. I did the same thing on another hard drive and it worked fine. cant get sound to work with same hardware other than HD.

help. Speakers are selected in playback options. Speaker cord is fine, Computer reads it as plugged in on the realtek device manager. It is the correct cord, and the speakers are getting juice.
Motherboard is sabertooth x58 (integrated HD audio). I got the realtek drivers from the sabertooth driver site.
Also I checked in bios to make sure it was enabled already.
Answer: Test: Control Panel - Hardware and Sound - Manage audio devices - Playback - Speakers are your "Default Device"


14g wire on 20amp circuits all over home

Question: A couple of years ago I bought an old house that was built in 1880. Right after moving in we had the old electrical fuse system replaced with a new circuit breaker box by an electrician. Our electric bills seem to be very high - almost twice that of other people in the area with similar houses.
I know a decent amount about electric but am no expert. I have not been able to determine what is using all of the power. I did however notice that when the new breaker box was installed, he used all 20 amp breakers even though most of the outlets in the house are wired with 14g wire. I've read that that is not safe to do, but could that also be the cause of our high electricity usage?
Comment: How did you ascertain that the wiring was awg14?
Comment: Until you can get this fixed (or it turns out you're mistaken about the wire gauge), you need to take care about running multiple high wattage appliances (with standard plugs); eg microwave, toaster oven, etc at once unless you know they're on separate circuits because your mismatched breaker/wire sizes mean that you're not protected against drawing too much current and overheating the wires damaging their insulation and/or starting a fire.
Comment: Can you upload a picture of your breaker box?
Comment: Welcome to [diy.se]. That is _definitely_ NOT SAFE and is a blatant code violation! I'd get the "electrician" back to fix his work, or, even better call the local building department and ask for an electrical inspection, _then_ call the "electrician" back in to fix his work.
Comment: There may be power loss if your wires go to very high humidity area/ even water. Why not test if there's power drain without any devices connected ?
Comment: @HotLicks The rules haven't changed - they're based on physics, which also hasn't changed.  Knob and tube can carry more current because it *is never allowed to run in insulation*.  The conductors are separated and run in free air.  The reduces the derating required for bundling cables together and stuffing them into insulated spaces where they can less efficiently shed heat.
Comment: 14g, is that short for AWG14 (2.5mm2)?
Comment: @Mast In the U.S., yes.
Comment: I will inject that the rules for the current capacity of wires have not been all that rigid over the decades.  In particular, knob-and-tube wiring tended to be rated for a higher current (for a given gauge) vs "romex".
Answer: Did the "electrician" pull a building permit prior to doing the work you commissioned?  If not, then you have more than one problem here.  If he did, presumably it was inspected and signed-off by the building inspector and perhaps you are misinterpreting what is actually installed.  No professional electrician would install 20A breakers on a 14g circuit.  Doing so is not only dangerous but illegal and unethical.
I suggest you contact this electrician and ask him to explain the work that was done.
If indeed the work was done by an unlicensed person without a permit, you should get a qualified electrician in immediately to inspect and correct the issues.  Yes that might be expensive but a fire is going to be much more expensive.
But to address your root question, NO, this would not cause excess electricity usage.  An electrician should be able to help you find the cause there as well but I'd be looking at the usual high-powered culprits, space heating, water heating, cooking.
Comment: Assuming you're not dead, then the fire damage is going to be challenged by insurance due to incorrect installation. The risk and cost in this situation is absolutely **massive**; don't play around and get it sorted out.
Comment: Also, if the "electrician" made such a basic mistake as systematically fitting the wrong breakers, you can be all but certain that the rest of the work is riddled with other problems, deficiencies, code violations, and hazards also.
Comment: Insurance would most likely pay out if there was a fire. They would go after the "electrician" for reimbursement if they paid out.
Comment: @PlatinumGoose only if this was officially done by an licensed electrician.
Comment: @Josef says Reinstate Monica that may be in other countries but in the US it's simply not true. Insurance actually covers stupidity and negligence but not intentional damage or destruction. I just reviewed my policy and there's no exclusion for me doing any work on my house. I believe this is a rumor started by the trades to discourage people from doing their own work. And if it is true then just about every electrical question on SE should be answered with "hire a licensed electrician"
Answer: The answer is no, the wire gauge will not affect the power usage. With that said any circuit that has 14 awg wire should be on a 15 amp circuit whether or not permitted.
Having 20 amp breakers on #14 wire is a recipe for a fire, especially if backstab connectors were used. They have enough problems on 15 amp circuits.
Answer: First and foremost, 14g wire on 20A breakers is absolutely a fire hazard, against code,  and the electrician should have their license revoked (assuming they carry one). No, this configuration would not cause higher electricity usage.
A high electricity bill can be caused by high power usage, obviously. If you unplug everything then does your electric meter keep ticking? Do you have a pool heater, air conditioner, electric stove, hot tub, electric water heater, etc... that requires a constant power draw?
Comment: I think that last paragraph has got to be completely wrong.  Utilities don't charge for current, they charge for energy.  There is no difference to your load on the grid whether you draw power from one or the other split-phase legs, it's all behind a transformer anyway, so the grid doesn't even see that imbalance.
Comment: Power in the US is actually 240V, but the breaker box splits this into two separate 120V circuits (breakers for 240V appliances take up two slots so they get both). If all the devices are on only one of the two 120V circuits, then you still pay for that amount of current at 240V.
Comment: Mind explaining the last paragraph? Is this kind of billing state specific? I've never heard of this.
Comment: @Akh I appreciate the clarification! My answer received one downvote so I can only assume it's because my last paragraph might have been worded in a confusing way :-)
Comment: @MonkeyZeus I've looked at it all a little more closely, and the electrical power meter that determines your charge will measure the current through the two 120V circuits separately, so off-balance should not in fact cause a difference in how you are charged for electricity.
Comment: Yeah that last paragraph is not true for anywhere I've ever lived.  It's possible some utility somewhere bills like that, but I don't think it's common.
Answer: What might be causing your high watt/hours usage may be a side effect of bad wiring or old appliances. Is the water heater, clothes drier, or washing machine from the 60's and built to last forever?
[edit] Well, utility prices have gone up. :-(
The first thing to look at when you see high electrical usage are your utilities, windows, and insulation; Old washers and driers do not work as efficiently, leaky windows and poor insulation will make heating and cooling systems run more often, if you put your electrical usage in a spreadsheet and you see a big spike with seasonal changes that's a sign that you're using your heating and cooling too much.
Also, if your old house was built in the 1880's it must have a fireplace, does that have a working flue that you keep closed when not using the fireplace? [/edit]
The 14ga. wire is a definite hazard and a sign of the installer cutting corners. When I was working as an electrician's assistant I was always against that choice and argued with owners and architects that it was unsafe. It's such a minor cost-saving it's just ridiculous. But it's just a signal that someone was cutting corners. I'd expect that there were other issues in electrical wiring that were either not addressed and possibly concealed.
Old water heaters can be maintained by cleaning the heating elements which makes them as efficient as when they were new, but the cost effectiveness is debatable.
Another sneaky fault can be a ground loop. The symptom might a mild electrical shock when you touch the sink faucet and the screw on the switch or outlet cover at the same time. Or if you are in the shower and touch the shower handle and the sink drain at the same time. This happened in one old house I worked on in 2012; The shower fan had been wired with 2 conductor lighting cord which was tied to both the ground and the negative side of the fan so when it was on there was approximately 70v on the ground all around the house. [edit] A ground fault can significantly increase the current draw of a fan but the only sign would be an annoying low current shock when touching the drain and the handle of that shower. That type of ground fault can raise the cost slightly, but it's a hazard as well. [/edit]
After 8 years as a full-time assistant electrician in the 90's my experience supports everything everyone has said about fire hazards and the 14ga. wiring. I would never put that stuff in a house. Maybe an LED lighting system in an RV.  [edit]However, that's not going to cause high watt/hours on your electrical bill. [/edit]
Recently helped a friend with a wiring issue in their basement. Circuit was blowing fuses. House was built in the early 70's here in Virginia. When they put in basement wiring with a 14ga. branch to an overhead light on the workbench, they forgot to think about the obvious. Somebody down the line will put an outlet on that circuit and plug in a dehumidifier that runs at 11-12 amps all the time. This caused a higher current on the smaller gauge and that was focused in the junction box where the 14ga. branch was tied in to power outlet. after four decades the outlet burned out and part of the copper was touching the ground. Put a fuse in, it pops (fun!). [edit] The point is, 14ga. wiring is dangerous if it is misused, but that alone doesn't cause high current draw. [/edit]
Comment: Some good information but it should be added in the comments like the other information because this doesn't actually answer the question.


Ubuntu 14.04 disconnects from the network via wifi

Question: Created a network on my desktop computer in windows 7 in mode "Ad-hoc" and tried to connect to it with laptop in ubuntu 14.04. Every time I tried to connect, identification status continues for some time and than ubuntu breaks off the connection. I had the message after disconnection from avahi-daemon about .local domain but when I managed with it nothing changed (but the message doesn't appear any more).
PS. The network in "Infrastructure" mode works just fine.
Answer: Happened to me once, fixed it by switching the "Ad-Hoc" mode into "Infrastructure" mode. Try that. :)
Edit: "Ad-Hoc" mode only works for the personal user account that created the network in first place. Upon switching to ubuntu, it becomes read as a different user, even if it's actually the same computer. So word of advice, keep it on infrastructure.


keyboard repeat is working improperly

Question: When I hold a key down, only several characters appear on the screen. In order to delete for example a sentence or few words, I need to press backspace many times.
I'd like to restore default behavior when you can hold a key and receive something like "rrrrrrrrrrrrrrrrrrrrr...", but now I have only "rrr" or in some cases "r". How can I achieve that?
I've tried solutions from here Keyboard repeat not working, but it's not working for me. I'm using ubuntu 16.04.
UPDATED: when I press Alt+F1 I can see that a new signal ^@ appears every second without any actions from me. I think that can cause the problem because it interrupts my keyboard holding. But I don't know who is sending that and why? Even when I unplug keyboard and mouse that signal is still appearing.
Comment: See: https://askubuntu.com/questions/995819/touchpad-gestures-and-holding-keys-does-not-work/995948#995948 the portion to remove `peaq_wmi` driver.
Answer: disabling peaq_wmi has helped me, you can find out how to do it here Touchpad gestures and holding keys does not work

keyboard repeat is working improperly


Why did no one attack the Geth after the events of Mass Effect?

Question: In Mass Effect 2 you learn that the Council still believes the Geth build Sovereign. So why did the Council (or anyone else) never tried to destroy a race supposedly capable of building a ship that bested the Ascension?
Answer: They did.
At the very beginning of Mass Effect 2, Shepard is actively searching for geth holdouts.  According to Anderson, by the time the game properly begins, the geth are no longer appearing regularly, and conflict between the geth and Council-aligned forces has become quite rare.  The Council presumably interpreted this as a de facto victory.
So the question is, why didn't they send a whole fleet after the geth right away?  Because sending a fleet into the Perseus Veil would almost surely result in war with the Terminus systems.  This is specifically discussed during the events of Mass Effect; Udina demands exactly this response and gets shot down (in favor of making Shepard a Spectre, so he arguably got the better end of the deal anyway).
After Mass Effect, the Citadel Defense Force is greatly weakened, possibly including the loss of the Destiny Ascension.  Starting two simultaneous wars at that point is simply unsustainable.
Answer:
So why did the Council (or anyone else) never tried to destroy a race supposedly capable of building a ship that bested the Ascension?

Because they believed the Geth built a ship that bested the Ascension, though that is just rumor. They also have little to no idea of how strong the Geth navy is, where their bases are, or if it really was the Geth. Most of all, the Geth in ME 1 Did not attack anyone except the Quarians. The Council and the intergalactic society at large still believed that the Geth were the Quarians problem and burden. Any remaining Geth in the Terminus systems after Sovereign was defeated by the FULL Systems Armada.
Mainly the Geth kept to behind a spacial divide, the Perseus Veil. Anyone that ventured in were overwhelmingly eradicated by the Geth, to keep themselves hidden. From the Codex:

The Veil's total opacity prevents Council intelligence from surveying geth activity. Theoretically, the geth could be preparing a devastating attack against which the Council could be defenseless, or the geth could have died out, so that the defense budget against them could be gaining the Alliance nothing but economic ruination.

Aside from that, the Council in every Mass Effect is full of morons masquerading as politicians. Not only are they slow to act, They are wrong at every turn, as demonstrated by your Shepard. In ME2, they (either the Council you let live, or the ones that took over after you let them die) believe the threat is gone, even though Shepard proves them wrong again in the story. After Sovereign's destruction, most of it was destroyed, and provided little evidence of Reaper existence.
In short, the Council is cheap, afraid, slow and short sighted.


What are some good Chinese short books/novels for beginners?

Question: Something a young Chinese kid would read (5-10 years old).
Answer: Here's one starting point:
我的第一本日记:二年级的美羊羊
I think it's part of a series of similar books called "我的第一本日记".
It's a schoolgirl's diary but not a real diary, I think an adult actually wrote it. It's got pinyin printed above the 汉字.
I read it myself; didn't understand everything but I still found it to be a rewarding read. Makes a nice change from all the boring textbook material. It's probably suitable for Chinese kids 8 years old or upwards.
I admit this one is probably more for intermediate students than beginners, but perhaps there are others in this series that are easier.
Answer:
I recommend some suitable story books for your children, it also can try to figure out how Chinese characters work and Chinese structures from very simple sentences, check this link, you will find a list of Chinese story books for whatever your need is!
http://www.hanbridgemandarin.com/article/kids-teenagers-chinese-learning-tips/best-chinese-story-books-for-children/

A Magic Paint Brush 神笔马良 (shén bǐ mǎ liánɡ)
The Water Dragon 雨龙 (yǔ lónɡ)
The Phoenix and the Hundred Birds 百鸟朝凤 (bǎi niǎo cháo fènɡ)
........

You kids will read Chinese story books better with a professional teacher's guidance.
Answer: For ages 8-10, I recommend 康軒(Brand) 國小學習(For Elementary level) 自修國語 (Self-study) level 1-3. These are books easily purchasable in Taiwan and are in traditional characters. It is important for ages 5-10 to read books that aid in pronouncing characters, whether it is pinyin or ㄅㄆㄇ (bo po mo).
It's pretty much the same teaching material as what they teach in school.
Here is a link for the picture http://www.pcstore.com.tw/ibookhouse/M10148138.htm
People have different opinions on textbooks as a "reading material", but I personally think they last longer, has more stories, and provide a better value in the long run.


What is cool-down time in Alibaba Cloud Auto Scaling?

Question: I am using Auto scaling on my Alibaba Cloud Elastic Compute Service Instances. I am not aware of what the cool-down time is and the implications?
Answer: I had a quick check of the cool-down time documentation  and it appears to refer to the time in which auto scaling will not occur after a previous auto scaling event has completed.
Answer: Cool-down time refers to a period during which Auto Scaling cannot execute any new scaling activity after another scaling activity is executed successfully in a scaling group.

During cool-down time, the scaling activity requests from CloudMonitor alarm tasks are rejected. Other tasks, such as manually executed scaling rules and scheduled tasks, can immediately trigger scaling activities without waiting for the cool-down time to expire.
During cool-down time, only the corresponding scaling group is locked. Scaling activities set for other scaling groups can be executed.

When the cool-down time specified by the scaling rule and the default cool-down time for the scaling group overlap, the former takes precedence over the latter.
When more than one instance is added to or removed from a scaling group, the cool-down time starts after the last instance is added to or removed from the scaling group.
As long as a scaling activity adds or removes one or more ECS instances, the cool-down time begins when the last ECS instance is added or removed.
If a scaling activity does not successfully add or remove any ECS instances, the cool-down time will not start.

After a scaling group is re-enabled after being disabled, the cool-down time is no longer in effect. For example, if a scaling activity is completed at 12:00 PM and the cool-down time is 15 minutes, the scaling group is then disabled and re-enabled, and the cool-down time is no longer in effect. If a request for triggering a scaling activity is sent at 12:03 PM from the CloudMonitor, the requested scaling activity is executed immediately.

For More Details you can visit AlibabaCloud Official Link


Detection of an optical noise with a photodetector, noise-equivalent power (NEP)

Question: I am trying to find the minimum power that can be detected by a photodetector for which I know its noise-equivalent power (NEP).
The standard formulas are:
$$\mathrm{SNR} = \frac{\langle i_s^2(t)\rangle}{\langle i_\mathrm{th}^2\rangle},$$
where $\langle i_s^2(t)\rangle$ is the mean-square signal current and $\langle i_\mathrm{th}^2\rangle$ is the mean-square current due to the photodetector's thermal noise, which is the dominant noise at low light intensity. We can express the thermal noise:
$$\langle i_\mathrm{th}^2\rangle = \tilde{\rho}_{\mathrm{pd}}^2\cdot B \cdot \left(\mathrm{NEP}\right)^2,$$
where $\tilde{\rho}_{\mathrm{pd}}$ is the photodetector responsivity (in units A/W), $\mathrm{NEP}$ is the photodetector's noise equivalent power and $B$ is the detection bandwidth.
So far, so good. My problem comes with $\langle i_s^2(t)\rangle$. I now consider the detection of an optical signal that is the noise coming from an erbium-doped amplifier (EDFA), having a certain optical power spectral density $S$ (expressed in W/Hz). Let's consider $S$ independent of frequency to simplify. I want to know how much I can attenuate this optical signal(that is actually noise) before I am no longer able to detect it with my detector (SNR <1). I am allowed any bandwidth I want at detection. I ignore here the effect of photons(shot noise). According to the formula for the SNR, the smaller the bandwidth $B$, the higher the SNR, so in principle for any input power, I can always reduce sufficiently my bandwidth to detect the signal.
But if we reduce the bandwidth, intuitively I think that we will filter the electrical power spectral density and decrease $\langle i_s^2(t)\rangle$ as well. So it looks that the bandwidth will have no effect. This is my intuition, is it correct? and if yes, how to compute $\langle i_s^2(t)\rangle$ in function of the bandwidth ?
EDIT: According to "The Photon", I am right and $\langle i_s^2(t)\rangle$ is proportional to the bandwidth. Then I have an additional, related question: I detect such a signal with an optical spectrum analyzer (OSA) and I have a choice of sensitivity levels (normal, high-sens1, high-sens2,...). I am guessing that these higher sensitivities decrease the detection bandwidth (e.g. by averaging). Thus, when I detect my EDFA noise with the OSA, I would expect that when I choose a higher sensitivity, both the signal and the noise should go down. However, when I do it, only the noise goes down but the signal remains at the same level (I keep the resolution bandwidth at the same value). How is that possible?
Answer:
According to the formula for the SNR, the smaller the bandwidth $B$, the higher the SNR, so in principle for any input power, I can always reduce sufficiently my bandwidth to detect the signal.

This is true if changing the bandwidth reduces $\langle i_{th}^2(t)\rangle$ more than it reduces $\langle i_s^2(t)\rangle$. This isn't an uncommon scenario in communications systems, or if you want to detect a optical source modulated with a single sinusoidal tone.
But you are trying to detect a white noise source (because you assumed $S$ is independent of frequency).
In this case when you reduce your receiver bandwidth, you will reduce your "signal" by just as much as you reduce your receiver's noise.

But if we reduce the bandwidth, intuitively I think that we will filter the electrical power spectral density and decrease $\langle i_s^2(t)\rangle$ as well. So it looks that the bandwidth will have no effect.

Agreed.

how to compute $\langle i_s^2(t)\rangle$ in function of the bandwidth ?

Because you have a white noise source, $\langle i_s^2(t)\rangle$ is proportional to bandwidth.


Store user passwords in database using Java Application

Question: I want to store user's password details in Database. My project is in Java. I want to know the best way of storing passwords and other important information like user data.
Comment: Use this http://www.mindrot.org/projects/jBCrypt/
Comment: Thanks a lot for the solution. But I want the solution which is well defined standardized API. like Apache etc., please provide me API for that standard, on which I can trust as per industry standards
Comment: Asking for ***"the best way of storing passwords"*** is asking for pretty subjective feedback and may quickly render the whole thing off-topic. Not only due to that, I would advise you to add a bit more information to your question, describing the exact threat model you are expecting, what system, etc. We don't even know if you use a database or flatfile storage, or if you're using any kind of networking in your Java project. Without such information, all answers will be pretty broad as they will have to guess/assume such important information, and can't really cover your individual situation.
Comment: "Industry Standards" when it comes to password storage are complete crap, essentially a single iteration hash with no salt. The "best" option is currently SRP6a with H = scrypt, the easiest "standard" option is PKBF2-SHA256. Either one may be bad/excellent based on your environment and requirements, and may require explicit parameter choices.
Comment: @RichieFrame PKBF2-SHA256 is a bit tricky as it is not always supported in frameworks, PKBF2-SHA1 is only slightly less safe and output less bits (per "block") and is normally supported. So it could be a better choice, but it depends on the application...
Answer: A lot depends on your threat model, your system setup, etc. Do you require mutual authentication? Are connections secured with SSL or a similar protocol?
For passwords scrypt or bcrypt would be the way to go. They are better than just a simple salt + password setup. It has been recommended by someone worth trusting (our very own @ThomasPornin) that bcrypt might be a better choice right now. If you do require mutual authentication, using SRP (and simply storing the authenticator in a locked down database) would be a very good option.
For storing other user information, it really depends on your requirements (and even laws in your country of residence). The US has laws for storing credit card numbers, health care related information, etc. Do you require that the data be kept confidential even if someone steals the disk? If so, full disk encryption would be one solution. If you only require that no unauthorized entity can read the information, then locking down your database with good access control policies would probably be sufficient.


What is the max frequency of sound in a given medium?

Question: When talking about acoustic waves, medium continuity (pressure, density) is implicit. But can the wavelength of an acoustic wave be as small as intermolecular separation? For example, can ~10 THz sound waves travel in water?
Comment: Yes, but they dissipate to heat in microns.
Comment: There are limits for the minimum wavelength. These are related to the spacing between molecules, as you guessed. However, the maximum frequency is not necessarily related to this minimum frequency by $ f=c/\lambda $. At very high frequencies the relationship may become non-linear. Regarding terahertz ultrasound, it is at the fore-front of research in the medical diagnostics by ultrasound. As people try to use it for medical diagnostics I suppose it propagates through water at least for a little bit.
Comment: I would guess the limit would be set by the number of  molecules for a given volume of space.   Using the experiment of a bell in a vacuum jar, one can determine the minimum number of molecules and their mean distance separation.  If there aren't "enough" molecules, the frequency of the sound does not matter.  If we are talking about "solids" and assuming that the sound energy does not break the molecular bonds,  it should pass to the end of the solid, but possibly attenuated.
Comment: "Inversely" Related:  [http://physics.stackexchange.com/q/121451/59023](http://physics.stackexchange.com/q/121451/59023) and [http://physics.stackexchange.com/q/192996/59023](http://physics.stackexchange.com/q/192996/59023).
Answer: I do not know how to answer your question directly. What happens at high (enough) frequencies is that the continuum model is not valid anymore. So, we can probably estimate that the maximum frequency is related to the minimum wavelength, that, is
$$\lambda_\min >> a$$
where $a$ is a characteristic scale at the micro-scale. Thus, when these two scales are far apart, we can trust the continuum model.
Below, you can see the derivation of the dispersion curves for a monoatomic crystal assuming that the interaction is with first neighbors and is mediated by linear springs. According to this model, there is a maximum limit for frequencies propagated through this material when the two length-scales are alike.
Example: Simple mass-spring lattice
Let us consider the system depicted in the following schematic

Simple mass-spring lattice.

The force in the plane $s$ cause by the displacement of the plane $s+p$ is proportional to the difference $u_{s+p}-u_s$ of the displacements. We will consider only nearest-neighbor interactions, so $p=\pm 1$. The total force on $s$ comes from planes $s=\pm 1$:
\begin{equation}
F_s = c(u_{s+1}-u_s)+ c(u_{s-1}-u_s).
\end{equation}
The constant $c$ is the stiffness between nearest-neighbor planes and will differ for longitudinal and transverse waves.
The equation of motion of the plane $s$ is
$$ m  \ddot{u} = c(u_{s+1} + u_{s-1} -2 u_s), $$
assuming harmonic time dependence $\exp(-i\omega t)$
\begin{equation}
-m\omega^2 u_s = c(u_{s+1} + u_{s-1} - 2u_s) \enspace .
\tag{1}
\end{equation}
Using the Bloch theorem
$$u_{s\pm 1} = u_s e^{\pm i ka}. $$
So (1)  is now
$$ -m \omega^2 u_s = c (u_s \exp(ika) + u_s \exp(-ika) - 2u_s) $$
and canceling $u_s$ from both sides, we have
$$ \omega^2 m = -c[ \exp(ika) + \exp(-ika) - 2 ] \enspace .$$
Using the identity $2\cos ka = \exp(ika) + \exp(-ika)$, and taking $\Omega^2 = \omega^2/\omega_0^2 = \omega^2 m/c$, we have the dispersion relation
\begin{equation}
\Omega^2 = 2 (1-\cos ka) \enspace .
\tag{2}
\end{equation}
The boundary of the first Brillouin zone lies at $k=\pm \pi/a$. We show from (2) that the slope of $\Omega$ versus $ka$ is zero at the zone boundary
$$\frac{d\Omega^2}{d\, ka} = 2\sin ka=0$$
at $ka=\pm \pi$, $\sin ka = 0$.
By a trigonometric identity (2) may be written as
\begin{equation}
\Omega^2 = 4 \sin^2 \frac{1}{2}ka, \qquad \Omega = 2\left\vert \sin \frac{1}{2} ka\right\vert \enspace .
\end{equation}

Plot of $\Omega$ versus $ka$. The region of $ka<<1$ or $\lambda/a>>1$ corresponds to the continuum approximation; where $\Omega$ is directly proportional to $ka$ (and is enclosed between the dashed lines). The First Brillouin Zone is placed between $-1$ and $1$.
Comment: So what is your conclusion? How is this related to the an answer to the OP question?
Comment: @nasu, that you can't have a wave that is shorter than the intramolecular distance
Comment: Is this conclusion a result or your calculations? Or it's an assumption you use?
Comment: @nasu, a result.


Is TM4C123 similar to Arduino?

Question: I'm currently studying embedded systems on eDx.
https://courses.edx.org/courses/UTAustinX/UT.6.01x/1T2014/info (must login to see)
http://users.ece.utexas.edu/~valvano/edX/index.html (don't need to login)
and I found out that TM4C123 is quite similar to Arduino.
but I haven't worked TM4C123 yet.(I ordered it and I'm waiting for it)
 I don't know much about it.
and it's not that popular as Arduino I guess.
so If anyone has used Tm4C123, please give me some information compared to Arduino.
Comment: It's a micro controller, just like an Arduino. But it's more powerful than an Arduino. 32-bit instead of 8-bit architecture, faster clock-speed, more flash memory, more s-ram, usb-support. You just don't get the ton's of libraries and tutorials that are available for arduino.
Comment: @Gerben: Seen the Due yet?
Comment: This link does not show anything about this course or requires registration, this is not acceptable. Rather try to copy part of the course description to your question so that we know what it is about.
Comment: @jfpoilpret I'm sorry. I've just added the link. thanks :)
Comment: Arduino'like IDE for Launchpad http://energia.nu/
Answer: The Tiva C LaunchPad is comparable to the Arduino Due in power and capabilities, but is incompatible with the stock Arduino ecosystem. It uses "BoosterPacks" rather than Shields, and Code Composer Studio (or other [some non-gratis] tools) instead of the Arduino IDE and libraries.
The Energia IDE is a port of the Arduino IDE and significantly simplifies configuration and programming Tiva C launchpads.
Beware of odd quirks with the Tiva C Launchpad board, such as the 0-ohm shunts that must be removed if you want all pins to be completely independent.
Comment: But if you're looking to jump from an AVR-based Arduino then I recommend the MSP430-based LaunchPads instead.
Comment: Actually, as the Tiva C has an ARM Cortex-M4 CPU it is likely that free toolchains can be used and an Arduino port seems possible.  But yes, it is quite different hardware and *from the manufacturer* a quite different environment.
Comment: @ChrisStratton: Corrected.
Answer: I have completed the edX course, and the TM4C123 is significantly different to the Arduino from a programming perspective. Each family of microcontrollers have (on the surface) a fair amount in common - GPIO pins, an ADC or two, timers etc. However the way these work internally are very different - different registers, different process for using them, different gotchas to look out for, etc. If you're looking at tackling a new MCU family, be prepared to effectively learn a new "language".
Incidentally, the Launchpads from Texas Instruments have a processing-based language similar to the Arduino - called Energia - which should work on your TM4C123.
Enjoy the course, I did.
Comment: Thank you for the information.
I have a question.
Do you think TM4C123 will be more popular or it's just for embedded students or hobbyists??
Comment: @StarbuckSb: With all due respect to TI, I honestly don't think they can make something that can displace the Arduino any time soon. Which is fine, they don't have to; their products are excellent regardless.

Is TM4C123 similar to Arduino?


How to recover data from unreadable hard drive?

Question: I have an 80GB Fujitsu 2.5" hard drive that died about a day ago and had nothing backed up. Is it possible to retrieve data off of it somehow.
Comment: "Died" is somewhat vague, it could simply be a corruption issue that is preventing the drive from mounting or it might be a physical issue. Can you elaborate, such as: does Disk Utility list the drive when attached? Is it greyed out? Have you tried any recovery software yet?
Comment: It the hard drive a hard drive in the classic sense or a SSD?
Answer: SSDs don't come in an 80GB size (that I've seen -- usually multiples of 32GB). It may be possible depending on why the drive dies. If its a mechanical failure, then you could take the drive to a specialty computer repair shop (try local before the big stores), and they should be able to help you with diagnosing the actual issue. Since the data is stored magnetically, (if the drive data is not corrupt) you can retrieve the data but you may have to remove the platters and put into a new HD unit with working mechanics... this might cost quite a bit of money -- you'd need a clean room to be safe.
Bottom-line, the data is retrievable (most likely) but the cost may prevent you from getting it back.
Answer: If your HD still has some life you could try a few tricks:

Some people have had success with hard drives that still spin but won't mount by cooling them down with aerosol coolant or refrigeration (in a completely dry rice or silica gel filled container) and then plugging back in and if they mount, quickly creating a virtual image of the drive.
Another trick is to replace the hard drive's printed circuit board with the one from a working identical drive and quickly create an image. Apple users have long used Disk Warrior to fix non-mounting drives -- in fact, if you can get a hard drive to mount long enough to create a virtual copy Disk Warrior will repair the image itself.
Finally, as the poster above mentioned, there are data recovery companies that will recover the data pretty much no matter what if the platters are intact but they are shockingly expensive.

You might consider all the common data recovery programs or dd_rescue. Try Disk warrior first and if none work, try mounting the disk again and again in Disk Utility -- sometimes it will suddenly come to life for a little while.
Otherwise try my first suggestions and if absolutely nothing works and you are ready to write the whole thing off and about to throw it away whack it two or three times laterally as hard as you would smack a bee that stuck you but no harder.
If that doesn't work send it off to professionals or if you are incredibly brave and very poor, get an identical drive and take both apart, replace the platters and immediately create a disc image because that is about how long it will continue working. It IS possible to do so and mount the disc without a clean room, it is just very very difficult and not likely to work due to contamination, the massive power of the magnets inside hard drives touching the platters, etc. Best of luck, we've all been there.
Answer: With the software DataRescue I have been able to recover data from an external hard drive but the folder structure was not recovered.
Answer: I resurrected most of my died external harddrives by changing the enclosure. Usually the problem is in the bridge between HD and USB.
Sometimes, I needed to rebuild the partition table with testdisk, or with tools present on a live DVD of Ubuntu (working with an OS other than OS X may help bypass OS specific features that prevent Diskutil from repairing disks).


Electric power for current density

Question: The electric power produced by a current $I\in\mathbb{R}^+$ and a voltage $V\in\mathbb{R}^+$ is
$$
P = IV.
$$
Now the current is given as an (alternating) current density $J(\mathbf{x},t)=\Im(e^{i\omega t} j(\mathbf{x}))$, $j:\Omega\to\mathbb{C}$, across the cross-section $\Omega\subset\mathbb{R}^2$ of a conductor. What is the generalization of the power in this case?
Comment: You've given us a nicely generalized description of the current, which is the number of electrons (let's say) flowing past a point in a certain direction per second.  Now you need to tell us how much energy each one is gaining or losing.  That is, you need to tell us the analog of the voltage.  And presumably that will just be the energy difference from one point in the conductor to another.  So you'll basically get back to $P=IV$.
Comment: Are you a mathematician, or math student, by any chance? A physicist probably wouldn't specify that $I\in\mathbb{R}^+$. Not that there's anything wrong with that, it's just a little unusual when talking about basic E&M.
Answer: In sinusoidal steady-state analysis, both voltage and current are represented by complex numbers $V$ and $I$, known in the trade as phasors:
\begin{gather}
v(t) = Re(Ve^{j \omega t}) \quad V=V_m e^{j \theta_v}
\\
  i(t) = Re(I e^{j \omega t}) \quad I= I_m e^{j \theta_i}
\end{gather}
Here $V_m, I_m , \theta_v, \theta_i $ are all real, and I'm using $j$ for the imaginary unit to avoid confusion with current $i$ (again common EE-speak).
Then the complex power $P$ is defined as:
$$ P = \frac{1}{2} V I^* $$
(with * indicating the complex conjugate).
With this definition, if you go through the math of multiplying the two time-domain waveforms to get the instantaneous power $p(t)=v(t)i(t)$, you find that the average power $P_{av}$ (the power averaged over a cycle) is real and given by
$$ P_{av} = Re (P) = Re\left(\frac{1}{2} V I^*\right) $$

Updates in response to comments:
Other measures of power (the names are standard but not the symbols, sorry):
Apparent power $P_{app}$ is what you get if you measure the root-mean-square voltage and current separately and multiply them:
$$P_{app} = \frac{V_m}{\sqrt{2}}\frac{I_m}{\sqrt{2}} = \frac{1}{2} V_m I_m =\frac{1}{2} |VI|=|P|$$
Obviously, $P_{app} \ge P_{av}$.
Reactive power $P_r$ is the third leg of the triangle formed by $P$ and $P_{av}$:
$$P_r = Im(P)$$
In power transmission lines, reactive power is undesirable because the current required to support it creates resistive losses in the line without contributing to the average power delivered.  (It's up to the load to minimize the reactive elements that draw reactive current.)
Finally: Reference directions must be chosen for both the voltage and current.  In principle these can be chosen independently.  However, it is most common to choose associated reference directions:  if $v(t)$ is the voltage across a circuit branch, measured from a "+" terminal to a "-" terminal, and $i(t)$ the current through the branch, then the reference directions are associated if a positive current enters the branch at the "+" terminal and leaves at the "-" terminal.  Then $v(t)i(t)$ is the power delivered to the branch at time $t$.
Note that associated reference directions mesh nicely with element constitutive relations, like Ohm's law for a resistor: $v_R=i_R R$; if non-associated directions were chosen instead, we would need branch current $i=-i_R$ (or an equivalent inversion of the voltages).
Comment: In principle, there's nothing that keeps $P_{\text{av}}$ from being negative here. Could you add a word about how to interpret this?
Comment: I browsed through https://en.wikipedia.org/wiki/AC_power and found that there are different notions of power for AC systems. Am I right when saying that $1/2 V I^*$ is the _complex power_, $Re(1/2 V I^*)$ the real power, and $|1/2 V I^*|$ the apparent power?
Comment: Yes.  I've added to my answer...
Answer: I was looking for an answer to the same question in general, and what I found might be relevant here. If we have the current within the volume of a conductor as proposed in the question, then we can find the power (both real and imaginary reactive powers) in two ways; Using volume integral of terms that go as current squared, or surface integrals of the Poynting vector. The full details can be found in the EM bible for physicists (Jackson's Classical Electrodynamics, 3rd edition ch. 6.9, pages 264 --267), however the useful formulas are never stated clearly and separately as far as I can tell. The average power loss (real Ohmic losses) is given in general by:
$P_{av}=\frac{1}{2}\int\limits_V \mathbf{j}^{*}\cdot \mathbf{E}\; d^3x$.
Inside a nice linear conductor, we can write $\mathbf{E}=\mathbf{j}/\sigma$. Then we can simplify the Ohmic losses even further:
$$P_{av}=\frac{1}{2}\frac{1}{\sigma}\int\limits_V |\mathbf{j}|^2\; d^3x$$
The reactive power is much more subtle. If we call the reactive power $Q$ to follow the electrical engineering convention, then $Q=\frac{\omega}{2}\int\limits_V \left(\mathbf{E}\cdot\mathbf{D}^{*}-\mathbf{B}\cdot\mathbf{H}^{*} \right) \; d^3x$. Again, in a typical case of a well behaved linear conductor like Aluminum for example, the first term $\mathbf{E}\cdot\mathbf{D}^{*}$ is negligible compared to the second one. In other words, the energy stored in the magnetic field dominates the reactive power. Also we have $\mathbf{B}=\mu \mathbf{H}$, so we get
$$Q\approx\frac{-\omega}{2\mu}\int\limits_V |\mathbf{B}|^2 \; d^3x$$
Therefore, you will need to go back to Maxwell's equations to find $\mathbf{B}$ within the conductor from $\mathbf{j}$ (e.g. in low frequency situations $\mathbf{j}=\nabla\times \mathbf{H}$).
The same results can be obtained using the complex Poynting vector which is defined as:
$$ \mathbf{S}=\frac{1}{2}\left( \mathbf{E}\times \mathbf{H}^{*} \right) $$
to find the total complex power, we can use:
$$ P_{av}+i\,Q=\oint\limits_S \mathbf{S}\cdot \mathbf{n}\, da$$
where we integrate over the surface of the conductor. The tricky part again is to write the electric and magnetic fields in terms of the current density, in order to find the Poynting vector in terms of the current density. The advantage here is that since the Poynting vector is complex, the surface integral will give us the real and imaginary parts of power at the same time.

Electric power for current density


Finite State Machine Minimization

Question:
I can't understand how to eliminate the states.
I draw this automa and after I create a table of the states (I must minimize it now and after create a minimal table of the states) Is someone who can explain it to me? This is an final state machine (original, not minimizated). In the Paul and Unger diagram I eliminate the equivalent state (are the states that produce the same output). But I see that I done it uncorrectly and I don't know how to proceed.
I think that my problem is in process to find the equivalent states.
Comment: There is a step-by-step algorithm. A very simple one. And since you are asking, it is in your textbook.
Comment: @EugeneSh. yes. And using it I'm going to eraise all the states, so for me this automa it's already minimal. But it's not so. So I'm asking here
Comment: Convert alpha to binary (hex is 0~F)
Comment: @TonyEErocketscientist I never do this kind of conversion. I must to minimize the Paull and Unger diagram and after create a new table of the states. The new table of the states must be minimale, and there I put an alpha state. Alpha state include all equivalets states. My problem is with the minimization, so I can't delete the equivalet states from the diagram. If I can't do this, so I can't do a minimal table of the states.
Comment: Then define present & Next states only in table not previous states with same X. Use 0,1 as table entry for next state
Answer: Welcome to EE.SE! This appears to be a homework question. As such, you need to show us your work so far, and explain which part of the question you're having trouble with. For future reference: Homework questions on EE.SE enjoy/suffer a special treatment. We don't provide complete answers, we only provide hints or Socratic questions, and only when you have demonstrated sufficient effort of your own. Otherwise, we would be doing you a disservice, and getting swamped by homework questions at the same time. See also here.

To minimize a state diagram, you look for states that do the same thing (both next state and outputs) for a given input.
In your state transition table on the left, that means that you are looking for identical rows in the table.
You need to be methodical — it may not be immediately obvious, but states B and F are identical, as are states E and H.
I hope this is enough information to allow you to proceed with the solution.

Note that in your state diagram on the right, you're missing an edge from H to G that's in the table.
Comment: Yess at the end I made it. I do not delet the not equivalent states, but equivalent yes. And in every couple of states I wrote theirs future states and after I delet those future states if thei return to the one of the deleted states. At the end I've got just a couple FB and GE. And using this I can do the minimal table of the states. Alpha state= ADG and Beta state=BEH. I thank all for the help

Finite State Machine Minimization


An example of neither open nor closed set

Question: I need a very simple example of a set of real numbers (if there is any) that is neither closed nor open, along with an explanation of why it is so.
Answer: $[0,1)$
It is not open because there is no $\epsilon > 0$ such that $(0-\epsilon,0+\epsilon) \subseteq [0,1)$.
It is not closed because $1$ is a limit point of the set which is not contained in it.
Comment: @MonkeyD.Luffy A finite union of closed sets is closed, an arbitrary intersection of closed sets is closed. DeMorgan's Law gives you the analogous statements for open sets.
Comment: One last Question, does the set has be connected? for example:- [1,2]U[3,4] ... what can we say about this set?
Answer: For a slightly more exotic example, the rationals, $\mathbb{Q}$.
They are not open because any interval about a rational point $r$, $(r-\epsilon,r+\epsilon)$, contains an irrational point.
They are not closed because every irrational point is the limit of a sequence of rational points. If $s$ is irrational, consider the sequence $\left\{ \dfrac{\lfloor10^n s\rfloor}{10^n} \right\}.$
Answer: Let $A = \{\frac{1}{n} : n \in \mathbb{N}\}$.
$A$ is not closed since $0$ is a limit point of $A$, but $0 \notin A$.
$A$ is not open since every ball around any point contains a point in $\mathbb{R} - A$.
Answer: Take $\mathbb{R}$ with the finite complement topology - that is, the open sets are exactly those with finite complement.  Then $[0,1]$ is neither open nor closed.  It is not open since $\mathbb{R}\setminus [0,1]=(-\infty,0) \cup (1,\infty)$ is not finite, and it is not closed since its complement, $(-\infty,0) \cup (1,\infty)$, is not open, as just demonstrated.
Answer: The interval $\left ( 0,1 \right )$ as a subset of $\mathbb{R}^{2}$, that is $\left \{ \left ( x,0 \right ) \in \mathbb{R}^{2}: x \in \left ( 0,1 \right )\right \}$ is neither open nor closed because none of its points are interior points and $\left ( 1,0 \right )$ is a limit point not in the set.
Answer: The rational numbers $\mathbb{Q}$ are neither open nor closed. Recall a subset S of a metric space X space is open if every point x in S has an $\epsilon$-neighborhood $N_{\epsilon}(x)$ that is a proper subset of S. And a set is closed if(and only if) its complement is open. So $\forall (q \in \mathbb{Q},r \in [\mathbb{R} \setminus \mathbb{Q}], \epsilon > 0, \lambda > 0)$ , $N_{\epsilon}(q) \cap [\mathbb{R}\ \setminus\mathbb{Q}]\neq \emptyset$ and  $N_{\lambda}(r) \cap \mathbb{Q} \neq \emptyset$. So $\mathbb{Q}$ is not open since every $\epsilon$-neighborhood or a rational number contains irrationals. But its complement $ [\mathbb{R}\ \setminus\mathbb{Q}]$, the set of irrational numbers, is also not open since no $\epsilon$-neighborhoods or irrationals contain exclusively irrationals. But the complement of the rationals is not open, so $\mathbb{Q}$ cannot be closed either. Therefore, the set of rationals is neither open nor closed.


Portable LaTeX?

Question: This isn't explicitly a question on TeX syntax, but is there a program available (or a flag for latex itself) that will create a complete standalone LaTeX file from one that has multiple dependencies?
Comment: There is a very trivial solution. For example, if your top-level file is called `a.tex` you could create a file that has one line: `\input{a.tex}`. This is probably not what you mean. Besides that I don't know any solutions. Why do you need this?
Comment: Sorry for getting back you so late, @MarcvanDongen, but my ideal solution would resolve all `\input`s (even those hidden by `\usepackage`, using `makeatletter` and friend as necessary) to produce a single file to be processed by `latex` with a minimal TeX distribution.

Alternatively, something that compiles LaTeX to plain TeX would be pretty cool, too.
Answer: There are bundledoc and arlatex.
The bundledoc package builds an archive which contains all needed LaTeX files (tex, cls,...).
arlatex is a Perl-script based on bundledoc which generates a single tex file, which in return produces the other files by using filecontents.
Answer: I am going to assume a few things:

You are not doing something funny (with \write18, for example)
The latex base format is ok for you (meaning you do not have to include it)
The fonts do not have to be included

First of all, use the \listfiles command in the preamble.
The include all the latex files listed by this command into your file using the  filecontents package. Pray that my assumptions are ok to whatever non-god you have (the Leslie Lamport Lion?). Send the file.

Portable LaTeX?


If your last words were the shahada and you committed suicide, would you still enter heaven?

Question: My friend recently hurt herself but instead of calling an ambulance, she just lied in bed and kept repeating the shahada. I later asked why and she told me she wants to enter heaven but cannot stand her life and hates herself. So if you committed suicide but your last words were the shahada, would you still enter heaven?
Answer: Assalamu Aleikum
I noticed many questions on this site are about matters that only Allah
knows. The pattern is "If I do x good deeds will I go to heaven?" and conversely "If I sin this way will I go to hell?"
No one except Allah knows the Ilm Ghaib (knowledge of the unseen).
Allah tells us in so many Ayahs in the Quran that He (tt) is the only one who possesses
the knowledge of the unseen.
Follow the tenets of Islam by using the Quran and the Sunnah of our beloved Prophet Muhammad (Salawaatulaahi Rabi Wa Salaamu 'Aleyhi) as your two weighty guides.
Answer: If a person is hurt and he/she has access to help (ambulance, etc) then he/she should not harm himself/herself by not getting treated. Instead, he/she should take necessary actions to save himself/herself.
What your friend did does not seem to be the right thing. She should have gone to the hospital or you could have called the ambulance.
Suicide is a major sin in Islam. It is a sin which has very dangerous consequences. A person would be killing himself again and again in hell (he would kill himself in the same manner in which he did suicide).
I advise you to visit www.islamqa.info and read articles about suicide. If your friend is alive call ambulance and urge her parents to force her to get treated.
If your friend is alive you may inform her through her brother or through her parents about the punishment of suicide.
At islamqa.info you would also find various articles about how to attain jannah


Do positively charged particles exchange photons?

Question: I learned in this video and in this answer that electrons repel from each other by exchanging photons. This makes sense when it comes to electrons, but what happens when two protons or two positrons repel each other? Do positively charged particles also exchange photons?
Comment: Related: http://physics.stackexchange.com/q/2244/50583 and its linked questions.
Answer: Yes. Photons are the carriers for the electromagnetic force, regardless of the charges involved.
Comment: Unless of course the charge is zero ;)
Comment: @gj255 reading your comment I'm getting curious how neutrons get scattered of each other?
Comment: I don't know the answer to this, but I can suggest two possibilities. Neutrons are composed of quarks, which are electrically charged. Hence, if two neutrons get sufficiently close together that their internal composition becomes important, the component quarks can exchange a photon. It's also possible, however, that the scattering involves the exchange of some particle other than the photon. At the level of 'effective theory', nucleon interactions can in fact be described by exchange of *pions*.
Comment: As I understand it, neutron-neutron (and neutron-proton) interactions involve the strong nuclear force, not electromagnetism at all.
Comment: @HolgerFiedler In addition to the strong nuclear force, neutrons experience a (feeble) dipole-dipole magnetic interaction mediated via photons.  Would make an interesting follow-up question.


What is the way to use Linux in VirtualBox on Windows

Question: For using Linux on my windows system,  I downloaded the ISO of Linux from the website.
The problem is that the Internet and many other devices are not working. So I want to use them using Virtualbox then I can use many other feature as well as I can use in windows.
When I use Linux in Windows it tells me to install or try.  I'm not in the mood to install, so I always use try method. In try method I need to install application everytime whenever I need to use.
I want a solution that never tells me much thing.  I need a solution that when I use Virtualbox then they just boot as I boot my windows.
Is it possible to install software whenever I boot from pen-drive?
The question is that how I can setup my linux on pendrive then I can use it from pen-drive. Is this possible?
Comment: This has nothing to do with virtualbox. You are inserting a live-CD that brings up an install/try out dialog. It sounds like you just want to install the LiveCD. Your question is very unclear so I may well have misunderstood.
Comment: This question doesn't make any sense. It's also off-topic here.
Comment: I don't understand what he is even talking about.
Answer: In the virtualbox bios set it to boot from CDrom first?
Answer: The easiest way to do this is to create a virtual machine, and install Linux to the virtual hard drive. This way, when you start the VM from Windows, it will be like running 2 computers at once - one real, and the other virtual.
Answer: Your questions is quite vauge and hard to comprehend. We can't understand what you are trying to do.

Are you trying to install Ubuntu in the VirtualBox Virtual Machine? If so please look at this section of the VirtualBox Manual.
Are you trying to dual boot Ubuntu and Windows? If so there is documentation on the Ubuntu site.
Are you trying to put Ubuntu on a live USB to try it? Download uNetBootin and use that to make a bootable USB stick.
Are you trying to try Ubuntu from the disk? Use IMGBurn or somthing similar to burn the .iso to disk, restart your computer and boot from the disk. This will let you try Ubuntu but any chages you make will be lost on restart.

Unless you edit your question to clarify your intent we can't help you much more.
Answer: Download Fedora Live USB creator, set apart some space in Persistence mode whatever you have installed should be retained.

If you want to use VirtualBox, when you choose to shutdown the VM, select to save machine state instead of shutting it down.


Preparing 29.97 and 30 fps video for VSE

Question: I have two videos I want to edit together, both are single long takes of the same event, taken from different angles with different cameras.  One is from an older Sony camcorder, 29 minutes long, 720x480, 29.97 fps; the other from an iPhone 6, 27 minutes long, 1920x1080, 30 fps.  Each has problems at various times, so I'd like to combine them with intercuts.  I understand that my first step is to convert the framerates to match. What's the best way to do this?  I've seen recommendations to use FFmpeg. With the frame rates so similar, is this overkill?  Thanks.
Comment: Even though there is a very small difference, it **is** significant, the sound will drift noticeably in half hour. Retiming/reencoding your sources to a common frame rate makes sense.
Answer: You will need to conform the footage to a single base rate. Although being very close, the values will be significantly off enough to cause sound slippage.
Regarding the Apple device, if from North America, I have extreme doubts that the footage is a base 30 rate. Typically most North American devices will list 24P or 30P and yet still be NTSC 24000/1001 and 30000/1001 respectively.
FFMPEG is probably a great entry point to conform any footage that requires such. Bear in mind that this may well have adverse effects on your footage as the frames in question may be dropped or doubled up depending on which target frame rate you are conforming to.
Comment: When I import each file into VSE, the video and audio tracks only match up when I choose 29.97 and 30 fps for the respective files.  I probably want to drop every 1,000th frame from the iPhone video. Do I need to do anything special to get FFMPEG to do that?  The tutorials that I found indicated that it would interpolate frames, which seems like overkill for what i need.
Comment: Use the FFMPEG command to identify the actual stream's framerate. The rather brute force command you need is "-vf fps=30000/1001" I believe. Frame interpolation can help if the dropped frames are too jarring.
Answer: The program that I use to convert my video footage to the same frame rate is Handbrake (https://handbrake.fr/). It's fairly easy to use.
Generally, in Handbrake, I change Anamorphic to none, Constant Quality down to Zero, and then I set to Constant Framerate.
When editing video in Blender, you almost always want to use the same exact framerate. I convert everything to the output framerate through handbrake first.
Answer: You could open the 'Video Sequence Editor', click 'Add', 'Movie' and open the first movie (from Sony). In the properties panel, change the fps according to that video and render it to images.
Then open a new Blender, open 'Video Sequence Editor', click 'Add', 'Image', and select every rendered image of the previous video. Now change in the properties panel the fps to 30 fps and render it as video. Now you have both videos at 30 fps.
Answer: Use AviSynth before using Blender to convert/change to the correct Frame Rate and then mount your AVS file with AFSmount and open the virtual AVI file in Blender.
Answer: If you use FFMPEG use it cautiously, it's not a playtool.
I'd recomend doing several steps like retime, recode, transcode both in a unique reading format so the editing tool doesn't crash in the middle of a computation. Setting a common frame rate won't hurt the audio at all depending on the tools, so plan your match before you play.
Once you've got both at the same frame rate, print size then you pull the audio track and get a single audio track from both.
Essentially you'd master it using 'steinberg's wavelab. Do not remove frames from audio. Just silence it using a fade. Once the studio audio is push, then join it from a separate track in your favorite compositing tool. Then cut and fade video at will in a single pass – the output will be transcoded to the final formats. Good luck.


How to set Visual Studio 2012 RC Compiler for Qt instead of MinGW?

Question: Windows 8 x86;
Qt 4.8.2;
Visual Studio Ultimate 2012 RC
Comment: huh?  Visual Studio doesn't use mingw to begin with.
Comment: Are you using Qt Creator? Plain qmake? Something else?
Comment: http://www.qtcentre.org/wiki/index.php?title=Qt4_with_Visual_Studio might be helpful.
Comment: I wonder if this question has been made obsolete by events?  Pulling the latest QT 4.8.x from git and it seems to process

configure -platform win32-msvc2012

just fine when called from the VS 2012 x86 native tools command prompt.

Version: "Microsoft Visual Studio Professional 2012 Version 11.0.51020.03 Update 1 CTP"
Answer: As far as I know Qt does not yet support Visual Studio 2012 RC. However, I managed to build Qt 4.8 with Visual Studio 2011 beta (the predecessor to Visual Studio 2012 RC - they just decided to rename it) myself. It required making some changes to Qt source code before compiling. Here are the steps I used:

Copy mkspecs/win32-msvc2010 to mkspecs/win32-msvc2012 and edit the qmake.conf file to specify _MSC_VER=1700.
Search for "msvc2010" in all files in the extracted directory and patch the ~10 places to also understand "msvc2012"
In a Visual Studio command shell, cd to tools/configure, run a previous version of qmake (which you need to already have), and then run nmake to update your configure.exe.
Search for "make_pair<" in all files and remove the template arguments.

This may not be required in VS 2012; in VS 2011-beta I got compile errors with make_pair when template arguments were specified.

In src\3rdparty\javascriptcore\JavaScriptCore\runtime\Structure.{h,cpp} change the make_pair calls to explicit JSC::StructureTransitionTableHash::Key constructor calls.
Edit src\3rdparty\clucene\src\CLucene\config\define_std.h to comment out _CL_HAVE_HASH_MAP and _CL_HAVE_HASH_SET
In a Visual Studio command shell, run the configure program that is installed with the source, e.g.: configure.exe -debug-and-release -platform win32-msvc2012 -opensource

[Optionally] add '-nomake demos -nomake examples' to the command line to save build time, and/or '-mp' to build in parallel

When the configure is complete, type nmake to start the build. This will build debug and release versions of all the libraries as well as release versions of all the tools (designer, etc.).

It took a little work but it worked for me and I now have dozens of Qt applications up and running, so I figured I'd share with anyone else who wants to build Qt 4.8.x on Visual Studio 11 (Visual Studio 2011 beta or Visual Studio 2012 RC.)
If this seems too complicated, just wait a bit; I'm sure Qt will support Visual Studio 2012 soon.
Comment: Follow this link if you see some build problems regarding "pair": http://qt-project.org/forums/viewthread/17771


Slow roasting fresh ham

Question: How long does it take to slow roast a 13 pound bone-in fresh ham? We want to bring it to 190 degrees F to break down the collagen.
Answer: There is no single answer to this question.
Even saying you want to bring it to a temperature of 190 (I infer F) is overly simplified, as the conversion of collagen to gelatin is dependent on both time and temperature.  It goes faster at higher temperatures, but still takes time.  There is no single magic temperature that when you hit it, the conversion is done.
The time it takes to cook the fresh ham will depend on the size of the ham, the method you use to cook the ham (for example, braising versus dry roasting, and the oven temperature you set.
The time will also depend on whether you want to be able to pull the pork (although should is somewhat better suited to that application), or carve it into slices.
Roasting at 225 F, 10-14 hours would not be out of the question.  At 325 F, it may take 6-9 hours.  Start checking for donenesss at the beginning of the time.
The ham will be done when you can put a fork in it and twist without too much resistance, demonstrating that it is pullable.
Comment: 160 to 170 would be quite well done, without the benefit of collagen conversion, so you would either go to 145 for a medium roast, or all the way to the high end.  in between is where you get the worst of both worlds.
Comment: Yes - my apologies we do mean 190 deg F. and I forgot to specify dry heat, not braised. We realize it depends on many factors but your answer gave sufficient range for us to start it at least 14 hours before service if roasted at 225 deg F. If not tender and not yet near 190 deg F after 10 hours we will turn up the heat a little to break through any temperature stall that will likely occur near 155 deg F. Thank you.
Comment: You may wish to treat it more like a pork roast than a pulled pork, and roast only to 145 F.
Comment: We have found that when cooked to a lower temp (even as high as 160 to 170 deg F) the leg is too tough for us as we like the more unctuous "pulled" pork texture.

Slow roasting fresh ham


Flyback Circuits

Question: So, for a diode circuit with a resistor and an inductor, I know that a diode in parallel is needed to provide current a path to travel if power is suddenly cut. But, what about RC, LC, and RLC circuits? Would they also need a flyback diode, or not? My thought is that if they have a capacitor, they shouldn't have a problem because the capacitor would store energy, but I'm not sure that's correct.
Comment: A capacitor in the circuit can absorb current and convert it into voltage at a rate of dV = I/C. It depends on where it is in the circuit though.
Answer: RC, LC, and RLC
RC no.  This is specific to inductors. If you disconnect a capacitor the voltage remains the same ideally.  Capacitors fight changes in voltage. Inductors fight changes in current.  See the math part for more.
Parallel LC:Yes under the right circumstances. In a parallel LC circuit if you had a high DC current component flowing through a large inductor and a small capacitor when the power was disconnected you could see a destructive voltage spike.  In effect all inductors are parallel LC circuits like this.  There are stray capacitances everywhere. In cases where you have to worry about destructive spikes the the capacitance is small.  The capacitance between the two inductor leads is usually picofarad level while the inductor is usually many turns around a ferrous core which leads to high inductance.
However when parallel LC circuits are designed instead of just happening because they can't be avoided, they are used to take of advantage of the fact that they can trade energy with each other. This means the capacitor should be able to absorb what the inductor can give it.
Series LC: there is ideally no DC component here.  Capacitors don't allow DC voltage to flow and the leakage current is negligible here.
RLC: same for the same reasons for both parallel and series.  In the parallel case the resistor even helps absorb the energy.
==========================================
Optional math:
An inductor stores energy in a magnetic field.  How much is stored at a moment is a function of instantaneous current:
(1/2) * L(henries) * I(amps)^2 = energy (joules).
The easiest way to understand the spike is to start with observing that the current through an inductor must change in a continous manner.  It can not jump from one value to another.
This can be understood by looking at power.
power = energy/time
If it jumps from one to another then the instantaneous power is infinite.  This is not possible in our current understanding of physics.
So given that current cannot change instantaneously through an inductor if you have 1A flowing through an inductor and you disconnect it, then there will still be current flowing through it.  As you approach the time of disconnection from the right the current will approach 1A.  The voltage across an inductor as you approach the disconnection time will be whatever is necessary to cause 1A to flow.  So if it is sitting in the air with it will cause an arc in the air.  This is why cars have coils for their spark plugs.  If the resistance between the terminals of the inductor is 100k ohms then the voltage will be 100kV.  If there is a diode connected the right direction then it will be about .7V and the diode should be rated for handling the current. If there's an active component like an expensive chip somewhere it will reach the breakdown voltage if it has nowhere else to go and current will flow.
A capacitor has a similar model just with currents and voltages reversed.  A capacitor stores energy in an electric field. How much energy is stored in the electrical field is
(1/2) * C(farads) * V(Volts) = energy (joules)
Similarly a discontinuity in the voltage over time implies infinite power at that moment and cannot happen.  In a capacitor the rate of change in voltage is a function of current.
dV/dt (volts per second) = I(amps)/C(farads)
So if you have a parallel LC circuit with 1A going through the inductor and you disconnect it, then the voltage will be changing at  1/C volts per second.  The larger the capacitance the slower the rise.  The current will continuously decrease along with the rate of voltage increase. How fast is based on the size of the inductor.
You can get a feel for voltage rise using the conservation of energy. An example with 1A going through a 1mH inductor with a 1uF capacitor in parallel.  Assuming steady state conditions the voltage across the capacitor will be 0 at the time of disconnection.
The energy in the magnetic field of the inductor is
1A^2 * 10^-3 mH * (0.5) = 0.5 mJ
The highest possible voltage rise in the capacitor would result from lossless components where all the energy is transferred to the capacitor.
0.5mJ = 0.5*C*V^2 = 0.5 * 10^-6 uF * V(volts)^2
V(volts)^2 = 0.5/(0.5 * 10^-6) (Volts^2) = 10^6 (Volts^2)
1000 Volts
So as a designer you would have to make sure anything that voltage could be applied to was rated for that(including the capacitor and inductor) or find a way to protect it.
Note that a 1mH inductor is pretty big compared to a 1uF capacitor. I can't think of a place where that would happen when it is being used as a LC tank for its resonance and would also have DC current going through it.  A DC motor with a small capacitor across it to shunt noise from the brushes might be a place where something near this model happens.
Answer: An analogy would be a capacitor connected to a voltage source where the source could suddenly be shorted, causing huge current to flow.
In a similar, but complementary, manner to the inductor, a series diode or a series resistor (or parallel L-R in series) would  prevent the current from reaching hazardous levels.
There is a bit of an apparent difference in that capacitors are generally much more ideal than non-superconducting inductors- an open capacitor could hold a charge for days, but a shorted inductor will not usually maintain a current for long due to resistance of the wire.
Answer: Yes, diodes are used in circuits to discharge energy stored on capacitors. It's an entirely different circumstance, though.
Inductors will reverse their voltage when discharging energy and if all their usual current paths are disabled or cut off, that voltage will rise rapidly until something gives in or breaks. Providing a diode (or a zener plus diode) provides a way manage the value of the inductor's reverse voltage.
In the case of capacitors, the reason for using diodes to discharge energy still exists but the situation is also a lot different then. They don't suddenly create huge voltages to manage. However, they often do need a path to discharge when used in switching circuits.
Here's an example modified from a post I recently made:

simulate this circuit – Schematic created using CircuitLab
In the above case, when this timing circuit ends the timing cycle and turns \$Q_1\$ off, the LOAD will rapidly pull down \$Q_1\$'s collector. But \$C_1\$ now has a number of volts stored on it (which is why the circuit finally timed out) and would normally have to leak out through a very large valued \$R_3\$ if it weren't for \$D_1\$ available there. When the top end of \$C_1\$ is rapidly now close to zero volts and the bottom end of \$C_1\$ is perhaps now suddenly at \$-4\:\textrm{V}\$, that diode helps to discharge it making \$C_1\$ ready rapidly for re-use in the next timing cycle. Otherwise, the RC time constant would be on the order of ten seconds and you'd need a number of those periods to completely discharge \$C_1\$.
That's an example of where a diode is useful to discharge energy in a capacitor. There are others. But unmanaged inductors can create very large and very difficult voltages. So there is a difference in magnitude which makes a qualitative difference in reasoning.

Flyback Circuits


What is the "Max current" for AWG#16?

Question: I read many informations from many webs,
all never give an answer with easy understand.
Comment: For smaller wires you could use [this nomograph](http://electronics.stackexchange.com/a/5405/4950). Don't know whether there is one for AWG 16.
Comment: Since previous question was closed, maybe mods could move Spehro's answer over here?
Answer: The reason you're getting lots of different answers is that there is no hard maximum current a particular cable can handle since it depends on the application.
You need to specify what physical limit you don't want to exceed for your "maximum" criterion.  Do you want the wire not to rise above ambient temperature some amount?  If so, what amount?  If you can only tolerate a 10°C rise, then the maximum current will be less than if you can tolerate a 50°C rise, for example.  Or maybe the limiting parameter for your application is voltage drop, which could make the maximum current quite different again.
AWG #16 copper wire has a resistance of 4.016 Ω per 1000 feet, or 4.016 mΩ/foot, or 13.18 mΩ/m.  If you need to keep the voltage drop along 1 m of wire to 100 mV or less, then you can't push more than 7.59 A thru it.  If you need to limit the power dissipation to 1 W/foot, then you can't push more than 15.8 A thru it.  1 W/foot would get noticably warm, but should not be dangerously so for most uses.
If you are using it for house wiring, then it becomes a legal matter and you simply look up the answer.  One chart I looked at says the limit is 3.7 A for "power transmission".  That was chosen to be very conservative so that some amount of degradation and screwups can happen and your house is unlikely to burn down due to overloaded wiring.  Legal limits will vary by jurisdiction and which electrical code is being applied.  You will have to consult the electrical code that applies to your area and circumstance to get the answer.
That same chart that shows 3.7 A as the maximum for power transmission also shows 22 A maximum for "chassis wiring".  Presumably more temperature rise is acceptable inside a chassis.
So to get a straight answer, you have to tell us what you are really trying to do.  There simply is no inherent maximum current until you get to where the copper melts.  Even that depends on ambient temperature assumptions.
Answer: This table says 3.7 A. According to the same table AWG 16 has a resistance of 13.17 Ω per km, which means that at 3.7 A one meter of wire would cause a power loss of 180 mW, and a voltage drop of 48 mV.
PetPaulsen's nomograph doesn't show a value for AWG 16, but you can compare the values for AWG 22 with those of the table. The table gives much lower current values. That's because the wire's electrical insulation also acts as thermally insulation, whereas the PCB traces the nomograph is about can drain their heat to both the PCB's mass and the air, so that their temperature won't rise as much as for insulated wire.
Answer: It is important to note that the current that can flow through a wire depends on a few factors:

allowable voltage drop. As mentioned in the answer by stevenvh, it depends on the length of wire you are using and the application in question
allowable temperature of the wire, and insulation

I've usually worked with the idea that a wire at 70 degrees is pretty damn hot. I believe a lot of the time the ratings for cable insulation sheath is rated to 100 degrees.
If you have 16 AWG wire with a silicon insulation you'll find its rating to be substantially higher than cheaper plastic insulation.
Comment: The two factors I can see are allowable voltage drop (which depends upon length) and allowable temperature rise (including both how the environment affects the wire and how the wire is allowed to affect its environment).  Are there any others?
Comment: Not that I can think of off the top of my head.

Picking the right wire can be complicated, but if you already have the wire you really need to consider voltage drop and temperature.
Comment: Unless someone else has something that I forgot :-)
Comment: Indeed, picking a wire is more complicated than deciding what one can do with wire one has, since both the amount of temperature rise that will occur with given amount of current and the amount of temperature rise that will be acceptable, can both be affected by the type of wire one uses, in ways which will depend upon the environment where the wire is used.

What is the "Max current" for AWG#16?


Not able to select entire image for wallpaper

Question: When I put the wallpaper in /dcim/Camera and go to change the wallpaper and choose Media gallery and I select the wallpaper I want, it asks me to choose only a small region of the image. What do I need to do to use the entire image?
Comment: The phone wants to make a wallpaper that's the right size and shape for your screen, on most phones that's as tall as your screen resolution and twice as wide as your screen width (notice how the wallpaper scrolls slightly as you move between your home screens). There are posts on here that list the correct wallpaper sizes for most Android devices.
Comment: List of wallpaper sizes for various devices http://android.stackexchange.com/questions/2026/what-size-should-images-be-for-android-wallpaper Also no need to put new pictures into the Camera folder (that's really only meant for your devices' camera to write to) just create a folder on your SD-card called pictures, or wallpapers, or something like that and put it in there.
Answer: If i remember correctly, you can drag the frame to the full size of the image, so that the whole picture will be selected as background.
Answer: The above answer is vague.  Here's a more complete answer.
First
Go through the wallpaper settings and open the image you want to use for wallpaper. You will be prompted to crop it.

Second
Drag the cropping reticule to the bottom right corner.

Third
Drag the left edge of the cropping reticule all the way to the left edge of the screen.  The reticule should grow to encompass the whole image.

Lastly
Tap the "Crop" button at the top right.  It will "crop" the image to the size that it already is, and set it as your wallpaper.
Dénouement
All this because the developers who wrote the wallpaper cropping app couldn't be bothered to check whether the selected image is already the correct size for the device. All they had to do was say "This image is already the right size. Would you like to crop it anyway?", and give us buttons labeled "Crop It" and "Just Use It". Instead, we're stuck with this thoroughly non-intuitive mess.
Well done, Android devs. slow clap
In case anyone is curious, the wallpaper shown in the screenshots above comes along with McKinley Tabor's excellent Asus Transformer Prime Wallpaper Template.
Comment: When I try to set wallpaper from gallery I only got option for portrait image not landscape scrolling image throughout screen, check here http://imgur.com/29USrQ4


Posts and Pages: 404 Page not found

Question: Every post and page is not found. I checked .htaccess, generated a new one, debugged (disabling plugins), checked the static page and the blog page, also nothig. The last thing I did was check if everything was ok in the database, and the posts and links are there and if I use the database url is the same 404 not found.
Answer: Did you try to re-save Permalinks?
Navigate to: WordPress Dashboard > Settings > Permalinks: Click "Save Changes" and then click on the link of the page that should work from the "Edit Page" of that page.
Also review Permalinks settings if they are correct.
If it still doesn't work, you can try to debug the generated permalinks with Debug This plugin.
After activating this plugin go to: Admin Bar > Debug This > Query > Rewrites and check if the rewrite rules are correct and exist for the url that should work.
Comment: Ok, what if you change your permalinks to Plain (Settings > Permalinks > Plain option). The new urls of the pages still don't work? If they do, could it be that hosting disabled mod_rewrite on apache?
Comment: Thanks for the answer, I tried all that and nothing happen :/ I also rechecked the static and the blog links, and all it seems ok
Comment: Do you have any cache plugin? And when you say you disabled plugins, did you disable all of them and still did not work?
Comment: I purged all the caches, and yes I disabled all the plugins, also I tried disabling one by one, but still nothing :/ Do yo have any other idea? This is weird it the first time it happens.
Comment: Indeed, mod_rewrite was disabled, 1 minute and 1 command later, done, hahaha. Thank you! :D

Posts and Pages: 404 Page not found


What is the difference between mutation per base pair and mutation per genome?

Question: Isn't genome size considered to be the number of base pairs present in DNA? So what is the difference between the mutation per base pair and mutation per genome? Are they similar or different?
Comment: I assume you read both terms somewhere?  Often, context supplies meaning. If you could directly quote the source of each term, you would likely get a good answer.
Answer: They are different normalizations of the same number. It's the question of whether you want to know how many mutations can be expected at a single position in a genome, or whether you want to know how many mutations occur across the entire genome.
See wikipedia, for instance:

There are several natural units of time for each of these rates, with rates being characterized either as mutations per base pair per cell division, per gene per generation, or per genome per generation.

Mutations per genome is the number of mutations per base pair times the number of base pairs in the genome (plus mutations that do not correspond to base pair substitutions, though they are usually ignored in these measurements).
E.g., $10^{-9}$ mutations per base pair in a genome of 3 billion base pairs correspond to $3$ mutations per genome.
Comment: not sure why this answer was downvoted/flagged. it's a pretty straightforward topic, not sure why a link is needed.


Require access to LAN when connecting through RaspberryPi VPN access point

Question: Apologies in advance for poor understanding of networking...
EXISTING SETUP

Existing LAN with internet access: 192.168.0.1, 255.155.255.0;
NAS device with installed Plex media server "Media Server":

connected to LAN by ethernet cable with static IP 192.168.0.xxx;
Able to access internet directly (i.e NOT connected through VPN);

RaspberryPi VPN access point:

Setup using https://pimylifeup.com/raspberry-pi-vpn-access-point/
Connected to LAN through Eth0;
Static IP setup: 192.168.0.xxx;
Devices connecting through wlan given IP addresses192.168.220.xxx;
Device with media server client app ("Client Device") connects to access point and given static ip (in network settings on Client Device NOT on RaspberryPi);
Openvpn installed with connection to commercial VPN provider (downloaded openvpn config file from vendor);
all traffic routed through VPN tun0.
Single iptables entry: sudo iptables -t nat -A POSTROUTING -o tun -j MASQUERADE

WHAT PRESENTLY WORKS

RaspberryPi VPN access point works well through VPN;
Other media client apps connected to LAN without VPN (NOT RPi access point) stream media from Media Server well;
media client apps connecting from internet cannot stream media from Media Server with/without VPN (NOT an issue - problem for another day).

PROBLEM AND ATTEMPTED FIXES

"Client Device" connection through RPi access point to Media Server unreliable and VERY slow (Presume routed through VPN);
Tried all config settings in Plex server and Client apps (manual IP and port etc.) without success;
I read the question and answer at  Route LAN traffic through eth0, not tun0, on my VPN access point and tried adding the following without success:
sudo iptables -A FORWARD -i wlan0 -j ACCEPT
sudo iptables -A FORWARD -i eth0 -j ACCEPT
my internet searches suggest that adding route or push route entries to openvpn config file may assist - but my attempts gave failed (likely user error).

Please assist if you can.
Answer: I was able to accomplish the split routing using the explanation provided at https://www.system-rescue.org/networking/Destination-port-routing/  You cannot use ip route directly to route traffic based on ports.  You first need to 'mark' traffic based on port, then create separate routing table to route the marked traffic to the interface you require.


Does it make sense to install the Frontpage Server extensions on a production server for (ASP).NET applications?

Question: Visual Studio offers some built-in deployment features that require Frontpage Server Extensions to be installed on the web server:

publishing of ASP.NET applications,
publishing of Windows applications accessible through ClickOnce.

Right now, I deploy such applications manually by copying the relevant files with a WebDAV client.
It's not a lot of work, but it feels like I'm doing unnecessary work, since there's already a built-in feature of Visual Studio that would do this automatically for me.
On the other hand, I have a strong gut feeling that warns me against doing so: Right now, I have a good understanding of which protocols can be used to access the server, which users can do so, and which parts of the server they can access. Since I don't understand everything that the "magic CGIs" of the Frontpage Server Extensions are doing, I fear that I might accidentally open some security hole due to lack of knowledge.
As a .NET developer, what is your take on this? Did I miss some obvious advantage/disadvantage? Or is there even some established "best practice" in the community w.r.t. using the Frontpage Server Extensions for .NET web servers?
Answer: You don't have to use Frontpage extensions anymore, you can use MSDeploy.  Rejoice!
Edit: Also see this blog post about doing continuous integration with MSDeploy.
Comment: Thanks, that will be useful once we don't need to support IIS6 anymore.


xsl:if at least one child node exists

Question: <node>
   <node1><node11/></node1>
   <node2/>
</node>

I want my XSLT to check
<xsl:if test="If at least 1 child node exists">
  Only node1 can pass the if condition
</xsl:if>

Thanks for any reply.
Answer: Firstly, be careful with your terminology here. Do you mean "node" or do you mean "element". A node can be an element, comment, text or processing-instruction.
Anyway, if you do mean element here, to check at least one child element exists, you can just do this (assuming you are positioned on the node element in this case.
<xsl:if test="*">

Your comment suggests only "node1" can pass the if condition, so to check the existence of a specific element, do this
<xsl:if test="node1">

Comment: Thanks for your answer. I got a confusion among those terms. Will be more carefull next time
Answer: In the context of the node you are testing, this should work to test whether a node has child elements:
<xsl:if test="*">
  Only node1 can pass the if condition
</xsl:if>

If you actually meant nodes (which would include text nodes), then this would work to include text nodes:
<xsl:if test="node()">
  Only node1 can pass the if condition
</xsl:if>

But <node> would also pass this test (<node2> wouldn't).  I assumed you were only speaking in the context of <node>'s child nodes, but perhaps not?
Answer: Expressions that match a node are truthy, whilst expressions that don't match anything are falsy, so:
<xsl:if test="node()">
   ...
</xsl:if>

However, your question and the implied condition "Only node1 can pass the if condition" are at odds with the example.  Both node and node1 have child nodes, so both would pass this if condition.
To limit it strictly to node1, you have to either ensure that the template context is appropriate, or check that the node in question is not the documentElement.
Answer: The wording of the question is unclear but I think you just want to process child nodes that have themselves got children (ie grandchildren of the current node)
<xsl:template match="node">
 do stuff for node
  <xsl:apply-templates select="*[*]"/>
</xsl:template>

will just apply templates to node1 as it has a child node, it will not apply templates to node2.

xsl:if at least one child node exists


How to implement billing for a desktop app

Question: I have a windows desktop application (actually it is cross platform) that users can sign up and i store auth data like mail and username and password in a mysql database. Now i want to add a subscription fee on a monthly basis for using the app so that i am thinking of implementing a payment gateway like stripe gateway by which the user pay the subscription fee and i then store in database that the user is subscribed and check that every month . Is this a good approach .
Is there any better idea.i want the best approach in this scenario
Answer: Stripe doesn't make any desktop client libraries, so your best bet for the payment part is to handle that part on the web using something like Checkout.