Woocommerce Subscription access from external php

Question: I have a Wordpress website with Woocommerce and Woocommerce Subscription plugins.
I need to write some PHP script that will check if a user has active subscription status.
From the database, I would like to get information: user id, status (if it's active - if payment was made and the subscription was renewed), end date of subscription...
The problem is that I don't even know where subscription info is saved?
Can somebody write me a snippet of code, that includes a query that will give me a list of users that subscribed, with the necessary information mentioned earlier?
I will post an update with code later, for now, I just need help with query and guidance where to look in the database tables.
Answer: I think what you meant is you want to access the Wordpress/Woocommerce Subscriptions API from a PHP file within your Wordpress installation. To do this I think the following will help:

Create a folder in wp-content/plugins called woocommerce-subscriptions-status-checker
Create a file called woocommerce-subscriptions-status-checker.php inside the above new folder.
Add this code in the file:

/*
Plugin Name: Woocommerce Subscriptions Status Checker
Plugin URI: http://www.XXXXXX.com
Description: XXXXXXXXX
Author: XXXXXX
Version: 2.0
Author URI: http://www.XXXXX.com
*/

if ( ! defined( 'ABSPATH' ) ) {
  exit;
}

class WC_Subscriptions_Status_Checker {

  function __construct() {

    // Avoids the function firing if we are in wp-admin backend
    if ( !is_admin() ) {
      // Fires on every page load after WordPress, all plugins, and the theme are fully loaded and instantiated
      add_action( 'wp-loaded', array( $this, 'check_current_user' ) );
    }
  }

  function check_current_user() {

    // Check if user is even logged in, if not exit
    if ( !is_user_logged_in() ) return;

    $current_user   = wp_get_current_user(); // get current WP_User
    $user_id    = $current_user->ID; // get user id

    $is_subscription = wcs_user_has_subscription( $user_id ); // check if user has subscription
    if ( $is_subscription )
    {
      $subscriptions = wcs_get_users_subscriptions( $user_id ); // get array of all subscriptions

      // Check if there is one subscription or multiple subscriptions per user
      if ( count( $subscriptions ) > 1 ) {

        // Example if you wanted to loop through all subscriptions, in the case of the user having multiple subscriptions
        foreach ( $subscriptions as $sub_id => $subscription ) {
          if ( $subscription->get_status() == 'active' ) {
            // Do something
          }
        }
      } else { // Only 1 subscription

        $subscription  = reset( $subscriptions ); // gets first and only value
        if ( $subscription->get_status() == 'active' ) {
            // Do something
          }
      }
    }

  }
}
new WC_Subscriptions_Status_Checker();

Visit the plugins section of wp-admin and Activate your new plugin.
Comment: Hello! Thanks for the reply. My subscription plan will be monthly or annual. I  had in mind that I will check the subscription status every time a user login and visits the site?! I copied your code and test it. I get a list of active subscriptions. $post->ID displays ID of active subscription. How can I limit results to one user and for current subscription status, if I have the ID of a logged-in user?
Comment: Hi, you will definitely want to do that in a plugin then. I will edit the answer to show you how.
Comment: @Tyler is it possible to get payment gateway details of the customer. Or is it possible to make customer autopay from your plugin?
Answer: You can try Woocommerce REST API.
https://docs.woocommerce.com/document/woocommerce-rest-api/
Basically, Woocommerce provide a restful API to access the data and interact with the ecommerce system outside of the traditional woocommerce workflow.
Answer: Here is my solution (not saying that it's the best, but for me, it solved the problem that I had).
Code in function.php (WP child theme)
add_action('init','getWPuser');
function getWPuser(){
$current_user = wp_get_current_user();
return $current_user;
}

Custom website
Code in my custom site that needs information about the user.
require_once '../wp-load.php';
require_once '../wp-content/themes/h-code-child/functions.php';
require_once '../wp-includes/pluggable.php';
require_once '../wp-blog-header.php';
$current_user = getWPuser();

Saving user ID information.
$logged_user_id = $current_user->ID;

Checking on specific subscription if it's active.
$has_free = wcs_user_has_subscription( $logged_user_id, $product_id, 'active' );


Why does Ubuntu 12.10 update to 13.04 on its own?

Question: I installed Ubuntu 12.10, after few minutes of working I've got an Update and allowed it.
After this I see that Ubuntu has been upgraded to 13.04. Why?
I am not a developer, just try to work.
In Software sources in one of tabs there is an  extras.ubuntu.com/ubuntu repo.
Is this responsible for updates to 13.04? If I disable those will the problem be gone?
Comment: It doesn't.  If you think it has, you will have to be more specific about why.
Comment: Where do you see it is 13.04?
Comment: in system details and few things are diferent
Comment: Are you sure you downloaded the right ISO file? Did you get your download from http://www.ubuntu.com/download ?
Comment: i download Ubuntu 12.10 x64 from ubuntu download site. all I want to know is why my Ubuntu after each install updates to 13.04 version
Comment: If the information [there](http://askubuntu.com/questions/254327/ubuntu-says-13-04-but-lsb-release-says-12-10) *doesn't* reveal the source of this problem, then it's a bug and should be [reported as such](https://help.ubuntu.com/community/ReportingBugs). See also [How do I report a bug?](http://askubuntu.com/questions/5121/how-do-i-report-a-bug) ([At least once before](https://bugs.launchpad.net/ubuntu/+source/ubuntu-docs/+bug/690248), information from a newer release's help was wrongly synced into an older release's help. It affected many users. It was reported as a bug, then fixed.)
Comment: @EliahKagan Thanks for Your respond :) now I know this happed when I was making Nautilus 3.6 by:

"sudo add-apt-repository ppa:gnome3-team/gnome3"
Answer: i don't think that its automatic update as 13.04 on beta
Because the ubuntu 13.04 is still on beta test , so it's not offcial released if you want to update to ubuntu 13.04 beta
open terminal , and type this   ( this is the easiest way )
sudo do-release-upgrade -d

any way its not bad to test beta as on 27 april its offcial released and u can update it


Does MW3 support cross-platform multiplayer?

Question: Does MW3 allow PC, PS3 and Xbox 360 users to play together?
How does the matchmaking work? Is it more like in Valve games, where users just select their servers, or more like console matchmaking, where you join as a group and wait to get matched?
Comment: Would this be better as 2 seperate questions?
Comment: there have been PC and Xbox live cross-platform games. Shadowrun, fable 3 are two I know of for sure. it's quite possible for it to work on MW3 also. windows has a program called "Games for Windows" for that.
Answer: It does not - the three platforms (PC, Xbox360, and PS3) are all distinct, separated multiplayer platforms (PC servers, Xbox live, and PSN).
This would require PSN and Xbox Live to interact via an agreement between Microsoft and Sony, which is unlikely given that they compete.  Additionally, the PC version supports dedicated servers and official servers, with VAC protecting against possible cheating.
Comment: Aren't Portal 2 and Dungeon Defenders cross-platform between PC and PS3?  So it's not impossible...
Answer: This has been a feature people have wanted since multi-platform releases started to hit the shelves, but to the best of my knowledge has never been implemented (please correct me if you can think of a good example, I'm sure at least a handful of games have made the attempt).
Aside from the technical challenges, there are balance problems with cross platform play between the PC and consoles. Having a mouse gives the PC player a serious edge, they can aim quicker and with greater accuracy. This is why many console games have some sort of "aim assist", which is a rare and generally unnecessary feature on a PC.
To give a more extreme example, imagine playing a game like Starcraft from a console against a player on a PC. You would be screwed, the pc player has a huge assortment of shortcuts and hotkeys in front of him, while you would spend your time slowly panning around the map just to keep units building.
While there are things that could be done to add balance, such as the previously mentioned "aim-assist", such features would cause social problems. The console players would feel cheated when a PC player headshots them with a mouse, and the PC players would feel cheated when a console player headshots them with auto-aim. Dying because you were out classed isn't fun, dying because the other player had some perceived advantage is even less fun. This is why people get upset with campers, and also why so many games have adopted a kill-cam.
Even without the psychological aspects, two people might be good at the same game for different reasons. Take for example to console players, one who gets kills through tactics, and one who gets kills from having excellent aim. Any artificial balancing against PC players would affect the two console players differently. While it's true that life isn't fair, games are more fun when they feel fair.
In my opinion, this is a technical problem that is best resolved with a business solution. I could imagine some sort of scheme where for less the full cost of buying the game twice, I could get a "multi-platform" version. Kind of like what we see now with blu-ray DVD combo packs. There would have to be some mechanism to prevent the resale of the second copy to keep the publishers happy. A shared two step authentication method is one possibility, although I'm sure there are better solutions out there.
Comment: Nice answer but you lost me with Citrix even though I know what is it.
Answer: So far, the only game I know of which two different platforms run on the same server is Final Fantasy 11. At the time I played it, it was both PC and PlayStation 2.
I have Call of Duty®: Modern Warfare® 3 for the Wii, and as it was said before, there would be some serious advantages as far as controls go. I wouldn't want to get owned by some kid who has easier controls.
Answer: Call of Duty: ELITE at least allows everyone to share and pool stats in clans and groups regardless of platform.


How to seek product input from forums?

Question: I'm seeking thoughts on how to get product/general feedback from a large public industry forum?
My time and means can be somewhat limited. So I'm looking into ways i can get qualitative input on user pain points, preferences, and general usage.
I know it's not perfect, and I'd have to say who i was because the users are a suspicious group. Thoughts? Pitfalls? Suggestions?
Answer: My first point is that you can be a little creative in how you say who you are. "I'm a researcher trying to find out how users are working with the UniCorp product" will get you much better answers than "I work for UniCorp".
My second point is that online forums tend to be a very focused group of people - most of them will be there to either complain about a product or to find ways to do the things they think they should be able to but can't - Either way, it's a negative relationship from the start - This will skew your results.
You would be better off getting hold of a list of users (talk to your legal department first) and emailing some randomly selected people with either an invitation to a video call (which you can record for further study) or just the questions you'd like them to answer.
Forums are a great place to see where your product might be falling short but they're not the best place to get a balanced opinion.

How to seek product input from forums?


Two functions in a loop, but only one is executed (anonymizing of DICOM files + moving them)

Question: so I have a question regarding a script i wrote including two functions.
The idea is to anonymize all DICOM files (the dataformat for CT files) in a given folder, and move the anonymized files to new folder.
The issue is - the anonymizing function works by itself, the function which moves all the files from one folder to another as well. Unfortunately I'm not able to make both functions work in one loop.
Function for anonymizing DICOM files:
folder = r"C:.../test1"
target = r"C:.../test2"

def forceAnonymizeDICOMFile(inFile, outFile, dictionary = ''):
currentAnonymizationActions = initializeActions()

    del currentAnonymizationActions[(0x0010, 0x0020)]
    del currentAnonymizationActions[(0x0010, 0x0040)]
    if dictionary != '':
    currentAnonymizationActions.update(dictionary)

    dataset = pydicom.dcmread(inFile, force=True)

    dataset[(0x0010, 0x0010)].value = dataset[(0x0010,0x0020)].value

    # Store modified image
    dataset.save_as(outFile)

Moving function:
def moving(folder, file, target):
    for file in files:
        shutil.move(os.path.join(folder, file), target)

Loop for connecting both:
subfolders = os.listdir(folder)

for idx, subfolder in enumerate(subfolders, 1):
    print(f"{idx}/{len(subfolders)} ({subfolder})")
    for file in os.listdir(folder+"/"+subfolder):
        filepath = folder+"/"+subfolder+"/"+file
        forceAnonymizeDICOMFile(filepath, filepath)
        moving(folder, file, target)

I feel like there is an error in my loop, since I get the error:
FileNotFoundError: [Errno 2] No such file or directory: 'C:../test1'
I don't assume the error lies in both of the functions since they both work fien standalone.
Any help would be highly appreciated, thank you!
Answer: I could actually solve it.
The issue was that I didn't specify the folder structure in the target folder:
for file in os.listdir(folder+"/"+subfolder):
    filepath = folder+"/"+subfolder+"/"+file
    target_filepath = target+"/"+subfolder+"/"+file
    if os.path.isfile(target_filepath):
        continue
    print(f"Anonymizing file {filepath}")
    forceAnonymizeDICOMFile(filepath, target_filepath)

Now it is working properly.
Thank you @Timus for your input!


Authentication required to modify a printer- what's the password?

Question: I have 12.04 and have 2 printers installed, both wirelessly over my personal network, no printer sharing. When I try to modify the printers I get a window asking for authentication (username and password). For the life of me I cannot think what these might be. At first I thought it might be my Ubuntu account username and password, but I can't get it to work. The printer username and password (admin and access) doesn't work either.
Does anyone know what it is asking for, and how I can turn that off?
Many thanks.
Comment: try the username & password which was set up first (when installing Ubuntu)
Answer: You might be affected by this bug.
Try running
gksudo system-config-printer

in a terminal window, then setting up the printer
However, if gksudo is not found, try:
sudo -H system-config-printer

Comment: Tried in Ubuntu 12.4.2 and it works. Thanks!
Comment: Tried in Ubuntu 13.10 and it works too.
Comment: I've tried that with the following results:-
Comment: Sorry these results:-(system-config-printer:3620): Gtk-CRITICAL **: 07:26:04.797: gtk_tree_store_insert_after: assertion 'G_NODE (sibling->user_data)->parent == G_NODE (parent->user_data)' failed

(system-config-printer:3620): Gtk-CRITICAL **: 07:26:04.797: gtk_tree_store_set_value: assertion 'VALID_ITER (iter, tree_store)' failed

(system-config-printer:3620): Gtk-CRITICAL **: 07:26:04.797: gtk_tree_store_set_value: assertion 'VALID_ITER (iter, tree_store)' failed
Answer: Adding my username to the lpadmin group, as suggested by msanderz, worked for me. Here is how you add yourself to the group:
sudo usermod -a -G lpadmin YOUR_USERNAME
Answer: I had a similar problem and solved it by adding my user name to the group "lpadmin" which allowed me to make changes in the printer. Since I have been trying to solve a different problem for about three days I do not remember exactly what I did. Try googling "ubuntu add user name to groups" for the sudo command to add your user name.


Is it possible to be permanently killed by the Black Death?

Question: It is a well known fact that one of the most dangerous monsters in the original Diablo is actually one that you encounter relatively early - a variant of the zombie monster known as Black Death.
These can be encountered on levels 3-5 and seem harmless enough, as they don't do a lot of damage and are just as slow as all the other types of zombies, but each time they hit you they take away 1 HP out of your maximum, permanently (I didn't realize this until a friend tipped me off, at which point I avoided these like, well, the black death).
Thinking about this now, I am wondering just how low you can get your HP by getting hit by these monsters. Specifically, I wonder what were to happen if you manage to reduce your maximum HP to 1 and then get hit by one of these (though I imagine this is tricky to pull off, seeing how at a certain point each hit by these would kill you off completely)?
Comment: Similarly, avoid certain shrines which can reduce your maximum mana by 10%: http://gaming.stackexchange.com/questions/47663/what-shrines-are-good-for-me
Answer: No: the lowest possible total HP is "1".

Black Death hit for more HP (6-22 HP/hit) than they deduct from your max HP (1 HP/hit).1 In most cases, their final blow kills you before their max HP modifier could. In single-player, all deaths "permanent" kills, as you're forced to load from your last save or start over.2 In multiplayer, you can restart naked at the nearest town (like in Diablo II's multiplayer).
If you get tricky, you can use Mana Shield—a spell that deducts damage from mana instead of health3—to reduce your max HP to "1". After this point, Mana Shielded Black Death hits only reduce mana, not health. Likewise, your next unshielded Black Death hit kills you but does not further reduce your max HP:
Comment: I tested it, and while Mana Shield brings you closer to 1 HP, you won't ever hit zero.
Comment: False, with Mana Shield you can be reduced below that. If I recall correctly you end up with 0 max health and die instantly upon restarting in town.
Comment: Also, deaths are not necessarily permanent. If you're playing on Battle.net or by yourself in "multiplayer" you can restart in town and recover your dropped items.
Comment: Hmm, yes, I see. My question is a little misleading. I'll edit it a little when I get back from work. Thanks for the great answer!
Comment: @Decency Now that's thinking outside the box. Thanks for the info, I hope this gets incorporated into the current answer (or maybe I'll go ahead and do some editing).


