Breeze.js cache limitations? Or Browser?

Question: We are investigating using Breeze for field deployment of some tools.  The scenario is this -- an auditor will visit sites in the field, where most of the time there will be no -- or very degraded -- internet access. Rather than replicate our SQL database on all the laptops and tablets (if that's even possible), we are hoping to use Breeze to cache the data and then store it locally so it is accessible when there is not a usable connection.
Unfortunately, Breeze seems to choke when caching any significant amount of data.  Generally on Chrome it's somewhere between 8 and 13MB worth of entities (as measured by the HTTPResponse headers).  This can change a bit depending on how many tabs I have open and such, but I have not been able to move that more than 10%.  the error I get is the Chrome tab crashes and tells me to reload.  The error is replicable (I download the data in 100K chunks and it fails on the same read every time and works fine if I stop it after the previous read) When I change the page size, it always fails within the same range.
Is this a limitation of Breeze, or Chrome? Or windows?  I tried it on Firefox, and it handles even less data before the whole browser crashes.  IE fares a little better, but none of them do great.
Looking at performance in task manager, I get the following:

IE goes from 250M memory usage to 1.7G of memory usage during the caching process and caches a total of about 14MB before throwing an out-of-memory error.
Chrome goes from 206B memory usage to about 850M while caching a total of around 9MB
Firefox goes from around 400M to about 750M and manages to cache about 5MB before the whole program crashes.

I can calculate how much will be downloaded with any selection criteria, but I cannot find a way to calculate how much data can be handled by any specific browser instance.  This makes using Breeze for offline auditing close to useless.
Has anyone else tackled this problem yet?  What are the best approaches to handling something like this.  I've thought of several things, but none of them are ideal.  Any ideas would be appreciated.
ADDED At Steve Schmitt's request:
Here are some helpful links:

Metadata
Entity Diagram (pdf) (and html and edmx)

The first query, just to populate the  tags on the page runs quickly and downloads minimal data:
var query = breeze.EntityQuery
                .from("Countries")
                .orderBy("Name")
                .expand("Regions.Districts.Seasons, Regions.Districts.Sites");

Once the user has select the Sites s/he wishes to cache, the following two queries are kicked off (used to be one query, but I broke it into two hoping it would be less of a burden on resources -- it didn't help).  The first query (usually 2-3K entities and about 2MB) runs as expected.  Some combination of the predicates listed are used to filter the data.
var qry = breeze.EntityQuery
                    .from("SeasonClients")
                    .expand("Client,Group.Site,Season,VSeasonClientCredit")
                    .orderBy("DistrictId,SeasonId,GroupId,ClientId")

    var p = breeze.Predicate("District.Region.CountryId", "==", CountryId);
    var p1 = breeze.Predicate("SeasonId", "==", SeasonId);
    var p2 = breeze.Predicate("DistrictId", "==", DistrictId);
    var p3 = breeze.Predicate("Group.Site.SiteId", "in", SiteIds);

After the first query runs, the second query (below) runs (also using some combination of the predicates listed to filter the data. At about 9MB, it will have about 50K rows to download).  When the total download burden between the two queries is between 10MB and 13MB, browsers will crash.
var qry = breeze.EntityQuery
                    .from("Repayments")
                    .orderBy('SeasonId,ClientId,RepaymentDate');

    var p1 = breeze.Predicate("District.Region.CountryId", "==", CountryId);
    var p2 = breeze.Predicate("SeasonId", "==", SeasonId);
    var p3 = breeze.Predicate("DistrictId", "==", DistrictId);
    var p4 = breeze.Predicate("SiteId", "in", SiteIds);

Thanks for the interest, Steve.  You should know that the Entity Relationships are inherited and currently in production supporting the majority of the organization's operations, so as few changes as possible to that would be best.  Also, the hope is to grow this from a reporting application to one with which data entry can be done in the field (so, as I understand it, using projections to limit the data wouldn't work).
Thanks for the interest, and let me know if there is anything else you need.
Comment: Regarding the in-memory size, a lot of extra memory is used when wrapping the entity properties in Knockout observables.  Using the Knockout model library takes 3+ times the amount of memory that, say, AngularJS properties require.
Comment: Can you give some more information about your data?  Maybe provide the metadata for the entities that you are caching?  It might help determine if there's a bug somewhere that is causing the problem.
Comment: Steve, thanks for the interest.  Updated the question to give a bit more information.
Comment: In your tests what are you doing with the query results? Throwing them away? Storing them? Clearing cache with `manager.clear()` between requests? Trying to understand what phase causes trouble. I do believe each browser has its own choke point for payload size but I doubt that's it. I'm leaning toward "too many entities in memory" in which case we need to rethink your approach.
Comment: Ward, good questions.  Right now, I'm doing nothing with the data between requests.  I'm just trying to get the data into the cache.  When I need the data I'll load handle that with queryLocally.  An interesting fact: if I read 4 MB of data, the browser memory usage increases by about 600 MB (tripling, or in the case of IE, quadrupling and using an additional 1+ gig of memory).  Yet, if I export the entities to save them in local storage, the entire JSON string is about 4 GB.  So something happening in in the actual downloading/processing is hogging system memory. Any thoughts on that?
Comment: ...entire JSON string is about 4MB..." not GB.  Sorry, too late to edit.  To emphasize: the export is acting exactly as expected (exporting about the same amount of data as downloaded), but something is eating system memory during the download.  THanks.
Comment: We are trying to repro your issue but so far no luck. We are trying to come up with a simple test ( and model) that repros your problem. Any help with this would be appreciated.
Comment: Great Jay.  What can I do to help.  I could send you my data and and EF schema, but my internet connection is pretty crappy here in East Africa.  Some additional information: I simplified the schema somewhat and was able to squeeze an extra 10% out of the browser, but that doesn't seem significant.  I'll try to trim some more tomorrow -- maybe I'll find the relationship causing the problem.  I used the noTracking option on the bigger part of the download and it, of course, showed no bump in browser memory usage no matter how big.  Anything you'd like me to try or provide? I'm v. willing.
Comment: I can send you what I am able to export.  If you import it it won't make the browser crash, but you might see the memory spike.  I could also send you 20+ MB of pojos with the metadata maybe converting them to entities will create the problem.  Just let me know.
Comment: @Jay, I don't know if you got my last comment since I didn't tag you. I'd be glad to help you recreate this issue.  I'm using Jeremy Danyow's suggestions, but finding that I'm having to code fairly differently when on-line versus off-line (For example, search by name or phone number) which is a bit of a maintenance burden that I was hoping Breeze could mitigate a bit more.  If I could regularly double the amount of data that I can currently load, that would take care of most of my problems.  Thanks.
Comment: @Beartums, we are still trying to repro your issue. We do see a significant memory bump during large queries, which is somewhat expected, but in our tests this memory appears to be reclaimed after the query completes.  Which means that you might be able to mitigate the issue by breaking the query up into pieces via take and skip.
Comment: @Jay, that's what I figured, too.  But I'm using .take(100) and .skip(100*pagesRead) for all my queries, and it doesn't make a difference.  I also tried querying some of the entities separately, but the memory usage keeps climbing and stays elevated until I explicitly clear the cache.  I'll keep trying from my side.  Let me know if I can help.  I appreciate you're getting back to me.  Thanks.
Comment: @Steve, thanks for the information.  That's good to know, though still surprising that 25MB of api data is eating up about 1GB of memory when being wrapped.  I'll see what we can do to work within these limits.
Comment: @Steve, Excellent get.  I just rewrote my app in Angular and am able to cache what appears to be an unlimited amount of data from the same EF6 model.  While the knockout version of the client app craps out at around 5MB (chrome memory peaking at about 1.7GB) unless I use the noTracking option, I have so far been able to cache over 50MB using Angular with chrome memory usage never going past about 625MB.  Valuable Information.
Answer: Here are some suggestions based on my experience building on an offline capable web application using breeze.   Some or all of these might not make sense for your use cases...

Identify which entity types need to be editable vs which are used to fill drop-downs etc.  Load non-editable data using the noTracking query option and cache them in localStorage yourself using JSON.stringify.  This avoids the overhead of coercing the data into entities, change tracking, etc.  Good candidates for this approach in your model might be entity types like Country, Region, District, Site, etc.
If possible, provide a facility in your application for users to identify which records they want to "take offline".  This way you don't need to load and cache everything, which can get quite expensive depending on the number of relationships, entities, properties, etc.
In conjunction with suggestion #2, avoid loading all the editable data at once and avoid using the same EntityManager instance to load each set of data.  For example, if the Client entity is something that needs to be editable out in the field without a connection, create a new EntityManager, load a single client (expanding any children that also need to be editable) and cache this data separately from other clients.
Cache the breeze metadata once.  When calling exportEntities the includeMetadata argument should be false.  More info on this here.
To create new EntityManager instances make use of the createEmptyCopy method.

EDIT:
I want to respond to this comment:

Say I have a client who has bills and payments. That client is in a
  group, in a site, in a region, in a country. Are you saying that the
  client, payment, and bill information might each have their own EM,
  while the location hierarchy might be in a 4th EM with no-tracking?
  Then when I refer to them, I wire up the relationships as needed using
  LINQs on the different EMs (give me all the bills for customer A, give
  me all the payments for customer A)?

It's a bit of a judgement call in terms of deciding how to separate things out.  Some of what I'm suggesting might be overkill, it really depends on the amount of data and the way your application is used.
Assuming you don't need to edit groups, sites, regions and countries while offline, the first thing I'd do would be to load the list of groups using the noTracking option and cache them in localStorage for offline use.  Then do the same for sites, regions and countries.  Keep in mind, entities loaded with the noTracking option aren't cached in the entity manager so you'll need to grab the query result, JSON.stringify it and then call localStorage.setItem.  The intent here is to make sure your application always has access to the list of groups, sites, regions, etc so that when you display a form to edit a client entity you'll have the data you need to populate the group, site, region and country select/combobox/dropdown.
Assuming the user has identified the subset of clients they want to work with while offline, I'd then load each of these clients one at a time (including their payment and bill information but not expanding their group, site, region, country) and cache each client+payments+bills set using entityManager.exportEntities.  Reasoning here is it doesn't make sense to load several clients plus their payments and bills into the same EntityManager each time you want to edit a particular client.  That could be a lot of unnecessary overhead, but again, this is a bit of a judgement call.
Comment: Jeremy, thanks for your thoughts.  They look like some good ideas and I'll try them asap.  A few questions: 1) if I use notracking, does that disrupt the relationships and LINQ capabilities? 2} I have already introduced filters to get the total payload below a certain size, but right now that size is a moving target, 3) Same questions as #1.  I want to retain the relationships and the LINQ capabilites, but maybe I'm not understanding what separate entity managers will do, 4) I don't think this is an issue, as exporting is working beautifully.  I will look into all these options.
Comment: When using noTracking you still get the linq style query stuff (where, orderBy, expand, etc).  The difference is the results of the query are not converted to entities and tracked by the EntityManager, which keeps the client-side processing minimal.

