How to include line-breaks in the_excerpt?

Question: how can I include a line-break inside the_excerpt. I've modified the length and the more-button via my functions.php. I'm using teaser for every blog-entry and sometimes it looks a bit ugly, that there no line-breaks included.
Answer: Same to Johannes Pille's solution, the bellowing solution should be more adaptive.
In detail:

override function wp_trim_excerpt
remove old filter and add new custom new filter

Here's full code:
// append to themes/{your_theme}/functions.php

define('EXCERPT_RARELY', '{[}]');
define('EXCERPT_BR', nl2br(PHP_EOL));

function so306588_trim_excerpt_custom($text = '')
{
    add_filter('the_content', 'so306588_trim_excerpt_custom_mark', 6);

    // get through origin filter
    $text = wp_trim_excerpt($text);

    remove_filter('the_content', 'so306588_trim_excerpt_custom_mark', 6);

    return so306588_trim_excerpt_custom_restore($text);
}

function so306588_trim_excerpt_custom_mark($text)
{
    $text = nl2br($text);
    return str_replace(EXCERPT_BR, EXCERPT_RARELY, $text);
}

function so306588_trim_excerpt_custom_restore($text)
{
    return str_replace(EXCERPT_RARELY, EXCERPT_BR, $text);
}

// remove default filter
remove_filter('get_the_excerpt', 'wp_trim_excerpt');

// add custom filter
add_filter('get_the_excerpt', 'so306588_trim_excerpt_custom');

Comment: I like. +1. Had the OP accepted mine ever, I'd comment "This should be the accepted answer (now)."
Comment: Worked perfectly, until it stopped working a few days ago... But I have not been able to narrow the error down yet. But since @Nitzki commented similiary on Johannes' solution, I guess wordpress did something in a recent update that killed it...
Answer: There is no filter that would allow you to set allowable tags not to be removed by the_excerpt(). Arguably a shortcoming of the core.
Anyhow, the actual excerpt generation does not happen in that template tag but entirely elsewhere:
Excerpts are generated by the function wp_trim_excerpt(), inside of which the excerpt filters you are already using (excerpt_length and excerpt_more) are applied and which calls wp_trim_words(), which in turn calls upon wp_strip_all_tags(). All three functions are located in wp-includes/formatting.php
Hence in the absence of a filter for the case and the inevitability of your excerpt running through wp_strip_all_tags(), the only possibility to preserve some tags is adding a custom replacement function for wp_trim_excerpt():
function wpse67498_wp_trim_excerpt( $text = '' ) {
    $raw_excerpt = $text;

    if ( '' == $text ) {
        $text = get_the_content( '' );
        $text = strip_shortcodes( $text );
        $text = apply_filters( 'the_content', $text );
        $text = str_replace( ']]>', ']]>', $text );
        $excerpt_length = apply_filters( 'excerpt_length', 55 );
        $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[...]' );

        $allowable = '
';
        $text = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $text );
        $text = trim( strip_tags( $text, $allowable ) );

        if ( 'characters' == _x( 'words', 'word count: words or characters?' )
            && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) )
        {
            $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
            preg_match_all( '/./u', $text, $words_array );
            $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
            $sep = '';
        } else {
            $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
            $sep = ' ';
        }

        if ( count( $words_array ) > $excerpt_length ) {
            array_pop( $words_array );
            $text = implode( $sep, $words_array );
            $text = $text . $excerpt_more;
        } else {
            $text = implode( $sep, $words_array );
        }
    }

    return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
}

remove_filter( 'get_the_excerpt', 'wp_trim_excerpt');
add_filter( 'get_the_excerpt', 'wpse67498_wp_trim_excerpt' );

Comment: Okay, thank you. But now it seems, that I can't shorten the excerpt anymore to 20 words and put a more button instead of [...]
Comment: So how can I now edit the excerpt_length and the excerpt_more? It doesn't work any more.
Answer: wouldn't it be simpler to apply the_content filter to the excerpt?
i only use this occasionally, right within the template file:
$excerpt = apply_filters('the_content',  ( get_post(get_the_ID())->post_excerpt) );
echo $excerpt;

Comment: Brilliant! It worked for me
Comment: This looks like what I need. But where in the template does one put this, @diette? Thank you!
Answer: At the moment, it is possible to use the_excerpt() funtion to display the excerpt with line breaks. But if you like to return the result  you can use for that purpose a function like this:
function get_the_excerpt_theme() {
    $excerpt = get_the_excerpt();
    $excerpt = apply_filters( 'the_excerpt', $excerpt );
    return $excerpt;
}