Nautilus calling stat/file on all directory entries

Question: I am writing a paper and I need to confirm something that is pretty obvious to me but I haven't seen the code that would authoritatively tell me that this is how it works.
When I open a folder in Nautilus, does it call stat syscall and file command on every regular file in that folder? I also wonder how it generates thumbnails but that is a side quest.
Answer: Nautilus is written in C. I have not found any reference to stat syscall in the source code, so cannot say with 100% certainty that it does or does not use it.
Mime type of files is obtained via nautilus_file_get_mime_type function, which is referenced a lot in multiple files such as nautilus-mime-actions.c , nautilus-properties-window.c , nautilus-window-slots.c and others.
However, i could not find the definition of that function, only assignments:
$ grep -iR 'file_get_mime_type'
nautilus-canvas-view-container.c:   mime_type = nautilus_file_get_mime_type (file);
nautilus-mime-actions.c:    mime_type = nautilus_file_get_mime_type (file);
nautilus-mime-actions.c:    mime_type_a = nautilus_file_get_mime_type (file_a);
nautilus-mime-actions.c:    mime_type_b = nautilus_file_get_mime_type (file_b);
nautilus-mime-actions.c:    mime_type = nautilus_file_get_mime_type (file);
nautilus-mime-actions.c:    char *mime_type = nautilus_file_get_mime_type (parameters->file);
nautilus-mime-actions.c:        mime_type = nautilus_file_get_mime_type (parameters_install->file);
nautilus-mime-actions.c:    mime_type = nautilus_file_get_mime_type (parameters_install->file);
nautilus-mime-actions.c:    mime_type = nautilus_file_get_mime_type (file);
nautilus-properties-window.c:       ret = g_list_append (ret, nautilus_file_get_mime_type (NAUTILUS_FILE (l->data)));
nautilus-properties-window.c:   mime_type = nautilus_file_get_mime_type (file);
nautilus-properties-window.c:   mime_type = nautilus_file_get_mime_type (target_file);
nautilus-window-slot.c:     mimetype = nautilus_file_get_mime_type (file);


Ubuntu USB Instalation problem

Question: I have a problem installing Ubuntu using a USB drive with Windows already installed. So i used the program Unetbootin and it booted up perfectly asked me if i want to try Ubuntu or installing.
I have tried both of them with the same result, it asks me the language, if i want to install updates and install 3rd party software and i say yes. After that it asks to restart the computer to install Ubuntu alongside Windows.
So, the computer restarts and the Ubuntu screen asks to remove installation media and press enter. I do so, but it does not install Ubuntu it just boots up Windows 7.
And inside Windows it does not prompt up a installation screen or nothing. I do not really know what i am doing wrong.
Thanks for the help and sorry if this was already asked.
Answer: Better use Ubuntu 15.10.
I guess your Problem is that you choose the wrong place for installing the bootloader.
Probably /dev/sda is the right one. NOT /dev/sda1 /dev/sda2...
See here:
http://www.dedoimedo.com/images/computers_years/2014_1/ubuntu-install-bootloader.jpg

Ubuntu USB Instalation problem


LightDM and GDM login loop. Ubuntu 15.04 Gnome 3