For example, lets say your users need to create new Client entities while offline.  You don't need a District entity to create a new Client.  You could load the list of Districts using noTracking and use the DistrictId and Name to create a the "district" select element on the new Client form.
Comment: re: separate EntityManagers, this might not make sense in your case but for my project, it did not make sense to serialize/deserialize all of the entities to/from localStorage when making edits.  In my case I used one EntityManager per set of entities I wanted to edit-  unit of work style.  In my case users could select several consumers to work with offline.  Each consumer is cached separately along with their phones, addresses, etc.
Comment: I was thinking you might be hitting performance problems / memory pressure when loading a lot of entities into a single EntityManager due to all the processing breeze has to do to connect all the relationships, track the entities.  I don't think the EntityManager is intended to be used this way, I think it's more common for an entity manager to track a subset of entities that are being edited on a particular screen.
Comment: Thanks.  Based on what you're saying, I'm still not sure how this all fits together. Say I have a client who has bills and payments. That client is in a group, in a site, in a region, in a country. Are you saying that the client, payment, and bill information might each have their own EM, while the location hierarchy might be in a 4th EM with no-tracking? Then when I refer to them, I wire up the relationships as needed using LINQs on the different EMs (give me all the bills for customer A, give me all the payments for customer A)?
Comment: Then, if I add a payment, does the foreign key propagate properly?  This is probably too large a topic for me to glean the intricacies in these comments.  Do you know of anywhere I could find examples and deeper explanation of these concepts? Thanks.
Comment: Jeremy, I'm using your suggestions, which have been helpful, but I have a few questions (maybe I should start a new question). If I use POJO's, I have to write my own search routines (by name, phone number, etc.), right?  Unless, of course, I'm online, when I can use LINQ to query the database.  I'm a bit worried about that.  It seems like I would have to develop two lines -- one for online, one for offline.  Obv., I could always search the offline data the same way (even when online), but the benefit of being online is being able to query the entire set.  How do you handle this?
Comment: Depends on your design. In my case attempting to search while offline displays a message like this "Looks like you're offline... you can access consumers you've made available offline on the Downloaded tab".  My email is in my profile, send me a message if you want to see this in action.  Maybe what we're doing doesn't map to what you're doing as well as I'm thinking.
Comment: Can't find your email in your profile, but I'd love to pick your brain a bit.  If you're game, please drop me a line at firstname.lastname@example.com so I have a way to contact you.  THanks!
Comment: Actually this one might be better: email@example.com. Thanks.
Answer: @Jeremy's answer was excellent and very helpful, but didn't actually answer the question, which I was starting to think was unanswerable, or at least the wrong question.  However @Steve in the comments gave me the most appropriate information for this question.
It is neither Breeze nor the Browser, but rather Knockout.  Apparently the knockout wrapper around the breeze entities uses all that memory (at least while loading the entities and in my environment).  As described above, Knockout/Breeze would crap out after reading around 5MB of data, causing Chrome to crash with over 1.7GB of memory usage (from a pre-download memory usage around 300MB).  Rewriting the app in ANgularJS eliminated the problem.  So far I have been able to download over 50MB from the exact same EF6 model into Breeze/Angular, total Chrome memory usage never went above 625MB.
I will be testing larger payloads, but 50 MB more than satisfies my needs for the moment.  Thanks everyone for your help.


Cannot uninstall Anaconda via any installer

Question: I cannot uninstall Ananconda due to this error:

Suddenly, today, my Ananconda stopped working and I followed all steps in the troubleshooting manual to uninstall and reinstall but its my 7th install and yet I have nothing.
I tried the latest installer and that screenshot is
So here are my questions:

How will I uninstall this?
My anaconda navigator does not pop up from the start and I could not find anaconda prompt anywhere to try anything else. I got an error while trying to do conda remove and install it back again( the navigator ) but no luck. Can anyone tell me what went wrong?
It used to work before without a PYTHONPATH variable. Should I add that to try to make this work?
Can anyone tell me what is wrong with my Anaconda? Please.
Comment: I did a lot of installing and uninstalling of Miniconda3 recently and the official uninstall broke my Windows Command Prompt actually. Could you should the output of your PATH variable at the current state and I assume you are using Windows 10?
Comment: One more question: Did you do a system-wide installation or a user installation?
Comment: I did a user installation.
Comment: I changed TEMP and TMP env according to https://stackoverflow.com/questions/60789886/error-failed-to-create-temp-directory-c-users-user-appdata-local-temp-conda
Comment: And removed the Anaconda elements from the PATH variable.I have literally tried everything. Now there is another problem. I cant delete conda_temp with a file called "CMcUploader". Its a log file. And its sitting in my C drive. I'm at my wits end with this :(
Answer: Have you tried running uninstall-anaconda3 with administrator privileges?
I see that your anaconda3 installation is in C:\Anaconda and so you probably launched the installation with administrative privileges.
If you are successful in uninstalling, I suggest you then redo the installation by choosing your home directory (usually C:\users<your_name>) and as a user with normal privileges.
Finally, the fact that anaconda-navigator suddenly stopped working could depend on PyQt5: it happened to me several times and I always solved it by removing the package:
<code>pip uninstall PyQt5
</code>


Yii 1.1 excessive amount of queries, how to optimise?

Question: I'm having a huge issue with Yii, as rendering simple things takes over 10 seconds.
For example:
Controller:
public function actionFailed($id=null) {
    if(!is_null($id)) $this->_viewcity=$id;
    $failed = Delivery::model()->findAll('failed IS NOT NULL AND city_id = '.$this->_viewcity.' ORDER BY id DESC');
    $cities = City::model()->findAll('active > 0');
    $this->render('failed',array(
        'failed'=>$failed,
        'cities'=>$cities,
        'city'=>City::model()->findByPk($this->_viewcity),
    ));
}

In the view only
foreach ($failed as $d) is used.
Query log: http://jsfiddle.net/kwqabmc0/
How can I optimise this? My SQL server is 23ms ping away and the previously mentioned page takes very long to load.
Answer: You are use lazy loading of Delivery.items and Delivery.user in the view.
Try
$failed = Delivery::model()->with('items', 'user')->findAll('failed IS NOT NULL AND city_id = '.$this->_viewcity.' ORDER BY id DESC');

or do not use these relations in the view.


Getting file size of bmp image

Question: I have a bitmap image and using this page I am attempting to read the file size.
In case the link breaks:

FileSize   |   4 bytes  |  File size in bytes

Here is part of the bitmap BM\xe6\x04\x00\x00\x00\x00\x00\x006 I want to read from, which as I understand it the file size is between the 3rd and 7th bytes.  So \xe6\x04\x00\x00.
I remove all the \x00 since they are null values and don't tell me anything about the file size, so I used:
raw = '\xe6\x04\x00\x00'
character_list = [raw[b:b+1] for b in range(0, len(raw))]
non_empty = [list_ for list_ in character_list if list_ != b'\x00']

This returned me: [b'\xe6', b'\x04']
Now I get all the values in the list using:
size = ''
for byte in non_empty:
    size += str(ord(byte))
    print(size)