It applies a filters to the excerpt using apply_filters('the_excerpt', $excerpt ) like in the wp function the_excerpt() but returns the string without displaying it.
Also, if you like to allow only line breaks in the excerpt, you can add  $excerpt = strip_tags($excerpt,'
') below the line apply_filters.
Hope it helps!
Comment: This does not work because it does not allow line breaks.
Answer: A simple solution is replacing line breaks before WordPress would replace them. I used an arbitrary selected character from the Unicode private area as it is not expected to appear in any content, also if it appears it is dedicated to be private use to indicate that handling is not standardised.
add_filter('wp_trim_words', function($text, $num_words, $more, $original_text) {
    static $filtering;
    if ( $filtering ) {
        return $text;
    }
    $filtering = true;

    // Random character from a unicode private use area
    $private_use_char = "\u{101425}";

    $text = str_replace( ["\n\r", "\n", "\r"], $private_use_char, $original_text);
    $text = wp_trim_words($text, $num_words, $more);
    $text = str_replace($private_use_char, "\n", $text); // or str_replace($private_use_char, "
", $text)

    $filtering = false;
    return $text;
}, 10, 4);

Note that this will result in "\n" characters in the output of the_excerpt() and get_the_excerpt(), so you probably want to call wpautop() on that before using it in HTML. Alternatively you can simply replace $private_use_char with
 instead of \n as indicated by the comment.
Answer: also could just use PHP's nl2br() function:
echo nl2br(get_the_excerpt());

-- or --
nl2br(the_excerpt());

Comment: This does not work.
Comment: Well latest version of wordpress seems to treat excerpt field like a normal post content field.. I just gave it a try on [SandboxWordpress.com](https://80832390856.sandboxwordpress.com/) and new lines now return as separate paragraph tags. That said, im sure this did work in the past, or else id not have shared it. Not sure a downvote was needed, but glad to have this brought to my attention.
Comment: Well, I can remove the downvote, not sure what's the proper way, because despite the fact I believe this might have worked in the past, I have tried it and it does not any more, so I felt like I wasted my time, but on the other hand for sure no answer can stand right forever when the system it is for changes. So what would be the proper way of indicating that the answer is not useful any more, even while it might have been in the past? I'm open to suggestions. Please put a note in the answer indicating it does not work any more with the latest version of WP, and I'll remove the downvote. Deal?


Unlisted ethereum wallet

Question: Unlisted ethereum wallet. Maybe can you help me?
Answer: This happened to me as well. I was in ropsten.
I noticed when I started the geth client directly and then tried to access the Mist wallet, was getting this error. But when I just started the Mist wallet directly without starting a geth client then was able to access the wallet UI.
I then tried initializing the geth with a new genesis config file. After doing that started the geth with a new networkid and on trying to access the Mist i was able to open it. So didn't face the error anymore
When I started with a different networkid starting with number different from 1 could again access my wallet.

Unlisted ethereum wallet


"Select All" from Contacts in WhatsApp

Question: In WhasApp, is there any button for "Select All" from Contacts; in order that one single message goes to all?
Answer: Well, nope there isn't any select all option available over the WhatsApp, rather than it has the feature called Broadcast messages !
To Broadcast the message:

Open up WhatsApp.
Tap over the three dots available on top right side of the screen.
Now Select the option "BroadCast Message".
Tap over the + button to add recipient name over the Broadcast list.
Next thing to do is tap over the continue button.

Like, the above user said that, presently it has a limit of 256 broadcast limit.
You can also refer to the WhatsApp Support Section for the same.
Answer: There is no "Select All" when sending a WhatsApp Broadcast Message. Presently there is a limit of sending 256 people a broadcast message.
Comment: from which soure/reference, this limit of 256 you found? I did not see this limit described in the link that you gave while Answering! You may want to remove that if there is no "official" source or put the reference to that official sourece
Comment: ^^ If you try sending a broadcast message, the counter on the top counts the people with a limit of 256 eg. 1/256, 2/256 and so on. Try sending one now and you'll see it. @MeTechnical

"Select All" from Contacts in WhatsApp


why sometimes touching old flickering tube lights starts them properly

Question: In my old house there are two old tube lights. Some times they don't start properly, (specially at evening time, may be it is because of low voltage), they starts flickering i.e. on and off continuously. And when my elder brother touches them, mostly at center they just goes on. Even i have tried many times, the touching works, and even after removing the hand, once it is on(working properly), doesn't stop them, and they remains on.
So why and how touching them works.
Sorry for my bad English.
Thanks in advance.
Answer: I've found this to be the case, too. Generally, my shop lights will flicker when turning on, especially when it is colder outside  .
There are two basic phases to this kind of light bulb: a start-up phase, and an operating phase. The start-up requires more voltage, because you are initiating the plasma stream between the terminals of the bulb.
So, these bulbs are filled with gas, generally mercury vapor. When you turn it on, you're really creating an electrical arc at the end of the bulb. This arc ionizes the gas, and that is the flickering you see. Eventually, the entire length of the bulb can arc, and a plasma stream is created (plasma is just a gas of free-moving ions and electrons).
When it is cold, or if the starter arcs are wearing out (and can't produce sufficient voltage), then the flickering lasts longer. By touching the bulb, you actually provide a shorter path for the plasma stream! In effect, you get two short plasma streams, each terminating at your touch point. Then, once the plasma streams interact, and since the voltage required to maintain the stream is less than the voltage needed to establish it, the streams merge into one and the lamp will light.
This is similar to some "glowing orbs" you see in gift shops or museums... a glowing plasma (looks like lightning inside a clear spherical shell) will arc and bend toward your touch, since you are providing your own set of electric and magnetic fields.
Comment: It is not dangerous to touch the light, because you're not actually acting as a ground. I'm sorry my explanation was a bit vague on this point. Your touch generates a capacitance field, and the change in capacitance is what affects the plasma. This is the same effect that is used in "touch switches" on metallic fixtures, like some lamps. See this Wikipedia [article](http://en.wikipedia.org/wiki/Touch_switch) for more detailed information about capacitave switches.
Comment: Sorry @OrangeWombat I did not want to downvote, my finger hit the wrong arrow :(. I will try to make a small edit and then I think I can change to what I wanted to vote.
Comment: @annav, no worries! :)
Comment: thanks for your answer. But i'm thinking, isn't it then dangerous to touch the tube lights, what amount of voltage and current the plasma has, and why can't we feel the current flowing in our body, because even we can the feel current while touching cable or telephone wires. Please can you explain these things
Answer: I'll throw this into the mix. If I plug in one end of my guitar cable to my amp, turn the amp on, bring up the volume a little, and touch only the center contact on the other end of the cable, I get a loud 60 Hertz buzz from my amp. I believe this is because my body is acting as an antenna - picking up some radiation from the house wiring, which is typically unshielded.
Could this "antenna effect" also play a part in triggering the fluorescent lamps to light when they are touched?
I also know that if you take a fluorescent tube and go stand under a high voltage line, it will glow because of the very high E-field levels.


Audio power amplifiers

Question: Is an audio power amplifier (not a preamp), commonly used in the high-end home sound systems of audiophiles, a voltage-controlled voltage-source?
Comment: An audio power amplifier must not oscillate, despite 10:1 variations in impedance and in phase shifts. Thus the power supplies have unusual requirements, compared to opamps driving resistive loads. And the magnetic fields of the power-cords may be adequate to couple into low-level cables from turntables, and upset the waveform precision, or just cause oscillation.
Answer: Short answer: Yes, a voltage-controlled voltage source.
The most-expected load is a low-impedance dynamic speaker in the 2-ohm to 16-ohm ballpark. An amplifier having a very low Thevenin equivalent output resistance is helpful to provide good damping. An ideal voltage source fits that profile.
A voltage-controlled voltage source might be specified as having a voltage gain, but you do not often see a spec like this for an audio amplifier. Of more interest is how many watts can be delivered to a load resistance before distortion sets in. The typical distortion type will be clipping of top peak and bottom peak of a sine wave.
The input side of an amplifier might have 10k - 100k input resistance: a voltage across this resistance is amplified and reproduced at the output. So a little current does flow from the driving source.Many audio amplifiers are AC-coupled, so that voltage gain does not extend to DC. Some audio amplifiers have DC-coupled output stages.
Answer: Yes, it is a voltage controlled voltage source, but not ideal. An input voltage of a few volts and a few micro-amps is amplified by about 20 to 30 times to drive a speaker of 2 to 8 ohms typical.
This requires the amplifier to source much more current with a rise in voltage, until the sound level the user wanted is reached, or the amplifier or speaker is overloaded. A quality amplifier will sense this and shut down.
A close-to-ideal amplifier has a very small output impedance much less than 1 ohm, so it has a firm grip on the motion of the speakers, especially the woofers which draw the most current. The power supply may have capacitors well above 20,000uF to support high current surges. There is a reason why high-performance amplifiers may be wired to the speakers with short runs of twisted 8 gauge Monster Cable. Also large diodes may be used to protect the outputs from back-emf from the woofers trying to return to a center position.
The frequency range of a high-performance amplifier is often way below and above the human range of hearing, so capacitors may be used for input and outputs to block DC offset voltages, but some of the best amplifiers use a servo-loop IC to cancel out any DC at the amplifier outputs.
This avoids using capacitors which tend to cause phase shifting at very low frequencies, hence the term "muddy" bass. However this could be the fault of the woofer enclosure as well.
Undersized speaker wire such as zip cord can also cause muddy and weak bass due to the resistance of the wire.
Answer: No, it is not that simple. For example, a VCVS, like any ideal voltage source, provides the same voltage regardless of the load current. A real audio amplifier doesn't do that. Likewise, an ideal VCVS doesn't draw any current from the controlling voltage but a real amplifier does draw current from the input.
The input to an amplifier is generally modeled as an impedance to ground. The output is best modeled using a Thevenin equivalent circuit.
Comment: Regardless of its actual output impedance (which is usually a tiny fraction of an ohm), the output of an audio amplifier is essentially a voltage source.

Audio power amplifiers


How do you find results that occurred in the past week?

Question: I have a books table with a returned_date column. I'd like to see the results for all of the books with a returned date that occurred in the past week.
Any thoughts? I tried doing some date math, but Postgres wasn't happy with my attempt.
Answer: You want to use interval and current_date:
select * from books where returned_date > current_date - interval '7 days'

This would return data from the past week including today.
Here's more on working with dates in Postgres.
Comment: This actually retrieves 8 days including the current day, not 7.
Comment: Good catch. Edited it to reflect that.
Answer: Assuming returned_date is data type date, this is simplest and fastest:
SELECT * FROM books WHERE returned_date > CURRENT_DATE - 7;

now()::date is the Postgres implementation of standard SQL CURRENT_DATE. Both do exactly the same in PostgreSQL.
CURRENT_DATE - 7 works because one can subtract / add integer values (= days) from / to a date. An unquoted number like 7 is treated as numeric constant and initially cast to integer by default (only digits, plus optional leading sign). No explicit cast needed.
With data type timestamp or timestamptz you have to add / subtract an interval, like @Eric demonstrates. You can do the same with date, but the result is timestamp and you have to cast back to date or keep working with timestamp. Sticking to date is simplest and fastest for your purpose. Performance difference is tiny, but there is no reason not to take it. Less error prone, too.
The computation is independent from the actual data type of returned_date, the resulting type to the right of the operator will be coerced to match either way (or raise an error if no cast is registered).
For the "past week" ...
To include today make it > current_date - 7 or >= current_date - 6. But that's typically a bad idea, as "today" is only a fraction of a day and can produce odd results.
>= current_date - 7 returns rows for the last 8 days (incl. today) instead of 7 and is wrong, strictly speaking.
To exclude today make it:
WHERE returned_date >= current_date - 7
AND   returned_date <  current_date

Or:
WHERE returned_date BETWEEN current_date - 7
                    AND     current_date - 1

To get the last full calendar week ending with Sunday, excluding today:
WHERE returned_date BETWEEN date_trunc('week', now())::date - 7
                    AND     date_trunc('week', now())::date - 1

BETWEEN ... AND ... is ok for data type date (being a discrete type), but typically the wrong tool for timestamp / timestamptz. See:

How to add a day/night indicator to a timestamp column?

The exact definition of "day" and "week" always depends on your current timezone setting.
Comment: Thanks this helped me very much.!
Answer: What math did you try?
This should work
select * from books where current_date - integer '7'

Taken from PostgreSQL Date/Time Functions and Operators


Examples of complex functions with infinitely many complex zeros

Question: What are some examples of complex functions with infinitely many complex zeros? There are no particular restrictions on the functions I am just curious and having a hard time finding examples. Also what can be said about a complex function with infinitely many complex zeros, must they have any special properties?
Answer: There is nothing special about functions with infinitely many zeros. In fact, it is the norm.
If $f(z)$ is any entire function which isn't a polynomial, then $\infty$
is an essential signularity of $f(z)$. By Big Picard's theorem, $f(z)$ takes on all possible values of $\mathbb{C}$, with at most a single exception, infinitely often.
This means if your $f(z)$ is entire, not a polynomial with finitely many zeroes, then $f(z) + \alpha$ for any constant $\alpha \ne 0$ has infinitely many zeros.
Comment: The answer may not have explicit examples, but it helps me understand whats going on with complex functions in a more general way, for this reason I think it is a fitting answer.
Comment: Thank you for the answer! I do not know much about complex functions and did not know about Big Picard's theorem, thank you for the link!
Answer: Remember that the real numbers are a proper subset of the complex numbers and so infinitely many real zeros satisfies the criterion of infinitely many complex zeros. Hence:
$$\operatorname{f}(z) := \sin z $$
If you want infinitely many non-real, complex zeros then note that $\cos(\operatorname{i}\!z) \equiv \cosh z$, and so
$$\operatorname{g}(z) := \cosh(z)-1$$
has infinitely many non-real complex zeros: $z \in \{2\pi\operatorname{i}n : n \in \mathbb{Z}\}$
Comment: Thank you for the example! I think I was a little of, I really should have asked about functions with infinitely many complex zeroes. I will edit my question. EDIT: Just saw your edit, that's the kind of example I was looking for thank you!
Comment: @Twiltie My pleasure. I'm glad that I could help.
Answer: $f(z)=0$ for all $z \in \mathbb C$
Comment: Thanks for the answer! But I was hoping for something a little less trivial.


Representing images as graphs based on pixels using OpenCV's CvGraph

Question: Need to use c for a project and i saw this screenshot in a pdf which gave me the idea
http://i983.photobucket.com/albums/ae313/edmoney777/Screenshotfrom2013-11-10015540_zps3f09b5aa.png
It say's you can treat each pixel of an image as a graph node(or vertex i guess) so i was wondering how
i would do this using OpenCV and the CvGraph set of functions. Im trying to do this to learn about and how
to use graphs in computer vision and i think this would be a good starting point.
I know i can add a vetex to a graph with
<code>int cvGraphAddVtx(CvGraph* graph, const CvGraphVtx* vtx=NULL, CvGraphVtx** inserted_vtx=NULL )
</code>
and the documentation says for the above functions vtx parameter
"Optional input argument used to initialize the added vertex (only user-defined fields beyond sizeof(CvGraphVtx) are copied)"
is this how i would represent a pixel as a graph vertex or am i barking up the wrong tree...I would love to learn more about
graphs so if someone could help me by maybe posting code, links, or good ol' fashioned advice...Id be grateful=)
Answer: http://vision.csd.uwo.ca/code has an implementation on Mulit-label optimization. GCoptimization.cpp file has a GCoptimizationGridGraph class, which I guess is what you need. I am not a C++ expert, so can't still figure out how it works. I am also looking for some simpler solution.


How to connect my private ethereum network to ethereum android app?

Question: I want to access my smart contract through a mobile app, which is on my private network. There is ethereum android app, can I connect that app to my ethereum network or if there any other app through which I can access my smart contract on the private network.
Comment: Did you get any idea about it?
Comment: i did not get any ideas.
Answer: First of all let's think about the mobile app as a client.
The client running web3 needs to connect to a node.
This node is brought by a Provider, whether HTTP, WebSocket or IPC.
The provider defines the remote node and port.
What you need to do is basically running a node on your server using geth or parity for example OR use a node provided by Infura.
Then in the mobile app, provide the node address and inject that provider into the web3 instance. Then you'll have a successful connection.
That's ideal, but it comes with challenges. Like managing the user's private keys. This will be your responsibility in the app, to secure and encrypt those keys. Also you need to provide a way to backup/restore keys.
Private keys are needed to sign raw transactions sent to the blockchain.
Now what we only need to finally answer your question is what framework should you use on Android to do this task? Luckily someone was brave enough to work on a java based web3 library called web3j: https://github.com/web3j/web3j
Let me know if you need more details!


Is a reboot required after edit/saving linux iptables?

Question: If I edit iptables and then save them then must I reboot for changes to take place?
Comment: What do you mean if mean by 'edit'?
Comment: sorry... on Ubuntu I issued the iptables-save command after adding a rule.  But on my other machine I was still not able to connect.  So that made me wonder about general inner workings of iptables.  Most docs don't specifically say whether or not a reboot is required.  I'm new to this iptables command. Thanks.
Answer: Changes to iptables take effect immediately when they are run.
However, your language of "edit and save" makes me think you are editing a conf file or script of some kind rather than actually running the iptables commands.
If you are making your changes in a script, you must make sure that script gets run in order for the changes to take affect. The rules are enforced as soon as the actual commands are sent to the kernel. You will need to figure out how to run the script or apply whatever conf changes you have saved to a file.
Comment: A reboot actually CLEARS all `iptables` rules. On first boot the tables will always be empty, you ALWAYS have to set all the rules after booting. That's what the iptables-save helper script thing does ... takes all the current rules and dumps them to a file that can then get re-run on the next boot. Rebooting doesn't make anything take effect, it actually forgets EVERYTHING. If you run `iptables -L` to list what is in the tables, whatever is there is what is being enforced that instant. This is very easy to prove in practice.
Comment: @fooledbyprimes: iptables is the user interface to the kernel netfilter subsystem. Changes happen in real time because you are actually modifying part of the kernel.
Comment: "Changes to iptables take effect immediately when they are run."
I tried to verify this in the docs, man docs, webs, etc.   But where in the world can I verify this?  Thanks.
Comment: If you have something that is not "taking effect" it's because you have entered the rules in the wrong order. First match wins. If you have a block rule that matches, the packet will get dropped even if some rule you added later allows it. You need to specifically allow the things you want before you deny everything else. You may need to flush the tables and start over if you have to change the order of something you've already entered. You can also specifically delete rules form the table and added them back in the right order.
Comment: @fooledbyprimes: If you really, really want to "verify" the behavior of iptables do something like 1. from a machine with no rules loaded, ping another 2. in another terminal, issue an iptables command to the OUTPUT chain to drop all packets to the pingee. Effect will be instant.


Is it possible to download and transfer PSN games to PSVita from PC?

Question: Is it possible to download PSN games (PSVita, Vita-compatible PSP games and minis) via PC software (i.e. Media Go) and then connect Vita with the PC and transfer Vita-compatible games (either by using Media Go, Vita Content Manager Assistant or some other way)?
Answer: No, it's not possible to do so because PS-Vita games can only purchasable via a PS3 with a valid account. You can only transfer PSN games via a PS3 (this restriction is not applicable for media contents, videos, music etc.)
See here http://mediago.sony.com/enu/features/devices for all the devices that supports MediaGo to transfer content, and PS Vita is not listed.
Comment: @sarmackie Well, you can always use a USB dongle to bridge a wired network connection from PC to a wireless one, like what Nintendo was offering when the DS came out.
Comment: I am not sure that's correct - I believe I did purchase a PSP game from PS Store, downloaded it and transfered to my PSP using Media Go. You can enter the Store and log in to your account in similar manner as on PSP. I wonder if it is also possible with Vita.
Comment: See here http://goo.gl/wqgpX for all the devices that supports MediaGo to transfer content, and PS Vita is not listed.
Comment: Ok, it seems Media Go does not work with Vita, but you can access PS-Store using it. It just won't work with Vita games. Now the question is - is the Content Manager Assistant or any other PC software compatible with Vita and PSN games?
Comment: As far as I know there isn't a way. Sony might integrate PSN game transferring support in MediaGo in future.
Comment: OK, if there is no other input I guess you can update your answer and I will accept it. Tough luck for the non-WiFi non-PS3 Vita owners.
Comment: Yeah, don't know how could I forgot about such a simple workaround :) Thanks a lot!
Answer: You can login and purchase games from PC, but it just adds them to a download list - then you can transfer from the PS3 after they are downloaded, or go direct to vita.


Critical Failures on Attribute rolls

Question: As it only says, in the Savage Worlds Pathfinder book, if you roll a 1 on both a skill and wild die, does that mean you can't critical fail an attribute roll and hence can reroll with a Bennie? Or does the standard rule book take precedence?
Answer: Misquote
If that was what the rules said then that would be the case. But the rules do not say that.
 Savage Worlds, page 88, Critical Failure:

A Critical Failure occurs when a Wild Card rolls a 1 on both the Trait die and Wild Die of a Trait roll.

Trait is a technical term that includes both Skills and Attributes.
Comment: You may want to look for errata for your copy of PFSW - that text is supposed to be identical. If you're using a pdf, download the most recent version.
Comment: ah - i was looking in the SWPF book - may be I should change my question.
Comment: just looked in the my hard copy and the latest 1.7 version of the pdf and on page 118 it still says 'skill'. I also checked the latest v6.0  pdf of SWADE page 88 it says 'trait'.
Answer: New answer for the much-revised question.
Partial Quote
What my copy of Pathfinder for Savage Worlds says is (page 118):

A Critical Failure occurs when a Wild Card rolls a 1 on both the skill die and Wild Die of a Trait roll.

There are two noteworthy punctuation notes. First, "skill" is lower-case, indicating a common word and not a rules term (per the Pinnacle Style Guide). Second, the statement includes "Trait roll", which is a rules term that includes both Attributes and Skills.
Therefore, Critical Failures can happen on Attribute rolls when playing Pathfinder for Savage Worlds.
Comment: normally I would agree but there are other text difference between SWADE and SWPF, and in these cases they have been deliberate changes.

Critical Failures on Attribute rolls


closing a question which already contains the answer

Question: Occasionally, a question pops up like this one.  Basically, the user posts a question about code that works.  It seems that this question should be closed, but it's difficult to pick a reasoning to close it.  Perhaps adding a statement like "this question answers itself" in the "not a question" category would be helpful?  (Or am I out in right field on this one, and the question really shouldn't be closed after all?)
Comment: "Too localized" is the reason I usually select in a case like this.
Answer: It might work for you (and everybody else :p) but is obviously not working for the OP (or not working as expected, etc), or they wouldn't be asking a question.
You are not helping the OP by voting to close.  A comment that it works for you and a request for some clarification on the issue the OP is seeing seems to be the way to go to me.  If you don't get any reply, THEN vote to close.  But voting to close without attempting to help the OP at all seems a bit draconian (and rude).
I've seen many people post working code and their question boils down to "why does this work?".  I think these kind of questions are the best.  The poster is obviously trying to learn and should be encouraged to do so.
It's a lot like that "give a man a fish and you've fed him for a day, teach him to fish and you've fed him for a lifetime".  You throw some code at them and they can deal with that particular situation, you teach them why and how and they can then apply it to other, different situations.
Comment: But if others have already made that comment, there's not much more to say ... I'm not advocating closing a post without (someone) providing a good reason.  In fact, I'm advocating the opposite... I don't like that the closed message and the comments might say 2 different things.  Also, how long do you wait before you make the close vote?  10 minutes?  30 minutes? Longer?
Comment: Well, I used to think like that too (see the [question I posted yesterday](http://meta.stackexchange.com/q/145065/167534)). However, sometimes waiting is not the best option (not sure about this particular case).
Comment: I *was* going to say 24 hours as I happen to not have the luxury of being a programmer by profession (or have a computer available to me all day), so I've been known to post a question and leave for work, not to return for 8+ hours.  But a better thought occurred to me...  If there's a request for clarification, check the request date/time against the users "last seen" time.  If the user hasn't been back since the question was asked, leave it be.  If they've been back and not provided the requested clarification, vote to close.  Of course if they haven't been back for a week...  :p


UK groups that investigate extraterrestrial life

Question: What are some UK based groups that research astrobiology, especially the chance of extraterrestrial intelligence?
Comment: The Open University has several researchers in astrobiology. (At the chemical/cellular level, not advanced creatures and civilisations.)
Comment: Not sure if this is good enough for a full answer but the definitive group appears to be the [UK SETI Research Network](http://www.seti.ac.uk/).
Answer: Extraterrestial intelligence is a hard research topic as the search for evidence is not straight forward in any way. The search for intelligent life as far as I know is limited to observations in radio and for that you want to see if any SETI members are UK based.
However if you're more into astrobiology in general you might wanna look up the UK Centre for Astrobiology which is based in Edinburgh. I don't know any of the faculty but I do know that they are hosting a meeting for early career scientists in 2017. There are also some smaller research groups based in the UK but you might wanna check out the specific research aim for these (e.g. the group at Imperial College in London is focused on Mars) as it might not be the area within astrobiology that interests you the most.
There is also Mark Burchell who is a professor at the University of Kent. His group did some exciting work on Panspermia (the idea of life travelling through space) that I happened to read earlier this year. Note that this is focused on microorganisms so this is probably as far from "intelligence" that it gets.
But you can try to look up departments at different universities. You probably want to look under astronomy or sometimes physical or Earth science as the research aims of some groups put them more in e.g. Earth science than actual astronomy. Sometimes you can also find smaller groups under biology or life science.


Receiving money on PayPal in Croatia?

Question: I can send money with PayPal from Croatia, but can't receive it.  Is there any workaround?
Answer:
Can you open a bank account in another country?
Do you have anyone you trust who would be willing to send the money to you?
Can you deposit USD checks? If so, you could have Paypal send a check to a US address (again you'd probably need a friend).
Answer: The workaround that I use in a recent time is very simple, effective and it is spreading very quickly - Payoneer.
What you will need is http://www.payoneer.com/USPService.aspx which will get you US bank account that you can link to your paypal account.

Receiving money on PayPal in Croatia?


How is the United States net foreign wealth affected by a depreciation of the US Dollar?

Question: My thought here is that if the dollar were to depreciate, then the value of US liabilities would decrease while the value of their assets would increase. Moreover, the US trade balance would become less negative in that their debts would be "cheaper." Is this intuition on the right track?
Comment: Value measured in what? USD?
Comment: @Giskard Yes, USD
Comment: What are the assets and liabilities denominated in? USD or foreign currencies?
Comment: What kinds of assets and liabilities?
Answer: If a dollar depreciates then:

Financial assets and liabilities (loans, bonds) denominated in US dollars are still worth the same number of US dollars.
Financial assets and liabilities (loans, bonds) denominated in foreign currencies are both worth more US dollars (because it costs more US dollars to get a foreign dollar).
Tangible assets (e.g. real estate) are worth more US dollars because each dollar is worth less "real stuff".
Tangible liabilities (e.g. an obligation to produce widgets) are worth more US dollars because it will cost more US dollars because each US dollar is worth less.

Essentially, if a currency depreciates, it means everything goes up when measured in that currency... except for contracts that refer to a specific amount of currency (like bonds). The foreign real estate is still worth one piece of foreign real estate, but now one piece of foreign real estate equals more dollars.


How to create custom rule event

Question: I'm working on integration of my D7 module with Rules. I have custom SQL table with 2 columns node_id and status. Status may have values 0, 1, 2, 3. How can I create event with hook_rules_event_info to react on status change? I.e. status changed from 0 to 1 -> send email to node owner.
Answer: If this is a formal drupal node you can use node update event , then check if the node->status is changed or not (you have 2 versions of node in this event one referring to unchanged and second refers to changed noge)

How to create custom rule event


How to make chrome truly full screen in lubuntu

Question: When I press F11 to go fullscreen in Chrome in Lubuntu, the LXPanel taskbar at the bottom disappears, yet all the menus, tabs, and the search bar all still visible, as if Chrome is in windowed mode. How do I get Chrome to truly go fullscreen as is possible in Windows and OSX?
Answer: ianorlin's answer is on-point, but I had a lot of trouble understanding what they were saying. Not feeling comfortable with Edit-by-Rewrite, I am posting my own answer.
The problem is that Openbox, the Lubuntu window manager, sees you press F11 before Chrome does. Openbox then performs its own fullscreen process and never informs Chrome about it.
The fix, then, is to either change Openbox's fullscreen key or to change Chrome's (to something Openbox isn't using).
The file ~/.config/openbox/lubuntu-rc.xml contains Openbox's keyboard configuration information. You may wish to make a back-up of it prior to changing things since you don't want to mess it up.
Look for the stanza that says:
<keybind key="F11">
  <action name="ToggleFullscreen"/>
</keybind>

It may be inline with the rest of the file, like so:
</keybind><keybind key="C-Escape"><action name="Execute"><command>lxpanelctl menu</command></action></keybind><keybind key="F11"><action name="ToggleFullscreen"/></keybind><keybind key="A-C-Delete">

But you can break it out onto its own lines to make it more visible.
Once you've made the changes described below use
openbox --reconfigure

to activate/test them.
Now, change the stanza mentioned above to read:
<keybind key="W-F11">
  <action name="ToggleFullscreen"/>
</keybind>

This will make the Windows/Super key into a modifier, so you press Windows+F11. I like this one because (probably) nothing is going to be using that key combo, whereas Shift+F11 and F11 are both used at the application level.
If you did want Shift+F11 to be your fullscreen key, you'd use:
<keybind key="S-F11">
  <action name="ToggleFullscreen"/>
</keybind>

More information about what actions you can perform using this config file is available here.
Comment: Yes that is better written than my answer.
Answer: Actually for lubuntu what is happening is openbox is seeing the f11 makes openbox the window manager behind lxde make the window fullscreen as you describe. However, you may need to change it to another key to still be able to change the key many keyboard shortcuts are listed in https://help.ubuntu.com/community/Lubuntu/Keyboard To do this you will need to edit ~/.config/openbox/lubuntu-rc.xml but it is a good idea to make a backup copy of this file as errors can end up with breaking window managment.

<keybind key="S-F11">
  <action name="ToggleFullscreen"/>
</keybind>

To bind shift plus F11 to make normal apps for fullscreen. Then to have the openbox window manager in the background and run the command openbox --reconfigure. To apply the new keyboard shortcut.
Comment: `F11` is already `ToggleFullscreen` on Lubuntu 14.04. I tried anyway to add your entry for `Shift+F11`, but it does not work.
Comment: Possibly helpful contrast: In my WM (notion), WinKey+f is bound to make-the-current-window-fullscreen, and F11 is unbound.  If I focus a chrome window and press WinKey+f, I get fullscreen with tabs and location bar like you describe. If I press F11, I get "true" fullscreen.


Find Last Index Of by Regex in Java

Question: i have a string %/O^/O%/O. I want to find the last / to split the string. First attemp was: \/[POL]$ but that gets it inclusive the "O" which is obvious. Has somebody a tip?
Answer: I agree that using the standard String.lastIndexOf() method is your best course of action, but I have recently had use for the Regex part (namely, I wanted to find the last non-alphanumeric character in a string).
I ended up writing it myself, and thought to share, in hopes that it would serve to help others:
/**
 * Indicates that a String search operation yielded no results.
 */
public static final int NOT_FOUND = -1;

/**
 * Version of lastIndexOf that uses regular expressions for searching.
 *
 * @param str String in which to search for the pattern.
 * @param toFind Pattern to locate.
 * @return The index of the requested pattern, if found; NOT_FOUND (-1) otherwise.
 */
public static int lastIndexOfRegex(String str, String toFind)
{
    Pattern pattern = Pattern.compile(toFind);
    Matcher matcher = pattern.matcher(str);

    // Default to the NOT_FOUND constant
    int lastIndex = NOT_FOUND;

    // Search for the given pattern
    while (matcher.find())
    {
        lastIndex = matcher.start();
    }

    return lastIndex;
}

/**
 * Finds the last index of the given regular expression pattern in the given string,
 * starting from the given index (and conceptually going backwards).
 *
 * @param str String in which to search for the pattern.
 * @param toFind Pattern to locate.
 * @param fromIndex Maximum allowed index.
 * @return The index of the requested pattern, if found; NOT_FOUND (-1) otherwise.
 */
public static int lastIndexOfRegex(String str, String toFind, int fromIndex)
{
    // Limit the search by searching on a suitable substring
    return lastIndexOfRegex(str.substring(0, fromIndex), toFind);
}

Also, it may be possible to make this method faster by first reversing the input string, then taking the ending index of the first group (rather than going over all the groups).
But to do that you would have to reverse the pattern as well; that can be simple in some cases (like my case of searching for a single character), but may prove problematic in others.
Answer: /(?=[^/]*$)

will match a / that isn't followed by any more /s. To split on it, use
String[] splitArray = subjectString.split("/(?=[^/]*$)");

Answer: The core question is good although the example you gave doesn't
need it. Java's indexOf doesn't take regular expressions. Answering
just subject part of the question, here's what you would need:
/**
* Version of indexOf that uses regular expressions for the search
* by Julian Cochran.
*/
public static int indexOfRegex(String message, String toFind) {
  // Need to add an extra character to message because to ensure
  // split works if toFind is right at the end of the message.
  message = message + " ";
  String separated[] = message.split(toFind);
  if (separated == null ||
      separated.length == 0 ||
      separated.length == 1) {
    return -1;
  }
  return separated[0].length();
}

If you need the last index:
/**
* Version of lastIndexOf that uses regular expressions for
* the search by Julian Cochran.
*/
public static int lastIndexOfRegex(String message, String toFind) {
  // Need to add an extra character to message because to ensure
  // split works if toFind is right at the end of the message.
  message = message + " ";
  String separated[] = message.split(toFind);
  if (separated == null ||
      separated.length == 0 ||
      separated.length == 1) {
    return -1;
  }
  return separated[separated.length - 1].length();
}

Comment: @Julian Cochran.  I bought a used book and it has your name and a picture was in it of you and your daughter and son?  If u, I would like to get the pic to you.  Sorry for the noise hear SE, but no other way to find...
Answer: Do you need to use regular expressions for this?  Would String.lastIndexOf("/") work to find the index, and then use String.substring(int start, int end) with the result?  Or is your actual data different and more complicated, requiring regular expressions?  With what you provided to split the string on the last /, here's code:
int lastSlash = mystring.lastIndexOf("/");
String start = mystring.substring(0, lastSlash);
String end = mystring.substring(lastSlash + 1, mystring.length);

Answer: If all you want is to find the last instance of a character regex is overkill, you should just use String's lastIndexOf
int pos = myString.lastIndexOf('/');

Comment: +1 - this is more efficient. On the other hand, a regex that finds the last `/` can be fed directly to `.split()` - it's probably personal taste as to which is more readable (compare my solution with justkt's).
Answer:         String name ="rami is good boy, and he is working for andorid,is completed";
    int lastSlash = name.lastIndexOf("is");
    String start = name.substring(0, lastSlash);
    String end = name.substring(lastSlash + 1, name.length());
    StringBuffer sb = new StringBuffer(name);
    sb.replace(start.length(), name.lastIndexOf(end)+1, "");

    System.out.println(sb.toString());

Answer: ref: https://github.com/apache/commons-lang/pull/273/files
   public static int lastIndexOfAnyChar( final CharSequence str,final String searchChars) {
    return searchChars == null ? INDEX_NOT_FOUND : lastIndexOfAnyChar(str,searchChars.toCharArray());
}

/**
 *
Search a CharSequence to find the last index of any
 * character in the given set of characters.

 *
 *
A {@code null} String will return {@code -1}.
 * A {@code null} or zero length search array will return {@code -1}.

 *
 *

 * StringUtils.lastIndexOfAnyChar(null, *)                = -1
 * StringUtils.lastIndexOfAnyChar("", *)                  = -1
 * StringUtils.lastIndexOfAnyChar(*, null)                = -1
 * StringUtils.lastIndexOfAnyChar(*, [])                  = -1
 * StringUtils.lastIndexOfAnyChar("zzabyycdxx",['z','a']) = 2
 * StringUtils.lastIndexOfAnyChar("zzabyycdxx",['b','y']) = 5
 * StringUtils.lastIndexOfAnyChar("aba", ['z'])           = -1
 *

 *
 * @param cs  the CharSequence to check, may be null
 * @param searchChars  the chars to search for, may be null
 * @return the last index of any of the chars, -1 if no match or null input
 */
public static int lastIndexOfAnyChar( final CharSequence str,final char... searchChars) {
    if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {
        return INDEX_NOT_FOUND;
    }
    int csLen = str.length();
    int csLast = csLen - 1;
    int searchLen = searchChars.length;
    int searchLast = searchLen - 1;
    for (int i = csLast ; i >= 0 ; i--) {
        char ch = str.charAt(i);
        for (int j = 0; j < searchLen; j++) {
            if (searchChars[j] == ch) {
                if (i < csLast && j < searchLast &&  Character.isHighSurrogate(ch) ) {
                    // ch is a supplementary character
                    if (searchChars[j + 1] == str.charAt(i + 1)) {
                        return i;
                    }
                } else {
                    return i;
                }
            }
        }
    }
    return INDEX_NOT_FOUND;
}

Find Last Index Of by Regex in Java


SQL Server Backup Database over ODBC

Question: I'm trying to write a program that is able to import and export a specific database, plus users and logins, from a Microsoft SQL Server database. I have an abstraction layer between my code and ODBC that much of our other software uses. The abstraction layer normally runs with autocommit off and handles transactions on its own, but since the BACKUP command doesn't like being run in any transaction, I"m using another method of the layer, called executeDirect, that runs it with autocommit on.
The method uses the SQLExecDirect function to run the BACKUP command. When it's done, the function returns SUCCESS_WITH_INFO, since the BACKUP command likes to give three lines of output. The code then attempts to get the output with SQLGetDiagField and is able to gather the first line from record #1, but there is no record #2.
The last thing the method wants to do is reset the connection to autocommit off, but when it attempts that, an error occurs, saying "Connection is busy with results from another command", SQL State is "HY000". So, obviously, the connection wants to remit the other two lines of output, but I don't know how to let it do so.
Answer: The BACKUP DATABASE command works as a batch, requiring a call to SQLMoreResults to continue with the backup.

SQL Server Backup Database over ODBC


How re-order activities in android?

Question: I have a simple problem. In my app I have 3 activities A,B,C. Activity A is the main activity.On some action on activity A it takes to activity B and then after some action it goes to activity C. When I am at activity C, I pressed home button and the home screen came. Now when I click on the app icon again it starts activity C again. But I want the activity A should be coming as I have to ask the password. I want all the activities should be finished when I press home button and when I click app icon again the login activity i.e activity A should be coming. Can anybody give me some solution?
Answer: If your firing intent to go from one activity to another like this ----->
Intent intent = new Intent(this, B.class);
startActivity(intent);
then add this thing to your code then all thing will get fine ---->
addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) like this ----->
Intent intent = new Intent(this, B.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivty(intent);
NOTE---> here (this) means your A activity.
Answer: I changed in Manifest file and I removed the intent filters from my activity B and C as launcher. Now whenever I press the app icon i reach to login activity.
Answer: Activity Lifecycle:
http://developer.android.com/reference/android/app/Activity.html
Use these callback functions to recognize what happens to your activity. When the user hits the homebutton, call finish() in your activity C. Activity B will regonize that C was finished and will finish() too. Than you are back at Activity A.
Answer: You can control your app while is onPause status (when the user press home).
<code> protected void onPause(){
    super.onPause();

}
</code>
Here you can do all the stuff you want.
Another way is to intercept "Home" button, and before the app goes in background it quickly come back to activity A.
Answer: Much of this answer is based off of the lifecycle of an activity.
When a user hits the home button, at the very least, an activity will be paused. Use the onPause() function to detect this. There are a couple of things which you could do from this point, the most basic would be to just end your activity C. Calling the finish() will kill the activity. This will allow you to navigate through the activity as normal, but will kill it if you quit it.
If the activity gets more complex, the onPause() might be called for other reasons, like memory is needed. It might be worth adding a bit of extra logic to detect if the person is in a sub function or not.
An alternative is to use the function onRestart(), and simply finish the activity. This might spare some of the oddness.

How re-order activities in android?


Is it possible to execute Azure automation runbook on Visual Studio?

Question: I am considering about two cases. One is edit runbooks on Visual Studio, then execute them to perform Automation task directly. Another one is that edit runbooks on Visual Studio, then I use PowerShell to execute those runbooks.
I'm not sure about these two options. Can anyone help me? Any help would be grateful.
Thank You
Comment: Worth reading [this](http://azure.microsoft.com/blog/2014/07/24/azure-automation-integrating-runbook-source-control-using-visual-studio-online/)..
Answer: Azure Automation runbooks are just PowerShell Workflows, which can be run locally on your machine as well. The only thing special about runbooks compared to PowerShell Workflows is in runbooks you can use the "Automation activities" (Get-AutomationVariable, Get-AutomationPSCredential, etc).
We don't have a blog post about this out for Azure Automation yet, but we do for Service Management Automation (the onpremise version of Azure Automation), which is very similar: http://blogs.technet.com/b/orchestrator/archive/2014/03/27/authoring-sma-runbooks-in-the-powershell-ise.aspx


What is the role of resistor in this schematic?

Question:
I am a beginner in Electronics and I am not able to understand why do we need to put this resistor(Resistor which comes after the switch) in this schematic? Does it save IC from current? but how ? Thanks
Answer: LED resistor
I originally thought you were asking about this resistor.  I'm leaving the explanation here since it might be useful anyway.
The point of this circuit is to let you get some intuition about flip-flops.  To do that, the LED is hooked up so that it lights when the flip-flop output is in the high state.
However, the output of the flip-flop tries to be a voltage source, which is a bad match for driving the LED.  It's also at the wrong voltage anyway.  The resistor drops the voltage between the flip-flop output and the LED's on voltage, while letting a predictable amount of current flow in the process.
Let's say the flip-flop is powered from 5 V, that you want to put 5 mA thru the LED when the output is high, and that the LED is a common green type that will drop about 2.1 V when on.  That means the resistor will have 5.0 V - 2.1 V = 2.9 V across it.  We already said it needs to allow 5 mA thru it in that case.  From Ohms law, 2.9 V / 5 mA = 580 Ω.  The standard value of 560 Ω is close enough and should work fine, as long as the flip-flop output can source the 5 mA.  Many digital outputs can do that, but not all, so you have to check.  If the flip-flop can't source enough current to drive the LED to sufficient brightness, you can use a transistor in between.
Switch resistor
I see now you asked about the other resistor, the one that is connected to the switch.  That's a pulldown resistor.  It makes the flip-flop input reliably go to the low state when the switch is not pressed.  It's value is a compromise between pulling the input hard enough low when the switch is off, but not requiring too much current thru the switch when it is pressed.
I go into a lot more detail about pullup (same thing, just the switch and resistor flipped) resistors at https://electronics.stackexchange.com/a/23647/4512.
Answer: The resistor is called a pull-down resistor.  If it were not there, when the switch is open there would be no defined voltage on the pin the switch is connected to.  This is called a "floating" input and generally does not guarantee that the input is in one state or the other.  By adding the resistor we know that the input will be low when the switch is open.
Comment: + 1
In short this make assurance that we should have standard logic "1" when button is pressed and "0" otherwise. In this case we are sure about the digital output. Being Flip-Flop output should be only logic "0" or "1" and nothing between them ! It's the best solution for making only two possibilities in output (Input also).
Answer: If there would be just a wire from the switch to ground and not a resistor, the switch would short-circuit the positive voltage and ground and nothing good would come of it.
On the other hand, if there would be nothing (no wire and no resistor) from the switch to ground, there wouldn't ever be a reliable low level in the clock input.
Answer: The resistor 'pulls' the input down to ground (LOW or logic '0'). When the switch is closed there will be a positive voltage at the input (HIGH or logic '1'). When it is released the input goes back to ground.
Answer: With the switch not pressed, and the resistor removed (replaced by an 'open'), the input would not be connected to anything. With modern CMOS chips, that will result in the input picking up stray signals, often the over-present 50/60 Hz 'hum'. That is not what you want!
As PkP explains, replacing the resistor with a short (wire) is not a good alterntive iether.


Web Pages That Just Do Too Much Stuff

Question: Concerning pages that build a web application:
Lately, I have found myself creating web pages that are simpler than the ones I used to. Before, I would try to jam as much functionality into a single page as I could to prevent from having lots of pages.
I am starting to realize that this was just making things way more complex, convoluted, and confusing than it had to be. Why not have more pages? I think the reason that I was doing this was because I didn't want the user to have to browse to other pages; just to have all the functionality they needed on a single page.
Well, these good intentions turned into an overly confusing interface for the user and very unmanageable source code. I am a new developer and I am trying to be very reflective of what I am doing so that I can improve. If it makes a difference, I am developing in ASP.net (though these are probably considerations for any platform).
My questions are:

Am I overthinking these things?
Has anyone else found themselves doing this?
Where is the happy medium?
Answer: There is no expert who can give you a rule that works in all places at all times. I have been known in my industry for years for "easy" interfaces and we've won significant amounts of business for it (as well as 5 "Best in Class" awards). I have also had people within my company and outside of it tell me - for years - that they like my work but wish that I would "jazz it up" with more graphics and such.  What always amazes me is how little connection people see between the two.
So...a few rules of thumb:

A page should do one main thing.
A page may well have multiple links related to the main thing
Menuing and link layout should be consistent across pages
Simpler is better than more complex
Pages should be visually appealing and inviting
Rule 4 is more important than rule 5.

For example, my product provides an interface that lets people define classes and events to be displayed in a calendar.  I could have one page that lets you Review, Add, Update, Delete and Edit the classes.  Indeed, in some simpler areas, I've used the gridview to let people manage everything in a grid. However, classes have too much information to do this and still follow the rules above.
So,

The main idea is: "Here is a list of classes for this location"
The links are "Add New" shown above and to the right of the grid, Change and Delete are links within each row. This is consistent across the app.
Menuing for the system as a whole is always across the right/top. Nothing else appears on the class/event page except for standard elements common to all pages (a logo, a header, a footer).
The grid is nicely styled but there are no spurious graphics (4,5,6)

A few last things about UIs and graphic design.
First, develop your own vision and be consistent across pages and apps.
Second, do not be afraid of simplicity.
Next, when soliciting advice from others keep in mind that you do not want their advice - you want their impressions: you want to understand the way they perceive the interface.  Advice is sometimes good but, more often than not, actually harmful. In my experience, everyone thinks that they are a UI expert.
When you do your hallway (or formal) useability testing you should discount almost all advice to the effect that "you should make that stand out more."  As you'll see, it will quickly become "and that," "and that," "and the other."  If you follow this advice, you'll end up with a mess due to Brittingham's first rule of design: If everything is important than nothing is. (There you go: when explaining why you can't make someone stand out more, just tell them that "it violates Brittingham's first rule of design!")
Hope this helps!
Answer: You hit the nail on the head. Use the KISS principle. (Keep It Simple Stupid)
I've done this in the past as well and not only does it make for a hideous UI, but confusing as to what operations you can do on the page due to having too much functionality. I've often found in testing that I did not have enough checks to see if the user could perform a certain operation based on the state of the data.
It's easy enough in ASP.Net to write several pages that do simple tasks and then link them together with Response.Redirect or Server.Transfer. Now all I try to achieve on any given page is what the design specs say. So if my page is just a search page, that's all I give. If the user wants to see the details of an item that was returned in the search, then I send them to an itemDetails.aspx page.
Comment: I agree. The only issue I have with multiple pages is saving and retrieving page data from page to page. That can generate a fair amount of code noise. What do you do to work around that?
Comment: Depending on the amount of data that has to be passed back and forth, I typically keep it stored in Sessions. If it's too much, then I'll make a trip to the database and fetch it again.
Answer: You've broken a wall that most software developers have, the one that was blocking your view on usability before. A lot of developers don't really think about it and try to make it easier for them by stuffing functionality in one window, web page or whatever.
The thing is once you start designing software from the user's point of view, i.e. making it easier, several things start to become clear. One is the issue of code maintenance, that code is easily more managable to work on if you don't stuff everything in one giant class or whatever travesty you've been doing. The other is usability itself, that you start to think how the user is actually using your application through the graphical interface. Third is avoiding requirements or scope creep where you stop developing functionality that the user doesn't need.
We as users want simplicity partly because we don't want to spend most of our time muddling through a bad UI when we can get our work done faster with a simple and slick UI. That makes it for us software developers the right thing to do, to think through your design on all levels... that and specs always lie.
Answer: Definitely agree: most attempts at writing pages/forms that do too much have resulted in

bugs and rewrites. Problems occur with keeping all parts valid/synchronized,
excess managing of users' expectations ("I've entered a bill number here and clicked "find person" there but it gives an error message. Why?") when the two are logically separate. These questions cannot arise if only the valid options are visible,
Formatting/layout issues: In ASP.NET pages, trying to layout independent User Controls turns out to be a nightmare ("But we really want all the buttons vertically aligned!" in separate user controls. Good luck with that.)

I'd consider webpages with more than one functionality only if the target audience consists of domain experts, i.e. people that need lots of functionality on one page for better productivity (think data-entry or financial software with lots of variables).
Even then, most of the time, it's possible separate pages into single units.
Answer:
No
Yes - me
I found the happy medium was to use Masterpages, and using it in a way that was familiar to IFrames. That I could have a lots of functionality combined well together. There is a more interesting way of doing this with WPF/Silverlight called Prism
Answer: The amount of functionality on a page is usually not determined by you but by your customer. If the customer demands a single page to update some VeryComplexObject, you're likely to end up with an aspx page that has a significant number of lines. Main reason is that you simply have a lot of event handlers for all actions on the page.
Whether that page is complex is entirely up to you. You should always attempt to make your code-behind file as simple and clean as possible. Some suggestions in that direction:

Move all business code to another application layer.
Use ObjectDataSource for providing data to data-bound controls such as ListView, GridView, Repeater, ... Delegating loading of data to a dedicated object prevents a lot of overhead in your aspx.cs file.

Another suggestion is to use user controls to implement portions of your page. You would usually only do this when you can reuse the user control, but it can also be of great help reducing page complexity (both of your code-behind file as well as your aspx).
Comment: From my stand point, the "customers" don't have specific design requirements. They generalize and I have to figure it all out. That's why I have to determine what goes where among the pages.
Comment: I agree with Ronnie on this one, the customer knows what their end goal is but is our job to make the implemntation as simple to use as possible. Having said that the UI sometimes needs to be more complex but that all depends on the job at hand and the type of person using it.
Comment: In that case I would first create an html mockup for your web site to show the customer what it's going to look like. Involve them as early as possible. You do not want to build a site only to have your customer say: 'that's not what we wanted'.
Answer: Sometimes I think we are all guilty of forgetting just who it is that we develop our applications for. It isn't always easy as a developer to be able to take a step back and have a look at your application as a user might do so. This is why big companies employee hundreds of people to do this for them and they don't always get it right.
Usability is a massive subject but it is defiantly something that all developers need to keep in mind. It has taken me a long time to learn this but when tackling any development task I always try to think about how my users are going to interact with what I am writing. This will make a difference to all levels of your development.
I would suggest reading Don't Make Me Think by Steve Krug. This book won't take you an age to read and it puts across some fantastic ideas that can help you to develop applications that are much easier to use and understand.
I always find that once I have thought about the user experience the decisions about what my web pages are going to do and how they are going to interact are much easier to make.
Answer: Maybe you should ask the people who are using your site.  Or better yet, just watch people use your site.  I think that would tell you if your site is designed well, or if you need to change it.

Web Pages That Just Do Too Much Stuff


What caused scientists to study Black Body Radiation?

Question: After spending hours understanding what exactly Black Body radiation and Ultraviolet catastrophe is, I cannot help myself asking what was the reason that scientists such as Wilhelm Wien and Max Planck studied Black Body Radiation in the first place? What intrigued them to study a hypothetical situation? What were they looking for exactly that made them study this phenomenon?
Answer: In the late 19th century physics seemed more or less complete, in the sense that it explained everything that could be measured. However when applied to a black body the accepted physics of the day predicted that the black body would emit an infinite amount of energy, and this was obviously in conflict with experiment. There's nothing hypothetical about this - theory predicted one thing and experiment measured something different.
This is an exciting situation for any ambitious physicist because it means that something must be wrong with the existing theory. Indeed, resolving the problem required the creation of quantum mechanics, and immortality for Max Planck (Wien is less of a household name, but he still has a law named after him ;-).
Comment: See http://galileo.phys.virginia.edu/classes/252/black_body_radiation.html. Einstein's work was an essential step in clarifying Planck's law and understanding why it worked. Einstein was the first to realise that quantisation of radiation was a universal phenomenon.
Comment: Thanks for your explanation. Can you also mention what was Einstein role in this study? Did he work on this field too or his work was just limited to General and Special Relativity. Cheers
Comment: This answer is false & perpetuates a common myth found in intro physics textbooks. First, people were working on black body way before UV catastrophe (it is in 1858/58 that Stewart and Kirchhoff developed their laws of black body radiation). Second, UV catastrophe in no way motivated Planck, who did not accept the equipartition principle as foundational. See for example [Helge Klagh's short piece on the relevant history](http://www.math.lsa.umich.edu/~krasny/math156_article_planck.pdf). I wish you hadn't answered this question, so someone could give a right answer since I am curious about it.


Comments: "You are not authorized to post comments."

Question: I'm using Drupal 7.
I'm trying to add comments to a node but I get this error back:"You are not authorized to post comments".
I can't find in the code which variables are being checked to don't allow me to post a comment.
Can someone tell me where to look in the code?
Thank you very much
Answer: Go to: admin/people/permissions
Check de permission:

Post comments

Click button "save permission".
Answer: You might be looking for the comment_access() function.

Determines whether the current user has access to a particular comment.

There's not much to it:
function comment_access($op, $comment) {
  global $user;

  if ($op == 'edit') {
    return ($user->uid && $user->uid == $comment->uid && $comment->status == COMMENT_PUBLISHED && user_access('edit own comments')) || user_access('administer comments');
  }
}

Answer: If you have not already checked, go to People>Permissions>Comments.
Comment: It is checked, thanks. The thing is that I want to know where in the code the comments system checks the permissions variables: user->id, global['user'], etc...


Which folders should be scanned for viruses in Ubuntu?

Question: I am using ClamAV to scan for viruses on my machine (Ubuntu 19.10). Are there specific folders that I should scan or should I pretty much scan everything under /?
Answer: Files to scan are:

Files on a NTFS partition
Files transported to Windows machines (ie. when your Ubuntu is acting as a gateway and services your Windows machines in your network).

If you plan to scan Linux systems: viruscanners use windows definitions to scan files so it is a pretty close to useless activity on Linux systems.
Personal observation: As of today I have yet to encounter a virus on any of the Linux (that would be Ubuntu, Debian, SUSE and Fedora) and Unix (that would be SCO, HP-UX, and AIX) systems I maintain for the past 25 years. I did see plenty of Windows virusses on Windows machines.
It is far better to secure your systems with a GOOD admin password and train users of those systems to not provide their user password when it is asked and not expected. And for the admin to ONLY install software from reliable sources. At the moment the only way to get a virus is when you install it yourself. So make sure you do not. And next to that: always make backups. Make sure those are disconnected from your system and preferably stored elsewhere (as in miles/kilometers; not in a nearby cabinet).
The thing to watch out for on Linux systems is something else, namely rootkits. The tool to use would be Lynis, Chkrootkit, and/or Rkhunter. But if you ever find one of those it is best to start from scratch: purge the system and restore a backup you can verify is untouched and then fix the issue it was caused by.
Comment: Thanks a lot for the detailed answer. I had heard that although a windows virus may not impact Linux, but it might move from Linux to another machine. This is why you recommend "Files transported to Windows machines", right? Should I also scan /home  in case someone has downloaded something harmful?
Comment: Also, I did use to scan /home and once ClamAV marked an email downloaded by Evolution as suspicious because a link within the email had a domain other than the senders domain. Is this valid? If yes, is this another use for ClamAV in Linux?
Answer: I do not think that this is necessary at all, but in case that this is your personal workstation, scanning everything in your home directory every once in a while should be enough. Assuming, you only install packages from trusted sources via apt, of course.
Answer: I would include all directories writable by users which could be potentially unsafe.
I consider having an antivirus a becoming necessity - quite some problems which
generate revenue are tied to computation time investment and resource stealing is thus an issue. Me myself am underways here because of Kinsing crypto currency miner after I attempted to set up server infrastructure with latest packages.
From https://serverfault.com/questions/17364/how-do-i-find-all-files-and-directories-writable-by-a-specific-user , this seem to work for me: sudo -u www-data find / -writable -type d 2>&1 | grep -v "Permission denied".
If you need to check for more specific access signatures, there are also answers for that.
When blind, I would go for:

temporary directories - /tmp, /var/tmp
webserver upload directories, webserver cache directories
some /home directories


Why is $\cos(i)>1$?

Question: I always thought that cosine only ranges from $-1$ to $1$. But, I found out that
$$\cos(i)=\frac12\left(e+\frac{1}{e}\right)$$
which is certainly greater than $1$. Why is that?
Comment: $-1\le\cos{x}\le1$ if $x$ is real.  $\cos{z}$ is unbounded if $z$ is complex.
Comment: Complex numbers typically break rules that were established within the confines of the real numbers.
Comment: Cosine has a geometric interpretation as a function on $\mathbb{R}$, but it is also useful to extend it to a function on $\mathbb{C}$. There are all kinds of extensions one could define, but it's very nice to preserve analyticity. This is easily accomplished by using the series expansion $\cos(z)=\sum_{n=0}^\infty\frac{(-1)^nz^{2n}}{(2n)!}$. In fact, someone correct me if I'm wrong, but I'm pretty sure that's the *unique* analytic extension to $\mathbb{C}$. From this falls out all kinds of nice identities like $\cos(z)=(e^{iz}+e^{-iz})/2$.
Comment: Not a bad question, but what do you actually know about complex trigonometric functions? What do you know about complex functions in general? Do you know definitions of exponential and trigonometric functions by their power series? By differential equations?
Comment: If $\cos(z)$ where bounded, it would be constant.
Comment: @BenW it's unique because in fact any two analytic functions that agree on a set with an accumulation point are equal everywhere.
Answer: It's true that the cosine of a real number must be between $-1$ and $1$, but this is not true for the cosine of a complex number. In fact, complex-differentiable functions can never be bounded (unless they are constant).
Here is an analogy, if you like. Let $f(x) = x^2$. Then we learn some rule that $f(x) \geq 0$ for all $x$. But wait a second, $f(i)$ is negative. There's no scandal, since $i$ is not a real number.
Comment: To be precise: non-constant complex-differentiable functions *in $\Bbb C$* can not be bounded.
Comment: +1 for "There's no scandal".
Answer: The general definition of $\cos(z)$ is
$$\cos(z)=\frac{{e^{iz}}+e^{-iz}}{2}$$
When you plug in complex numbers into $\cos(z$), you can get values greater than $1$ or less than $-1$
Comment: @MathLover: If you want to know where the value of $\cos(i)$ *comes from*, then you should say so in your question. As it is, your question seems to be simply about why the value is unexpectedly large.
Comment: @Math Lover to look deeper into this topic, look into hyperbolic trig. cos(ix)=cosh(x). We define a trig function as circular because it parametrizes a circle. Now, just because you put an imaginary input into a trig function doesn't mean it's not a trig function, but then it parametrizes the shape of a hyperbola and is a hyperbolic trig function. sin(ix)=i sinh(x). Putting in an imaginary angle ix gives the hyperbolic version of the trigonometric function and tanh, sech, etc satisfy the same relations to the other hyperbolic functions. Hyperbolic angles are better called imaginary and on cont
Comment: Can you prove this?
Comment: Sure, do you want me to add the proof as part of the answer?
Comment: @Math Lover and anyone else reading, also you can come to this formula by trying to calculate cos(i) from Euler's formula, or just come to it visually. I (think) it's valid because it's an analytic continuation. At z=ix you get the average of the graph $e^x$ and the same graph flipped over the y axis, which isn't bounded. Just try some sort of large values or set its absolute value greater than one and solve algebraically.
Comment: @Math Lover the circular graph, but are real angle inputs on the hyperbolic graph. But they are both still just regular angles, one labeled circular and the other labeled hyperbolic.
Answer: The function $\cos z$ belongs in the interval $\left[-1,1 \right]$ when $z$ is a real number, not necessarily when $z$ is a complex number. An example of this is $\cos i > 1$, as you correctly pointed out.
Answer: Hint
Use the identity$$\cos(x+iy)=\cos x\cosh y-i\sin x\sinh y$$
Answer: Here's what happening visually: cosh is essentially cosine with domain of imaginary numbers, as I said in the comments. Cosine and sine trace the unit circle, and COSH (the specific one you asked about) and sinh for the unit hyperbola. The circle parametrization functions (sin and cos) have range between $-1$ and $1$, whereas the unit hyperbola ($x^2-y^2=1$) is unbounded. You could look up these graphs to see this or even deeper see their shape through their relation to conic sections. So that's some visual intuition if want a reason whilst skipping all the knarly mindless algebra.
*If you continue the graph of the unit circle, putting in outputs outside the unit circles range and getting out imaginary numbers, it traces the unit hyperbola. And it sort of makes sense that if a real angle gives the circle, a hyperbola might come from something imaginary. Anyways, there are also other reasons this particular hyperbola is considered "unit" too. cosh and sinh parametrize the unit hyperbola because subbing the cos and sin for a function of their hyperbolic counterparts in the identity $cos^2(x)+sin^2(x)=1$ you get $cosh^2(x)-sinh^2(x)=1$, which is why the hyperbolic sine and cosine parametrize the unit hyperbola, which again is $x^2-y^2=1$, letting x=cosh(t) and y=sinh(t).

Why is $\cos(i)>1$?


How can I increase the number of USB outputs of a powerbank which only has one output?

Question: I'm talking about outputs which we use to charge our devices with. Would using USB male to two USB female cord be a bad idea?
Comment: First ask yourself if the power bank is capable of supplying enough current to power your two devices. Often are designed to supply 2A from a single USB port. If your two devices require a total of less than 2A (_you should check that figure on your powerbank_), than you probably can split it, connecting the data lines only to one device or shorting them at the powerbank, and not connecting the lines to any device.
Answer: Normally is it a bad idea to use a splitter cable on real USB devices, as the data pins would conflict. If you are using this for power only devices, ones that do not connect the data pins, then yes, a male to two female cable would work. If you are connecting two phones, then no.
Answer: Plugging multiple devices into one powerbank for charging may not work because the resistors which set the maximum current draw may conflict with each other. It (probably) won't hurt anything to try.
You could try a USB hub as an alternative, but it will waste some power on its own.


Why do people behave normally when they come across Ted

Question: Ted is famous and most of the people will be aware that a walking talking teddy bear exists in the world but its not normal to come across a walking talking teddy bear in daily life at a public place. It is strange that people are not even excited to see him. Why is that so?
Comment: I dont mind the downvote but it will be good if someonce can explain the reason. It may help to improve the question.
Answer:
Its not normal to come across a walking talking teddy bear in daily life at a public place

It's not normal in our reality but it is normal in this movie universe
As Wikipedia says*

In 1985, 8-year-old John Bennett is a lonely child living in Norwood, Massachusetts, a suburb of Boston, who wished for his new Christmas gift—a jumbo teddy bear named Ted—to come to life and become his friend. The wish coincides with a shooting star and comes true; word spread and Ted was briefly a celebrity.

Ted has been around for over 25 years and his existence is well known. Certainly he's unique and one could argue that he should be more of a celebrity but people get blase about such things.
* Thanks to @BCdotWEB
In fact, as noted by @Gallifreyan it's stated that

"Eventually, nobody gives a shit"
Comment: I think it's actually said by the narrator in the first film: "eventually, nobody gives a shit" (here: https://www.youtube.com/watch?v=dbKwJM06fRM)
Comment: Understood that he is around from last 25 years but people are so neutral that he walks unnoticed even on the busy streets of Manhattan, Boston etc.
Comment: He's not unnoticed...it just that it' snot unnatural to them.
Comment: @Gallifreyan That's the perfect answer.


How can be the neutral wire at 0 volts when current flowing through it?

Question: Voltage is potential difference, and current flows because of voltage. So if the voltage is zero, how can current flow through the neutral wire.
Comment: Is the circuit open? Please add details to your question to clarify all ambiguities
Comment: If you have ever put your hand on the 'neutral' wire (hint: do not do this, especially if you live in a 2xxV country) you will realise that the voltage on it is very often not even approximately zero.
Comment: It can't.  If the wire is not a superconductor, then the voltage *must* be different at every point along the length of the wire while current is flowing.  The voltage of the neutral conductor is only _nominally_ 0 volts (i.e., zero volts in name only.)  If the guage of the wire is heavy enough, then the voltage difference from one end to the other won't be enough to matter (as far as your electrician or your building inspector is concerned.)
Answer: You are taking a shortcut when you say, "The voltage is zero."
Voltage is always measured between two points.  In electrical engineering, when we say the voltage at point X is V, we actually are measuring the voltage between point X and an implicit other point called "ground".
In the electric power grid, "neutral" is ground, by definition.  So the voltage of the neutral wire is always zero...  By definition.

The reality is a little different.
If you measure the voltage between any two points on a superconducting wire, you will measure zero volts no matter how much current is flowing, but the neutral wires in the power grid are not superconductors.
If you measure the voltage between two different points on a neutral wire that is carrying current, you will be able to measure a small difference.
Usually, that difference is small enough to be ignored for most purposes.  If it's not small enough to be ignored, it means that the neutral wire is too small (diameter) for the amount of current that it's carrying.

current flows because of voltage

Well, yes, but no.  Current will flow forever in the windings of a superconducting magnet with no applied voltage at all.  It takes voltage to start the current flow, but once the current is flowing in the coil, no voltage is needed to keep it flowing.
Current only stops flowing in the coils of an ordinary electromagnet when the voltage is removed because of the wire's resistance.
It's like the difference between an airplane flying through the air, and a satellite orbiting the Earth far above the atmosphere.  The plane won't fly for long if its engine quits because of the resistance it encounters as it moves through the air, but after its initial boost, the satellite will keep orbiting forever.
Comment: From a different vantage point - is this also why when I move a AC current sensing stick (non-contact type) along a "live" neutral wire, it doesn't alert? That's what I'm observing. (And since this is a specific case, it's a hot-side-only switch to lights, which are on, and energy returns via neutrals. The sensor things there isn't anything in the neutrals, but I know there is since the switch activated the lights).  Thanks for your answer and anything you can add.
Comment: @Crossfit_and_Beer, Sorry, I don't know how those voltage probe things work, but it would not make sense if they only worked when a load was drawing current from the line. The voltage probe is a safety device, and the live wire is dangerous whether current is flowing or not. My guess is, the capacitance between your hand and the device and, between the device and the line, allows a minute AC current that the device can detect. But, since your body normally should be close to the same potential as the neutral line, that minute current only flows when the probe comes near the "hot" line.
Comment: Thanks. The "can't be (due to) load" part makes perfect sense, since unpowered. I Googled a bit more and I see these devices can be magnetic/inductive or capacitive. I can't summarize and there's a bit left to understand, but this points me in the right direction :-)
Answer: The key thing to remember here is that we are talking about an ideal wire. This means that there is (effectively) no resistance in the wire, and therefore no voltage drop along the wire. Now if there is a voltage difference between the two ends of the wire, that induces a constant electric field along the wire, causing current to flow.