Question: At first the GDM worked just fine but all of a sudden I lost the ability to login. I can still get to my desktop using startx (sound doesn't seem to work when I do that but it might be a by-product of having to use root privileges to get startx to run.) There doesn't seem to be anything especially incriminating in any of the error logs or journalctl except for
<code>Mai 10 03:56:38 curtis-UX301LAA systemd[1]: Started Light Display Manager.
Mai 10 03:56:38 curtis-UX301LAA systemd[1]: Started ACPI event daemon.
Mai 10 03:56:38 curtis-UX301LAA systemd[1]: Starting ACPI event daemon...
Mai 10 03:56:38 curtis-UX301LAA systemd[1]: Started Run Click system-level hooks.
Mai 10 03:56:38 curtis-UX301LAA acpid[1295]: starting up with netlink and the input layer
Mai 10 03:56:38 curtis-UX301LAA acpid[1295]: 9 rules loaded
Mai 10 03:56:38 curtis-UX301LAA acpid[1295]: waiting for events: event logging is off
Mai 10 03:56:38 curtis-UX301LAA acpid[1295]: client connected from 1288[0:0]
Mai 10 03:56:38 curtis-UX301LAA acpid[1295]: 1 client rule loaded
Mai 10 03:56:38 curtis-UX301LAA systemd[1]: Received SIGRTMIN+21 from PID 384 (plymouthd).
</code>
I know this is really vague but if someone could point me towards where to start finding potential errors I'm sure I'd be able to make progress on this.
Q:What is the best way going about debugging this?
P.S. The issue isn't with permissions and I've uninstalled-reinstalled both GDM and lightDM many times. The only thing I can think of is there is something up with my lightdm config file but all I have in there is autologin and user-session=gnome. Also there is nothing in .xsession-error. This is what makes my issue different from Ubuntu gets stuck in a login loop.
Updates: It seems that the sessions are getting correctly started and actually persist (at least as far as I can tell by looking at the journalctl output.) There are no errors getting returned from X but I do see dbus errors scattered a little bit everywhere.
Comment: The point of me pointing out that there was no permission issues was so that it wouldn't be marked as a duplicate of that question.
Answer: I'm not sure exactly what I did to get lightdm to successfully start a session for me except maybe allowing anyone (not just consoles) to connect to the xserver. The gnome-shell desktop still doesn't appear when I login through lightdm while it does when using startx.


How can I let player click text to use a command?

Question: I want players to be able to click text to run an OP command even if that player is not an OP. For example something like:
Console: Do you want to enable Fly? [If you do, Please click here]

*Player1 clicks that text*

Console: /fly Player1

Is something like this possible?
Comment: Have you made any attempt to solve this yourself? Arqade works better when askers show effort to solve their own problems; we see that you have a problem you've worked on, and answerers respond to that. You also get a more specific answer that's tailored exactly to the part you're stuck, and Arqade gets a very specific question. Everybody wins!
Comment: Yes, I did try this myself in my test world, but I really can solve this out myself.... So I came here for help :(
I use scoreboard and trigger command to test it but I just... stuck for about 3 hours.
I see Xisuma's one player sleep video before, so I know some basic commands.
I have a small Server, not too many peoples play it, I just want my players can fly to build something but I don't want players to use fly all the time, So I decided to try it.
and.... I am sorry for my broken English.
Comment: I really thank all of you guys correcting my broken English and help me to solve this out! I really appreciate it!
Answer: It is a bit of a chore but you can use tellraw command along with a scoreboard.
First create a trigger objective (manually type this in chat):
/scoreboard objectives add TellTrigger trigger

Then you have to enable the trigger for the players who should be able to access your command.  You can put this command into a repeating / unconditional / always active command block to allow anyone access:
/scoreboard players enable @a TellTrigger

You could also be more selective with the target selector if you have teams or some other selection method. (ex: @a[team=red])
If using the always repeating command block, I recommend disabling command block output to prevent chat spam using command:
/gamerule commandBlockOutput false

The trigger command can now be used:
/trigger TellTrigger set 1

Use that command as a clickEvent in a tellraw command.  Here is a tellraw generator you can use to create it.
Here is a tellraw command you can use:
/tellraw @a ["",{"text":"Do you want to enable flight?  "},{"text":"[Click Here]","color":"aqua","clickEvent":{"action":"run_command","value":"/trigger TellTrigger set 1"}}]

Note: Players with the trigger enabled can just type /trigger TellTrigger set 1 and it will do the same thing as clicking the tellraw.  They would have to know the objective name though, so it is unlikely.
Note 2: When a player clicks the tellraw, it disables their access to trigger.  If you are not using the repeating command block, you will have to re-enable for them to use it again.

That was just the setup.  Now you have to create a chain of command blocks to detect the score, set fly mode for player, and set that players objective score back to 0.  If you have only specific players trigger enabled, you can also re-enable their trigger in this chain.
The first block will detect the objective score, it starts everything.  It is a repeating / unconditional / always active command block running this command:
/testfor @a[score_TellTrigger_min=1,score_TellTrigger=1]

The next block runs the desired higher authority command.  It is a chain / conditional / always active command block with:
/fly @a[score_TellTrigger_min=1,score_TellTrigger=1]

The next block is used to re-enable access to trigger.  If you are using the repeat command block to enable access, you can skip this block.  It is a chain / conditional / always active command block with:
scoreboard players enable @a[score_TellTrigger_min=1,score_TellTrigger=1] TellTrigger

The final block resets the objective score to 0 so that it will not continue to be detected by the first command block.  It is a chain / conditional / always active command block with:
scoreboard players set @a[score_TellTrigger_min=1,score_TellTrigger=1] TellTrigger 0

If there is still confusion, Dragnoz has a youtube video with a similar method:
Here
You can also do an internet search with string minecraft tellraw trigger and it brings up several different examples.
Answer: I can give you an idea of how it should look like, but /tellraw would execute the command as if the player typed it, so it's not possible to override the permissions they (don't) have. If you want them to use fly they would still need the proper permissions.
There may be a workaround for that using other stuff, but in /tellraw directly it's not possible.
Anyway, here is how you would do it:
/tellraw @p {
    "text":"Your message",
    "clickEvent":{
        "action":"run_command",
        "value":"/say Hello world!"
        }
    }

This shows as "Your message" and lets you say "Hello world!" when clicking on it.
Or in your case if the command was valid:
/tellraw @p [
    "",
    {"text":"Do you want to enable Fly? ["},
    {"text":"If you want, Please click here",
     "clickEvent":{
        "action":"run_command",
        "value":"/fly player1"
         }
    },
    {"text":"]"}
]

As you can see you can even have more than one text here giving you the opportunity to make players choose from commands or build a text with different things, colors, etc.
/tellraw @p {one text parameter}
/tellraw @p ["",{multiple},{text},{parameters}]

Comment: I try this before, It just let players forced to use command, but it did not work with out permission. I only use this to fool my players to suicide themselves XD
Comment: They know fly command but don't know how to use trigger command!
And now I know how to use it, I can even add a ``/scoreboard players disabled Fly @a`` to disabled trigger command!


pygame.midi.Input could not detect MIDI device

Question: I have this code
from pygame import midi
from time import

midi.init()
midi_in = Input(-1)

while True:
    if not midi_in.pool(): break
    print(midi_in.read())
    time.sleep(.25)

In the pygame.midi.Input constructor (line #5) an exception was raised:
pygame.midi.MidiException: 'Device id given is not a valid input id, it is an output id.'
pygame raised an error because it could not find the MIDI Input Device?
But pygame.midi.get_device_info(device_id) returns:

A valid result
1 is present at index 2 signifying that this device is an input device
0 is present at the last index of the result meaning that this device is closed

I am on pygame 2.1.2, Python 3.10.0 and Windows 10 and
I have taken the following actions countless times:

I have restarted my computer
I have replugged the MIDI cables
I have reinstalled Pygame

After doing all of this, I was expecting pygame.midi to function, but to no avail... It did not work.
I am completly clueless! Can anybody tell me how to fix this error?
Thanks
Comment: "pygame.midi.MidiException: 'Device id given is not a valid input id, it is an output id.'" Okay; so **what is unclear** about this message? It's clearly telling you about the code `midi_in = Input(-1)`, right? So. Did you **read the documentation** for `Input`, in order to understand what values should be used to call it? Does the value `-1` make sense there? Why? How did you decide to write `-1`, and not some other value? Was it based on reading the documentation? What do you think it should mean, and why?
Comment: Note that `pygame.midi.get_default_input_id()` returns the default device ID or -1 if there are no devices. That strongly suggests that -1 is *not* a valid device number.
Comment: "I have taken the following actions countless times:" As a **programmer** - not a computer user - these are the **last** things to try, because they mean that you're blaming someone else's code instead of your own. The **first** thing to try, when you get an error message, is to **read** the error message and **try to understand** it. "pygame raised an error because it could not find the MIDI Input Device?" I don't understand how you got this message from the error message that you quoted.
Comment: "But pygame.midi.get_device_info(device_id) returns:" There is nothing in the code that you show that says `pygame.midi.get_device_info(device_id)`, so there's no way we can explain the result you got from it. In particular, there is no way we can know what the value of `device_id` was when that code was run. Please read [ask] and [mre].
Comment: @RolandSmith advice about MIDI from someone named "Roland" seems auspicious :)
Comment: @KarlKnechtel its a shorthand for default input..... If you read the source file you whould know
Comment: Well, I know what the error message says, and it says differently, in very clear English.
Answer: The argument of pygame.midi.Input is the device ID. You can get the default input device ID with pygame.midi.get_default_input_id. e.g.:
from pygame import midi
midi.init()

device_id = midi.get_default_input_id()
if device_id == -1:
    raise Exception('no midi input device found')

midi_in = midi.Input(device_id)

Comment: @codeforever10 What did not work? `midi.get_default_input_id()` or `midi.Input(device_id)`? Anyway it seams to be a problem with your system, but not with your code. We can't help you with your system. We can only answer questions about your code.
Comment: Yes, I did that but it did not work.


Add new column with times same value was found in 2 columns

Question: Add new column with value of how many times the values in columns 1 and 2 contends exactly same value.
input file
46849,39785,2,012,023,351912.29,2527104.70,174.31
46849,39785,2,012,028,351912.45,2527118.70,174.30
46849,39785,3,06,018,351912.12,2527119.51,174.33
46849,39785,3,06,020,351911.80,2527105.83,174.40
46849,39797,2,012,023,352062.45,2527118.50,173.99
46849,39797,2,012,028,352062.51,2527105.51,174.04
46849,39797,3,06,020,352063.29,2527116.71,174.13,
46849,39809,2,012,023,352211.63,2527104.81,173.74
46849,39809,2,012,028,352211.21,2527117.94,173.69
46849,39803,2,012,023,352211.63,2527104.81,173.74
46849,39803,2,012,028,352211.21,2527117.94,173.69
46849,39801,2,012,023,352211.63,2527104.81,173.74

Expected output file:
4,46849,39785,2,012,023,351912.29,2527104.70,174.31
4,46849,39785,2,012,028,351912.45,2527118.70,174.30
4,46849,39785,3,06,018,351912.12,2527119.51,174.33
4,46849,39785,3,06,020,351911.80,2527105.83,174.40
3,46849,39797,2,012,023,352062.45,2527118.50,173.99
3,46849,39797,2,012,028,352062.51,2527105.51,174.04
3,46849,39797,3,06,020,352063.29,2527116.71,174.13,
2,46849,39809,2,012,023,352211.63,2527104.81,173.74
2,46849,39809,2,012,028,352211.21,2527117.94,173.69
2,46849,39803,2,012,023,352211.63,2527104.81,173.74
1,46849,39803,2,012,028,352211.21,2527117.94,173.69
1,46849,39801,2,012,023,352211.63,2527104.81,173.74

attempt:
awk -F, '{x[$1 $2]++}END{ for(i in x) {print i,x[i]}}' file

4684939785 4
4684939797 3
4684939801 1
4684939803 2
4684939809 2

Answer: Could you please try following.
awk '
BEGIN{
  FS=OFS=","
}
FNR==NR{
  a[$1,$2]++
  next
}
{
  print a[$1,$2],$0
}
' Input_file Input_file

Explanation: reading Input_file 2 times. Where first time I am creating an array named a with index of first and second field and counting their value on each occurrence too. On 2nd time file reading it printing count of the first 2 fields total and then printing while line.
One liner code:
awk 'BEGIN{FS=OFS=","} FNR==NR{a[$1,$2]++;next} {print a[$1,$2],$0}' Input_file Input_file

Comment: @OXXO, usually non-one liner codes are better to understand but as per your request I have added them now, lemme know if any queries here.


derivative of square root of quadratic form with respect to matrix

Question: How would I go about calculating $ \frac{d\textit{$\alpha$}}{d\boldsymbol{A}}$
for $$\textit{$\alpha$} = \sqrt{\boldsymbol{x}^{\intercal}\boldsymbol{A}\boldsymbol{x}}$$
where $\alpha$ is a scalar, $\boldsymbol{x}\in\mathbb{R}^{n}$, and $\boldsymbol{A}\in\mathbb{R}^{n\times n}$.
Sorry if this question is straightforward. I'm trying to implement an algorithm and came across this equation. I'm not familiar with matrix and vector derivatives. Also, any links to a comprehensive introduction to matrix/vector calculus would be appreciated.
Comment: Can you furnish a reference so we can see it in context?
Comment: Here's the [paper](http://www.cs.cmu.edu/~epxing/papers/Old_papers/xing_nips02_metric.pdf). I am/was trying to implement 2.1
Answer: Let us define the Frobenius product by a colon and use it's cyclic property
\begin{align}
{\rm Tr}\left( A^T B C \right)
&:= A: BC \\
&= AC^T: B
\end{align}
So,
\begin{align}
\alpha = \sqrt{x^T A x} \Longleftrightarrow \quad \alpha^2 = x^T A x \equiv x: Ax.
\end{align}
Now, we can use differentials and then obtain gradient.
\begin{align}
2 \alpha d\alpha &= x: dAx \\
   &= xx^T:dA \\
\Longleftrightarrow  d\alpha &= \frac{xx^T}{2 \alpha} :dA = \frac{xx^T}{2 \sqrt{x^T A x}} :dA
\end{align}
The gradient is
\begin{align}
\frac{\partial \alpha}{\partial A} = \frac{xx^T}{2 \sqrt{x^T A x}}.
\end{align}
Comment: +1 but you forgot $\,:\!dA\,$ on a couple of those differential expressions.
Comment: @greg Thank you so much for the feedback -- updated now.
Answer: $x^\top A x$ can be written as $\sum_i \sum_j a_{ij} x_i x_j$. In this form, it is not hard to see what the partial derivative with respect to $a_{ij}$ is for any $i,j$. Then $\frac{d}{dA}(x^\top A x)$ can be viewed as a matrix consisting of all such partial derivatives.
To deal with $\sqrt{x^\top A x}$ you can just use the usual chain rule with the map $z \mapsto \sqrt{z}$.


iOS - UIButton become first responder to open keyboard

Question: I need to open keyboard on button click for UIButton (not using/for UITextField). I have tried to create custom button by overriding variable canBecomeFirstResponder but it's not working.
Is there any other way to do so?
Note: I want to set UIPIckerView as an input view of UIButton in key board frame.
Here is my code.
class RespondingButton: UIButton {

    override var canBecomeFirstResponder: Bool {
        return true
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        // common init
    }

}

In my view controller, I connected button action.
class TestViewController: UIViewController {

   @IBAction func testBecomeFirstResponder(button: RespondingButton){
      button.becomeFirstResponder()  // Not working.
   }
}

Comment: Do you want to use a keyboard to change data shown by UIPicker?
Comment: @Phyber You may know, we can set UIPickerView as an inputView for UITextField, just similar way, I need to do it with UIButton
Comment: Possible duplicate of [UIBUTTON and picker view](https://stackoverflow.com/questions/6429900/uibutton-and-picker-view)
Comment: Maybe this is weired, but what is about a hidden textfield and set this to first responder - just if nothing else is working for you.
Comment: @Retterdesdialogs, I have this choice in my mind but this would be last choice for me to get it work.
Comment: For sure, because of that I asked very kindly :)
Comment: @dan Thanks dear, it's working...
Answer: Add conformance to UIKeyInput like this. It should work.
class RespondingButton: UIButton, UIKeyInput {

    override var canBecomeFirstResponder: Bool {
        return true
    }

    var hasText: Bool = true
    func insertText(_ text: String) {}
    func deleteBackward() {}
}

Comment: Partially means?
Answer: Here is what I would do.

Create transparent textField 1x1px, lets say it is myTextField.
Then add your desired button. In the button action make the myTextField.becomeFirstResponder().

Create view:
let pvBackground: UIView = {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
        v.backgroundColor = .white
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
}()

In viewDidLoad:
pvBackground.addSubview(yourPickerView)//add the picker into the pvBackground
myTextField.inputView = pvBackground

I added the pickerView into the another view to be able to customize it more.


Antlr4 grammar not-greedy does not stop matching

Question: I have this grammar:
<code>grammar Test;

startnode
:
    BEGIN PART_A

    (
    dont_care |
    care
    )*

    END PART_A EOF
;

dont_care
:
    BEGIN I_DONT_CARE

    .*?

    END I_DONT_CARE
;

care
:
    BEGIN CARE

    VALUE STRING

    END CARE
;

BEGIN : '/begin';
END : '/end';
PART_A : 'PART_A';
I_DONT_CARE : 'I_DONT_CARE';
CARE : 'CARE';
VALUE : 'VALUE';
STRING : '"' .*? '"';
WS : ( ' ' | '\t' | '\r' | '\n')+ -> skip;
</code>
And the following input:
<code>/begin PART_A

/begin I_DONT_CARE

    something something

/end I_DONT_CARE

/begin I_CARE

    VALUE "Hello World"

/end I_CARE

/end PART_A
</code>
The problem is, that the dont_care rule does never stop matching, even though I used the non-greey operator. How can I fix that?
Answer: You need to use lexical modes for this.  Please see the book or the answer I just gave to the last question ;)