Here are the results of the conversion:
\xe6 > 230
\x04 > 4
This returns me 2304 (since '230' + '4' is 2304), while my bitmap image has the size of 1,254 bytes and 4,096 bytes on disk.  Clearly this is not the image size.  Where have I gone wrong?
As a side note.  If I take another image of size 90 bytes and run the same process with Z\x00\x00\x00 it returns 90 as I expected.  (ord('Z') returning 90).
Comment: Summing up 230 and 4 isn't the correct operation to calculate the file size. Think of the four bytes `\xe6\x04\x00\x00` as a 4-digit number. The first digit is `\xe6` (or 230), the 2nd digit is `\x04` (or 4) and other two digits are zero. Summing up the digits of a number will obviously not give the number as result. As an example, take the number 23: 2+3 gives 5, not 23. To get 23 from 2 and 3, you have to calculate `2*10+3` (`*10` because it's a base 10 number). Similarly, to get the correct number from 230 and 4, you have to calculate `4*256+230 = 1254` (because it's a base 256 number).
Comment: I would suggest using the built-in [`struct`](https://docs.python.org/3/library/struct.html#module-struct) module which could handle this and a lot more.
Answer: From poking around it looks like the byte order for the size in a bitmap is little endian (https://en.wikipedia.org/wiki/Endianness#Little-endian).
There's a built-in method for int that can convert bytes to a integer.  https://docs.python.org/3/library/stdtypes.html#int.from_bytes
So for example:
raw = b'\xe6\x04\x00\x00'
size = int.from_bytes(raw, byteorder='little')
print(size)

Comment: Much easier and more efficient that I have been trying to use before.  Thank you.

Getting file size of bmp image


Where to find the driver for Epson WorkForce WF-2860 under Ubuntu 18.04 Bionic?

Question: I cannot scan with the Epson WorkForce WF-2860 under Ubuntu 18.04 Bionic. The scanner is plugged in per USB and still the Utsushi scan program is unable to detect the scanner. Does someone know where to find the correct drivers and can give the instructions to install it?
Answer: I know where to find the scanner driver.
It is here https://download.ebz.epson.net/dsc/search/01/search/?OSC=LX
You could easily find it too by googling "epson linux drivers".
Comment: I have been there but failed to install the "All-in-one package" due to some dependencies on pipelight that is not supported for Ubuntu 18.04 and end up at `E: Failed to fetch http://ppa.launchpad.net/pipelight/stable/ubuntu/dists/bionic/main/binary-amd64/Packages  404  Not Found`
Comment: This is not related to the drivers. pipelight is obsolete. Remove this ppa. But this error doesn't stop installing everything else.
Answer: Visit the Official Ubuntu documentation SANE - Scanner Access Now Easy.
It may be necessary to also install the sane packages listed on that page for functioning if you haven't already.
Attempt to detect scanner in a terminal with:
scanimage -L
sane-find-scanner
I would also suggest launching the epson imagescan utility from a terminal so you can see any output to the terminal that may give you more information.
A look through the Imagescan source files can give you clues to other packages that may be needed for functionality.
imagescan_3.62.0-1epson4ubuntu18.04.debian.tar.xz
imagescan_3.62.0-1epson4ubuntu18.04.dsc
Another GUI utility that may be of use is Simple-Scan.
sudo apt install simple-scan
Here is a link to another site that may provide some more information.
A Scanner How-To for Epson Scanners


Is it possible to declare a 2d array class member inside the constructor with a for loop?

Question: Currently I have this
//gameboard.h

class GameBoard
{
public:
    GameBoard(bool showShips);
    ~GameBoard();
    void draw();
    void placeShipStart(int x, int y);
    void placeShipEnd(int ship, int x, int y);
private:
    bool defaultShowShips;
    Field playerBoard[10][10];
    vector<Ship*> ships[5];
};

//gameboard.cpp

GameBoard::GameBoard(bool showShips)
{
    defaultShowShips = showShips;
    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
        {
            xyzCoord ul, lr;
            ul.x = j * 5.0f;
            ul.y = i * 5.0f;
            ul.z = 2.0f;
            lr.x = j * 5.0f + 5.0f;
            lr.y = i * 5.0f + 5.0f;
            lr.z = 0.0f;
            playerBoard[i][j] = Field(ul, lr);
        }
};

The way it is right now it's telling me that I need to have a default constructor for field. I'm trying to accomplish initializing each position in a different position. Am I doing this completely wrong? I've seen the vector of vectors approach. If possible I would like to avoid that because it wasn't working for me earlier.
Comment: Can we please see your `Field` class? When it says **default constructor**, it means that all of the variables declared in the constructor function declaration must be provided with **default** values. I see your `Field` constructor has at least 2 parameters of type `xyzCoord`. So, either provide default values in the parameter list (I can show you when I see your class). Or add a second constructor which takes no parameters.
Comment: Is it not possible to initiate these values without using a default constructor? Like can I allocate the space and then construct each one individually?
Comment: See my updated answer. Seeing the constructors for xyzCoord would help.
Answer: I am guessing here to a certain degree, but try this:
Field::Field()
{
    // Provided default values to your two member variables
}

Field::Field(xyzCoord ul, xyzCoord lr)
{
    // Populate your two member variables with the passed in values
}

The first constructor will be your default as it has no parameters.
I hope this helps. Apologies if I miss-understood your question.
Update
The alternative is:
This in the header:
Field::Field(xyzCoord ul = xyzCoord(), xyzCoord lr = xyzCoord())

This in the source:
Field::Field(xyzCoord ul /*xyzCoord()*/, xyzCoord lr /*xyzCoord()*/)
{
    // Populate your two member variables with the passed in values
}

I am conveying the principles. Without seeing the Field and xyzCoord class I can't see what the suitable declarations would be. With this last approach the constructor how provides default values for each parameter.
See this default constructor topic for more information. In part it mentions:
Comment: I want to avoid being able to create a Field object without the ul and lr's. Is it possible or am I barking up the wrong tree? I want to initiate these values in the constructor of the gameboard.
Comment: @VincentJenkins I have updated my response to show you how you can use your constructor and provide default values.


Help asking a question

Question: I would like to ask what is the opposite of egocentrism and if someone who is never speaking of himself and present himself as very altruistic can be egocentric as well. My whole question is: can exist a correlation between idealists and the narcissistic trait?
The narcissism comes from denying any human fragility and imperfection. Altruism could be considered as: "I am a good person caring of others" and often people which are very empathetic experienced suffering.
Who has an open wound can become strongly lacking of empathy on some topics.. but how could I formulate the question in a better neutral way?
Answer: Pick one question and do some background research!
Which one of the following is the one you are interested in? If you do not yet have an answer, don't start spin-off questions.

"what is the opposite of egocentrism"
"[can] someone who is never speaking of himself and present himself as very altruistic [-] be egocentric"
"can [there] exist a correlation between idealists and the narcissistic trait?"

Help asking a question


Why is my line-to line voltage only 2V, but each line to ground is ~120V?

Question: I lost one phase of power yesterday, so only half of my circuits are working.  We've had heavy windstorm where I'm at and I'm trying to diagnose the issue.  I'm assuming there is a loose connection at my overhead service line.  Power company is supposed to be coming out eventually but they are quite busy with all the outages.
When I measure line-to-line it should read 240V, but it reads 2V.  When I measure each phase to ground they are 120V for the good phase and 118V for the bad phase.  Why am I getting a reading of 118V?
I shut off all the circuits to the bad phase.  If I turn on some of the circuits, the line-to-ground voltage of the bad phase drops.  If I measure voltage on some of the circuits that are turned OFF from the bad phase, I am getting up to 20V.
Comment: Did you measure line to neutral?
Comment: Yes, Line to neutral is what I have been measuring.  I measured from the main breaker where the service wires land, and the lug where the neutral wire lands.  Also both sides of the bonded neutral bar which gives the same reading.
Comment: What you are seeing is exactly what one would expect with one phase dead.
Answer: Turn off your main breaker and re-measure. With everything still connected, you are going to get confusing readings.
Let's say to have two phases, A and B, 120V to ground each, 240 phase-to-phase. You've lost phase B.
Compared to the high impedance of a digital multimeter, household loads are practically dead shorts. The schematic of the power company and your house now looks like this if you have loads still connected. Phase B is connected to Phase A through a tiny resistance, so it's not dropping any voltage. It's basically equal to Phase B, so you see ~120V B-N but ~0V A-B.
<code>Power  |                           |                           |
Co     |                           |                           |
       |                           |                           |
-----  |                           |
       |        120V loads         |         120V loads        |
House [A]----[tiny resistance]----[N]----[tiny resistance]----[B]
       |                                                       |
       +-----[tiny resistance]---------------------------------+
                240V loads
</code>
Shut off your main breaker, and you'll see 120V A-N but ~0V A-B and B-N.
You should turn off all of your 240V circuit breakers until the power company fixes this outage. Until it is repaired, all of your phase-B circuits are being powered through whatever 240V loads happen to be connected at any given time. That's not good for anything involved, as it can cause wildly varying voltages.
Comment: Thanks for the explanation!  I did turn off all circuits connected to B-phase.
Comment: Great answer!  @Buzz 240V circuits are connected across A and B phase, so need to be shut off also.  One leg going dead does not take them out of the game.  In fact often water heaters will regain temperature simply by being in series with the 120V loads on the dead phase. Then the thermostat cuts it out, the 120V loads go stone dead and the homeowner is "WTH just happened?"


Why does city tax value differ between title screen and county screen?

Question: First image shows that income tax for city Dioclea is 6.85 while second screen shows a value of 6.22.
I was able to calculate city tax value using the formula provided in the wiki and I got value of 6.22.
Also the values differ for other cities as well but I noticed the difference between these two values is small.
Why is there a difference between the two screens?
Note: I am playing base game without any DLC activated.
Answer: This is more of an educated guess then a completly true answer since i can't test it myself at the moment.
When i add together all the taxes you should get from your first image i get a value of 30.2 gold, however the calculated number in the outer list only shows 18.54. Even further when i add all you tax categories together its also short of 1 gold to the 108.19 you should get.
In my opinion this is most likely a visual bug and the numbers there forget to incorporate some modifiers. Another possibility could be, that the gold amounts shown besides the names of the mayors is the full "normal" amount you would get and depending on the color (red, yellow, green, etc.) this amount is in reality either reduced or increased because of modifiers not stated there.


Is it possible to see what processes did last mounted USB device?

Question: Is it possible to see what last mounted USB device? I am afraid, that last device infected my ubuntu machine and want to find out something about that device.
Answer: The Linux operating system, and many applications that run on it, do a lot of logging. These logs are invaluable for monitoring and troubleshooting your system. https://ubuntu.com/tutorials/viewing-and-monitoring-log-files#1-overview
Comment: could you clarify the answer? I knew, that operating system do a lot of logging and there are huge documentations to read, but maybe you could post commands and explain what should I look for? It was big chip something like 4G USB dongle, how can I check if it not installed any malicious software?
Comment: you can install malicious removal like as that mentioned
 in this answer https://askubuntu.com/questions/579949/how-to-remove-malware


fcitx won't trigger IME on super+space

Question: I'm on Ubuntu 14.04 LTS.
When I just finished installing the sougoupinyin IME with fcitx,Everything works fine.
I want to change the default hotkey combination of Trigger Input Method from L-CTRL + Space
to Super + Space(Win + space) ,so that it make no difference from Microsoft Windows.
The combination do changed to Super + Space , as shown from the Configration panel.
However , the combination won't working.
Found the similar case here What is eating the Super+Space shortcut?
Since the desktop of ubuntu 14.04 is based on Unity ,the combination itself  work fine when I use the ibus-based IME previously.
No idea about what to do. My  keyboard layout is English-US.
Sorry for my poor English and formatting.
Thanks
Answer: As the comment mentions that in 18.04 and 18.10 the hotkey SUPER_SPACE does not work.
This can be fixed by unsetting the system hotkey in

System settings -> Devices -> Keyboard -> Switch to next input source
Answer: So I just had the same issue on Lubuntu 16.04, and have managed to fix it.
The Background
Basically when you change the Trigger Input Method variable in the Fcitx Configuration to Super+Space, the display shows it changing to SUPER_SPACE, but it actually gets set to SPACE (you can still type spaces by using Super+Space). The Fcitx configuration just changes the files in ~/.config/fcitx, so you can manually edit them. Look at these lines in ~/.config/fcitx/config, the TriggerKey has been set to SPACE not SUPER_SPACE:

 # Trigger Input Method
TriggerKey=SPACE

The Fix

Manually change Line 3 of ~/.config/fcitx/config to TriggerKey=SUPER_SPACE and save.
Reopen the Fcitx Configuration tool and apply without changing anything (updates your settings).

That should do it
Comment: In my ubuntu 18.04, the setting in the config file is TriggerKey=SUPER_SPACE by default.  But the key combination still doesn't work.
Answer: For Ubuntu 20.04, you can unset the system hotkey in

Settings -> Keyboard Shortcuts
Answer: In my case, after I changed the Trigger input method to Super+Space, I needed to disable the Keyboard shortcuts:

Settings > Keyboard shortcuts > Switch to next input source >
[backspace] (to disable the shortcut)

To my understanding, since they're both changing the input, there is either a conflict or double-changing of the input source.

fcitx won't trigger IME on super+space


Finding out which class is calling a function - iOS, objective C

Question: I have a function - myFunc() in class A. There are multiple other classes calling this function.
How will I be able to find out which class is calling myFunc() at a particular instance?
Would someone be able to help me with this?
Comment: possible duplicate of [Objective C find caller of method](http://stackoverflow.com/questions/1451342/objective-c-find-caller-of-method)
Answer: Use the Visitor pattern

Have each of the calling classes implement a common protocol that defines the interface of the behavior you are looking to achieve.
Add the protocol as a parameter to myFunc.
When calling myFunc(), specify self as the parameter.
myFunc can now invoke any of the protocol methods without knowing about the other specific classes.

This way you adhere to the concepts of encapsulation.
Answer: Conceptually, this information is available in the stack, though it isn't easy to get to. Most solutions would involve creating an exception in order to capture the stack trace, and then reading the trace. I haven't tried this, but it might work:
void myFunc()
{
    NSArray *stack = [NSThread callStackSymbols];
    // I have no idea if the current function call is at the 0 or last position
    // of the array. Experiment here!
}

Pertinent documentation: NSThread Class Reference
Note that if you want your function to behave differently depending on who is calling, DO NOT DO THIS. It's fragile (there are no guarantees about whether the format of what callStackSymbols returns will change).
It's better to simply pass a parameter into your function. If you're dealing with a C-function callback API, there is typically a void * "context" or "info" parameter that you can use to pass in an arbitrary pointer. This could be a pointer to your object.
Comment: This is a nice debug tool.


Bumblebee problem after installation

Question: Yesterday I was using Kubuntu 13.10. I had a problem using my Intel and Nvidia graphics cards. I thought this was a KDE problem, so I changed distros to Xubuntu. After the installation I installed Steam and it was working. I was happy. I got this error
ERROR: Could not open display :8

Next I installed an update, and after the update I was trying to install nvidia-prime but after restarting lightdm didn't start. I reinstalled Xubuntu, installed an update, and install the nvidia-319 driver and bumblebee using the following commands:
sudo apt-get install nvidia-319 nvidia-settings-319
sudo apt-get install bumblebee linux-headers-generic

I restarted the computer and installed Steam. After Steam started I got an error exactly like the error I got before on Kubuntu. While using the Intel card and running Steam I got this error:
ERROR: Could not open display :8

Nvidia running using bumblebee was giving me a primus error.
I reinstalled the operating system again and installed updates and Steam is working.
How do I install Bumblebee without getting a graphic cards problem?
Comment: Official Optimus support is out for Linux.
Comment: Optimus support? On 13.04 i was using bumblebee. What change now about this support? Nvidia-primus is not working for me.
Comment: @set4812 Bumblebee by default uses `nvidia-current` driver. If you are using `nvidia-319` you need to change `/etc/bumblebee/bumblebee.conf` and restart Bumblebee.
Answer: Remove all Bumblebee packages you have installed (along with the nvidia319). Start afresh. Specific instructions for Ubuntu 13.10 version are as follows:
From the Bumblebee on Ubuntu installation wiki-
"You need to open your terminal and enter the commands below.
If on 12.04.3, replace linux-headers-generic with linux-headers-generic-lts-raring.
sudo add-apt-repository ppa:bumblebee/stable

Enable the Universe and Multiverse repositories (for bumblebee and nvidia packages respectively).
sudo apt-get update

Install Bumblebee using the default proprietary nvidia driver for 12.04 - 13.04 :
sudo apt-get install bumblebee bumblebee-nvidia virtualgl linux-headers-generic

***And for 13.10 :
sudo apt-get install bumblebee bumblebee-nvidia primus linux-headers-generic
Reboot*** "

First purge the nvidia-319 you have OR update it ( I didn't do either because Bumblebee handled it for me ). Then follow the highlighted instructions for 13.10.
Then REBOOT( very important ). If it shows an error like :"Not added to the Bumblebee group". Then add yourself using groupadd
This should work.

Bumblebee problem after installation


Activity doesnt mantain connection to its service after minimalising it

Question: I have a problem with an activity after minimalising. Everything is going ok when i start an activity and press start button. But when i minimalise activity and again maximalize it, it doesnt respond to my buttons and commands. Anybody know what to do? This is my first android app so i dont know what is going on..
here are my classes :

TrackerService

package sk.tuke.smart.makac.services;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class TrackerService extends Service implements LocationListener  {

    private Intent commandIntent;
    private long duration;
    private boolean paused,checkedAfterPause;
    private int sportActivity;
    private double distance,pace,calories;
    private ArrayList<Location> finalPositionList = new ArrayList<Location>();
    private LocationManager locationManager;

    private static final String TAG = "TrackerService";

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i(TAG,"onStart intent " +intent.getAction());
        commandIntent=intent;
        checkedAfterPause=true;
        if(intent.getAction() == "sk.tuke.smart.makac.COMMAND_START"){
            if(intent.getAction() == "sk.tuke.smart.makac.COMMAND_START") {
                duration = 0;
            }
            new Timer().scheduleAtFixedRate(new TimerTask()
            {

                @Override
                public void run() {
                    if(!paused){
                        duration++;
                        Intent intent1 = new Intent();
                        intent1.setAction("sk.tuke.smart.makac.TICK");
                        intent1.putExtra("duration", duration);
                        intent1.putExtra("distance",distance);
                        sendBroadcast(intent1);
                        Log.i(TAG,"" + duration);
                    }
                }
            }, 1000, 1000);
        }else if (intent.getAction() == "sk.tuke.smart.makac.COMMAND_PAUSE"){
            paused=true;
            locationManager.removeUpdates(this);
        }
        if(intent.getAction() == "sk.tuke.smart.makac.COMMAND_CONTINUE"){
            paused=false;
            checkedAfterPause=false;
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,10,this);
        }

    }

    @Override
    public void onCreate() {

        super.onCreate();
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,10,this);

    }

    @Override
    public void onDestroy() {
        locationManager.removeUpdates(this);
    }

    @Override
    public IBinder onBind(Intent intent) {

        return null;

    }

    @Override
    public void onLocationChanged(Location location) {
        finalPositionList.add(location);
        Location lastLocation;
        double minDistance;
        if (finalPositionList.size() != 1 && checkedAfterPause) {
            lastLocation = finalPositionList.get(finalPositionList.size() - 2);
            minDistance=location.distanceTo(lastLocation);
            if(minDistance>=2){
                distance += location.distanceTo(lastLocation);
            }else{
                finalPositionList.remove(finalPositionList.size()-1);
            }
        }
        if(commandIntent.getAction() == "sk.tuke.smart.makac.COMMAND_CONTINUE" && !checkedAfterPause){
            Log.i(TAG,"checking distance after pause");
            lastLocation = finalPositionList.get(finalPositionList.size() - 2);
            minDistance=location.distanceTo(lastLocation);
            if(minDistance<=100){
                distance += location.distanceTo(lastLocation);
            }
            checkedAfterPause=true;
        }
            Log.i(TAG,"locations " + finalPositionList);
            Log.i(TAG,"distance = " + distance);

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    public long getDuration(){
        return duration;
    }

    public double getPace(){
        return pace;
    }

}

SportsActivity

package sk.tuke.smart.makac;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import sk.tuke.smart.makac.helpers.MainHelper;
import sk.tuke.smart.makac.services.TrackerService;

public class StopwatchActivity extends AppCompatActivity {

    private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 111;
    private static final String TAG = "StopwatchActivity";
    private boolean started;
    private boolean running;
    private boolean paused=false;
    private long duration;
    private double distance;
    private MainHelper helper;
    private TextView durationView,distanceView;
    private Button startButton,endButton;

    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction()=="sk.tuke.smart.makac.TICK"){
                duration = intent.getLongExtra("duration",duration);
                distance = intent.getDoubleExtra("distance",distance);
                durationView.setText(helper.formatDuration(duration));
                distanceView.setText(helper.formatDistance(distance));
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stopwatch);
        IntentFilter intentFilter = new IntentFilter("sk.tuke.smart.makac.TICK");
        registerReceiver(receiver,intentFilter);
        started=false;
        running=false;
        helper = new MainHelper();
        durationView = findViewById(R.id.textview_stopwatch_duration);
        distanceView = findViewById(R.id.textview_stopwatch_distance);
        startButton = findViewById(R.id.button_stopwatch_start);
        endButton = findViewById(R.id.button_stopwatch_endworkout);
        if(!canAccessLocation()){
            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_FINE_LOCATION);

        }
    }

    public void toggle(View view){

        Intent intent = new Intent(this,TrackerService.class);
        started=true;
        this.running = !this.running;
        if(running && started){
            startButton.setText("Stop");
            endButton.setVisibility(view.GONE);
            if(paused){
                intent.setAction("sk.tuke.smart.makac.COMMAND_CONTINUE");
                paused=false;
            }else
                intent.setAction("sk.tuke.smart.makac.COMMAND_START");

        }

        if(!running && started){
            startButton.setText("Continue");
            endButton.setVisibility(view.VISIBLE);
            intent.setAction("sk.tuke.smart.makac.COMMAND_PAUSE");
            paused=true;
        }

        startService(intent);

    }

    public void endWorkout(View view){
        Intent intent = new Intent(this,TrackerService.class);
        intent.setAction("sk.tuke.smart.makac.COMMAND_STOP");
        startService(intent);
        setContentView(R.layout.activity_workout_detail);
        onStop();
    }

    public void openMaps(View view){
        Intent intent = new Intent(StopwatchActivity.this, MapsActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Intent intent= new Intent(this,TrackerService.class);
        stopService(intent);
    }

    private boolean hasPermission(String perm) {
        return(PackageManager.PERMISSION_GRANTED==checkSelfPermission(perm));
    }

    private boolean canAccessLocation() {
        return(hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
    }
}

Answer: You aren't creating a connection to the service.  You're only starting it, not binding it.  So there's no connection to maintain.
It looks like you're trying to do quasi-binding via actions.  Don't do that, properly bind the service and avoid a whole raft of problems like this.
Comment: Yes thank you, i bound services and its working correctly now. Now i have new problem. After i hit back button, onDestroy is called and i want to save state of my activity and then i want to refresh it again with onResume. Can you help me with this? Basically i want same functionality in onDestroy as onPause method. When i call super.onPause in onDestory , it doesnt work.
Comment: Put the functionality to save state in a helper function, and call the helper in both places.


jQuery get count value of console log with duplicate value

Question: I need to count in console.log for each duplicate value.

As you can see above image, I need to get the count of true and false for each.
2 false
1 true
2 false
1 true
2 false
1 true

My code so far
 console.log(document.getElementById("lights").checked);

Is it possible to get it or if any another way without using console.log will be better?
Comment: A photo of the console uploaded and re-hosted on SO, yet no code...
Answer: You're clearing using a loop, or repeated events, or similar. Simply keep track. Declare counters somewhere they'll be accessible to the place where that console.log is, but outside whatever loop or event handler it's in:
var trueCount = 0;
var falseCount = 0;

...and then in place of your console.log:
if (document.getElementById("lights").checked) {
    ++trueCount;
} else {
    ++falseCount;
}


"An unexpected error has occurred within this region of the page" when check code file on Azure Devops

Question: When I locate our project on Azure Devops, it cannot display code content as this error occurs when I open any C# file:

An unexpected error has occurred within this region of the page.
You can try reloading this component or refreshing the entire page.
Answer: I think this could be a browser compatibility issue. The UI of the devops page is not compatible with some versions of the browser.
As a workaround, you can try to use chrome browser, or the latest edge browser. I use chrome to test without problems.


limit at infinity of a meromorphic function using residues

Question: Let $z_1,\dots,z_n\in\mathbb{C}$ be different points and let $f:\mathbb{C}\setminus\{z_1,\dots,z_n\}\to\mathbb{C}$ be a holomorphic function.
Suppose that $\lim\limits_{z\to\infty}f(z)=0$. Prove that
$$\lim\limits_{z\to\infty}zf(z)=\sum\limits_{k=1}^n  \operatorname{Res}_{z_k}(f)$$
Clearly, we can look at $\lim\limits_{z\to 0}\frac{1}{z}f(\frac{1}{z})$. I have read something about residue at infinity, but I don't see how to use it.
Answer: Let $R>0$ be a radius such that all the singularities $z_j$ are inside the disk $D(0,R)$. (Center $0$ and radius $R$) Hence by the residue theorem, one has
$$2i\pi \sum\limits_{k=1}^n  \operatorname{Res}_{z_k}(f) = \int_{C(0,R)^+} f(z) dz.$$ Now perform a change of variable $z=1/w$ to get $$\int_{C(0,R)^+} f(z) dz = -\int_{C(0,1/R)^-} \frac{1}{w^2}f\left(\frac{1}{w}\right) dw= \int_{C(0,1/R)^+} \frac{1}{w^2}f\left(\frac{1}{w}\right) dw.$$ Since the $z_j$ were inside $D(0,R)$, it is clear that the $1/z_j$ are now outside $D(0,1/R)$. Hence, the only singularity of $\frac{1}{w^2}f \left( \frac{1}{w}\right)$ inside $D(0,1/R)$ is $0$. Hence, by the residue theorem again, one has $$\int_{C(0,1/R)^+} \frac{1}{w^2}f\left(\frac{1}{w}\right) dw = 2i\pi\operatorname{Res}_{0}\left(w \mapsto \frac{1}{w^2}f\left(\frac{1}{w}\right)\right).$$ If we put everything together, we get $$\sum\limits_{k=1}^n  \operatorname{Res}_{z_k}(f) =\operatorname{Res}_{0}\left(w \mapsto \frac{1}{w^2}f\left(\frac{1}{w}\right)\right).$$ Now the only thing you have to prove is that $0$ is a simple pole of $w \mapsto \frac{1}{w^2}f\left(\frac{1}{w}\right).$ Indeed if you do this, you will have $$\operatorname{Res}_{0}\left(w \mapsto \frac{1}{w^2}f\left(\frac{1}{w}\right)\right) = \lim_{w\to 0} w \frac{1}{w^2}f\left(\frac{1}{w}\right)=\lim_{z\to \infty}zf(z)$$ and you are done. Are you able to do that ?
Comment: (+1) Really nice!
Comment: Thanks, I understand it in full, except for the part that I need to handle... I mean I tried to use Taylor expansion for $f$ around  $0$ but when using $\frac{1}{w^2}f(\frac{1}{w})$ I got a Laurent expansion with infinitely many negative coefficients.
Comment: Ok. On $\mathbb{C} \backslash D(0,R)$, you can write $f(z)$ as a Laurent series right ? Then, you can use your hypothesis $\lim_{z\to \infty} f(z) = 0.$ This will imply that your Laurent series has a specific form, etc ...
Answer: Those are initial thoughts... Unfortunately not a solution
Consider the domain $D$ limited by a circle $C(R)$ centered at the origin (with clockwise orientation) and with a radius $R$ large enough in order for the disk $D^\prime$ it limits to contain $\{z_1,\dots,z_n\}$ and small circles $C_1, \dots, C_n$ (oriented counterclockwise) centered respectively on $z_1, \dots, z_n$ all contained in $D^\prime$. As $f$ is holomorphic in $D$, you have
$$\begin{aligned}
0=\frac{1}{2i \pi}\int_{C(R)} f + \sum\limits_{k=1}^n \int_{C_n} f &= \frac{1}{2i \pi}\int_{C(R)} f+\sum\limits_{k=1}^n Res_{z_k}(f)\\
&= -R \int_0^{2 \pi} f(Re^{2i \pi t}) \ dt+ \sum\limits_{k=1}^n Res_{z_k}(f)
\end{aligned}$$
As $\lim\limits_{z\to\infty}f(z)=0$, for all $\epsilon >0$ you can find $r >0$ such that for $\vert z \vert \ge r$ you have $\vert f(z) \vert \le \epsilon$. Hence if $R \ge r$...
I don't know how to move further from there ...


How do I sort my downloaded PS3 games by size?

Question: I'm out of space on my PlayStation 3 and would like to remove the games with the largest download sizes. I don't see an option to sort by size. Is there some way I can do this?
Answer: Unfortunately, this is not possible as far as I know.
You can try to start from this list of games:
The individual games' pages are supposed to have the install sizes in them.
Depending on the number of games, this might take a while.
This however doesn't solve the problem with respect to patches, as some games have really huge patches. For example, I remember "Need for Speed Most Wanted" downloading a patch with more than 2 GB, so you should also check the "Game Data (PS3)" section on your console.
I know this is all pretty unsatisfactory, so I personally chose to not download all the PS Plus games anymore and just look for 1-2 bigger games and/or install data to delete whenever I need space for new games.


Python jsonschema not flagging date-time errors

Question: I'm having some trouble understanding how to validate data using jsonschema, which came to light when I started trying to validate date-time values.
The following code should raise a ValidationError exception, but it doesn't. It's the shortest example I've been able to come up with.
def val(data, schema):
    try:
        jsonschema.validate(data, schema)
    except jsonschema.ValidationError as e:
        return e.args[0]

result = val('2008-09-0X22:47:31-07:00', {'format': 'date-time'})
print(result)

The result is None for any string value, although
val(42, {'type': 'string', 'format': 'date-time'})

raises the exception with "42 is not of type 'string'". This does not happen if I omit the 'type' schema item, and the validator again returns None.
It seems to me I have some fundamental misunderstanding about how to use the package.
Answer: As stated in the jsonschema documentation:

By default, no validation [of format] is enforced, but optionally, validation can be enabled by hooking in a format-checking object into an IValidator.

It then shows an example of how to do that:
validate(
    "-12", {"format" : "hostname"}, format_checker=FormatChecker(),
)

So all you need to do is:
jsonschema.validate('2008-09-0X22:47:31-07:00', {'format': 'date-time'}, format_checker=jsonschema.FormatChecker())

Do note that, as stated at the bottom of the page, the date-time format is only enforced if you also have the strict-rfc3339 package installed.
Comment: Thanks. `strict-rfc3339` _is_ installed. I'm actually trying to replace the validation done by the `connexion` package, so it might be quite a big job.
Comment: `from jsonschema import validate, FormatChecker
validate({"2001-02"},  {"type": "string", "format": "date"}, format_checker=FormatChecker()) # throws validation error as expected
validate({"dob": "2001-02"}, {"dob": {"type": "string", "format": "date"}}, format_checker=FormatChecker()) # Doesnt throw error which is wrong`
Can someone help ? am i missing something ?


Why is my state undefined?

Question: Trying to follow a simple clock/countdown tutorial in React:
constructor(props) {
    super(props);
    this.state = {
      secondsRemaining: 10
    };
  }

  componentDidMount(){
    let interval = setInterval(this.timer, 1000);
    this.setState({ secondsRemaining: this.state.secondsRemaining })
    this.setState({ interval: interval });
  };

  componentWillUnmount() {
    clearInterval(this.state.interval);
  };

  timer(){
    this.setState({ secondsRemaining: this.state.secondsRemaining -1 });
  };

Very obvious what everything does but when I run it, I get an error saying cannot read property secondsRemaining of undefined in the timer function
It is probably something stupid I have missed out but I just cannot see it
followed the answer to this question: setInterval in a React app
Comment: `this.timer.bind(this)`
Answer: The myfunction.bind() method specifies what this will be refering to inside the method when its being called. To be sure that when you call this.timer() you are actually refering to your components state and not the object thats invoking it you will have to pass this.timer.bind(this).
Answer: Because setInterval will call this.timer and this will be window object.
you can use closure:
componentDidMount(){
   let currentInstance = this;
   let interval = setInterval(function(){ currentInstance.timer(); }, 1000);
   ...
};

at the moment of executing method componentDidMount it context with initialized property state, save into variable currentInstance.
Then we closure value of currentInstance into setInterval first argument.
Answer: Define timer as an Arrow Function.
  timer() => this.setState({ secondsRemaining: this.state.secondsRemaining -1 })

OR
.bind your method inside constructor:
constructor(props) {
    super(props);
    this.state = {
      secondsRemaining: 10
    };
    this.timer = this.timer.bind(this);
}

I don't recommend this.timer.bind(this) inside render; because doing that, .bind will create a new function on every render.
Answer: Because of your bounding context. You can use an arrow function or this.timer.bind(this)

Why is my state undefined?


Update and cancel outlook appointment using ICS file

Question: I'm trying to create an application which will create, update and cancel an appointment on target user's outlook calendar using ICS file.
I've successfully created the ICS file and send to target user's successfully for the first time.
But I'm unable to edit and cancel the appointment through an ICS file.
Here's my current code:-
private static byte[] CreateiCal(string subject, string location, DateTime startTime, DateTime endTime)
    {
        var a = new StringBuilder();
        var guid = Guid.NewGuid();

        a.Append("BEGIN:VCALENDAR\r\f");
        a.Append("VERSION:2.0\r\f");
        a.Append("PRODID:-//ince/events//NONSGML v1.0//EN\r\f");
        a.Append("BEGIN:VEVENT\r\f");
        a.Append(String.Format("DTSTART:{0}\r\f", GetFormatedDate(startTime)));
        a.Append(String.Format("DTEND:{0}\r\f", GetFormatedDate(endTime)));
        a.Append(String.Format("LOCATION:{0}\r\f", location));
        a.Append(String.Format("UID:{0}\r\f",guid));
        a.Append(String.Format("SUMMARY:{0}\r\f", subject));
        a.Append(String.Format("DESCRIPTION:{0}\r\f", subject));

        a.Append("BEGIN:VALARM\r\f");
        a.Append("TRIGGER:-PT15M\r\f");
        a.Append("REPEAT:2\r\f");
        a.Append("DURATION:PT15M\r\f");
        a.Append("ACTION:DISPLAY\r\f");
        a.Append("DESCRIPTION:Reminder\r\f");

        a.Append("END:VALARM\r\f");
        a.Append("END:VEVENT\r\f");
        a.Append("END:VCALENDAR\r\f");
        byte[] b = Encoding.ASCII.GetBytes(a.ToString());
        return b;
    }

    private static string GetFormatedDate(DateTime date)
    {
        return String.Format("{0}{1}{2}T{3}{4}00Z", date.ToUniversalTime().Year, date.ToUniversalTime().Month.ToString("00"), date.ToUniversalTime().Day.ToString("00"), date.ToUniversalTime().Hour.ToString("00"), date.ToUniversalTime().Minute.ToString("00"));
    }

    private String CreateBody(String title, String description, String location, DateTime startTime, DateTime endTime)
    {
        const String successStyle = ".success{color: #333333;font-family: Century Gothic, Arial;font-size:1.4em;margin-top:5px;margin-bottom:5px;}";
        const String standardStyle = ".standard{color: #333333;font-family: Century Gothic, Arial;font-size:1.0em}";
        const String reminderStyle = ".reminderStyle{color: red;font-family: Century Gothic, Arial;font-size:1.0em;font-variant:italic;margin-top:2px;margin-bottom:2px;}";
        const String contentsStyle = ".contentsTable{color: #333333;font-family: Century Gothic, Arial;font-size:1.0em;border-collapse:collapse;border-spacing:0px;padding:0px;margin:0px;} .contentsTable > td {padding-right:5px;}";
        var b = new StringBuilder();
        b.Append(String.Format("", successStyle, standardStyle, contentsStyle, reminderStyle));
        b.Append(String.Format("
You have successfully registered for the following event
"));
        b.Append(String.Format("
{0}
", title));
        b.Append(String.Format("
Please click on the calendar invitation to add this appointment to your calendar.
"));
        b.Append(String.Format("
"));
        b.Append(String.Format("
Time	{0} - {1}
", startTime, endTime));
        b.Append(String.Format("
Location	{0}
", location));
        b.Append(String.Format("
Description	{0}
", description));
        b.Append(String.Format("
"));
        return b.ToString();
    }

    public void SendAppointment(string from, string to, string title, string body, DateTime startTime, DateTime endTime, String location)
    {
        try
        {
            SmtpClient smtpClient = new SmtpClient();
            MailMessage message = new MailMessage();

            smtpClient.Host = "my.smtp.server";

            smtpClient.Port = 25;

            smtpClient.EnableSsl = false;

            smtpClient.UseDefaultCredentials = true;

            message.From = new MailAddress(from);
            message.To.Add(new MailAddress(to));
            message.Subject = "Successfully registered";
            string result = "Sample text";

            message.Body = "" + CreateBody(title, body, location, startTime, endTime) +  "";
            message.IsBodyHtml = true;

            byte[] attachment = CreateiCal(title, location, startTime, endTime);
            var ms = new MemoryStream(attachment);
            message.Attachments.Add(new Attachment(ms, "eventappointment.ics", "text/calendar"));

            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

            smtpClient.Send(message);

            string sMessage = "Email sent.";

            Console.WriteLine(sMessage);

        }
        catch (Exception ex)
        {
            Console.WriteLine("Couldn't send the mail!" + Environment.NewLine + ex.Message);
        }

    }

And in my main method I made a call as given below:-
DateTime startTime = new DateTime(2017, 08, 29, 14, 15, 0);
DateTime endTime = new DateTime(2017, 08, 30, 16, 35, 0);
CreateICS objCreateICS = new CreateICS();
objCreateICS.SendAppointment("firstname.lastname@example.com", "firstname.lastname@example.com", "Title", "Subject", startTime, endTime, "Location");
Console.ReadLine();

Now I want to update and cancel the same appointment through ICS.
I've tried to implement solution using below links, but nothing works :
Cancel Outlook meeting
replace-existing-outlook-calendar-appointment
Can anyone please guide me on how to do this?
Thanks in advance.
Answer: To cancel appointment use:
"METHOD: CANCEL"

To update appointment use:
"METHOD: REQUEST"

followed by sequence greater than the one which created the appointment:
int sequence = appointment.Sequence + 1;

"SEQUENCE:" + sequence .ToString()
"X-MICROSOFT-CDO-APPT-SEQUENCE:" + currentSequence .ToString()

Github Sample
For sample working project check out my implementation on GitHub:
https://github.com/pzarebski/AppointmentNotificationManager
Comment: attach your appointment ics file and your appointment update ics file
Comment: Referred to your Github project https://github.com/pzarebski/AppointmentNotificationManager
Got it working now. thanks
Comment: glad that was helpfull, i'll edit my answer and include github project :)
Comment: where do u get the sequence from ? Can you edit the code that worked for you @ASHISH_TECHIT


Check kubernetes pod name from other VM

Question: I have a separate VM in the same network as my kubernetes in Azure.
I have a kafka pod and I am able to reach this pod using the IP. The problem is that the pod IP is changing all the time.
Is there any way to get the correct IP each time the pod IP is changing?
Answer: I would suggest using a kubernetes service to expose pod. This avoids the problem with change in POD IP because service IP does not change.
Kubernetes ServiceTypes allow you to specify what kind of Service you want. The default is ClusterIP.
Type values and their behaviors are:
ClusterIP: Exposes the Service on a cluster-internal IP. Choosing this value makes the Service only reachable from within the cluster. This is the default ServiceType.
NodePort: Exposes the Service on each Node's IP at a static port (the NodePort). A ClusterIP Service, to which the NodePort Service routes, is automatically created. You'll be able to contact the NodePort Service, from outside the cluster, by requesting :.
LoadBalancer: Exposes the Service externally using a cloud provider's load balancer. NodePort and ClusterIP Services, to which the external load balancer routes, are automatically created.
ExternalName: Maps the Service to the contents of the externalName field (e.g. foo.bar.example.com), by returning a CNAME record
Since you are accessing the POD from outside the kubernetes cluster itself use NodePort or LoadBalancer type service.
Comment: by setting nodeport service name will be reachable? or IP will be static..
Comment: by name you mean pod name or service name?
Comment: I am not sure how you were getting name of a pod actually..can you explain? You were hitting the pod ip directly from outside the cluster? I think that's not possible unless you run the pod with `hostNetwork:true`
Answer: As mentioned by @arghya-sadhu already going for Kubernetes service, is the best option. The kubernetes service has an IP depending on the type of kubernetes service.

For services of type ClusterIP, you get a cluster IP address
For services of type Load Balancer, you get a Loadbalancer IP address (i.e) public IP address
For services of type NodePort, you can access using the node's address.

But, whatever the type of service is, you can access the service using the kube-DNS within the cluster. So, let's say your service name is other-service and it exposes port 8080, running on namespace abc, then you can access the service as follows:

http://other-service.abc:8080

Since, your VM runs outside the cluster, it is better to use Loadbalancer and access the pod using Loadbalancer url or IP address. You can set an ingress in case there are multiple pods in the cluster that you want to connect to.

Check kubernetes pod name from other VM


Can 2x6 ceiling joists support a temporary point source load of 1500#

Question: I'm installing a residential elevator in my home. The installation requires a padeye in the ceiling to carry 1500 lbs. I have 2x6" ceiling joists spanning 16'. I planned to bridge a 2x10 across two joists in the attic and pass the padeye post through it from below to carry the load. The padeye is 5/8" diameter rated for 5000 lbs. Will the ceiling joists and 2x10 bridge be sufficient to temporarily carry the 1500 lb load?
Comment: 16 foot span, 2x6, 1500lbs.  Not something I would stand under.
Comment: Define "temporary" please. How will you bridge the 2x10? to the joists?
Comment: For those of us not familiar with the term, what's a "padeye"?
Comment: Wow, what's the purpose of doing this temporarily? Shoot for permanent and you might find that the 2x10 might not even be sufficient. Consult an engineer because it sounds like you might be out of your depth with this project.
Comment: "temporary"? when the beam breaks all it was feeling was the load.
Comment: do you have a photo of the pad eye, how is it attached to the wood beam
Comment: Rough estimate, the 2x6 can carry 30psf.
Comment: Distributing the 1500# load between (2)2x6 members spanning 16'-0" will not be safe. You might want to look into using (4)2x10s Hem Fir No2 or equivalent, (2) each side.

You will want to reconsider using a flat 2x10 as well, there is no way that's strong enough. Not to mention the screws that would be required to hold that padeye in place. Just because the padeye is rated for 5000# doesn't mean the connection from the screw to the wood is.
Comment: @represton, answers go down there.
Comment: Seems to me you should be looking at putting in some posts up to the attic with a beam sitting on them that you fasten your padeye to. This would require you to get the right size beam, maybe a steel I-beam and make sure your posts are sitting on appropriate support. As is I'd say @isherwood answered your question. I think you need to look at a different design for this.
Answer: No. At least not safely or wisely.
16' is a really long span for a 2x6, even as just a ceiling. Even with two of them you'd have massive sag, and if either aren't very robust specimens I wouldn't be surprised by catastrophic failure. Even if they were up to the task, tip/twist is a real possibility without boxing or bracing. That would mean game over.
Comment: Thanks to all. I think I'll double the 2x10 and run perpendicular from the rim joist across three ceiling joists with a steel post below to carry the load.
Comment: You're welcome. Please take the [tour] so you know how to resolve your posts.


Why did the neutral wire burn out in my electric shower?

Question: I've had my shower fitted for about 3 years and just yesterday it went bang and stopped working. (My wife was using it and says there was a blue flame!)
When I checked inside the unit I saw that the neutral wire was burned out along with the adjoining section of the connector block. The wire had become so hot it had actually melted into the casing.
I'd like to know why this might have happened, after it had been running fine for so long. How dangerous was it- could I have been given a shock if I'd been touching the casing when it blew up? Also I'd like to know whether repairing it is a job it is safe for me to undertake myself or do I need a qualified electrician.
Comment: If you're asking this question, I'd be happier if you found an electrician... but you can start by defining "burned out". A photo of the damage, as you found it, would be tremendously useful. This *sounds* like a bad connection, but... (This would be the reason Americans find the concept of an "electric shower" so weird.)
Comment: Current causes heat, heat causes expansion. Over time, the heating and cooling cycle can cause connections to loosen. This is especially true for higher drawing appliances, such as heaters and stoves.  The documentation for some such appliances, suggest inspecting and tightening connections from time to time.  If the connection wasn't properly tight to begin with, this problem can lead to catastrophic failure (as you've seen). I'm guessing the wire heated to the point that it broke, then ended up coming into contact with the "hot" terminal. Which caused the spark.
Comment: Of the breaker/fuse didn't do its job, it could have been much worse.
Answer: Rip that thing out of the shower. You do not want mains power in a shower even on a good day.
Comment: How else can an electric shower work?
Comment: These seem to be fairly common in the UK; can't vouch for anywhere else in Europe. I've presumed it's some sort of retrofit for old houses that originally had cold-water-only showers or that  Yes, it surprised me too, but "if it happens, it must be possible."
Comment: Had a missionary friend nearly die of one of these in Peru. He found it's quite common for something to come unstuck and let you be the ground conductor there. He became an advocate of cold showers unless there was a central water heater.
Comment: I reset my case despite the fact that someone saw fit to down vote my answer.
Comment: @MichaelKaras Really? Your solution for "why did the wire blow in my electric shower" is "don't have an electric shower"? Seriously though, I'd guess nowadays electric showers outnumber standard showers at least 5 to 1 in the UK. I can't actually think of anyone I know who doesn't have one. They're not the death-traps you imagine.
Answer: yes, it can burn after long time. I do not see your setup, but I guess (and hope) that your connection block is in a sealed box, this sealant is aging and water can end up going in.
it could have been dangerous (fire hazard) if there were some flammable material around it. You could have got an electric shock while touching it when it happened but most likely you would have got a burn.
repairing should be safe (given that you put it off the grid while doing it), but take care of the wire gauge you are using and most importantly, investigate to understand what happened, if you just repair without knowing the cause, you might simply have it burn again later as you did not fix the real issue. and that time, you might be not so lucky.
Comment: Thank you. Sounds good advice. Yes it is all in a sealed box, and I can't see any moisture inside. Any advice on diagnosing the cause? I'm guessing it's a loose connection, but it's tricky to say which one now that it's all burned out and melted.
Comment: well, seeing only the burnt connection box, that is hard to help further as it can be virtually anything. The loose connection is a good explanation, I have no idea what you call an electric shower (in my country, they work with water :) ) maybe a malfunction as well generated an extreme current leading to heat generation at the weakest point of the circuit... all that is just guess work, if you really can not pinpoint the cause, seek for professional advice.
Comment: That's my own guess. Setscrews worked loose or weren't tightened properly in the first place, loose connection caused resistance/sparking/heat and made things worse, eventually heat got bad enough to melt the plastic and let the wire really disconnect which caused the big arc, blue flash, and "loss of magic smoke".
Comment: the comment from Tester101 below your question is also a good explanation (the heat cycles)
Comment: Hadn't realised "Electric Showers" weren't a universal concept. [Here's a little diagram I found](http://timwolverson.files.wordpress.com/2013/09/electric-shower-internal-parts.jpg?w=474&h=716), if you're interested. (Obviously they've got a case over the front when they're actually active.)
Answer: A Loose connection at the neutral pole/junction is many times the first suspect.
Unfortunately you will not notice this until the circuit breaker trips due to overheating because of the loose connections (or overrated amps flowing through it).
And its a definite fire hazard in waiting.  Consider yourself lucky if the Circuit breaker trips. Don't reset it immediately, just give a thought before as to why it happened (or call a qualified electrician).  If it keeps tripping, something is really wrong.
As a rule of thumb, if you have appliances using heavy amps (ACs, Induction Stoves, Ovens...you know what i am saying), its a good investment to periodically open your Main Switch Box and check for any signs of burns/chars at the circuit breaker joints. A visual inspection sometimes reveals any potential damage.
Avoid using heavy appliances all at once (unless you have a properly distributed electrical (2/3) phase connection. This is another reason why the circuit breaker would trip with a potential to cause fire.
Better safe than to be sorry.
There are many here who have answered to the point (tester101 gave a quick short and perfect explanation)
Answer: neutral cable is the return path for current, so when the heater is switched on it draws a lot of current and flows through the coil then to the neutral cable is the size of the cable is small definitely the cable will got burned
Comment: I seriously doubt this is a case of the neutral wire being undersized (that's a rather major factory defect if it were to be the case)


How to make rectangular and round corner panel like facebook

Question: I am very new in android and want to make a rectangular and round corner pan/view  in with a grey background without using facebook SDK. such pan is also used in many other mobile apps like linkedin.
Not able to post snapshot due to no reputation :(
thanks in advance.
Ajay
Comment: post a link to the image.
Answer: We can do that using background image
Code example :
   <FrameLayout
        android:id="@+id/layout_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="@dimen/d10"
        android:layout_marginLeft="@dimen/d20"
        android:layout_marginRight="@dimen/d20"
        android:layout_marginTop="@dimen/d10"
        android:background="@drawable/background_withoutgrid" >

        <RelativeLayout
            android:id="@+id/canvas_container"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="@null" >

            <ImageView
                android:id="@+id/canvosImageView"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </RelativeLayout>
    </FrameLayout>

It viewed as below
Comment: Dear Salem, I have tried this approach but unable to get the shape appearing above. Hope the image is not with me.
Answer: create shape.xml in drawable folder
like
shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
  <stroke android:width="2dp"
     android:color="#FFFFFF"/>
  <gradient
    android:angle="225"
    android:startColor="#DD2ECCFA"
    android:endColor="#DD000000"/>
<corners
    android:bottomLeftRadius="7dp"
    android:bottomRightRadius="7dp"
    android:topLeftRadius="7dp"
    android:topRightRadius="7dp" />
</shape>

and in myactivity.xml
you can use:
<Button
    android:id="@+id/btn_Shap"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Shape"
    android:background="@drawable/shape"/>

Comment: Thanks a lot. I am now able to make the shape as wanted using your suggestion.


add 2d object on 3d Model using sceneKit

Question: I am new to SceneKit and some issue on SceneKit, i need to add 2d objects on 3d model
Right now I already added 2d objects with skNode but that object is not moving with 3d model.
Like if I rotate or zoomIn and zoomout 3d model then that 2d objects also needs to move with the 3d object, when we add annotations on map
Here is link of 3d car model link with annotations,
I need to achieve this type of output

And I have done this type of code, but object not moving.
<code>   let rectangle = SKShapeNode(rect: CGRect(x: 0, y: 0, width: 20, height: 20), cornerRadius: 10)
    rectangle.position = CGPoint(x: 50, y: 56)
    rectangle.fillColor = #colorLiteral(red: 0.807843148708344, green: 0.0274509806185961, blue: 0.333333343267441, alpha: 1.0)
    rectangle.strokeColor = #colorLiteral(red: 0.439215689897537, green: 0.0117647061124444, blue: 0.192156866192818, alpha: 1.0)
    rectangle.lineWidth = 5
    rectangle.alpha = 0.4
    let labelNode = SKLabelNode(text: "Hello World")
    labelNode.fontSize = 20
    labelNode.fontName = "San Fransisco"
    labelNode.position = CGPoint(x:100,y:100)
    shipHud.addChild(rectangle)
    shipHud.addChild(labelNode)

    sceneView.overlaySKScene = shipHud// = shipHud

    shipHud.shipHudFlashAlert(alert: "Oh My God!")
</code>
Please please help
Comment: Create a node using `SCNBillboardConstraint` instead of an overlay. https://developer.apple.com/documentation/scenekit/scnbillboardconstraint
Comment: Your links don't work but you should post code and images 'inside' your question. Don't use links.
Comment: Okay I am editing question..
Answer: we can add node by SCNNode. its works for me.
<code>let cubeNode = SCNNode(geometry: SCNBox(width: 2, height: 2, length: 0.1, chamferRadius: 10))
cubeNode.position = SCNVector3(10, -2, -0.2) // SceneKit/AR coordinates are in meters
sceneView.scene?.rootNode.addChildNode(cubeNode)
</code>


How to load different menu based on current page in wordpress?

Question: I have inherited a site from a new client who has a wordpress site that was heavily hand-coded by their previous webdev. The current code (in the header.php file) is:
<code>//When page loads...
    $(".tab").hide(); //Hide all content
//Find URL location
var idToShow = location.pathname.split("/")[1];
//If URL location is one of these, then show its proper menu. If it isn't just show the home's menu.
if (idToShow == "unknown" || idToShow == "home" || idToShow == "parish" || idToShow == "formation" || idToShow == "school" || idToShow == "youth-ministry" || idToShow == "councils" || idToShow == "committees" || idToShow == "organizationsactivites" || idToShow == "contact") {
    $("#nav li."+idToShow).addClass("current").show(); //Activate first tab
    $("#"+idToShow).show();
}
else {
    $("#nav li.home").addClass("current").show(); //Activate first tab
    $("#home").show();
}
</code>
I am in the process of moving this site to a new host, and this works on the old host, but not the new host. I'm not sure where I could look for error logs (if there are any) or any other information that would help me solve this. Any ideas? Thanks!
Comment: errors in the console? is the slug/permalink settings the same?
Comment: Are you using the root url on both hosts? This line: var idToShow = location.pathname.split("/")[1] will break if your url structure changes due to the hardcoded 1.
Comment: Right now, we have the site on the new host running on an IP address. We have done search & replace on the database as well as on theme files to get everything working. @atmd I don't have access to the server console if that is what you are referencing.
Comment: no the console in dev tools
Comment: @atmd Ah, that makes more sense. There are no errors except for a MIME type error, but I assume it isn't relevant.
Answer: <code>$(function() {
//When page loads...
    $(".tab").hide(); //Hide all content
//Find URL location
var idToShow = location.pathname.split("/")[1];
//If URL location is one of these, then show its proper menu. If it isn't just show the home's menu.
if (idToShow == "unknown" || idToShow == "home" || idToShow == "parish" || idToShow == "formation" || idToShow == "school" || idToShow == "youth-ministry" || idToShow == "councils" || idToShow == "committees" || idToShow == "organizationsactivites" || idToShow == "contact") {
    $("#nav li."+idToShow).addClass("current").show(); //Activate first tab
    $("#"+idToShow).show();
}
else {
    $("#nav li.home").addClass("current").show(); //Activate first tab
    $("#home").show();
}
});
</code>
Hello, try this. This will solve your problem.


How can I find an R dataset with Factors & NA's

Question: I'm looking for a standard data set attached to an R package that I can use to test code.  I usually use iris or mtcars but they only have a single factor variable and no missing values.  Any suggestions for packages / data sets with multiple factor variables and NA's, or ways to search the included R datasets for specific criteria?
Comment: You can see all datasets in your installed packages by calling `data()`. A brief inspection suggests that `forcats::gss_cat` might be useful?
Comment: It might be more straightforward to use a package like wakefield or fakeR to generate simulated data with your desired characteristics.
Comment: The web is full of opensource datasets that might be helpful for you. Also look at Kaggle datasets
Answer: Here is a programatic way to search a package's datasets for your desired characteristics:
available_datasets <- data(package='datasets')[['results']][, 3];

meets_reqs <- function(datasets) {
    sapply(datasets, function(ds) {
        dat <- get(sub(" .*", "", ds))
        hasfactors <- "factor" %in% sapply(dat, class)
        nas <- anyNA(dat)
        hasfactors && nas
    })
}

res <- meets_reqs(available_datasets)

res[1:3]
# AirPassengers                BJsales BJsales.lead (BJsales)
#         FALSE                  FALSE                  FALSE

res[res]
# attenu
#   TRUE


locating and removing malware in a Rails app

Question: I am using Ubuntu 12.0.4 for my Rails app hosted on a VPS. I have followed the instructions for using IP tables to create a firewall, and also added fail2ban. However, within 24 hours of launch the site to the IP address (i.e. no domain) and giving it to about 5 test users, the site's already been infected by some php scripts. I found this in the logs..
<code>(No route matches [GET] "/admm/scripts/setup.php"):
Started GET "//mysqlmanager/scripts/setup.php"
</code>
Is there a recommended way to locate and remove the malware in a Rails app? My instinct is to destroy the server and restart from scratch but that's obviously not ideal as I assume it'll just happen again...
I'm afraid to rsync the app to my local machine as it might bring crap onto my local computer. I'm looking through individual files in the Rails app with nano but I can't see any of the actual malware. Should I be looking in a server directory rather than the Rails app itself?
Comment: How's the site running since the time of this post? Any malware issues? Curious about your experience.
Answer: This is not malware.
What you are seeing is an exploit scanner looking for security holes. It is a GET request coming from a remote machine and your Rails app is responding correctly with HTTP 404 for the URL.
Those requests will keep coming, there is nothing you can do about it.