Is there an SD Card diagnostic utility?

Question: Are there any SD Card diagnostic utility programs out there for Ubuntu? I would like to run tests on my SD card to check capacity, write speed etc. I have one for windows but I am looking for a Linux flavor and hope to find some source code.
Answer: Look for Disk Utility on you dash (as an option press Alt+F2 and type palimpsest)

Click on the disk you want information from, to test it click on Benchmark

To start benchmark, select Read only or Read/Write benchmark
Comment: On 13.04 (raring) palimpsest was replaced with gnome-disks ("Disks" when you access it from the menu). The instructions are the same as posted by Bruno Pereira.
Comment: "disk utility" is the nice title for `palimpsest`
Comment: Hey, there are screenshots! Cant miss those! :)
Comment: On a german ubuntu - like mine - looking for "disk utility" does not yield any results.
Comment: fair enough, solved.
Comment: @cweiske: Look for "Laufwerke"
Answer: For Ubuntu 13.04 and later...

From the dash

From the command line
gnome-disks

Usage
Select the disk you wish to test.

Find the menu in the top right and select Benchmark...

A window will appear. Click Start Benchmark... to see:

I left the defaults and clicked Start Benchmarking.... It will run for a while, building the chart over time.

You can see that my new SD card's read rate is around 7 MB/s, while the write rate is only slightly over 2 MB/s.
The model shown here is a SanDisk Ultra SDXC with an advertised speed of up to 30 MB/s. As you can see, the transfer rate is not as advertised.
Answer: Reported Capacity
$ df -h /media/sdcard

Real capacity and write speed
$ dd if=/dev/zero of=/media/sdcard/testfile bs=10M
1xx+0 records in 1xx+0 records out 9xx bytes (9.4 GiB) copied, 34.xx seconds, 271 MB/s

dd will fill up all the space. Remove the testfile afterwards.
Comment: `df` will reveal the capacity reported by the SD card, but that may not be the true capacity. `dd if=/dev/null` does nothing because `/dev/null` is always empty. I think you mean `dd if=/dev/zero`.
Comment: What if his sd card is only 1Gb???
Comment: Or `cat /dev/zero > /media/sdcard/testfile`
Answer: There is also f3 (Repository, doc), that specifically aims at detecting fraudulent cards (f3 stands for "fight flash fraud").
It was suggested here first.

Is there an SD Card diagnostic utility?


Change label backcolor when click

Question: Hello guys i have a easy problem here, if i click the label1 it will change back Color to Red but my default Back Color is transparent.
   private void label_Click(object sender, EventArgs e)
   {

       label1.BackColor = Color.Red;
   }

   private void label2_Click(object sender, EventArgs e)
   {
       label2.BackColor = Color.Red;
   }

what if i click the label again i want it to change color to transparent, how do i code that? Thank you in advance! :D
label.BackColor = Color.Transparent;

Comment: Gleng has done that for you. http://stackoverflow.com/a/19498816/2530848
Comment: if statement would do that
Comment: yeah but how do i do that i tried `if(label1.click == true)` haha and i feel silly coding that.
Answer: You just need to flip the color based on its current value. That can be done by doing:
label1.BackColor = label1.BackColor == Color.Red ? Color.Transparent : Color.Red;

The above is a conditional operator and is basically just shorthand for an if/else statement,
if (label1.BackColor == Color.Red)
    label1.BackColor = Color.Transparent
else
    label1.BackColor = Color.Red;

Comment: @MarilouMagat I've updated my answer for clarity. Hope it helps!
Answer: Why don't you just add an if statement:
private void label_Click(object sender, EventArgs e)
{
    if(label1.BackColor == Color.Red)
    {
         label1.BackColor = Color.Transparent;
    }
    else
    {
        label1.BackColor = Color.Red;
    }
}

Comment: Initially `BackColor` will not be `Color.Transparent`
Comment: It says in the question the default background color is transparent, but I have altered my answer all the same
Answer:   private void label_Click(object sender, EventArgs e)
   {
       Label label1 = (Label)sender;
       if (label1.BackColor == Color.Red)
            label1.BackColor = Color.Transparent;
       else
            label1.BackColor = Color.Red;
   }

by using the line   Label label1 = (Label)sender; You can apply the same event for all your labels.
Answer: if( label.BackColor == Color.Red)
{
     label.BackColor = Color.Transparent;
}else
{
    label.BackColor = Color.Red;
}

Change label backcolor when click


How do you proc specific mega veggies in Veggie Samurai?