youtube video location in firefox

Question: As I moved to newer version of firefox-8.0 I lost the location firefox use to store flash videos
previously it used to be in /tmp/FLASH****, but now it's not there
even in .mozilla/firefox/profile-name/Cache they have changed the storage scheme. So is there any way to know where these videos/flash are stored ? moreover if it get changed again then how can we locate the location of video being buffered.
Edit : Also about:cache and locating video didn't help.
Answer: Edit dated 20130204:
What I'm using currently is this:
find /home/username/.mozilla/firefox/random.default/Cache/*/ -type f -size +1M -printf "%p\n" | tee ~/Desktop/zlist.txt && xargs -a ~/Desktop/zlist.txt mv -t /home/username/Downloads/fcache

I've made an alias for this in .bash_aliases.
Notes:
username and random.default will vary per user. An inspection of each file in the file manager should identify file types. I'm currently using Firefox 19.0 (beta).
1M can be increased to whatever one wishes.
It requires a folder, fcache, to exist in ~/Downloads.
It creates a file, zlist.txt, which can be deleted.
It doesn't work with some YouTube videos. I don't know why.
I'm sure someone better at this will have something more elegant.
Comment: worked. I though it's not inside cache
Comment: For version 4, Firefox capped the size of files in cache to 5 MB. Now, it's 50 MB or 1/8th of your total cache size, whichever is smaller according to comment #19 in [bug 647391](https://bugzilla.mozilla.org/show_bug.cgi?id=647391).
Answer: Answering your immediate need: I don't know about /tmp/FLASH, but throughout my browsing experience flash videos are stored in the normal cache.
You should be able to find them using (the resource intensive search):
 find .mozilla/firefox -type f -exec mimetype {} \; | grep "shockwave"

Change the path to something other than mozilla/firefox for a more broad/specific search.
The code searches for all files (-type f) in the folder, and executes "mimetype" on it. Then it filters out results that don't have "shockwave" in the results.
However, if you're trying to save bandwidth by not re-downloading the same youtube video, perhaps you want to use youtube-dl?
Comment: youtube-dl does not pick from the firefox cache. And your response is reasonable, but realise that you can't watch until you download/save. So you might as well save them once... (again, if it's a bandwidth issue). Though I could see how you wouldn't want to switch to the terminal after every youtube video...
Comment: fyi: vasa1's results return in... 0 seconds.
mine: ~ 2 minutes. Checking the mimetype of all those files takes a while.
Comment: generally I want to save video after watching them. so youtube-dl doesnt make sense in that case. Does it pick from firefox cache too ?
Comment: x% of videos are rejected after watching 10% on youtube. So if x is > 30 then also youtube-dl does not make sense. There should be some plugin on firefox which does this job (pick it from cache if available otherwise download ).
Comment: That reason makes sense. I wonder if you can preview them while you're downloading them (using youtube-dl).
Answer: Add these scripts in your .bashrc and try from console.
yt(){
    # HTML 5
    find ~/.mozilla/firefox/*.default/Cache -type f -size +100k -ls|awk '{printf $11 "\n"}'|xargs file|grep -i webm|awk -F: '{printf $1 "\n"}'
    # Flash Video
    find ~/.mozilla/firefox/*.default/Cache -type f -size +100k -ls|awk '{printf $11 "\n"}'|xargs file|grep -i 'Flash Video'|awk -F: '{printf $1 "\n"}'

}

yt2(){

    # This shows mozilla-media-cache/media_cache (deleted) which is cache of HTML5
    FX=`ps -ef|grep '/usr/lib/firefox/firefox'|grep -v grep|head -1|awk '{printf $2}'`
    if [ $FX -ne 0 ] ; then {
        echo /proc/$FX/fd/;
        ll /proc/$FX/fd/|grep media_cache
    }
    else echo 'No running firefox';return 0;
    fi;
}

youtube video location in firefox


Hide menu sidebar when clicking outside the bar or the button

Question: I am trying to make a menu like the semantic UI but I only achieved to click the menu button and open the menu and vice versa. I use toggle class to show the sidebar but I dont know if this way is completely right:

$('#menu-button').click(function(event) {
     $('#hide-menu').toggleClass('show-menu');
});

.hide-menu {
    background-color:#336ca6;
    position: absolute;
    top:0;
    right:0;
    z-index: 1;
    width: 300px;
    height: 100%;
    -webkit-transform: translate3d(300px,0,0);
    -moz-transform: translate3d(300px,0,0);
    -o-transform: translate3d(300px,0,0);
    -ms-transform: translate3d(300px,0,0);
    transform: translate3d(300px,0,0);
    -webkit-transition: all 0.3s linear;
    -moz-transition: all 0.3s linear;
    -ms-transition: all 0.3s linear;
    -o-transition: all 0.3s linear;
    transition: all 0.3s linear;
}

.show-menu {
    -webkit-transform: translate3d(0,0,0);
    -moz-transform: translate3d(0,0,0);
    -o-transform: translate3d(0,0,0);
    -ms-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
 }

I've tried the event propagation but I can't manage to make it play.
Comment: Show the whole code or a JSfiddle
Comment: Where is `hide-menu` and `show-menu`?
Comment: Would you show a demo please?
Comment: Try the solution of this other question: https://stackoverflow.com/a/65236502/7688047
Answer: Edit your js code to following
$('#menu-button').click(function(e){
    e.stopPropagation();
    $('#hide-menu').toggleClass('show-menu');
});

$('#hide-menu').click(function(e){
    e.stopPropagation();
});

$('body,html').click(function(e){
   $('#hide-menu').removeClass('show-menu');
});

Hope this will work.
Here is fiddle.
http://jsfiddle.net/ex8ddv5q/1/
Answer: For a different take on it check this Fiddle
$('#menu-button').click(function (evt) {
    evt.stopPropagation();
    $('#hide-menu').toggleClass('show-menu');
});

$('body,html').click(function (e) {

    var container = $("#hide-menu");

    if (!container.is(e.target) && container.has(e.target).length === 0) {
        container.removeClass('show-menu');

    }
});

Answer: In case somebody comes here and is using Angular instead of JQuery, we got this to work with something similar to the above like this:
public toggleSideNav() {
    this.showSideNav = !this.showSideNav;
    console.log('show side nav', this.showSideNav);
    event.stopPropagation();
}

public hideSideNav() {
    this.showSideNav = false;
    console.log('hide side nav');
}

And this in the template:
<app-sidenav></app-sidenav>

    <router-outlet></router-outlet>

Answer: Suppose if your sidebar width is 270px,check the mouse click coordinate.If it's greater give its style left attribute as -270px;
function handleMousePos(event) {
      var mouseClickWidth = event.clientX;
      if(mouseClickWidth>=270){
            document.getElementById("mySidenav").style.left='-270px'
           }
}

document.addEventListener("click", handleMousePos);

Here is my sample:https://codepen.io/johncy/pen/oMyzZr
Answer: $('body').click(function(){
     $('#hide-menu').removeClass('show-menu');
});

Comment: Because your body height = button height


Isometric mapping of periodic paralellapiped into periodic rectangular prism

Question: I have a parallelepiped defined by the three vectors $\vec{a}, \vec{b}, \vec{c} \in \mathbb{R}^3$ (which happen to be a periodic crystal unit cell). They define a periodic quotient topology on $\mathbb{R}^3$ by:
$$
\vec{x} \sim \vec{x} + \vec{a} \sim \vec{x} + \vec{b} \sim \vec{x} + \vec{c}
$$
Is there an isometric mapping from this space onto the 3-torus given by the quotient topology of $\mathbb{R}^3$ induced by:
$$
\vec{x} \sim \vec{x} + \left<n_x L_x, n_yL_y, n_zL_z\right> \text{ for } n_{x, y, z} \in \mathbb{Z}
$$
for some chosen $L_x, L_y, L_z \in \mathbb{R}$?
(Some background: I'm trying to efficiently do a very large number of periodic nearest neighbor queries in this space; the standard data structure for doing so would be a KD-tree, and the KDTree I have available -- scipy's -- supports a toroidal topology. If I can isometrically map my original periodic space onto a 3-torus, I can use the existing tools.)
Comment: $L_x$, $L_y$ and $L_z$ appear to be real numbers, is that correct?
Comment: @LeeMosher: Yes, edited to make that clear.
Answer: No, there is not in general any such isometric mapping.
Here are several conditions, each of which is logically equivalent to the existence of such an isometric mapping. To express them, let $M$ denote the matrix whose rows are the coordinates of your three vectors,
$$M = \begin{pmatrix}
a_1 & a_2 & a_3 \\
b_1 & b_2 & b_3 \\
c_1 & c_2 & c_3
\end{pmatrix}
$$
Also, let $\Lambda$ be the "lattice" generated by your three vectors,
$$\Lambda = \{l \vec a + m \vec b + n \vec c \mid l,m,n \in \mathbb R\}
$$
The first equivalent condition is

There exists a $3 \times 3$ orthonormal matrix $O$ (meaning a matrix with the property that produce $O O^T$ of $O$ with its transpose is equal to the identity) such that $OMO^{-1}$ is a diagonal matrix.

If $O$ exists, then the diagonal entries of that matrix $M$ are then the numbers $L_x,L_y,L_z$ that you are looking for.

There exist three linearly independent vectors $\vec u, \vec v, \vec w \in \Lambda$ which generate $\Lambda$ such that any two of the three are orthogonal.

If these three vectors exist, then the orthonormal matrix $O$ you need in order to verify 1 is
$$O = \begin{pmatrix}
u_1 / |\vec u| & u_2 / |\vec u| & u_3 / |\vec u| \\
v_1 / |\vec v| & v_2 / |\vec v| & v_3 / |\vec v| \\
w_1 / |\vec w| & w_2 / |\vec w| & w_3 / |\vec w| \\
\end{pmatrix}
$$
Finally, if $L_x,L_y,L_z \in \mathbb R$ exist as you say, then you can simply take $\vec u = \langle L_x,0,0 \rangle$, $\vec v = \langle 0,L_y,0 \rangle$, $\vec w = \langle 0,0,L_z \rangle$ in order to verify 2. Altogether this proves that your condition is equivalent to 1 and to 2.
Okay, but there's still an issue of how to use these to produce a counterexample. For that purpose, here's one more equivalent condition, which is somewhat more constructive: CAUTION: THIS ONE IS WRONG. It is correctible, but I don't have the time at the moment.

Let $\vec u$ be an element of $\Lambda$ such that $|\vec u| \ne 0$ and such that $|\vec u|$ has the smallest possible value. Let $\vec v$ be an element of $\Lambda$ such that $\vec u, \vec v$ are linearly independent and such that $|\vec v|$ has the smallest possible value. And let $\vec w$ be an element of $\Lambda$ such that $\vec u, \vec v, \vec w$ are linearly independent and such that $\vec w$ has the smallest possible positive value. Then:

(*) Any two of $\vec u$, $\vec v$, $\vec w$ are orthogonal to each other.

So, here's a counterexample: $\vec a = \vec u = \langle 1,0,0 \rangle$, $\vec b = \vec v = \langle  1/2 , \sqrt{3}/2 , 0\rangle$ (which is just $\vec a$ rotated by angle $\pi/3$ around the $z$ axis), and $\vec c = \vec w = \langle 0,0,42 \rangle$. Now one has to think a little bit to convince oneself that these three vectors satisfy the first part of 3, but they do NOT satisfy the conclusion (*) of 3.
Comment: Thanks so much for taking the time to compose an answer. I'll have to take some time later to go through this with pen and paper; you'll probably hear from me soon :)


Jquery : Automatic type conversion during parse JSON

Question:
   Is there a way to specify type while parsing Json, so that the conversion happens automatically.
So I have the jsonData, and the x and y values needs to be number. So, the only way I can think about is looping and converting each. Any better logic, or efficient way?
var jsonData = '[{"x:"1", "y":"2"}, {"x:"3", "y":"4"}]'
var needed = [{x:1, y:2}, {x:3, y:4}]
var vals = $.parseJSON(jsonData);
//
var Coord = function(x, y){
this.x = x;
this.y = y;
}
var result = [];
function convert(vals) {
for (var i=0,l=vals.length; i<l; i++) {
        var d = vals[i];
        result.push(new Coord(Number(d.x), Number(d.y)));
    };
}

Comment: Are you retrieving the json with ajax?
Answer: The JSON in the jsonData variable is not valid. Only the attribute should be inside of the double quotes. Whenever you convert data to JSON, use a parser (explained on json.org) and don't write it by hand. You can always check if JSON is valid by using tools like JSONLint.
Any number (integers, decimal, float) are valid JSON data types and doesn't have to be encapsulated with double quotes.
This is valid JSON: [{"x": 1, "y": 2}, {"x": 3, "y": 4}]
However, if you don't have control over the source and retrieve the JSON with ajax you can provide a callback function to the dataFilter option. If you're using jQuery 1.5 there's also converters which are generalized dataFilter callbacks.
I suspect that the x and y coords could be a decimal number which is why I chose to use parseFloat instead of parseInt in the examples below.
Example using a dataFilter callback function (pre jQuery 1.5):
$.ajax({
    url: "/foo/",
    dataFilter: function(data, type){
        if (type == "json") {
            var json = $.parseJSON(data);
            $.each(json, function(i,o){
                if (o.x) {
                    json[i].x = parseFloat(o.x);
                }
                if (o.y) {
                    json[i].y = parseFloat(o.y);
                }
            });
        }
        return data;
    },
    success: function(data){
        // data should now have x and y as float numbers
    }
});

Example using a converter (jQuery 1.5 or later):
$.ajaxSetup({
    converters: {
        "json jsoncoords": function(data) {
            if (valid(data)) {
                $.each(data, function(i,o){
                    if (o.x) {
                        data[i].x = parseFloat(o.x);
                    }
                    if (o.y) {
                        data[i].y = parseFloat(o.y);
                    }
                });
                return data;
            } else {
                throw exceptionObject;
            }
        }
    }
});

$.ajax({
    url: "/foo/",
    dataType: "jsoncoords"
}).success(function(data){
    // data should now have x and y as float numbers
});

Comment: thank you for the detailed answer.. I would ultimately may use ajax.. thanks again
Comment: @bsreekanth, I'm glad to be of help! If you're not using ajax I hope that you will be able to incorporate some of the code above to get the desired result. Happy Walpurgis night!
Answer: The only way is to loop through you JSON data and convert the strings you find into numbers using parseInt("2");.
Answer: I had the same problem.  In one line of code, I remove any quotes that are immediately before or after a numeral, or before a minus sign.

var chartData = $.parseJSON(rawData.replace(/"(-?\d)/g, "$1").replace(/(\d)"/g, "$1"));

In my case it was coming via AJAX from PHP code which I have control over, and I later found out I could simply use the JSON_NUMERIC_CHECK - see PHP json_encode encoding numbers as strings.
These solutions convert anything that looks like a number to a number.  So if you can have something that looks like a number but needs to be treated as a string, you will need to go and figure out something else, depending on your data.
Comment: +1 Recommended as last resource. In my case, I used this regexp: `$.parseJSON(rawData.replace(/"(-?[\d]+\.?[\d]+)"/g,"$1")` as I had values like "80FF00" which were being treated as numbers.
Answer: If you have control of the json source you can remove the quotes from the coordinates.
Acording to json.org, a value can be a sting, number, object, array, true, false, or null. A string is identified as a sequence of characters inclosed in douple quotes. A numeric value not contained in quotes should be interpeted as a number. You might to verify with the parser engine that is in use.
If your just consuming the json, the datafilter and converter methods, mention already, would be the most jquery way to solve the task.
Comment: well, I use jQuery, and as per http://api.jquery.com/jQuery.parseJSON/ I need to have "" .. thanks
Comment: @bsreekanth, you only need double quotes for the attributes, not for the values. `[ { "x": 35.21423, "y": 14.32543 } ]` is valid JSON. You can always use [JSONLint](http://jsonlint.com/) to check :)
Comment: It is proper json and it is parsed correctly in jquery. Quick test in firebug to prove it.
>>> $.parseJSON('{"test":1.23}');
Result: Object { test=1.23}  Sounds like the jquery documentation is mistaken.
Comment: Another side note from api.jquery.com/jQuery.parseJSON: "Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse the string." So its still relevant to test the actual implementation of the parser your are using.


how to configure wordpress to run with PHP 7

Question: I have a dev wordpress instance and want to test compatibility of WP and plugins with php 7. I installed php 7 using ppa:ondrej/php. Now I have two PHP installations and Wordpress is still using php 5.
How can I configure Wordpress cleanly to use php 7?
I run
    update-alternatives --config php
as suggested by DopeGhoti and php 7 was and is set up as default php.
However, the when calling the phpinfo.php in my wordpress root, it displays php 5 is being used.
Comment: `update-alternatives --config php`.  Also, make sure that Apache only has the php7 module enabled and not the php5 module (or that it is configured to only send `.php5` files to the older version of PHP).
Comment: @DopeGhoti thank you. I tried that and php 7 is selected, but wordpress still uses php 5. see update in question.
Comment: Did you check your Apache module installation settings?
Answer: You need to install libapache2-mod-php7.0 and if it doesn't enable automatically (it should) at install time, enable it with:
a2enmod php7.0

If libapache2-mod-php5 is still installed, either disable it first with a2dismod php5 or uninstall with apt-get purge libapache2-mod-php5.


Using a Watson knowledge-studio model directly

Question: Has anyone ever tried to use the model that has been generated by the Watson Knowledge studio outside of the Alchemy language API?
Or do I always need to upload the model to knowledge studio and from then on talk to the api?
Answer: Though I have always used my Knowledge Studio based models on Natural Language Understanding, I believe it's possible to deploy these models to Discovery and Watson Explorer as well for text extraction.
Check this documentation for details on how to deploy the model to different components.
Comment: So I understand it correctly, that you can only use this within one of the IBM/Watson/Bluemix frameworks?
Comment: Yes. We can use it with those Watson services or tools where natural language identification for a specific domain might be necessary. Watson Studio is the tool to train those services.


Bind to property in a nested static class

Question: I have the following construction:
public static class Constants {
  public static class Foo {
    public static string Bar {
      get {
        //Constants.Foo.Bar == "FooBar"
        return "FooBar";
      }
    }
  }
}

I want to bind this to a button in a usercontrol.
<Button Content="{Binding Source={x:Static ns:Constants.Foo.Bar}}" />

(where ns points to the assembly and namespace where "Constants" is defined).
This results in two errors:

"Cannot find the type 'Constants.Foo'. Note that type names are case sensitive."
"Type 'ns:Constants.Foo' was not found."

I also tried:
<Button Content="{Binding Source={x:Static ns:Constants+Foo.Bar}}" />

This results in one error:

"Type 'ns:Constants+Foo' was not found."

Is is possible to bind to a static property in a static class in a static class? If yes, how?
Comment: It would work if you could change `public static class Constants` to `namespace Constants`. Is that an option?
Comment: Will did you also include the namespace before here `Constants+Foo.Bar` ? like `[namespace].Constants+Foo.Bar`
Comment: no, but I don't think it's needed (resharper removes the namespace). Testing 1, 2...: adding it doesn't help, same error ("was not found"), but now including the namespace.
Comment: It would require some refactoring, but that would be an option.
Answer: this works for me
 <Button Content="{Binding Source={x:Static local:Constants+Foo.Bar}}" />

local is
 xmlns:local="clr-namespace:WpfTestApp1"

Comment: You're right, but for some strange reason it does not work in XAML designer (VS2010).
Comment: Yes. Ouch. I didn't actually run the project, because the XAML design view gives errors. But it *does* work, you're right. I think I'll stick to the namespace solution, as suggested by Clemens, because a non-functioning designer is not acceptable during development.
Comment: just a hint the designer of VS2010 and Blend are not working the same way ;)
Comment: It works, but XAML designer write an error. I hate errors even if they don't hinder project to run :)


How can I wire a panel heater?

Question: Bought my Mum a Dimplex Panel Heater for Christmas.
My plan was to plug it into the single socket beside where I am mounting it however it did not come with a plug and look like it should be wired into a fused unit.
Can I just stick a 13A plug on it and use existing socket? Its only 0.5KWH.
Comment: Could you link to the product, or include a model number?  Is it designed to be installed as a permanent fixture (hard wired)?
Comment: Product URL: http://www.alertelectrical.com/prod/76/dimplex-electric-panel-convector-heater-05kw-output
Comment: Found the [Installation Instructions](http://www.dimplex.de/downloads/uploads/dimplex_plx500-3000_fd8512_fr-2009-07-23.pdf), but could only find it in French and German (neither of which I can read).
Comment: The picture on the product page appears to show a heater that is wired directly as opposed to plugged into an outlet.
Comment: [Google translated English installation instructions](http://translate.google.com/translate?sl=auto&tl=en&js=n&prev=_t&hl=en&ie=UTF-8&layout=2&eotf=1&u=http%3A%2F%2Fwww.dimplex.de%2Fdownloads%2Fuploads%2Fdimplex_plx500-3000_fd8512_fr-2009-07-23.pdf)
Comment: One consideration: it's not CE/UL/CSA/whatever-approved to have a plug, and so if a fire was ever [suspected to be] caused by this, your insurance company may not have to pay the claim.
Comment: [Natively English instructions](http://www.dimplex.com/cms/publications/DEC_Series_-_Delux_Electronic_Panel_Convection_Heater_-_Owners_Manual,_Model_%23DEC_-_7204310100R04_EN.pdf). At .5KW, I don't see why you can't stick a regular 13 amp plug (fuse it to 3 amps) on there, but I'm completely unfamiliar with the electric codes over there... I'm shocked at .5KW, though. My electric plug-in 120 volt one here is 1.4KW.
Answer: These are designed to permanently wired through a fused switch. As gregmac points out in his comment there may be insurance issues if you use a normal plug and socket, particularly in area of fire risks.
However, you can replace the current socket with a fused switch panel. Make sure you get one with a hole in the surface for the wire to go through.
Something like this

How can I wire a panel heater?


Android - FATAL EXCEPTION: main - Unable to start activity ComponentInfo NullPointerException

Question: I am a android newbie and using asynctask and java i am trying to create an instant messaging system. But this is what i am getting.
I have been stuck for weeks in this. Can anyone trace out where i am going wrong and why that error is showing ?
IndividualActivity.java
package com.example.soc;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
public class IndividualActivity  extends Activity {

    private ProgressDialog pDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLayoutInflater().inflate(R.layout.individual, null);
        Intent intent = getIntent();
        int uuid = intent.getIntExtra("uuid",0); //if it's a string you stored.
        new openMsg(IndividualActivity.this).execute();

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }
    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

openMsg.java
package com.example.soc;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.soc.adater.msgAdapter;
import com.example.soc.model.MSList;
import com.example.soc.util.JSONParser;

public class openMsg extends AsyncTask<Object, Object, JSONArray>{
    final IndividualActivity main;

    public openMsg(IndividualActivity indv) {
        this.main = indv;
    }

    private JSONParser jsonParser = new JSONParser();
    //private static final String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private List<MSList> imlist = new ArrayList<MSList>();
    private ListView listView;
    private msgAdapter adapter;
    String myip = "10.0.2.2";
    private JSONArray json = null;
    ArrayList<Integer> uidList = new ArrayList<Integer>();

    @Override
    protected void onPreExecute() {
         super.onPreExecute();

            listView = (ListView)main.findViewById(R.id.listx);
            adapter = new msgAdapter(main, imlist);
            listView.setAdapter(adapter);
    }

    protected JSONArray doInBackground(Object... v) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        json = jsonParser.getJSONFromUrl("http://"+myip+"/resource/android/MSG.php", pairs);
        return json;
    }

    protected void onPostExecute(JSONArray json) {

        for (int i = 0; i < json.length(); i++) {
            try {
                JSONObject c = json.getJSONObject(i);
                MSList iml = new MSList();
                iml.setpname(c.getString("name"));
                //iml.setuname(c.getString("username"));
                iml.setppUrl("http://"+myip+"/"+c.getString("img"));
                iml.setmsgcon(c.getString("content"));
                iml.setmsgtime(c.getString("time"));
                int uuid = Integer.parseInt(c.getString("user_id"));
                iml.setUid(uuid);
                iml.setme(Integer.parseInt(c.getString("me")));

                imlist.add(iml);

                uidList.add(uuid);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        adapter.notifyDataSetChanged();
    }

}

Individual.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".IndividualActivity" >

    <ListView
        android:id="@+id/listx"
        android:layout_width="fill_parent"
        android:layout_height="350dp"
        android:layout_above="@+id/individual_bottomAction"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_row_selector" />

    <LinearLayout
        android:id="@+id/individual_bottomAction"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true" >

        <EditText
            android:id="@+id/msgTypeBox"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp"
            android:layout_weight=".70"
            android:ems="10"
            android:hint="Write a message"
            android:inputType="textMultiLine" />

        <Button
            android:id="@+id/msgSend"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:layout_weight=".2"
            android:text="Send" />
    </LinearLayout>

</RelativeLayout>

LogCAT
02-24 19:22:47.399: E/AndroidRuntime(6255): FATAL EXCEPTION: main
02-24 19:22:47.399: E/AndroidRuntime(6255): Process: com.example.soc, PID: 6255
02-24 19:22:47.399: E/AndroidRuntime(6255): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.soc/com.example.soc.IndividualActivity}: java.lang.NullPointerException
02-24 19:22:47.399: E/AndroidRuntime(6255):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at android.os.Looper.loop(Looper.java:136)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at android.app.ActivityThread.main(ActivityThread.java:5021)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at java.lang.reflect.Method.invokeNative(Native Method)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at java.lang.reflect.Method.invoke(Method.java:515)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at dalvik.system.NativeStart.main(Native Method)
02-24 19:22:47.399: E/AndroidRuntime(6255): Caused by: java.lang.NullPointerException
02-24 19:22:47.399: E/AndroidRuntime(6255):     at com.example.soc.openMsg.onPreExecute(openMsg.java:60)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at android.os.AsyncTask.execute(AsyncTask.java:535)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at com.example.soc.IndividualActivity.onCreate(IndividualActivity.java:37)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at android.app.Activity.performCreate(Activity.java:5231)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
02-24 19:22:47.399: E/AndroidRuntime(6255):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
02-24 19:22:47.399: E/AndroidRuntime(6255):     ... 11 more

Comment: what's line no.60 on `OpenMsg` class?
Comment: http://stackoverflow.com/questions/17808177/difference-between-setcontentview-and-inflater
Comment: its `listView.setAdapter(adapter);`  @YuvaRaj
Comment: Please learn android's basics ... you did inflate the view but you didn't set it as content view
Comment: And while you're at it, I feel like a refresher of the basics of Java (including naming conventions) would go a long way.
Comment: do you mean `setContentView(R.layout.individual);` @Selvin ?
Comment: `setContentView(R.layout.individual);`!!!
Comment: then whats the difference between `getLayoutInflater().inflate(R.layout.individual, null);` and `setContentView(R.layout.individual);` ?? @SorryForMyEnglish
Answer: Try Changing
getLayoutInflater().inflate(R.layout.individual, null);

to
setContentView(R.layout.individual);

Let me know if it works


Design for C program

Question: Is it good/correct way to do like this for a robust C program
//File1 => Module1.h

static int Fun(int);

struct{
int (*pFn)(int)
}Interface;

//File2 => Module1.c
static int Fun(int){
//do something
}

Interface* Init(void)
{
  Interface *pInterface = malloc(sizeof(Interface));
  pInterface->pFn = Fun;
  return pInterface;
}

//File 3 => Module2.c
#include"Module1.h"
main()
{
  Interface *pInterface1 = Init();
  pInterface1->pFn(5);
}

My intention is to make each module expose an interface...
Questions:

Is it good to write a C code like above to expose an interface... ??
What better ways are available for exposing interface??
Are there any references for design principles for C programming (not C++) ??
Comment: Better to post one [code review site](http://codereview.stackexchange.com/questions)
Comment: You forgot the `typedef` for the `Interface` type.
Comment: Can you suggest any links or references for some common patterns in C structured programming
Comment: You are holding it wrong. You need to expose `Init` in your .h file, and not `Fun`.
Comment: Yes, Assuming typedef there...is it a good design?
Comment: Looks like you'll be better off with C++. Your approach is valid so even though not very C-ish.
Comment: It's a common pattern, both for "modules" and for OOP in C. It doesn't matter much for the program being "robust" or not though.
Answer: This is more idiomatic for a dynamically loaded module. (Or something along these lines.)
Usually an interface between two source files is defined using extern functions and objects which are accessed directly. You would need to make a case for doing anything more sophisticated.
Answer:
If you use it for solving simple task, it may only increases code
base and complexity. But certain places it could be useful.
For example: If you want to implement STRATEGY-pattern in C, that is
one way to do it.
You may hide content of the Interface struct from users by using FIRST-CLASS ADT pattern. Or you can combine above patterns.
Answer: My short answer is no.
Ignoring the comments that point out that the static function should not be declared in the .h file (that is the part you want to hide -- it is static after all), here are some things to keep in mind.
It seems like you are trying to use the interface in order to de-couple the implementation from consumers of the module; a noble goal. This can allow increased flexibility as the implementation can change in the .c file without breaking calling code. However, think about the interface you have defined.
Any code using this module should be guaranteed to be able to get an Interface instance, via Init (although this needs to be included in your .h file). That Interface instance will point to the functions to use. One such function has the signature
int Fun(int);

So what have you hidden? Of course, you can change the function they are calling, but you still have to provide a function with that signature.
Alternatively, you could just define the .h as:
int Fun(int);

And then in the .c file, something like:
static int StaticFun(int i)
{
    // something
}

int Fun(int i)
{
    StaticFun(i);
}

You could make Fun call a different function based on some internal state it manages, or a config file, whatever you want. Why is this better? Besides being simpler, it is a static call; the compiler can inline the call to StaticFun, or even the function StaticFun completely, for example. Calls through function pointers usually incur a noticeable performance hit.
Now, there may be a case for an "Interface" object, such as you have defined. But I would be inclined to suggest that there isn't one in your case, not without modification.
Suppose your Init function changed to:
Interface* Init(some state info);

Now the Interface object you pass back can change depending on the state or configuration passed in, which allows your module to dynamically map functions. Basically, my opinion is that if you are actually calling a static function underneath, then you are working much harder than needed, and preventing compiler optimizations.
As a note, if you are going to go the Interface route (I'm working on a project with something similar right now) then may I suggest a modification? Something like...
.h file:
const Interface* Init(some state);

.c file:
static int FunTyp1(int);
static int FunTyp2(int);

static const Interface typ1 = { &FunTyp1 };
static const Interface typ2 = { &FunTyp2 };

const Interface* Init(some state)
{
    if (some state == type1)
       return &typ1;
    else if (some state == type2)
       return &typ2;
}

Advantages:

You probably don't want consuming code to modify the interface? At least, I can't think of a good reason.
Defining it statically avoids the unnecessary heap allocation and the memory leaks when consumers repeatedly request Interface objects and forget to free them (or don't know they should -- who owns this object?).
You can share a single (static) instance of the Interface object for all the consuming code in the process without worrying that someone changes it.

Note that by having several statically initialized instances, you can define a different "Interface" object for each function mapping you want to support.

Design for C program


Why 60+ console-kit-daemon processes?

Question: I have over 60 processes of console-kit-daemon that won't stop reappearing after I've used sudo killall console-kit-daemon. I have no idea what the daemon is for.
I'm running ubuntu 10.04. What's going on?
Answer: They're not processes, they're threads under one process.
By default htop shows threads and in this case, is very misleading. You can alter this by going into Setup (F2), Display options and checking Hide userland threads.

Press F10 when you're done.
Comment: Here is some more info on what ConsoleKit actually does: http://www.freedesktop.org/software/ConsoleKit/doc/ConsoleKit.html
Comment: F10 - good joke. It opens terminal file menu.

Why 60+ console-kit-daemon processes?


What products are advertised in the game?

Question: It's hard to miss energy drink product placement in your private room.
But is there anything else? Is whiskey Mads Mikkelsen's character drinks real?
Answer:
Energy drink:

  Table in private room, backpack attachment, consumable.

TV Show with Norman Reedus:

 Toilet doors in private room, special type of reverse trike.

Wine

 in "Fine Wine" Cliff's memory.


How can I fetch the array from my firebase to flutter?

Question: I have a simple app where I want to fetch all of my data and show it but I can only fetch the simple strings (name,id and size) but whenever i try to fetch the Array it errors :(
Can someone give a simple and quick example how to fetch the array of strings into my flutter app?

class _PokedexHomeState extends State<PokedexHome> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(
          leading: const Icon(MdiIcons.pokeball),
          centerTitle: true,
          title: const Center(child: Text('Pokédex')),
          backgroundColor: Colors.red),
      body: StreamBuilder(
        stream: readPokemon(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return const Text('Couldn\u0027t find any Pokémon :( ');
          } else if (snapshot.hasData) {
            final users = snapshot.data!;
            return GridView.count(
              //amount of cards next to eachother
              crossAxisCount: 2,
              childAspectRatio: (1 / .5),
              children: users.map((e) => buildPokemon(e, context)).toList(),
            );
          } else {
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

class Pokemon {
  String id;
  final String name;
  final String size;
  final List<dynamic> elements;

  Pokemon(
      {this.id = '',
      required this.name,
      required this.size,
      required this.elements});

  Map<String, dynamic> toJson() =>
      {'id': id, 'name': name, 'size': size, 'elements': elements};

  static Pokemon fromJson(Map<String, dynamic> json) => Pokemon(
      id: json['id'],
      name: json['name'],
      size: json['size'],
      elements: json['elements'] as List<dynamic>);
}

Comment: This post from the stackoverflow might help you https://stackoverflow.com/questions/63091889/flutter-firebase-get-array-from-firestore-and-assign-it-to-a-list
Comment: What error are you getting?
Answer: Try changing
json['elements'] as List<dynamic>

to
List.from(json['elements'])


Why must I hold the start button for my dryer to work?

Question: I moved into an apartment with an old dryer that had issues starting and getting the clothes very hot. I had to hold the start button in and the dryer would "ramp up" before it would start. Anyway, I bought a new dryer and hooked it up and it too requires the button to be held in until it ramps up and will then run. When a load of clothes is put in it, it tries to turn very slowly and will not start. Now for the voltage measurements:
at the 3 prong outlet:
240vac from leg to leg
120vac from each leg to neutral
at the breaker:
same measurements leg to leg
120vac from each leg to ground
The only other thing I noticed is that on one side of the breaker, the voltage jumped up to @180vac when I had someone hold in the start button on the dryer until it got started. Since V=IR, wouldn't that increase in voltage indicate that the current would decrease (assuming a steady resistance)? If the current going to the motor is decreasing, could that be the cause of the difficulty getting the motor to start and, if so, what could be causing this to happen?
Comment: I'd look for an open, or high resistance neutral. Check all the neutral connections, and make sure they are clean and well connected.
Comment: Make sure the grounded (neutral) conductor is solidly connected at the service panel, the receptacle, and the dryer itself. Where are you measuring the 180 volts, at the dryer, or the service panel?  What are you measuring 180 volts between, leg to neutral, or leg to ground? When you see the voltage on one leg jump up, do you see the voltage on the other leg dip? FYI: Typically in an electric dryer, the motor and heating element are 240V, while only the controls are 120V.
Comment: I measured the 180 volts at the service panel from one leg to neutral. Not sure if the other leg dipped or not but it seems like it did.
Comment: Does it jump to 180 volts leg to ground as well?
Comment: I'm not really sure...I'll test it again later today and post my findings here. Hopefully I'll be able to find a loose connection somewhere and solve the problem.
Comment: One side of the breaker goes to 180vac and the other goes to 66vac while measuring to ground and trying to start the dryer
Answer: Solved the problem.  Figured out that there was a potential between neutral and ground of 6v.  They weren't bonded at the box. Thanks for your help!
Comment: Not sure what you mean by "at the box" but ground and neutral are definitely **not** supposed to be bonded at the outlet. They should be bonded at the main service panel **only**. And if your neutral wasn't already bonded to ground at the service panel I would seriously question the entire electrical installation.
Comment: That's what I said... An open neutral!
Comment: At the main service panel is what I meant by "at the box". It's all good now. A licensed electrician fixed it...I just stood over his shoulder and watched.


Backbone each undefined

Question: Why is the item variable undefined in this Backbone example?
var Action = Backbone.Model.extend({
defaults: {
    "selected": false,
    "name": "First Action",
    "targetDate": "10-04-2014"
}
});

var Actions = Backbone.Collection.extend({
    model: Action
});

var actionCollection = new Actions( [new Action(), new Action(), new Action(), new Action()]);

_.each(actionCollection, function(item) {
    alert(item);
});

jsFiddle here: http://jsfiddle.net/netroworx/KLYL9/
Answer: Change it to:
actionCollection.each(function(item) {
        alert(item);
});

And it works fine.
This because actionCollection is not an array, so _.each(collection) does not work but collection.each does because that function is build into Backbone collection.
That being said, this also works:
_.each(actionCollection.toJSON(), function(item) {
        alert(item);
});

Because now the collection is an actual array.
Answer: _.each accepts an array as first argument, but you passed a Collection.
Just use the Collection.each method:
actionCollection.each(function(item){
  //do stuff with item
});

Backbone each undefined


Angular2 *ngIf with child directive

Question: I can't seem to get my directive to work and wonder if it is due to the use of an *ngif.
Component HTML:

{{ticket.raisedBy.firstName}} {{ticket.raisedBy.surname}}

Directive
 import { Directive, ElementRef, Input } from '@angular/core';

 @Directive({
  selector: '[appUsername]'
 })

 export class UsernameDirective {constructor(el: ElementRef) {
    console.log('App Username directive init');
    el.nativeElement.style.color = 'red';
 }
}

The *ngIf is required in the component HTML as I am collecting data from a JSON service on ngOnInit.
Code ignored for brevity: I am adding the directive to a "shared" module which exports the Directive. This module is then imported in to the main app module.
Is this a known problem or is it my code ?
Update I got this working now however I am having to import the directive in to the module which contains the component. Can I not import it in to the AppModule and then use is globally ?
Comment: What is not working? What is the expected behavior? Have you tried to move your `red` code to `ngAfterViewInit()`?
Comment: @GünterZöchbauer The Directive is not changing the colour of the text in the h4 within the component HTML. Nor firing the console.log
Comment: Did you import the shared module to the module that contains above component?
Comment: @GünterZöchbauer The imports all work and there are no coding errors within the console of the application.
Comment: If the constructor is not executed it's almost 100% a problem with module configuration. The selector matches, there is not much else that could cause it.
Answer: The Angular module system works like this:

You need to declare a Component/Directive/... in exactly ONE NgModule.
You can then use it in the Components that are part of this NgModule.
To use a Component/Directive/... in any other NgModule, you need to export it in from the declaring NgModule and import the declaring NgModule in the NgModule where you want to use it.

In your case you declare and export the Directive in the SharedModule and import the SharedModule in the AppModule, but you use the Directive in another NgModule, which does not import SharedModule and does not import AppModule and therefore does not know your Directive.
So to use something in a NgModule, it needs to declare it, import the declaring NgModule or import a NgModule, which imports the declaring NgModule.
Importing only works if the declaring NgModule exports the Directive.

Angular2 *ngIf with child directive


Find the differential equation of $y=e^{-x}+ax+b$

Question: Find the differential equation of $$y=e^{-x}+ax+b$$   where $a,b$ are arbitrary constants.
I differentiated both sides first, and got $$\dfrac{dy}{dx}=-e^{-x}+a.$$
Making substitution for value of $a$ in the original equation and differentiating again, I got $$x\dfrac{d^2y}{dx^2}=2e^{-x}-xe^{-x}.$$
So, the differential equation turns out to be $$\dfrac{d^2y}{dx^2}=\dfrac{e^{-x}(2-x)}{x}.$$
Have I made any mistake here? My teacher struck the whole thing out and gave me a $0$ here. Please help.
Comment: What do you mean by THE differential equation?
Comment: This question makes no sense as it stands. There are infinitely many ODEs we could construct from the original function. So, as Zachary pointed out, what do you mean by _the_ differential equation?
Comment: I don't know how you got the third line but it is wrong since $$\frac{d^2y}{dx^2}=e^{-x}$$
Comment: @ZacharySelk I hope it makes sense now.
Comment: No, it still doesn't make any sense
Comment: I just want to say that I am a high school student and whatever you are saying does not make any sense to me. If it would be possible for you to understand my situation, that would be really helpful.
Answer: Perhaps you saw this in the context of linear second order differential equations with constant coefficients? Then in the form of the solution, you recognize what should be the solution of the homogeneous part (in blue) and a particular solution (in red):
$$y=\color{red}{e^{-x}}+\color{blue}{ax+b}$$
Now for the homogeneous part, you need a double zero root to the characteristic equation so this is clearly the solution to:
$$y''=0$$
To get $e^{-x}$ as a particular solution, the inhomogeneous part of the differential equation (the "right-hand side") will be of the form $Ae^{-x}$ and you can verify (easily) that $A=1$ does the trick, so:
$$y''=e^{-x} \tag{$\square$}$$
has $y=\color{red}{e^{-x}}+\color{blue}{ax+b}$ as general solution.

Addition after comment.

$$\dfrac{dy}{dx}=-e^{-x}+a. \tag{$*$}$$
Making substitution for value of $a$ in the original equation and differentiating again, I got $$x\dfrac{d^2y}{dx^2}=2e^{-x}-xe^{-x}.$$

If you substituted $(*)$ in the original solution, where did the $b$ go? Why not differentiate $(*)$ again, this immediately yields $(\square).$
Comment: I think you may have understood what I was trying to ask. Would you please help me, kind sir with why my approach is wrong in substituting the value of $a$ in the original equation if you have understood the problem which others did not?
Comment: @Swadhin I'm not really sure what you were doing, but I added a part to my answer.
Comment: Yes, it makes sense, thank you for your time. After all this, I am not sure about all this myself. So, I guess it would be better if I asked my teacher directly.
Comment: Alright; you're welcome and good luck with that!