Question: I am a big fan of iPhone/iPad games Fruit Ninja and Veggie Samurai, the latter being a clone of the former.  In the game, there is a concept of a "Mega-Veggie".  Essentially, normal veggies stop being thrown up, and one huge veggie comes out and you have to dice it many times to score a bunch of points.
In the current iteration of the game, there are three mega veggies I am aware of:
1) Mega Onion (Turns into Onion Blossom, +100 points)
2) Mega Carrot (Once diced grants +500 points)
3) Mega Pepper (Once diced grants +100 points)
4) Mega Potato (Once diced grants +100 points)
While I have certain intuitions about how to proc these mega veggies, there must be some underlying rules as to what makes them pop up.
What do you need to do to trigger each mega veggie type?
Comment: I just want to say that "Veggie Samurai: Proc the Mega Veggies" would be a great title for a musical album.
Comment: hahaha, I absolutely agree.  If you go ahead and record a studio album, I grant you all rights to use it as you please.
Comment: Still a few too many uncertainties to select an answer, will wait until someone has something more concrete about each.
Comment: The peas are mega veggies too. You have to get all 3 of the peas to get the points
Answer: Onion - 4 Dice combo including an Onion.
Pepper - 4 Slice combo including a Pepper.
Potato - 2 Dice combo with 2 Potatoes.
Carrot - I am not sure on this one but I know it has something to do with very large dice combos prior to seeing it.  (30+)
Answer: To get the mega pepper you have to cut at least 4 veggies in one slash with one of the veggies being a pepper.
There's also a mega potato, to get that you need to cut and dice 2 potatoes completely in one go.
The others I'm not sure how to get
Answer: The minimum is not three 10 dice chains for the mega-carrot. I agree that it involves high dice chains, but I know I have gotten the carrot with only two 10-dice chains. I imagine it is more like the pepper or potato. You could potentially come to the conclusion that getting the mega pepper happens after getting 5 or more 4-slice combos, but that would be erroneous. It seems pretty well established that it simply requires one 4 slice combo that includes a pepper. But you might come to the conclusion that it takes 5 slice combos simply because not every combo does include a pepper. I think that the mega carrot really only requires one 10-dice chain (10 or more) that includes 2 or 3 or 4 carrots. That would seem more consistent with what is required to make the other Mega Veggies. Carrots do not seem to be the most common of veggies to pop up, and they are some of the easiest to lose your chain on because of their small pieces (the key to fame and glory on this game is a three-finger method. SOOO much easier to dice carrots and everything. Anyway...)
Well, that's my two-cents on the mega carrots. Speaking from my own experience, of all of the mega carrots I have gotten (probably a few dozen), I don't remember any round where I only got one 10-dice chain and got a carrot, but I have gotten two mega carrots in close time-proximity, which wouldn't have allowed for 2 or three chains in between.
Comment: Also, I'd like to know if anyone has any input on what makes the peas show up. I've seen them on harmony mode at like 5 veggies in. I've even seen them show up on harmony mode without doing anything. Are they totally random?
Comment: Hey Flink, if you have a separate question (about the peas) I recommend using the "ask question" button on the top-right to ask a new question about it. Not only is it the "proper" way to ask questions on this site, it is also more likely to be seen by other users :)
Answer: Mega Pepper - 4 (or higher)x slice combo, including at least one pepper
Mega Onion - Dice 5 (?) onions in a row (not absolute row, but not let any onion undiced through the game)
Mega Potato - Multi-dice x 2 (or higher I suppose) including at least 2 potatoes.
Mega Carrot - It keeps appearing randomly after succeeding 3 (I think it worked for 2 also) 10-dice chain.
1st and 3rd are 100% percent accurate.
As for 2nd and 4th, it's really close but you'll need to try it out and see if it works out.
Last note is about mega carrot: Everytime i got 3 10-dice chains, it shows up. And if you fail to dice it, it'll show up again, sooner or later. I'm pretty sure it's appearance after that is random. Or depends to current score. Need more opinions here.
Comment: I'll edit it so it looks more like an answer to the original question rather than a conversation starter. Though, I still believe it's adding info on the original question.
Comment: Welcome to the site ifrit. This is a Q&A site, not a discussion board, so what your post should be an answer to the original question, and not as a response to another answer - see the [FAQ](http://gaming.stackexchange.com/faq) for more information. In any case, if you want to add more information about mega veggies later, please write it here by *editing your existing answer* and not by adding a new answer. Good luck with finding out the data.
Answer: In order to spot the MEGA EGGPLANT, you need to have three 20 dice chains and successfully cut a carrot. This is hard, but worth trying.
Answer: The minimum for the mega carrot is this:
Any combination of at least 30-dice chains, for instance:
3 separate 10-dice chains
or one 20-dice chain, and then one-10 dice, or vice-versa
or 30-dice chain
Note that if you get, say, a 16-dice chain, then later get a 14-dice chain, that doesn't get you the carrots: it is only recorded as two 10-dice chains.
Then they start popping up randomly. However, even when they pop up, they're pretty hard to cut. I have yet to figure out the strategy for cutting them.
Comment: For strategies on how to cut them, use all your fingers!  Don't start cutting until it reaches the top of the trajectory, and pay special attention to the smaller end of the carrot as it has a lot of places it needs to be cut to get credit.


Buy the server contents

Question: How i can buy the contents of the server of archive.ubuntu.com (for lucid lynx)? In my country i have ultra slow connection. It will take years for downloading all these gigabytes.
Because, canonical will stop supporting ubuntu 10.04, i want all the files now, before it's too late. i know that all files will be transfer to old.dir but i think some will be lost. And anyway i want the files.
My question is:
Can canonical provide (with payment) a disk with the contents of the server?
Cheers
Comment: Why not contact Canonical and ask?
Comment: Should we ask which country?
Answer: Random thought:
If 10.04.4 LTS is no longer supported, then an install would not need (or have) any further updates.

Suggestion:
Would it not be altogether better to try to arrange for CD/DVD by Post (from some helpful enthusiasts) for Ubuntu 12.04 LTS server instead?
Answer: You can purchase complete repository dvd sets from various company's, usually 6-8 dvds or double that if both 32 & 64 bit
So just search the web till you find what you wish, obviously more recent Ubuntu releases would be more available.
For example this shows up for 12.04 & seems ok, (16 dvd's) -
http://www.osdisc.com/cgi-bin/view.cgi/products/linux/ubuntu/ubuntu-1204-lts-software-repository-pc.html
An ex. of 10.04 would be here though  not sure how splitting 32 & 64 bit works out as .all.deb are 32 bit but still needed on 64 bit installs
32 bit - http://www.zyxware.com/shop/software/free-software/operating-systems/gnu-linux/ubuntu-10-04-i386-repository-8-dvd-pack
64 bit - http://www.zyxware.com/shop/software/free-software/operating-systems/gnu-linux/ubuntu-10-04-64bit-repository-8-dvd-pack
Comment: Thank you very much and the answer is answered more than i expected. Thank you. But is there a way that Canonical can provide these disks?
Comment: I guess they could but don't see why they would. (certainly not for free & there isn't much money/demand for these that hasn't been beyond what's supplied by the likes of what I posted above

Buy the server contents


Applying conditional discounts in WooCommerce cart based on product attributes and user roles

Question: I'm working on a WordPress site with WooCommerce and facing a challenge in applying discounts to the cart based on specific product attributes and user roles. The discounts should apply to products with a custom size attribute (e.g., 'S (23 x 15 CM)', 'M (50 x 15 CM)', etc.) and only for users with specific roles ('distributor' and 'dr52').
I need to apply different discount prices based on the total quantity of products in the cart and their size. For example, if there are more than 20 products in total (which could be of different sizes), a specific price should be applied.
I've attempted several solutions to modify prices in the cart, including directly changing the product prices based on total quantity and size. However, the prices in the cart are not updating as expected.
$size_based_discounts = [
    'S (23 x 15 CM)' => [7.80, 7.02, 6.38, 5.85],
    'M (50 x 15 CM)' => [10.10, 9.09, 8.26, 7.57],
    'L (28 x 26 CM)' => [11.01, 9.91, 9.01, 8.26],
    'Baby (25 x 12 CM)' => [7.80, 7.02, 6.38, 5.85]
];

function is_distributor_or_dr52() {
    $user = wp_get_current_user();
    return in_array('distributor', $user->roles) || in_array('dr52', $user->roles);
}

function count_products_by_size_in_cart($size_based_discounts) {
    $total_quantity = 0;
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( ! isset( $cart_item['data'] ) ) {
            continue;
        }
        $product = $cart_item['data'];
        $size = $product->get_attribute('pa_tamano');
        if ( array_key_exists( $size, $size_based_discounts ) ) {
            $total_quantity += $cart_item['quantity'];
        }
    }
    return $total_quantity;
}

function apply_discount_by_quantity($cart) {
    if ( ! is_distributor_or_dr52() ) {
        return;
    }

    global $size_based_discounts;
    $total_quantity = count_products_by_size_in_cart($size_based_discounts);

    $discount_range = 0;
    if ( $total_quantity > 49 ) {
        $discount_range = 3;
    } elseif ( $total_quantity > 27 ) {
        $discount_range = 2;
    } elseif ( $total_quantity > 13 ) {
        $discount_range = 1;
    }

    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        $product = $cart_item['data'];
        if ( $product->is_type( 'variable' ) ) {
            $size = $product->get_attribute('pa_tamano');
            if ( array_key_exists( $size, $size_based_discounts ) ) {
                $discounted_price = $size_based_discounts[$size][$discount_range];
                $cart_item['data']->set_price( $discounted_price );
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'apply_discount_by_quantity', 10, 1 );

function show_original_price_struck_in_cart($price, $cart_item, $cart_item_key) {
    if ( ! is_distributor_or_dr52() ) {
        return $price;
    }

    if ( isset( $cart_item['original_price'] ) ) {
        $original_price = $cart_item['original_price'];
        $discounted_price = $cart_item['data']->get_price();
        if ( $original_price > $discounted_price ) {
            return '' . wc_price( $original_price ) . ' ' . wc_price( $discounted_price );
        }
    }
    return $price;
}
add_filter( 'woocommerce_cart_item_price', 'show_original_price_struck_in_cart', 10, 3 );

While the logic to calculate the total quantity and discount range seems to work (as per debugging logs), the prices in the WooCommerce cart do not reflect the calculated discounts. Interestingly, a test with a simple function to set all prices in the cart to a fixed value (e.g., 1€) worked correctly, suggesting that modifying prices in the cart is feasible in the current setup.
Attempts at Resolution:
Review of discount logic and attribute verification.
Use of different WooCommerce hooks (woocommerce_before_calculate_totals, woocommerce_cart_calculate_fees).
Testing with simplified logic to rule out conflicts with other plugins or the theme.
Is there anything in my current approach that I might be overlooking or that could be causing the prices not to update correctly in the cart?
Are there any known interactions or limitations when modifying prices in the WooCommerce cart that might be affecting this functionality?
Comment: @LoicTheAztec Thank you for the reminder about the language requirements on Stack Overflow. I appreciate your guidance in ensuring that my post adheres to the community standards. I've revised the code and the description to be in English. If there are any further adjustments needed, please feel free to let me know. Your help in maintaining the quality and accessibility of content on this platform is greatly valued. Thanks again!
Comment: Perfect, nothing else is needed…
Answer: I'm back to share the successful resolution of my WooCommerce pricing challenge, thanks in part to the valuable input from @LoicTheAztec. The key issue was correctly identifying the product type in our logic.
The main problem was in handling product types. Our initial approach incorrectly checked for products of type 'variable' when it should have been 'variation', as the discounts were applicable to product variations based on size attributes.
The critical change was in apply_discount_by_quantity, where we switched the check from 'variable' to 'variation':
function size_based_discounts() {
    return [
        'S (23 x 15 CM)' => [7.80, 7.02, 6.38, 5.85],
        'M (50 x 15 CM)' => [10.10, 9.09, 8.26, 7.57],
        'L (28 x 26 CM)' => [11.01, 9.91, 9.01, 8.26],
        'Bebé (25 x 12 CM)' => [7.80, 7.02, 6.38, 5.85]
    ];
}

function is_allowed_user_role() {
    if (!is_user_logged_in()) return false;
    $user = wp_get_current_user();
    return in_array('distribuidores', $user->roles) || in_array('dr52', $user->roles);
}

function count_products_by_size_in_cart() {
    $total_quantity = 0;
    foreach (WC()->cart->get_cart() as $item) {
        $size = $item['data']->get_attribute('pa_tamano');
        if (array_key_exists($size, size_based_discounts())) {
            $total_quantity += $item['quantity'];
        }
    }
    return $total_quantity;
}

function get_discount_range() {
    $total_quantity = count_products_by_size_in_cart();

    if ($total_quantity > 149) {
        return 3;
    } elseif ($total_quantity > 49) {
        return 2;
    } elseif ($total_quantity > 27) {
        return 1;
    } elseif ($total_quantity > 13) {
        return 0;
    } else {
        return -1;
    }
}

add_action('woocommerce_before_calculate_totals', 'apply_discount_by_quantity', 10, 1);
function apply_discount_by_quantity($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;
    if (!is_allowed_user_role()) return;

    $size_based_discounts = size_based_discounts();
    $discount_range = get_discount_range();

    foreach ($cart->get_cart() as $item) {
        $product = $item['data'];
        if ($product->is_type('variation')) {
            $size = $product->get_attribute('pa_tamano');
            if (array_key_exists($size, $size_based_discounts) && $discount_range >= 0) {
                $product->set_price($size_based_discounts[$size][$discount_range]);
            }
        }
    }
}

add_filter('woocommerce_cart_item_price', 'show_original_price_struck_in_cart', 10, 3);
function show_original_price_struck_in_cart($price, $cart_item, $cart_item_key) {
    if (!is_allowed_user_role()) return $price;

    $product = $cart_item['data'];
    $original_price = $product->get_regular_price();
    $discounted_price = $product->get_price();

    if ($original_price > $discounted_price) {
        return '' . wc_price($original_price) . ' ' . wc_price($discounted_price);
    }

    return $price;
}

A huge shoutout to @LoicTheAztec for pointing me in the right direction. Your insights on WooCommerce internals were incredibly helpful.
This solution is now working flawlessly on my site, applying discounts correctly to variable product variations and displaying prices as intended. I hope this helps anyone facing a similar issue!


Everything after a Greek letter is empty in my database

Question: I'm encountering what I'm sure is an encoding error but I can't seem to find the weak link in my logic.  In particular, when trying to insert a Greek lambda into my database, the cell is blank after the lambda.
The process:
Before any html is printed, I'm doing:
header('Content-Type: text/html; charset=utf-8');

Next, I'm connecting using PDO:
$dsn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['dbname'] . ';charset=utf8';
 $options = array(
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );
        try {
            $dbh = new PDO($dsn, $config['username'], $config['password'], $options);
            $dbh->exec("SET NAMES utf8");
            $dbh->exec("SET FOREIGN_KEY_CHECKS = 1");

When I do

SHOW FULL COLUMNS FROM my_table

I can see that the collation is utf8_general_ci.
When I do:

echo mb_detect_encoding($data_to_be_entered);

I get UTF-8
When I echo out $data_to_be_entered into the console right before I insert it into the database, I see: (=23)
However, in my database, I just see ( as the entry.
Comment: You can have a look at [Cannot properly insert greek characters in mysql database](https://stackoverflow.com/questions/32782413/cannot-properly-insert-greek-characters-in-mysql-database)
Comment: See Truncation in https://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored
Comment: @Atif - Your reference talks about Mojibake; the problem here is Truncation.  And it turns out not to be Greek.
Answer: That lambda  is the Mathematical symbol.  It is encoded in UTF-8 as the four bytes hex F09D9C86.  Therefore, it needs MySQL CHARACTER SET utf8mb4, not utf8.
If you want the Greek lambda λ, that works fine with CHARACTER SET utf8 (or utf8mb4).  The hex for it is CEBB.
Comment: Why did you reopen the question? The [dupe](https://stackoverflow.com/a/279279/285587) says exactly the same.
Comment: @YourCommonSense - (1) Truncation and Mojibake are different issues with different causes.  (2) It was not a Greek letter that caused trouble, but a math symbol.  (3) This needed utf8mb4; the other needed other solutions.
Comment: @YourCommonSense - And...  I struggled for years with UTF-8 issues; it took a long time to realize that there were at least 5 different causes of the problems, at least 4 different visible symptoms, and at least 6 different ways to fix them.  Using the wrong fix (because of misdiagnosis, or because of assuming it is an exact dup) does the user a disservice.


Why do Protectrons sometimes attack me?

Question: Sometimes I activate the Protectron in Corvega Assembly plant, go to the side of the room and sneak as I watch it attack raiders. Then, all of a sudden, it would turn and start attacking me. Sure, sometimes I had tried to help it by firing a few shots, and maybe it saw that as being bad, but other times during the entire duration of it being active I don't use any weapons and just try to hide off to the side.
The strange part is it doesn't always happen, either. There are good odds it will not attack me unless I attack it first, but sometimes it seems to just decide it doesn't like me and attacks. Why is does it sometimes attack me?
Answer: This has to do with the mode they're in:
What are the effects of the various Protectron Personality Modes?
If they're in Construction or Law Enforcement mode, you can turn them hostile if you do not meet their requirements.
In Construction mode, you need to be wearing a Hard Hat.
In Law Enforcement mode, you cannot have a weapon drawn.
Answer: As a continuation of Nelsons answer, there is also a Subway Attendant mode that you can put the protectron in. Once the protectron is in that mode, you can give him a subway token and he will no longer be hostile to you but will still attack any enemies.

Why do Protectrons sometimes attack me?


Where to put an header file for a git repository if it is missing during make?

Question: I am installing from source and while make I get the error that a file is missing:
  CXX      src/math/libbitcoin_la-crypto.lo
  CXX      src/math/libbitcoin_la-elliptic_curve.lo
src/math/elliptic_curve.cpp:23:10: fatal error: secp256k1.h: No such file or directory
 #include <secp256k1.h>
          ^~~~~~~~~~~~~
compilation terminated.

I think this header file can be found here so I could download it to include it. But I don't know where to put it.
Also, I am not sure if this is a usefull thing to do.
The readme says 'A minimal libbitcoin build requires boost and libsecp256k1.' so I installed libsecp256k1 on my system already. But I am not certain that this is what they meant.
Comment: For Ubuntu, they likely meant to install `libsecp256k1-dev` rather than just `libsecp256k1` (which won't include header files)
Comment: Please see below
Answer: In principle, you can place header files anywhere you like - so long as you tell the compilier where they are using an appropriate -I directive:
g++ -Ipath/to/include/ ...

If the compiler is being run via a make it's often possible to pass such options via the appropriate FLAGS variable rather than trying to modify the Makefile. For C++ that would typically be CXXFLAGS, so you could do something like:
make "CXXFLAGS=-Ipath/to/include/"

If the Makefile already specifies a location for the software's private header files, you could simply place it there. Or you could place it in one of the default search locations - which you can find for gcc/g++ by executing
: | gcc -E -v -

and scrolling down to the #include <...> search starts here section. For user-installed headers, probably you should avoid all of those locations except /usr/local/include, since system packages may overwrite files in the others.
However in your specific case, you should simply install the libsecp256k1-dev package, which will install the header file into /usr/include and will also install the libraries required to successfully link the application.


How to grant application access for Facebook account

Question: Good day to all!
I've been trying to use Empathy for Facebook chat for quite some time now but whenever I try to enable it, I get the "Applications can no longer access your Facebook online account blah, blah, blah..." and so I tried going to Online Accounts and then grant access.  But whenever I click the button to grant access, it reverts back to "off" after maybe three seconds. What's happening and how can I solve this?
P.S.
I already tried using Pidgin but I still get the same error.  Sometimes I get the "authorization failed" error as well.
Also, I can log into my FB account using my web browser.
Comment: Great! So we have that ruled out. Please [edit] your question, so future readers can see this fact more easily.
Comment: Can you still log into your Facebook account with a web browser? If you're already logged in there, log out and back in to check.
Comment: Hi! Thanks for your response! Yes, I already tried that but I still get the error. :-(
Comment: Ok, but can you log into Facebook from the web browser?
Comment: Yes,  I still can. D:
Comment: Possible duplicate of [Can't log in to facebook accounts using pidgin](http://askubuntu.com/questions/645920/cant-log-in-to-facebook-accounts-using-pidgin)
Answer: A note upfront: It appears that Empathy doesn't support Facebook's messaging service, but Pidgin, a similar multi-messaging client based on the same library libpurple, does with a plug-in as described below.

The purple-facebook plugin is a replacement for the builtin Facebook XMPP plugin. Facebook is in the process of shutting down their XMPP service, which will inevitably break existing support.

(Source)
The following instructions are written for Pidgin and while they should work for the same for Empathy in theory (since they're both based on libpurple), people report that Empathy doesn't accept this plug-in for some reason.

To install purple-facebook in Ubuntu, Linux Mint and derivatives, you can use its official repository. To add the repository and install the plugin, use the following commands:
sudo add-apt-repository "deb http://download.opensuse.org/repositories/home:/jgeboski/xUbuntu_$(lsb_release -rs)/ /"
wget -O- 'https://jgeboski.github.io/obs.key' | sudo apt-key add -
sudo apt-get update
sudo apt-get install purple-facebook

If you don't want to add the PPA, you can download the DEB from HERE (but you won't receive any updates unless you add the repository). Or, grab the source and build it yourself. […]
Once installed, add a new account in Pidgin (Accounts > Manage Accounts > Add) and in the Protocol dropdown, select "Facebook"
  (important: NOT "Facebook (XMPP)"):
Pidgin Facebook I should also mention that in the username field, you can enter either your emil, your Facebook username or phone number associated with your Facebook account.

(Source with some modifications)

Official installation instructions

As of October 18, 2015, jgeboski's GSoC work was merged into the mainline Pidgin project. It will appear in the next major release of Pidgin.

This means, future libpurple versions in Ubuntu (and probably earlier in the Pidgin PPA) will include purple-facebook and supersede the above procedure.
Comment: Hey!  This solved it!  Didn't work with Empathy though.  But it worked for Pidgin!
Comment: Still doesn't work with Empathy or GOA but yeah, with Pidgin it's okay.
Answer: If I remember correctly - Facebook changed their API, which effectively prevented several packages from accessing your account and utilizing the API options - such as chat.
You can find more information with a simple Google search, for example: http://www.omgubuntu.co.uk/2015/04/facebook-chat-api-empathy-pidgin-stop-working
Last I heard, Pidgin and Empathy teams are working on a solution, I wish them the best of luck too.
Comment: Ohhh. I saw this article before but dismissed  it since it was published way back April but apparently it's still the issue. :[

Can you suggest an alternative then? I don't really go on the website to browse or anything. I mainly use FB for chatting with friends, therefore, I really liked Pidgin/Empathy which allowed me to chat with them without going to the website itself. :[

Thanks a lot for taking the time to answer my question! :]
Answer:
I follow the steps for installing The purple-facebook plugin for
Pidgin.
I install Pidgin.
Created facebook account in Pidgin.
In Empathy, import the facebook account from Pidgin. 5- Removed
Pidgin software after facebook account imported.

And its working


Show that $a(XY)=X(aY)$ where $a$ is an element of field and $X$ and $Y$ are $m\times n$ and $n\times p$ matrices

Question: Show that $a(XY)=X(aY)$ where $a$ is an element of field and $X$ and $Y$ are $m\times n$ and $n\times p$  matrices.
Comment: An idea for how to approach this problem on your own: start by showing that this is true for an easy but non-trivial case, such as $m=n=p=2$.  In order to make that initial proof work in general, rewrite the statements involved in summation notation (i.e. with a $\sum$).
Comment: Welcome to MSE. Please include your own thoughts and the effort made thus far, so that people can work with you accordingly. (Please add those in the body of the question instead of commenting.)
Answer: By using the notation to designate the coefficient of the $i$th row and $j$th column of a matrix $A$: $(A)_{i,j}$, we have
$$(a(XY))_{i,j}=a\cdot (XY)_{i,j}.$$
On the other hand,
\begin{align}
(X(aY))_{i,j} & =\sum_{k=1}^{n} (X)_{i,k} (aY)_{k,j}
\\ & =\sum_{k=1}^{n} (X)_{i,k}\  a\cdot(Y)_{k,j}
\\ & = a\cdot\sum_{k=1}^{n} (X)_{i,k} (Y)_{k,j} = a\cdot(XY)_{i,j}.
\end{align}
Answer: Matrix multiplication $\pi:(X,Y)\mapsto XY$ is linear in each slot. By definition $X(aY) = \pi(X,aY)$, which by linearity in the second slot equals $a \pi (X,Y)  = a (X Y)$. Hence $a(X Y) = X(aY)$.
Comment: Stating "matrix multiplication is linear in each slot" is shorthand for saying that we have both $X(aY) = a(XY)$ and $X(Y_1 + Y_2) = XY_1 + XY_2$, as well as the corresponding conditions on the first slot.  In other words, you have assumed the statement that we are trying to prove (and a little bit more).


Best way to store and retrieve synonyms in database mysql

Question: I am making a synonyms list that I will store it in database and retrieve it before doing full text search.
When users enters like: word1
I need to lookup for this word in my synonyms table. So if the word is found, I would SELECT all the synonyms of this word and use it in the fulltext search on the next query where I contruct the query like
MATCH (columnname) AGAINST ((word1a word1b word1c) IN BOOLEAN MODE)
So how do I store the synonyms in a table? I found 2 choices:

using key and word columns like
val  keyword
-------------
1    word1a
1    word1b
1    word1c
2    word2a
2    word2b
3    word3a
etc.

So then I can find exact match of the entered word in one query and find it's ID. In the next select I get all the words with that ID and somehow concate them using a recordset loop in server side langauge. I can then construct the real search on the main table that I need to look for the words.

using only word columns like
word1a|word1b|word1c
word2a|word2b|word2c
word3a

Now I so the SELECT for my word if it is inside any record, if it is, extract all the record and explode it at | and I have my words again that I can use.
This second approach lookes easier to maintain for the one who would make this database of synonyms, but I see 2 problems:
a) How do I find in mysql if a word is inside the string? I can not LIKE 'word1a' it because synonims can be very alike in a way word1a could be strowberry and strowberries could be birds and word 2a could be berry. Obviously I need exact match, so how could a LIKE statement exact match inside a string?
b) I see a speed problem, using LIKE would I guess take more mysql take than "=" using the first approach where I exact match a word. On the other hand in the first option I need 2 statements, one to get the ID of the word and second to get all the words with this ID.
How would you solve this problem, more of a dilemma which approach to take? Is there a third way I don't see that is easy for admin to add/edit synonyms and in the same time fast and optimal? Ok I know there is no best way usually ;-)
UPDATE: The solution to use two tables one for master word and second for the synonym words will not work in my case. Because I don't have a MASTER word that user types in search field. He can type any of the synonyms in the field, so I am still wondering how to set this tables as I don't have master words that I would have ID's in one table and synonims with ID of the master in second table. There is no master word.
Comment: Thanx for fixing my text and made it clearer, I'll try to do the same next time!
Comment: No, 1 table is problematic, since word B can be in more grups and if WORD is unique, that cannot be done with this approach.
Answer: Don't use a (one) string to store different entries.
In other words: Build a word table (word_ID,word) and a synonym table (word_ID,synonym_ID) then add the word to the word table and one entry per synonym to the synonyms table.
UPDATE (added 3rd synonym)
Your word table must contain every word (ALL), your synonym table only holds pointers to synonyms (not a single word!) ..
If you had three words: A, B and C, that are synonyms, your DB would be
WORD_TABLE            SYNONYM_TABLE
ID | WORD             W_ID | S_ID
---+-----             -----+-------
1  | A                  1  |  2
2  | B                  2  |  1
3  | C                  1  |  3
                        3  |  1
                        2  |  3
                        3  |  2

Don't be afraid of the many entries in the SYNONYM_TABLE, they will be managed by the computer and are needed to reflect the existing relations between the words.

2nd approach
You might also be tempted (I don't think you should!) to go with one table that has separate fields for word and a list of synonyms (or IDs) (word_id,word,synonym_list). Beware that that is contrary to the way a relational DB works (one field, one fact).
Comment: You mean 2 tables: word table with WordID and word columns and a synonims table with WordID and synonim column? And I can search a word table and join it with synonyms table to get the results in a recordset that I loop then and put them together somehow?
Comment: You are correct ... I was trying to add that to my answer while you commented.
Comment: SELECT synonim FROM wordtable w LEFT JOIN synonymstable sy ON sy.WordID=w.WordId where word = 'mysearchword'? Is there a way to get results back in ONE row not number of synonims rows? To concat the rows somehow in the same SELECT?
Comment: I think you made a very good point yes about the tables. I can then select only once. If there would only be a way to somehow CONCAT the rows into one row to get the result as word1a word1b word1c somehow so it is easier to enter into a main search query (no RS loop would be needed then)
Comment: I think I found answer to my own question: It may be group_concat is what I am looking for ;-)
Comment: Seems my problem is still not solved, please take a look at my update post.
Comment: @Jerry2: please see my explanation/example how the two table approach was intended
Comment: Thanx, this works well if you have 2 synonims, as you need 2 entries in synonims table. But if you have like 10 synonims you would have to store... all the combinations in the second table? That would make hundreds... or I don't understand properly. Can you please make example with 3 synonims of a word?
Comment: @Jerry2: I've added a 3rd synonym... and yes, there would/could be hundreds of entries, but since they actually reflect the relationships between the words, and you want to be able to search for each word, this can't be helped. "Space saving" approaches, like the '2nd approach' I mentined, aren't any better (space, performance, complexity), if you look at them closely.
Comment: It's only hard to manage this database if I add or remove any synonyms, but I guess this can not be helped.
Comment: @Jerry2 : look at
Hasan Amin Sarand's suggestion below ... very clever
Answer: I think 3 columns  and only one table is better
WORD_TABLE
ID | WORD | GroupID
---+----------------
1  |  A   |   1
2  |  B   |   1
3  |  C   |   1

Comment: you make a good suggestion... this would solve the OP's problrm, that he added in a comment, regarding managing the table ..
Answer: Another approach is to store meaning (this does not use master words, but a meaning table that groups instead)
would be to store the words in a words table without synonyms and with only text, like this:
Many words, one meaning
meaning_table

meaning_id
---
1
2
3

And store the words in another table, for example if A, B and C were all synonyms of 1 meaning
word_table

word_id | meaning_id | word
--------+------------+------
1       |  1         |   A
2       |  1         |   B
3       |  1         |   C

Even though it looks a lot like what Hasan Amin Sarand suggests, it has the key difference that you don't select from the WORD_TABLE but instead select from the MEANING_TABLE, this is much better and I learned that the hard way.
This way you store the meaning in one table and as many words for that meaning as you like in another.
Although it assumes that you have 1 meaning per word.
Many words, many meanings
if you want to store words with multiple meanings then you need another table for the many to many relationship and the whole thing becomes:
meaning_table
-------------
meaning_id
-------------
1
2
3

word_meaning_table
--------------------
word_id | meaning_id
--------+-----------
1       |  1
2       |  1
3       |  1

word_table
--------------
word_id | word
--------+-----
1       |   A
2       |   B
3       |   C

Now you can have as many words with as many meanings as you want, where any word can mean anything you want and any meaning can have many words.
If you want to select a word and it's synonyms then you do
SELECT
meaning_id,word_id,word
FROM meaning_table
INNER JOIN word_meaning_table USING (meaning_id)
INNER JOIN word_table USING (meaning_id)
WHERE meaning_id=1

You can also then store meaning that does not have a word yet or that you don't know the word of.
If you don't know what meaning it belongs to then you can just insert a new meaning for every new word and fix the meaning_id in the word_table later.
You can then even store and select the words that are the same but mean different things
SELECT
meaning_id,word_id,word
FROM meaning_table
INNER JOIN word_meaning_table USING (meaning_id)
INNER JOIN word_table USING (meaning_id)
WHERE word_id=1


How to do a high-jump on springboards?

Question: I have tested and tried to figure out what the secret is to doing a big jump on Springboards in the original Super Mario Bros, but have been unable to figure out what triggers it. The closest theory I seem to have is that you have to press "B" while in the air and then hit "A" as you are jumping, but sometimes I still only do a small jump?
Can someone tell me what the official way to get a big jump is when using these annoying things?
Comment: Pretty sure you just have to jump the moment the springboard reaches it's peak compression and is about to send you flying.
Comment: My only guess is that the title was too generic and sounded too simple and there are people who judge the question by title, not the actual question. I edited the title to be more descriptive, hopefully it will help.
Comment: Sheesh, okay, no need for a downvote.
Comment: That comment seems like it's directed at my comment, so I feel like I should let you know that I did not downvote anything.
Comment: Sorry, I don't understand why everyone is down-voting this question? Did I ask something wrong?
Answer: You have to press A when the trampoline is fully compressed, before it sends you in the air. There's nothing else to it, just got to get the timing right.
Source saying it's all about timing (mariowiki.com):

With the right timing of pressing the A Button button, the player will have Mario (or Luigi) be able to go high in the air.
Comment: That's how it always worked for me. Unfortunately, I have no way to test it, other than playing the game until I reach an area with a springboard and my Mario skills are quite rusty... I am fairly certain it works the same in Smash as well. I'll see if I can find any other sources, can't promise anything though.
Comment: Ah, okay. Now don't take this the wrong way because it's not like I don't believe you (I do), but do you have any verifiable sources or personal experience for that or is that just how you think it works?
Comment: @Guy I added a source (from mariowiki that *you* linked) saying that you can do the high jump with the right timing.
Comment: Oh wow I'm an idiot I skipped right over that sentence some how when I read that page. Conveniently, the page doesn't elaborate on what that timing is..

So press A when the trampoline is fully compressed. Thank you!
Comment: You're welcome, glad I could help :P

How to do a high-jump on springboards?


`Read-only file system` error using tab completion, and terminal window closing randomly

Question: First is simply an oddity with the command cd. If I type in cd, then a space, then press Tab to view the available directories, I get this error message:

bash: cannot create temp file for here-document: Read-only file system

The more troublesome issue has been random closings of the terminal window. It has happened while testing the cd oddity, and also while ssh'd into another server doing simple things like git status and such. [Edit] It seems if I press enter exactly 31 times it triggers the auto closing of the terminal window (verified 3 times now).
I recently upgraded from 12.04 to 14.04 late last week, and this behavior did not occur the entire day I used it after upgrading. This is the first time attempting anything on this computer since that day.
Please advise any other information I can provide, and what I need to do to resolve this.
Comment: Just a friendly reminder to make the question title more descriptive, which helps get better responses: "odd terminal behaviour" is not very descriptive.
Comment: I appreciate it.
Comment: In order to better diagnose your problem, can you tell me if you are using the default partitioning that Ubuntu set up, are you using whole disk encryption or LVM, and have you done anything to your fstab?  What is the output of the `mount` command?
Comment: mount output: https://gist.github.com/anonymous/74dc62ccd5602d1e9742
Comment: Thanks for providing that - it looks like no issue with the way the mounts are configured and no problems at mount time but maybe errors with the / (root) mount encountered since then?  The `remount-ro` specifies that the root partition will be remounted as read-only in the event of certain filesystem errors.  Doing a fsck from recovery or a Live CD would be good.
Answer: I rebooted in recovery mode and followed the instructions the system gave me.  I ran fsck on /dev/sda2, and that fixed the problem.
Comment: How do you reboot into recovery mode without a live-cd?
Answer: The Read-only file system error is the major clue here.  I would guess that your home directory, where bash tries to store your command history and so forth, is inside a read-only partition.
I would guess that it tries to update your recent command history on disk once every 32 commands, which is why it's failing on the 32nd command you type in a session.
Now, a partition may be mounted as read-only if you do it deliberately, but it may also be mounted as read-only if there was an error - this latter behaviour is usually the default for the root partition.
I'd be surprised if you weren't experiencing other problems if your root partition is mounted read-only.
You can try rebooting and checking the disk from the recovery menu.  Press and hold shift as the computer boots, right after the BIOS screen disappears and right before the Ubuntu logo appears.
Comment: Had the same problem. Rebooting worked. Thanks.
Answer: This exact issue happened to me too.
It occurs intermittently.
So I finally had enough with it and decided to reinstall OS - ubuntu-gnome 14.04 (clean).
It fixed it! At least for a few days.. Then that exact same problem occurred again...
So I went to Fry's and got a new hdd (Seagate).
So far so good ( 6 months & counting ).
side note: stock hdd was Toshiba
Comment: @ArchismanPanigrahi "the disk is bad, get a new one" is an answer.
Comment: That's my answer. What's your answer?
Comment: What I wanted to say is that reinstalling OS or buying a new hard disk is not a proper solution. You may want to comment on other posts and you will be able to comment when you have enough reputation (15).
Comment: wow. So all those upvoted the answer went and bought new hdd (?)
Comment: Welcome to Ask Ubuntu. Since this is not a proper answer to the question,  please delete it.
Comment: Truly. Only time I've ever seen this come up is when the storage for a host has become unavailable while the host is still up. Annoying for one host, very problematic when it's a few hundred because the storage sub-system disappeared for awhile.
Answer: As others have pointed out, a read-only /tmp filesystem causes further problems.
As for the 31 lines, it's related to gnome-terminal's internals.
It keeps a certain amount of lines in memory, in a so-called "ring". The rest, lines that scroll out of this ring are placed in a "stream". In older versions of gnome-terminal the stream was pretty much directly written into a file under /tmp, in newer versions there's buffering, compression and encryption before it's written out. (I can't remember off the top of my head whether the file under /tmp is opened when the first chunk of data is written into the stream, or when the stream first tries to actually write to /tmp; it's a minor implementation detail.)
The size of the ring is always a power of two (each slot containing 1 line of the terminal; except for 1 slot is not used due to technical reasons), and is doubled every time it's required due to the growth of the terminal height (but never shrinks back). E.g., with the default height of 24 lines the ring contains the last 31 lines of output, the rest goes to the stream (eventually to /tmp). If you increase the window's height to let's say 40 lines, the in-memory ring will grow to accommodate at most 63 entries at a time.
What you experience is that gnome-terminal tries to open a file in /tmp to store the stream, and exits because of the unexpected failure here. Try with a taller window than the default; it'll crash after pressing Enter 63 (or maybe 127) times.
That being said, /tmp should be fixed to be writable (with permissions 1777).
Answer: My problem was that a process was running with 100% CPU and probably took all disk resources (Some backup process: Ur-Backup).
Once i killed it, all went well. So I would think that a bottle-neck on the IO could cause this error even if there is enough space and you have write permission.
(Raspberry Pi with Jessy 18/03/16)
Answer: Ubuntu 18
Strangely enough, I had a read-only /tmp filesystem.
I hardened my /tmp directory and bash-completion worked as it should. Make sure you do not have any processes using the /tmp folder or moving the /tmp folder might be denied to you.
dd if=/dev/zero of=/var/TMP bs=2048 count=1048576
mke2fs -j /var/TMP
mv /tmp /tmp_backup
mkdir /tmp
mount -o loop,noexec,nosuid,rw /var/TMP /tmp
chmod 1777 /tmp
cp -R /tmp_backup/* /tmp/
rm -rf /tmp_backup


Getting a function to work on every row of a dataframe (pandas)

Question: I want to pass each cell of a column in a dataframe to a function which then creates a new cell
I've looked here and here but these don't address my issue.
I'm using an obscure package so I'll simplify the method using the base packages to ask the question, hopefully the issue will be clear.
Method:
Load the data
import pandas as pd
import math

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

Pass the values of one column to a variable
lat = df['A']

Create a new column by applying the function to the variable
df['sol'] = df.apply(math.sqrt(lat))

This gives the error
TypeError: cannot convert the series to <type 'float'>
The error I'm getting using the pyeto package is actually
Traceback (most recent call last):

File "<ipython-input-10-b160408e9808>", line 1, in <module>
data['sol_dec'] = data['dayofyear'].apply(pyeto.sol_dec(data['dayofyear']), axis =1)            # Solar declination

File "build\bdist.win-amd64\egg\pyeto\fao.py", line 580, in sol_dec
_check_doy(day_of_year)

File "build\bdist.win-amd64\egg\pyeto\_check.py", line 36, in check_doy
if not 1 <= doy <= 366:

File "C:\Users\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\generic.py", line 731, in __nonzero__
.format(self.__class__.__name__))

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().`

I think the issue is the same in both cases, the function will not apply to every cell in the dataframe column, and produces an error.
I want to be able to apply a function to each cell of a dataframe column (i.e. get the square root of each cell in column 'A'). Then store the result of this function as a variable (or another column in the dataframe i.e. have a 'sqrtA' column) , then apply a function to that variable (or column) and so on (i.e. have a new column which is 'sqrtA*100'.
I can't figure out how to do this, and would really appreciate guidance.
EDIT
@EdChum 's answer df['A'].apply(math.sqrt) or  data['dayofyear'].apply(pyeto.sol_dec) (for the package function) helped a lot.
I'm now having issues with another function in the package which takes multiple arguments:
sha = pyeto.sunset_hour_angle(lat, sol_dec)

This function doesn't apply to a data-frame column, and I have lat and sol_dec stored as Series variables, but when I try to create a new column in the dataframe using these like so
data['sha'] = pyeto.sunset_hour_angle(lat, sol_dec) I get the same error as before...
Attempting to apply the function to multiple columns:
data['sha'] = data[['lat'],['sol_dec']].apply(pyeto.sunset_hour_angle)

gives the error:
Traceback (most recent call last):

File "<ipython-input-28-7b603745af93>", line 1, in <module>
data['sha'] = data[['lat'],['sol_dec']].apply(pyeto.sunset_hour_angle)

File "C:\Users\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\frame.py", line 1969, in __getitem__
return self._getitem_column(key)

File "C:\Users\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\frame.py", line 1976, in _getitem_column
return self._get_item_cache(key)

File "C:\Users\pflattery\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\generic.py", line 1089, in _get_item_cache
res = cache.get(item)

TypeError: unhashable type: 'list'

Answer: Use np.sqrt, as this understands arrays:
In [86]:
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df['sol'] = np.sqrt(df['A'])
df

Out[86]:
     A   B   C   D       sol
0   52  38   4  71  7.211103
1   59   4  36  15  7.681146
2   37  28  33  73  6.082763
3   58  26   4  96  7.615773
4   31  48  47  78  5.567764
5   43  58  45   4  6.557439
6   69  35  27  39  8.306624
..  ..  ..  ..  ..       ...
98  42   6  40  36  6.480741
99  22  44  11  24  4.690416

[100 rows x 5 columns]

To apply a function you can do:
In [87]:
import math
df['A'].apply(math.sqrt)

Out[87]:
0     7.211103
1     7.681146
2     6.082763
3     7.615773
4     5.567764
5     6.557439
6     8.306624
7     7.483315
8     7.071068
9     9.486833
        ...
95    3.464102
96    6.855655
97    5.385165
98    6.480741
99    4.690416
Name: A, dtype: float64

What you tried was to pass a Series to math.sqrt but math.sqrt doesn't understand non-scalar values hence the error. Also you should avoid using apply when a vectorised method exists as this will be faster for a 10K row df:
In [90]:
%timeit df['A'].apply(math.sqrt)
%timeit np.sqrt(df['A'])

100 loops, best of 3: 2.15 ms per loop
10000 loops, best of 3: 99.7 µs per loop

Here you can see that numpy version is ~22x faster here
with respect to what you're trying to do, the following should work:
data['dayofyear'].apply(pyeto.sol_dec)

Edit
to pass multiple columns as args to a method:
data.apply(lambda x: pyeto.sunset_hour_angle(x['lat'],x['sol_dec']), axis=1)

Comment: Is the `apply(math.sqrt)` meant to be `applymap`, or am I missing something here?
Comment: `applymap` operates on every element in a df `apply` will apply on each column or row for a df or each row for a `Series`
Comment: Thanks, been trying to read the docs of both methods and not quite got it yet, because was constantly mixing up Series and DataFrames.
Comment: @EdChum Thanks for this! `data['dayofyear'].apply(pyeto.sol_dec)` worked. I've hit another issue with the next step, where a custom function from the package takes two arguments - I've edited the post to clarify, the solution you gave doesn't seem to work when the function takes multiple arguments
Comment: Try `data.apply(lambda x: pyeto.sunset_hour_angle(x['lat'],x['sol_dec']), axis=1)`
Comment: Yes this (and the further similar functions taking more arguments based on previous functions) worked! Thanks again.


Methods of installing software in Ubuntu (command-line)

Question: I want to get information on what are different methods to install softwares/applications in Ubuntu (14.04)?
Example like :

Install by apt-get
Install from package-source or build-dependencies
Compile from source
Using binary package
Install downloaded debs by dpkg

etc from my knowledge but Give right & appropriate different methods.
So, It can be knowledge base for new users to aware from different method and when to use which?
I am talking about different command-line methods rather than GUI or software-center because of knowledge-base and package-management.
Comment: @RaduRădeanu Yes [this](http://askubuntu.com/a/321954/256099) answer is helpful.
Answer: You can install downloaded deb's through Ubuntu Software Center\Muon\etc. Almost always by double clicking in file manager, or
xdg-open <file>

You can build it from source with make and then, instead installing, use checkinstall to compile distribution package (deb\rpm\etc).
Answer: Installing packages through apt-get,
 sudo apt-get install <package>

Installing packages through aptitude,
sudo aptitude install <package>

To install a .deb package through dpkg,
sudo dpkg -i file-name.deb

To install .deb packages through gdebi,
sudo gdebi file-name.deb

Installing packages through apt
sudo apt install <package>


WPF TwoWay Binding some elements to ObservableCollection

Question: I need bind some ComboBoxes to one ObservableCollection.
I have this ListView.
<ListView x:Name="lwCoefTables" Grid.Column="1" ItemsSource="{Binding Source={StaticResource CollectionCoefContainers}}">
<ListView.ItemTemplate>
    <DataTemplate>
        <ComboBox x:Name="cmbCoefTableTypes" ItemsSource="{Binding Source={StaticResource CollectionCoefLinksTable}}"
                SelectedItem="{Binding CoefLinksTableType, Mode=TwoWay}" Grid.Column="1" VerticalAlignment="Center"
                HorizontalAlignment="Left" Width="180" DisplayMemberPath="Name">
        </ComboBox>
    </DataTemplate>
</ListView.ItemTemplate>

I want bind my collection to all ComboBoxes and save selected items for each ComboBox.
If I fill one collection and bind it to all comboboxes in TwoWay mode I get this:
Picture
I think I need helper class that will contain some similar collections. How to do that?
Answer: So I assume the CoefLinksTableType property is on the items inside CollectionCoefContainers?
In which case this should work, unless you have the same instance repeated inside CollectionCoefContainers.
e.g.
Something like this would behave as you describe.
var vm = new VM();
CollectionCoefContainers.Add(vm);
CollectionCoefContainers.Add(vm);
CollectionCoefContainers.Add(vm);
CollectionCoefContainers.Add(vm);

The solution would be
CollectionCoefContainers.Add(new VM());
CollectionCoefContainers.Add(new VM());
CollectionCoefContainers.Add(new VM());
CollectionCoefContainers.Add(new VM());

It might be useful to have you definitions of CollectionCoefContainers and CollectionCoefLinksTable


What is the most appropriate way to ask a user to select a few (10 for example) categories from a list of thousands to proceed with the app?

Question: I am working on a mobile app which relies on the categories/themes of interest chosen by the user and show content accordingly.
These categories are coming from another website and are similar to the numerous Stack Exchange sites, i.e., you must choose what content you have to see. In my case, the overall number of categories could be 1000s, however many of them may have overlapping content.
The idea is to have the user select a minimum of 10 such categories before moving to the main app content. The content is based on the user's selections.
How can I let the user begin exploring the app's content without taking a lot of time with selection of categories?
I am currently showing the whole list to the user. However, since the list is huge, I feel like the user may lose interest before even starting.
Comment: I think I can speak for most people: if an app makes me do this then I will give up using it. Tumblr only asked for three and that was annoying enough.
Comment: This situation is similar to what happens right after creating a new Pinterest or LinkedIn Learning profile; you might have a look at how they've solved this problem (popular categories first, then more relevant suggestions based on what you've just selected). Note, however, that I've always found frustrating to have to click 10 categories before accessing the app (without — at least for Pinterest, afaik — be able to skip this step).
Comment: Twitter also does it, but it is kind enough to have a skip button. After I start to browse content on my own I normally go follow topics I find interesting.
Comment: @johnwick - be careful of the most popular categories - they become popular because generally users are annoyed to get a list so they start randomly picking the first few they see.  These first few continue being selected by other users causing these categories to actually become popular - not because people like them but because they were the first categories a user clicked on.  You always want to take these so called popular categories and mix with them a random number (come up with it based on your business needs) of categories that are not so popular and mix them in with the popular result
Comment: What about filters?
Comment: @ebosi your analogy is correct, and we really need this to start off with the application
Comment: As a privacy-conscious user, I won't use any app that asks about my personal preferences without knowing how this data is gonna be used and how the data would impact my experience with the app. So, if I didn't know what the app will offer me and that selecting some categories is paramount to using the app, I would immediately kill and uninstall the app if selecting categories is necessary before even seeing what the app can do.
Comment: You should not make this a mandatory sr Modal step. Allow the user to discover categories over time with exploration and recommendation. If you must start with a initial selection just offer a few coarse categories.
Answer: I would suggest creating a short list of broad "top-level categories" that every other category can be grouped into (maybe around 20 of them). For example:
Technology, Art, Leisure, etc.
Then (painfully) link your thousands of categories to those top-level categories.
That way, when the user signs up, they can pick which of those handful of top-level categories interest them. Then you can automatically assign all related categories to that user (or limit it to a random subset if you don't want too many).
I would then suggest that a feature of the application is that when showing content to the user, they can clearly see the original category and provide an easy option for them to "unsubscribe" if they don't like that content.
Yes, it's a lot of work for you in the back end, but that's your selling point - you do the heavy lifting, so that the user doesn't have to.
Comment: Exactly. As a user I IMMEDIATELY skip this step and if there is more then 10 to 20 categories, then I don;t ever get to it again. If something requires the dedication of going through thousands of options to select/unselect them, there should be proportional incentive to even do it!
Comment: You don't necessarily need to manually link all the categories to each other based on what relations you think exist. Let your users do that for you. There will likely be at least a handful of users willing to search the whole thing and find the exact categories they actually like, use those as potential links. 70% of users who like A also like B so make A and B strongly linked, 20% of users who like A also like C so make A and C weakly linked. See Amazon's "Other people who bought this also bought..." section for inspiration
Comment: @musefan your answer and comments seem to hit in the right direction for me. Thanks!
Comment: Can categories belong to multiple top-level categories?
Comment: [medium](https://medium.com/) solves this problem as well
Comment: @StacyH: Well that would be a design decision to make, but I don't see any reason why not.
Comment: One helper approach is to syndicate from linked categories into the top categories. So initially user can select a top category (Tech) and see Tech content. If they like an article, one option is to select its sub-category (Cameras or Cars) or even its precise topic (Classic British sports cars, or Austin-Healey)
Answer: This is a frame challenge.  What you ask for is impossible.
If you require users to select ten categories of interest before you let them access the app, most users will not proceed beyond that step.  No UX polishing can fix this.
The few people who get past this will have chosen ten categories quickly, without much thought.  They will have missed categories they are really interested in, and included categories they are only marginally interested in.  Again, no UX polishing can fix this.
I think you should rethink your whole approach.
Comment: "There is no appropriate way" is a perfectly valid answer.
Comment: @musefan  This is indeed not an answer to the question.  It is a frame challenge.  As stated in the very first sentence.
Comment: @musefan I don't know if UX has any specific rules regarding frame challenges. But I have seen them (and sometimes answered with them myself) on other SE sites and I think they can be a very useful tool.
Comment: Although it is a fair point, I am not sure this actually attempts to provide an answer to the question.
Comment: I strongly agree with this answer.  The question above perfectly demonstrates the Paradox of Choice - the myth that more options offer a better chance of finding the perfect one.  In fact, the more options presented, the harder it is to choose any option.  Humans don't make rational choices based on a known preference of absolute value.  Rather, they react situationally to the relative value of compared options.  This requires VERY FEW OPTIONS (think 3 - 5).  Construct taxonomies accordingly.
Answer: This sounds like a job for a type-ahead -- the user starts typing a category of  interest, and the system returns valid responses that can then be selected.
Bonus points if you account for fuzzy spelling or can link the user to synonyms.
Comment: While this would be a useful feature to have regardless, it does have the limitation that the user needs to know what categories are available (by name) before they search.
Comment: @musefan This is a problem with 1000 categories anyway. Usually such a select box accepts that the result will not be optimal, as independent of the UI the user will never read all available options, so it makes sure the user finds something that is relevant to him. Aliases for some important options can be helpful, but the user will still likely make a selection from his first 20 ideas instead of finding the *best* 10 categories, what would require him to either already know them and be sure they are available or check the whole list.
Comment: @allo: like I said: `"this would be a useful feature to have regardless"`. I am not saying this isn't a useful suggestion, I am just saying it doesn't help solve the problem of how to get around the user having to search through the full list
Comment: This may have worked if there were not too many choices. There could be bias against the choices that the user may want to explore but doesn't know about them in the first place
Answer: Browse by popular categories
In addition to the other answers, I'd also recommend enabling the user to view which categories are the most popular, based on statistics of your user base.
This will empower users to be able to quickly get value from your service—before they lose interest—by choosing from categories that are already successful in your app.
You do the discovery for them: provide intelligent recommendations
If you're feeling a bit more advanced, perhaps you could get into providing recommendations, based on communities the user is already a part of. This could also be done by using the statistics of your user base to find groups of categories that typically are subscribed to together.
Comment: One of the drawbacks of this approach is that it gives bias to the categories which are already popular, and results in them becoming even more popular. Depending on how other users are expected to "discover" the lesser categories, it may end up that they never get seen at all.
Comment: @musefan You're right, but that could be tuned to occasionally include a small number of "weaker" community suggestions.
Answer: Do your users really need to select all 10 categories at the beginning? Maybe you can let them select 3-5 categories and gradually introduce them to select more.
If you collect enough data, you can try to suggest something like: "Users who are interested in Category 1 also choose these Categories"
Asking users to select too many options at once will most likely lead to choice overload right at the beginning of their journey.
Comment: Yes, this issue posed as a solution in the question above, causes a second big problem - barrier to entry.  In mobile apps, true conversion isn't represented by app download.  But rather by 'second use.'  Until a user uses the app a second time, they haven't really started using it at all.  Thus the enemy of true app conversion is SETUP - any and all steps that stand between new users and the content they seek.  When confronted by any setup steps, many uses just bail, never using the app again.
Answer: Depending if this is applicable to your subject matter you could take a hint from some music streaming applications: instead of asking if you like Pop, or R&B or Jazz or Classical, they ask some of your favorite artists and then deduce (or propose) some categories from that. I think Apple Music's setup starts like that.
Again, it is hard to say if this approach would fit your use case or not without knowing what which sort of content we are dealing with.
Answer: There are a number of assumptions that need to be considered when addressing a pattern like this.

why is the user adopting your app?
how did they arrive at your app?
what happens if they try to skip category selection?
how confident are you that the user and the app describe categories the same way?
can we employ some form of behavioral analysis to surface more applicable categories?
Do your users have an opinion on 1000 possibilities? Do they demonstrate any behavior around this list? Can you quantify a preference for items at the top of the list vs items it the bottom?
what happens if the user only selects 5 items, or just one? Is there anything to suggest that 10 categories results on a better experience than 9 or 5 or 1?

These are all questions that draw focus back to putting the user and their considerations at the center of the solution. I have often received a recommendation for a curation product and dropped in and had no idea how to proceed. In situations where I was unfamiliar with the options available to me, I often appreciate a general suggested or what's trending now playlist. As my familiarity with the product increases, I can do more exploration and adopt new relationships to people, groups and topics.
But my suggestion is that you take some effort to test your 1000 item list with users and see how they react to it. Make a cheap prototype with a skip button on it, and see how often users try to skip it. Results from these experiments in the context of your user, with your interface, and your content will give you much better results than suggestions from our limited point of view.


Accidentally changed PATH variable and I cant change it back, or use vim etc..help

Question: I know there are many questions like this, but I unfortunately dont know enough about Ubuntu to be able to apply it to my situation. I have all my stuff saved for work on a remote machine, that i access via ssh. I was trying to change something with a conda environment i have there, and changed something in the .bashrc file, and now I cant use vim, or ls - no text editor or command seems to work.
echo $PATH
returns:
/home/percyrou/bin:/home/percyrou/bin:/home/user/bin:~/ghf_env/bin/
as far as i remember from the .bashrc file before i accidentally changed it, the PATH was just something like : /home/user/bin:
I think all these extra parts got added because i tried to change it with :
echo 'export PATH="/home/percyrou/bin:$PATH"' >> ~/.bashrc (or just with user instead of percyrou, because i wasnt sure which it was), and it seems to add it to the PATH rather than replace it. I did already run source ~/.bashrc
i also tried to use scp to download the .bashrc file to my local machin and edit there, but that also returns bash: scp: command not found, i guess because scp is also contained in my .bashrc file.
Please help! I have no idea how to proceed from here to access my path variable again. :(
Comment: When your PATH is broken, use full path to executable like `/usr/bin/scp` instead of `scp`.
Comment: You could add /usr/bin to PATH so "scp", "ls", etc can be found.  export PATH=/usr/bin:$PATH.
Comment: Your vim is there: `/usr/bin/vim`
Answer: You are still able to use scp and other commands, only you need to type the absolute path like /usr/bin/scp instead of just scp (or similarly /usr/bin/ls instead of ls etc.) because the shell cannot find these commands on your $PATH.
Try /usr/bin/cat .bashrc to display the contents of your .bashrc file or /usr/bin/vim .bashrc to edit it. If you can't make the file work properly by editing it, there is a default .bashrc file (that is copied to each user's home directory when creating account) under /etc/skel/.bashrc. Use the following command to copy it over your current .bashrc file:
/usr/bin/cp /etc/skel/.bashrc .bashrc

Comment: Okay this is great thank you !Its still not working yet, but at least with ```/usr/bin/vim``` i can at least open it, thanks already so good to know!
Comment: Okay I copied over the default, and it still doesnt work. But since my question was mostly about how to access my stuff again, your answer was a success! Thanks so much :)
Comment: Did you log in again to a new session after copying the default? It's strange that the default file doesn't work... What is your `$PATH` after logging in to a new session with default `.bashrc` file?
Answer: Reset your path to a minimum usable version
PATH=$(getconf PATH)

Then fix your .bashrc


How much better Power Within spell gets with each level of upgraded Pyromancy Flame?

Question: I found the pyromancy spell Power Within to be very useful for increasing dealt damage. I wonder how much Pyromancy Flame casting item upgrades increase its power. Info I found on various wikis is incomplete and only lists the basics.
Answer: Power Within does not increase with upgrades for pyromancy flame. There is literally no way to make Power Within more powerful. PWI adds +40% damage to all output.
Pre-1.05 patch Upgrading the Pyromancy Glove would actually increase the damage done to the player, leading many people who used PWI to never upgrade their glove because it was only detrimental. This has been addressed and if you are fully patched, The level of your glove has absolutely no effect on Power Within.


Implementing a countdown timer in React with Hooks

Question: Im trying to render a count down timer on screen with react hooks, but I'm not sure the best way to render it.
I know i'm supposed to use the useEffect to compare current state to previous state, but I don't think I'm doing it correctly.
I would appreciate the help!
I've tried a couple of different ways, none of them work, like setting state whenever whenever it updates, but it just ends up flickering like crazy.

const Timer = ({ seconds }) => {
    const [timeLeft, setTimeLeft] = useState('');

    const now = Date.now();
    const then = now + seconds * 1000;

    const countDown = setInterval(() => {
        const secondsLeft = Math.round((then - Date.now()) / 1000);
        if(secondsLeft <= 0) {
            clearInterval(countDown);
            console.log('done!');
            return;
        }
        displayTimeLeft(secondsLeft);
    }, 1000);

    const displayTimeLeft = seconds => {
        let minutesLeft = Math.floor(seconds/60) ;
        let secondsLeft = seconds % 60;
        minutesLeft = minutesLeft.toString().length === 1 ? "0" + minutesLeft : minutesLeft;
        secondsLeft = secondsLeft.toString().length === 1 ? "0" + secondsLeft : secondsLeft;
        return `${minutesLeft}:${secondsLeft}`;
    }

    useEffect(() => {
        setInterval(() => {
            setTimeLeft(displayTimeLeft(seconds));
        }, 1000);
    }, [seconds])

    return (

{timeLeft}

    )
}

export default Timer;```

Comment: Classic issue with hooks and intervals. Have  look at https://overreacted.io/making-setinterval-declarative-with-react-hooks/
Comment: And pay attention to canceling the interval also on teardown
Answer: const Timer = ({ seconds }) => {
  // initialize timeLeft with the seconds prop
  const [timeLeft, setTimeLeft] = useState(seconds);

  useEffect(() => {
    // exit early when we reach 0
    if (!timeLeft) return;

    // save intervalId to clear the interval when the
    // component re-renders
    const intervalId = setInterval(() => {
      setTimeLeft(timeLeft - 1);
    }, 1000);

    // clear interval on re-render to avoid memory leaks
    return () => clearInterval(intervalId);
    // add timeLeft as a dependency to re-rerun the effect
    // when we update it
  }, [timeLeft]);

  return (

{timeLeft}

  );
};

Comment: @AmirShitrit Do you mean `setTimeout`? Both are valid options but `setTimeout` suppose to trigger the function once while `setInterval` suppose to trigger the function every x amount of time. because of the nature of `useEffect` where we need to set and clear the timer every time `timeLeft` changes i guess it doesn't really act like a "real" `setInterval` and i can see your point of `setTimeout` in this case.
Comment: Could be made more robust against setInterval drift by calculating a `Date.now() - start` delta instead of subtracting one second at a time.
Comment: Does it make more sense to use setTimer here?
Comment: Yes. I meant set Timeout. Thanks!
Comment: @AmirShitrit Yes, I prefer setTimeout
Comment: the thing i like most about this is that it works.
Comment: isn't it setting interval over and over.
Answer: You should use setInterval. I just wanted to add a slight improvement over @Asaf solution. You do not have to reset the interval every time you change the value. It's gonna remove the interval and add a new one every time (Might as well use a setTimeout in that case). So you can remove the dependencies of your useEffect (i.e. []):
function Countdown({ seconds }) {
  const [timeLeft, setTimeLeft] = useState(seconds);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setTimeLeft((t) => t - 1);
    }, 1000);
    return () => clearInterval(intervalId);
  }, []);

  return
{timeLeft}s
;
}

Working example:

Note in the setter, we need to use this syntax (t) => t - 1 so that we get the latest value each time (see: https://reactjs.org/docs/hooks-reference.html#functional-updates).

Edit (22/10/2021)
If you want to use a setInterval and stop the counter at 0, here is what you can do:
function Countdown({ seconds }) {
  const [timeLeft, setTimeLeft] = useState(seconds);
  const intervalRef = useRef(); // Add a ref to store the interval id

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      setTimeLeft((t) => t - 1);
    }, 1000);
    return () => clearInterval(intervalRef.current);
  }, []);

  // Add a listener to `timeLeft`
  useEffect(() => {
    if (timeLeft <= 0) {
      clearInterval(intervalRef.current);
    }
  }, [timeLeft]);

  return
{timeLeft}s
;
}

Comment: Will this actually be exact? Isn't there some tiny amount time passing between the next execution of `useEffect`?
Comment: The interval will run infinitely
Comment: You could stop the counter by unmounting the component if you want to stop at 0: `{seconds > 0 && }`. But true, depending on the requirements, it might need some adjustments. Here it won't update the interval value if you update the `seconds` in props either. I just wanted to present a valid alternative to `setTimeout`, using `setInterval` (and not resetting it each render).
Comment: That's the thing, the parent doesn't know anything about `timeLeft`, updating the interval on each re-render is perfectly fine and gives you options to do things when `timeLeft` reaches a certain point like 0. You could do it inside the state updater callback but that's just ugly in my opinion
Comment: ESLint has a rule `react-hooks/exhaustive-deps` that enforces adding the dependency of `timeLeft` in the array. But still, agree with not having to clear the interval every time. I think in that case I'll have to use `setTimeout`
Answer: Here's another alternative with setTimeout
const useCountDown = (start) => {
  const [counter, setCounter] = useState(start);
  useEffect(() => {
    if (counter === 0) {
      return;
    }
    setTimeout(() => {
      setCounter(counter - 1);
    }, 1000);
  }, [counter]);
  return counter;
};

Example
Answer: Here's my version of a hook, with a "stop" countdown.
Also, I added a "fps" (frames p/sec), to show the countdown with decimal places!
import { useEffect, useRef, useState } from 'react'

interface ITimer {
    timer: number
    startTimer: (time: number) => void
    stopTimer: () => void
}

interface IProps {
    start?: number
    fps?: number
}

const useCountDown = ({ start, fps }: IProps): ITimer => {
    const [timer, setTimer] = useState(start || 0)
    const intervalRef = useRef<NodeJS.Timer>()

    const stopTimer = () => {
        if (intervalRef.current) clearInterval(intervalRef.current)
    }

    const startTimer = (time: number) => {
        setTimer(time)
    }

    useEffect(() => {
        if (timer <= 0) return stopTimer()
        intervalRef.current = setInterval(() => {
            setTimer((t) => t - 1 / (fps || 1))
        }, 1000 / (fps || 1))
        return () => {
            if (intervalRef.current) clearInterval(intervalRef.current)
        }
    }, [timer])

    return { timer, startTimer, stopTimer }
}

export default useCountDown

Answer: Here is a small component - CountdownTimer - accepting an input parameter expiresIn representing the time left in seconds.
We use useState to define min and sec which we display on the screen, and also we use timeLeft to keep track of the time that's left.
We use useEffect to decrement timeLeft and recalculate min and sec every second.
Also, we use formatTime to format the minutes and seconds before displaying them on the screen. If minutes and seconds are both equal to zero we stop the countdown timer.
import { useState, useEffect } from 'react';

const CountdownTimer = ({expiresIn}) => {
    const [min, setMin] = useState(0);
    const [sec, setSec] = useState(0);
    const [timeLeft, setTimeLeft] = useState(expiresIn);

    const formatTime = (t) => t < 10 ? '0' + t : t;

    useEffect(() => {
        const interval = setInterval(() => {
            const m = Math.floor(timeLeft / 60);
            const s = timeLeft - m * 60;

            setMin(m);
            setSec(s);
            if (m <= 0 && s <= 0) return () => clearInterval(interval);

            setTimeLeft((t) => t - 1);
          }, 1000);

          return () => clearInterval(interval);
    }, [timeLeft]);

    return (
        <>
            {formatTime(min)} : {formatTime(sec)}
        </>
    );
}

export default CountdownTimer;

Optionally we can pass a setter setIsTerminated to trigger an event in the parent component once the countdown is completed.
const CountdownTimer = ({expiresIn, setIsTerminated = null}) => {
    ...

For example, we can trigger it when minutes and seconds are both equal to zero:
if (m <= 0 && s <= 0) {
    if (setTerminated) setIsTerminated(true);
    return () => clearInterval(interval);
}


Mips Help for Converting decimal into octal

Question: I'm having trouble converting an input (decimal number) and converting into an octal and displaying that number, using MIPS. In the project, I have to use Masking, are there any good sample codes for this?
Answer: To mask out all but the bottom 3 bits of the number in $t0 use:
andi $t1,$t0, 0x7    # 0x7 is binary 0111


Namespace cannot be found in one form but it can in others in the same project VB VS2010

Question: I'm having an issue here which I can't resolve. I can't include the namespace which is correct because visual studio correct it into another namespace wich is incorrect. But in other forms in the same project it doesn't have the same behavior.I have checked that my project is configured in .NET 4 and I have restart it and nothing happens. What's going on?
Could you please help me?
Imports ProjectName.BusinessLogicLayer -> This is the correct namespace
Imports Projectname.BusinessLogicLayer -> This is the incorrect
Comment: possible duplicate of [VS2010 refuses to compile a namespace, says it doesn't exist](http://stackoverflow.com/questions/4785302/vs2010-refuses-to-compile-a-namespace-says-it-doesnt-exist)
Comment: Thank you very much because I resolved my problem Nidzaaa! I found the solution in http://stackoverflow.com/questions/4785302/vs2010-refuses-to-compile-a-namespace-says-it-doesnt-exist
Comment: Click right on the file->Properties->Build Actions -> Choose Content, not Compile
Answer: I figured out how to solve my proble with Nidzaaa help! The answer is: Click right on the file->Properties->Build Actions -> Choose Content, not Compile


2 prong outlet with 3 wires

Question: Our 1950s era house has a 2-prong switched outlet by the front door. Both plugs are turned on/off by the switch next to the front door, so it's not one of those split kind where one plug is always hot and the other is switched.
The outlet has 3 wires like this:

The metal between wires 2 and 3 on the left is connected, so it's not like the modern outlets where you can break the tab to stop the continuity between these 2 screw terminals.
I did an experiment where I disconnected each wire one at a time and found these results:

Disconnected 1: Both plugs on this outlet stop working.
Disconnected 2: Both plugs on this outlet stop working.
Disconnected 3: Both plugs on this outlet work, but another outlet on a different wall stops working.

I held a non-contact voltage detector by each wire and it shows 1 and 3 with voltage. The really baffling part is that the voltage tester still shows voltage on 1 and 3 when the switch is turned off, but I've read that you can have "phantom voltage" so maybe it's showing that. The switch doesn't turn off the other outlet, just this one.
Does the following sound like a correct assessment?

Wire 1 is the incoming hot for this outlet.
Wire 2 is the neutral.
Wire 3 is the neutral leg coming from the outlet on the other wall.

I'm also curious how the switch is involved here to turn off the outlet. Maybe Wire 1 is being turned off despite the tester showing voltage there. I also thought perhaps the switch is interruping the neutral wire 2, but if that's the case then the other outlet would be shut off too.
Comment: Are there other wires in the box spliced together?
Comment: What does your voltage tester read between wire 3 and ground?
Comment: Good question on the other wires being spliced. I will look in there. Regarding the voltage tester, I wasn't sure what to use as a ground because there isn't one in there. What could I use as a substitute? Run a long wire to the grounding rod outside attached to the cold water pipe I guess?
Comment: I guess I could test the voltage on 3 if I assume 2 is a neutral? I just wasn't sure if 2 turns out not to be a neutral and it won't give me an accurate reading.
Comment: Are all of the wires coming into the box separately? If they are you could be dealing with Knob and Tube wiring where the Line and Neutrals are run separately.
Comment: Can you post a photo of the inside of this box?  I suspect something's up here -- Wire 1 being a switched hot returning from a loop with the hots nutted in the back of the box and a lazy installer who didn't want to pigtail the neutral would explain this perfectly, but we'd need a photo to know for sure.
Comment: Hi ThreePhaseEel, I never got a pic of it and the outlet is closed up and behind the big bookcase again. Sorry about that. Thanks for trying to help--I wish I could learn from your knowledge. I appreciate your input.
Answer: I used a continuity tester and found that

The right wire #1 comes from the switch. The switch's other wire is the hot, so when the switch is turned on, the power flows through the switch, then to this wire that feeds this outlet on that right wire.
The bottom-left wire #3 comes from the other outlet, and it's a neutral in that outlet, so basically it is the continuation of that outlet's neutral. (I'm not sure why they hooked it up this way rather than using a cap to tie it together with a pigtail to the outlet? But I guess electrically it's the same. I think I will rewire it the way I'm used to seeing.)
The top-left wire #2 must be the neutral.

As far as why there's voltage on #3, I'm baffled! I don't know how hacky this is but I used my jumper cables to hook to the grounding rod outside so I had a definite ground (this is a 2 prong outlet so I didn't know what else to use as ground), then tested the wires and #1 had 120V as expected with the switch on, but #3 had 70V even when it was disconnected from this outlet! I'm going to have to call an electrician to investigate this further because I have no clue why.
Comment: 70V is what you would expect when measuring voltage in series, which is exactly what happens when you measure a neutral coming out of one device into another ground or neutral. The lamp or other upstream device is getting 50V, and your tester measures the other 70V, for a total of 120V. Connecting electrical devices in series splits the voltage according to resistance (I believe, not an EE) and connecting them parallel uses more amps. To measure the 120V, you need to measure hot to ground, not an in-use neutral to ground. A disconnected neutral to ground would be 0V.
Comment: IF there is a device connected to that other outlet, then what you are seeing is the live coming through that device. Disconnect it and you'll see it drop to 0.
Answer: Wire number 1 is your switched power wire from the switch, wire number 2 is the neutral path back towards the panel, and wire number 3 is the neutral wire coming from other outlets down the line.
The reason you read 70 volts on number 3 is that something on that circuit is using power and you disrupted the path. You can be shocked if you complete the circuits. Even if nothing is plugged into the other outlet there is most likely another outlet on that neutral with something plugged in. You see this with a lot of homes with knob-and-tube wiring.
Think of it like this you turn on the faucet and fill a glass of water, you put the rim of the glass halfway in the stream, some water fills the glass the rest is going down the drain. Think of the number 3 wire as the drain and a light bulb for example as the cup. That's why you read 70 volts
Answer: I had trouble following your description. Where do these wires enter the box? Is there more than one cable entering the box? For the two switched outlets in the same box, there are a couple of ways this can be wired.
A single power cable enters the switch box with the hot connected to the switch and the other switched wire becomes the hot wire to the outlet. In the outlet the switched hot connects to one side of the outlet and neutral to the other side. In the switch box, neutral from the outlet is pigtailed to neutral from the supply. If downstream devices are supported, they are wired from the live hot and neutral fed through their own cable.
If the supply cable enters the outlet box, the hot side is fed to the cable to the switch box and the neutral wire in that cable is coded as hot in both boxes and connects to the hot side of the outlet and one side of the switch. Downstream devices must be supplied by a cable from the outlet box  that is pigtailed to the corresponding supply wires.
Given that new outlets are cheap, you might wish to replace the old two-prong outlets with child-safe (if you approve of children) modern outlets.
Comment: thanks for answering. I will try to post a picture of it. There are 3 cables that enter the box, I believe. It's the old tar-cloth 2-wire Romex style of cable. I believe it's the way you described it first, ie, "A single power cable enters the switch box with the hot connected to the switch and the other switched wire becomes the hot wire to the outlet". The wire I labeled #2 is the neutral, I'm pretty certain, it was #3 that was really confusing me. That's coming from a separate cable.
Answer: Based on a recent exercise I went through in dealing with phantom voltage, it is possible the 70 volts you measured on line 3 is phantom voltage. If it was a typical hot wire, it would read 120 volts (unless something else is badly wrong.) You might want to test the voltage on the outlet the #3 neutral wire comes from to confirm it is also reading 120 volts. I don't know of a good way to check if voltage is phantom. One article I found in this forum said an older volt meter may not sense phantom voltage. The other possibility is there may be a timer or dimmer on the circuit that continuously runs a low voltage through the system to keep the timer/dimmer working. If there is more than the single outlet connected to line #3 (e.g. the neutral in the other outlet goes somewhere else as well) anything upstream could be adding the phantom voltage.
btw, I didn't see it mentioned in the other responses, but if a 2-prong receptacle is wired correctly, the hot wire will go into the smaller of the two prongs (as shown on the right side of your picture) and the neutral wire goes to the larger of the two prongs. So your analysis is consistent with a correctly wired plug.
In the situation you describe, I would be worried about where the hot wire in the other outlet is coming from (the one with the neutral wire as wire #3). I hope it is coming from the box that contains the switch that works the first outlet, but if it is coming from somewhere else, there may be a risk that it is on a different fuse/circuit breaker. You might want to confirm that everything is on the same circuit. And if they are all on the same circuit, shutting off the circuit should also eliminate the 70 volts you are measuring on wire #3.
Answer: We need to establish some terminology:
Cable - is a three-wire of black or white insulation and bare copper wrapped in an insulator. This is a fabric in older cables and plastic in newer cables.
Wire - is a copper conductor that is bare for ground wires, black for hot wires and white for neutral.
You appear to have established that one cable goes to the switch box, one connects to the power panel and the other connects to further downstream devices.
You appear to be comfortable with electricity so I will remind you to do all work with power off at the panel and a lock or note on the door.  Trust no one, least of all yourself. Always test for live current before touching anything.
In normal usage the hot wire from the panel can be connected to the hot wire to the switch and to the hot wire to downstream. The white wire from the switch could be 'coded to black' with electrical tape or paint. This last wire will be connected to the hot side of your outlet.
The ground wires will all be connected together, attached to the box with a  machine screw and also connected to the outlet's green screw (if you love your family and used a new outlet like I suggested).
New three-prong outlets can be tested with those little testers that plug in and light up so nicely.
The three neutral wires will all be connected and a white pigtail will connect to the neutral side of the outlet.
Comment: It seems to me like they used the spare terminal for wire #3 as an alternate way to connect the neutrals #2 and #3, rather than twisting them together with a cap and then having a single white pigtail connect to the neutral side of the outlet like you said. From the electricity's point-of-view, using the spare terminal will still work, right? But it's confusing because you can't tell what is going on. Which makes me wonder if twisting the neutrals together and having a pigtail is partly done for clarity so you can tell what the heck is going on!
Comment: @JamesToomey -- partly for clarity and partly because it means that pulling a device out won't interrupt the neutral wire.

2 prong outlet with 3 wires


Fetching data but "Cannot read property '0' of undefined"

Question: I try to fetch some data from the https://randomuser.me/api/  . I wanna take an random user gender but i don't know why my function doesn't do it and i get this error "Cannot read property '0' of undefined"
My code:
const [fetchData, setFetchData] = useState('');

    fetch('https://randomuser.me/api/')
        .then((response) => response.json())
        .then(setFetchData)
        .then(console.log(fetchData.results[0].gender));

Comment: you are trying to access state immediately after it is set . https://stackoverflow.com/questions/38558200/react-setstate-not-updating-immediately
Comment: You should make the API call in a useEffect.
Comment: @selbie i think yes, because i did the same thing on my last project and it went well
Comment: Does this answer your question? [addEventListener calls the function without me even asking it to](https://stackoverflow.com/questions/16310423/addeventlistener-calls-the-function-without-me-even-asking-it-to)
Answer: fetchData doesn't get updated when setFetchData is called.  Remember, it's just a local variable that got assigned when you invoked useState.  It doesn't magically get updated until the next call to your function. And even then, setState is asynchronous, so it might not change immediately.
This is what you likely really want.
fetch('https://randomuser.me/api/')
    .then((response) => response.json())
    .then((json)=> {
         setFetchData(json);
         console.log(json.results[0].gender);
     });

I tried it out locally and it worked for me.
Also, as an aside.  For robustness, so you don't throw an exception on a console statement when the response is completely unexpected:
if (json && json.results && json.results[0]) {
    console.log(json.results[0].gender);
}