Is there an on end event where I can free up drawable resources in android?

Question: In my android app, I use Imageview's to show images. But I want to properly free it up when the activity ends. I read somewhere you can use imgview.setImageDrawable(null); to free it up. But I would like to do this when the activity ends. Is there some function like on destroy or on end that I can override so I can free it up there?
Thanks
Comment: Yes, you can do this in `onDestroy()`. How useful is this? No clue. Keep in mind that `onDestroy()` may or may not be called.
Answer: Actually there is onDestroy in Activity, but you don't need to null Drawables like that unless you introduced a memory leak somewhere else in code.


Keeping up with the Joneses (or Bio.SEs)

Question: As is often lamented on A51 and the metas of science sites, the metric of graduation don't make much sense for science sites. Unfortunately, the current metrics make it hard to see how we are doing, so our best option is to look to an older site for guidance.
Our older cousin, Bio.SE, turned 250 days old today. We will turn 250 in exactly 5 weeks, on September 25th. A good way to make sure we are doing well, is to have the same (or similar) stats to Bio on this milestone. This is how they are doing:

For comparison, here are our stats at 215 days:

As you can see, we are a little behind and have some catching up to do. This is made even more important by the start of the school term (in the Northern Hemisphere at least) and the potential influx of new users we will encounter. Let's be in tip-top shape for that!
From what I can see, our biggest weakness is the number of visits per day. Let us work hard to increase this metric over the next few days. When you ask or answer a question, share it on twitter, G+, or reddit. When you see a good question or answer, do the same! What are some ways we can increase the number of visits?
The questions per day is also lacking, but we are capable of achieving similar numbers as we showed in June. Ask questions and share this site, both offline and on!
What are some other ways we can improve?
Comment: To be frank, bio appears more accepting of less rigorously researched questions. The kinda stuff I'd close if it's CogSci themed brother showed up on this site. I sincerely hope both sites fair well and attract a scientifically founded audience of experts, but I'm not sure we want to copy the apparent key to their success thus far.
Comment: @BenBrocka I am not proposing we relax our standards (in fact, I am usually a proponent of increasing them), but that we should advertise the content on this site more actively through social media.
Answer: Share good posts. Ideally to wide, relevant audiences, though I'm afraid I'm not aware of too many easily accessible social media sites related to the cognitive sciences.
There's two kinds of sharing; deep, personal sharing and broad, impersonal sharing. Hopefully if you know anyone that would be personally interested in the site, you'll give them a direct referral and explain what we're about. More generally however, the broad net is easier to cast and can pick up some good traffic.
There are the following Reddit sites related to our scope (feel free to add more relevant social media locations):

Psychology (63,385 readers)
Cognitive Science (53,095 readers)
Neuroscience (12,233 readers)
Neurophilosophy (8,035 readers)
Neruopsychology (5,882 readers)
Psychopharmacology (4,011 readers)
Behavioral Economics (3,661 readers)
Academic Psychology (3,354 readers)
Cognitive Linguistics (2,008 readers)
Mathematical Psychology (1,579 readers)

Follow etiquette when sharing (share relevant stuff politely, not too many links in too short a time). Try and engage users who comment on your links.
Speaking as Mod on The Workplace and User Experience I can say we've had a couple huge temporary spikes of traffic due to sharing on reddit/Hacker News. After these spikes there's much smaller, but permanent, traffic increases; after the initial wave of new visitors, a significant amount really did stick around. I'd suggest trying to catch a little of that attention and see how it works out. Moderation-wise it can be a bit of a challenge to keep up, but it's been quite manageable in my experience.
Comment: So the reddit promotion was more effective than expected. I was able to produce a [significant visitor spike](http://i.stack.imgur.com/N0Crq.png) with just a few shares.
Comment: There seems to be a whole list of [subreddits here](http://www.reddit.com/r/ScienceNetwork/comments/l8u2y/psychcogneuro/)
Comment: @ArtemKaznatcheev yeah, I noticed those, none of them seemed worth sharing all that much to though; most 10x smaller than the others, though perhaps more academic-level (I'm not very familiar with any)
Comment: we don't necessarily need the biggest threads, since it is easy to become just part of the noise there. In the smaller groups it might be easier to have our links noticed even if it is by fewer eyeballs. I tried some posts yesterday, [but only one](http://www.reddit.com/r/neurophilosophy/comments/ym20s/homunculus_fallacy_in_asking_where_is_the_visual/) generated any up-votes and that was on Neurophil.
Answer: We tried:

We Improved or maintained all of our stats, but the gain was not drastic enough to catch Bio.SE. This is what our traffic looked like (measured by quantcast):

The vertical line separates the last 35 days from the 35 before. The spikes are correlated to popular posts on reddit. I have learnt a few things while advertising there, and will try to make a separate post about that later. However, it seems that most of my shares on the most relevant subreddits did not go through :(.
Comment: Spikes aside, sure looks like a positive trend nonetheless! Nice work, and FWIW, enjoy the reminder of how far you all have come in the past 16 months :)


Is this piece of code correct?

Question: I compiled it on Linux with: g++ test.c -o test
I rewritten the original example.
Now made the first process to wait 2 seconds, (so that process2 could write on the shared memory), then I made process1 to read from that memory. Is this test correct?
Secondo question: where should I put:
shmdt(tests[0]); // or 1
shmctl(statesid, IPC_RMID, 0);

//Global scope
char *state[2];
//...
//...

struct teststruct {
  int stateid;
  teststruct *next;
  //other things
};

void write(teststruct &t, char* what)
{
  strcpy(state[t.next->stateid], what);
  printf("\n\nI am (%d), I wrote on: %d", t.stateid, t.next->stateid);
}

void read(teststruct &t)
{
  printf("\n\nI am (%d), I read: **%s**", t.stateid, state[t.stateid]);
}

int main() {

  key_t key;
  if ((key = ftok(".", 'a')) == -1) {
    perror("ftok");
    exit(1);
  }

   int statesid;
  if ((statesid = shmget(key, sizeof(char*)*50, 0600 | IPC_CREAT )) == -1) {
    perror("shmget error");
    exit(1);
  }

  state[0] = (char*)shmat(statesid, NULL, 0);
  state[1] = (char*)shmat(statesid, NULL, 0);

  teststruct tests[2];
  tests[0].stateid = 0;
  tests[0].next = &tests[1];
  tests[1].stateid = 1;
  tests[1].next = &tests[0];

  int t0, t1;
  switch (t0 = fork()) {
  case (0):
    sleep(2);
    read(tests[0]);

    exit(0);

  case (-1):
    printf("\nError!");
    exit(-1);

  default:
    wait();
  }

   switch (t1 = fork()) {
  case (0):
    write(tests[1], "1 write on 0 in theory.");

    exit(0);

  case (-1):
    printf("\nError!");
    exit(-1);

  default:
    wait();
  }

  return 0;
}

In particular I am asking if "state" is really shared between the two process, and If what I've done is a good way to do that.
My goal is to make char *state[2] shared (reading/modifying) between the two processes after fork.
Comment: I advise you to write a very simple piece of code first and play with it to get a good feel of what shared memory is about. Right now this program is full of pitfalls and will only work by chance (because forked processes usually inherit the same virtual mapping, but there is no guarantee that would still work on another operating system).
Comment: Ok, thanks. I just need it to work on Linux as "exercise" purpose.
Answer: You don't need to call shmat() twice.  You've only allocated enough space for two pointers, so you can't communicate much between the two processes.  And you can't rely on being able to copy a pointer to memory in the first process into shared memory and then have the second process read and use it. The address may be valid in the first process and not in the second; it may well point at completely different data in the second process (dynamic memory allocation in particular could screw this up).  You can only rely on the contents of the shared memory being the same in both processes.  You should allocate enough shared memory to hold the shared data.
However, with that said, the two processes should be sharing that small piece of shared memory, and in both processes, state[0] and state[1] will point at the shared memory and you should be able to communicate between the two by writing in the shared memory. Note that after forking, if either process changes the value stored in its state[0] or state[1], the other process will not see that change — the other process can only see what changes in the shared memory those pointers point to.
Of course, you've not set up any synchronization mechanism, so the access will likely be chaotic.

How can I modify my code just to make it works as intended (without considering synchronization issues)?

It isn't entirely clear how it is intended to work, which complicates answering the question.  However, if you want (for sake of example) the child process to write a word to the shared memory and the parent process to read the word from shared memory, then you allocate enough shared memory for the biggest word you're willing to process, then arrange for the child to copy a word from its per-process memory into the shared memory (and notify the parent that it has done so), and then the parent can copy or read the word from shared memory and compare it with data from its per-process memory.
Because you have a parent-child process which are forks of the same process, you will find that the two processes share a lot of the same memory addresses containing the same information.  This is, however, coincidental.  You can have unrelated processes connect to shared memory, and they need not have any addresses in common.  Thus, it would be trivial to get spurious results from your current setup.

Working Code
For some definitions of 'working', the following C++ code does.  The code is subtly C++; the code assumes struct teststruct declares type teststruct, and uses references as parameters.
Note that the (revised) code in the question has its wait() calls infelicitously placed.
shm2.cpp
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>

static char *state = 0;

struct teststruct
{
    int stateid;
    teststruct *next;
};

void sm_write(teststruct &t, char* /*what*/)
{
    //strcpy(state[t.next->stateid], what);
    printf("[%5d] I am (%d), I wrote on: %d\n", (int)getpid(), t.stateid, t.next->stateid);
}

void sm_read(teststruct &t)
{
    printf("[%5d] I am (%d), I read: **%s**\n", (int)getpid(), t.stateid, state);
}

int main(void)
{
    key_t key;
    if ((key = ftok(".", 'a')) == -1) {
        perror("ftok");
        exit(1);
    }

    int statesid;
    if ((statesid = shmget(key, sizeof(char)*512, 0600 | IPC_CREAT )) == -1) {
        perror("shmget error");
        exit(1);
    }

    if ((state = (char*)shmat(statesid, NULL, 0)) == 0)
    {
        perror("shmat");
        exit(1);
    }

    sprintf(state, "This is a string in shared memory %d", 919);

    teststruct tests[2];
    tests[0].stateid = 0;
    tests[0].next = &tests[1];
    tests[1].stateid = 0;
    tests[1].next = &tests[0];

    int t0, t1;
    if ((t0 = fork()) < 0)
    {
        perror("fork-1");
        exit(1);
    }
    else if (t0 == 0)
    {
            sm_read(tests[0]);
            printf("[%5d] sleeping\n", (int)getpid());
            sleep(2);
            printf("[%5d] waking\n", (int)getpid());
            sm_read(tests[0]);
            exit(0);
    }
    else if ((t1 = fork()) < 0)
    {
        perror("fork-2");
        exit(-1);
    }
    else if (t1 == 0)
    {
        printf("[%5d] sleeping\n", (int)getpid());
        sleep(1);
        printf("[%5d] waking\n", (int)getpid());
        strcpy(state, "1 write on 0 in theory.");
        sm_write(tests[1], state);
        exit(0);
    }

    int corpse;
    int status;
    while ((corpse = wait(&status)) > 0)
        printf("PID %5d died with status 0x%.4X\n", corpse, status);

    return 0;
}

Example run
[20440] sleeping
[20440] waking
[20440] I am (0), I wrote on: 0
[20439] I am (0), I read: **This is a string in shared memory 919**
[20439] sleeping
[20439] waking
[20439] I am (0), I read: **1 write on 0 in theory.**
PID 20440 died with status 0x0000
PID 20439 died with status 0x0000

Comment: Incidentally, calling a program `test` is usually a bad idea.  The shells have a built-in command called `test`, which can lead to confusion of all sorts.
Comment: (1) The `shmdt()` is optional for the child processes (they detach, of necessity, when they die).  In the parent, you could `shmdt()` before or after the `wait()` loop.  The `shmctl()` to destroy the shared memory segment should go after the `wait()` loop; you don't want to (or won't be able to?) destroy the shared memory before the children finish with it.  For self-consistency, I'd put both after the `wait()` loop, though that means the parent is hanging on to the shared memory when it is not going to use it.
Comment: How can I modify my code just to make it works as intended? (Without considering synchronization issues)
Comment: You wrote: "Note that after forking, if either process changes the value stored in its state[0] or state[1], the other process will not see that change", can you please post a small, simple, code snippet to show, instead, how to make this work? Especially in function "dosomething" I want that a process would be able to modify/read from the shared "state" array.
Comment: Thanks a lot, the last two questions, please: 1. Where should I put shmctl e shmdt? 2. If state would be an array of strings, could I do tests[0] = schmat, ecc?
Comment: (2) If `state` were made into an array of `char *`, then you could initialize those pointers to point into the shared memory. After forking, each child process could manipulate its own copy of those pointers, but that manipulation would not affect the `state` of the other child (or the parent — pun semi-intentional, semi-unavoidable). You'd have to define what you're seeking to do with the structures; I simplified them because I don't know why you needed them. (I'm not interested in the answer — it's a rhetorical question. But once you've defined what you need them to do, the design follows.)
Answer: You have a problem with the size of the shared memory. In:
 (statesid = shmget(key, sizeof(char*)*2, 0600 | IPC_CREAT )

you are just reserving space for 2 pointers to char. You need to allocate enough space for all your data, that based on the struct is kind of linked structure. The code could be something like the following, though the purpose of the fork() and shared memory is not very clear to me:
struct teststruct {
    int stateid;
    teststruct *next;
    //other things
};

void dosomething(teststruct &t){
    //forget about global space, you don't need it
}

int main() {

    key_t key;
    if ((key = ftok(".", 'a')) == -1) {
        perror("ftok");
        exit(1);
    }

    int statesid;
    int size_struct = sizeof(teststruct)*2; //assuming you will have only 1 level of linking
    if ((statesid = shmget(key, size_struct, 0600 | IPC_CREAT )) == -1) {
        perror("shmget error");
        exit(1);
    }

    //if you need to hold just one teststruct object data, you can do
    teststruct* p_test_struct = (teststruct*)shmat(statesid, NULL, 0);

    for (int i=0; i<2; i++){
        *p_test_struct = tests[i]; //this actually writes tests[i] into shared mem
        int t0, t1;
        switch (t0 = fork()) {
        case (0):
            dosomething(*p_test_struct);
            exit(0);
        case (-1):
            printf("\nError!");
            exit(-1);
        default:
            wait();
        }
    }

    return 0;
}

Comment: The purpose of fork is just to "play" with "char *state[2]", which needs to be correctly shared (reading/modifying) between the two processes after fork.
Answer: No, it does not. Because you are using fork (multiprocess) instead of threads (multithread). Memory zones are not shared into parent and child process. You will have the same value into it on the child but after that it will be independent to the another one.
Comment: Using shared memory via shmat *is* establishing communication between the processes.
Comment: You have to find a way to establish a communication between both processes. You have many option, sockets, file, DBs. In my opinion Redis es the best choise. But if you want to resolve it only with C, you can try with files. I dont know if it is the best option anyway.

Is this piece of code correct?


Opening Maps via intent the first time centers on user location, ignores geo:

Question: I've seen this example posted everywhere to open google maps centering on a specific point:
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", lat, lon);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);

However it seems to me at least in the newest maps version the very first time this is called it ignores this and and instead zooms to the users location.  Is this a bug?
Comment: This also happens for me... Using Android 4.2.2
Answer: I was able to solve this by calling the intent twice via an AsyncTask. I have no idea if this is the correct way to do it but it worked for me!
Here's my code:
@Override
public void onClick(View v) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            String uri = String.format(Locale.ENGLISH, "geo:0,0?q=%f,%f(%s)&z=40", lat, lon, square);
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
            mContext.startActivity(intent);
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            String uri = String.format(Locale.ENGLISH, "geo:0,0?q=%f,%f(%s)&z=40", lat, lon, square);
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
            mContext.startActivity(intent);
        }
    }.execute();
}

Answer: I realize I never answered this question.  This is eventually what I used and it seems to work OK.  The above answer may as well!
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                Uri.parse("http://maps.google.com/maps?q="+lat+","+lon);
startActivity(intent);

To do the same thing except to start Maps in driving mode, do this:
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                Uri.parse("http://maps.google.com/maps?daddr="+lat+","+lon);
startActivity(intent);


Every way to split a list in half in python without duplicates

Question: I have a list of unique items, such as this one:
myList = ['a','b','c','d','e','f','g','h','i','j']

I want to find every possible way to split this list in half. For example, this is one way:
A = ['g','b','j','d','e']
B = ['f','a','h','i','c']

The first thing I thought of was to find all the combinations of 5 items from the list, and make this be sub-list A, and then everything else would be sub-list B:
for combination in itertools.combinations(myList, 5):
    A = combination
    B = everything_else()

This however does not work, as I will get every result twice. For example, if one of the combinations is ['a','b','c','d','e'] then, from this loop, I will get:
A = ['a','b','c','d','e']
B = ['f','g','h','i','j']

But then later on, when the combination ['f','g','h','i','j'] comes up, I will also get:
A = ['f','g','h','i','j']
B = ['a','b','c','d','e']

For my purposes, two sets of combinations are the same, therefore I should only get this result once. How can I achieve this?
EDIT: And to clarify, I want every single possible way to split the list (without any element appearing in both A and B at the same time, of course).
Comment: So the lists would be random?
Comment: @U10-Forward I made my question a bit more clear, I need a method to generate every single possible way to do this split. The order does not matter, the elements are unique and should only appear in one of the two sub-lists. I should not get the same set of combinations twice (which is the part that is making this difficult for me).
Comment: My initial instinct was to throw both halves (A and B) into a set and then return a set of sets.
Comment: Does order matter?
Comment: @VasiliSyrakis Nope, hence why I used combinations and not permutations
Comment: What if you have an odd number of elements in list? How do you want to split then?
Comment: @Austin That would be the next step in this problem, which is defining the length of each list (for example, stating that A should have 6 and B should have 4 or A should have 15 and B should have 2). However I simplified it a bit in the question because this is the problem ive run into now. I guess assume an even number in the original list.
Comment: for even length you can set the counter and break the loop when the half of combination will be recieved
Answer: Liberal application of sets can solve this quite easily:
def split(items):
    items = frozenset(items)
    combinations = (frozenset(combination) for combination in itertools.combinations(items, len(items) // 2))
    return {frozenset((combination, items - combination)) for combination in combinations}

Which works as expected:
>>> split([1, 2, 3, 4])
{
    frozenset({frozenset({2, 4}), frozenset({1, 3})}),
    frozenset({frozenset({1, 4}), frozenset({2, 3})}),
    frozenset({frozenset({3, 4}), frozenset({1, 2})})
}

This follows your basic idea—we use the combinations of five from the original large set of items, and then get the other elements (which is easy enough with a set difference). We can then simplify down the duplicates by making the pairs sets as well, so the order doesn't matter and the two in any order are treated as equivalent. We then make the outer structure a set, which means the duplicates are removed.
The use of frozenset over set here is because mutable sets can't be members of other sets. We don't need any mutation here though, so that isn't a problem.
Obviously this isn't the most efficient possible solution, as we are still generating the duplicates, but it is probably the easiest and most foolproof way of implementing it.
This also leads pretty clearly into a simple upgrade for the later extension to the problem you give in the comments:
def split(items, first_length=None):
    items = frozenset(items)
    if first_length == None:
        first_length = len(items) // 2
    combinations = (frozenset(combination) for combination in itertools.combinations(items, first_length))
    return {frozenset((combination, items - combination)) for combination in combinations}

Comment: Isn't the problem to get the actual lists?
Comment: @RonaldAaronson If you want lists you can easily construct lists from the sets, but unless you need lists for some reason (which seems unlikely given the question specified that order doesn't matter), there isn't much point in doing so.
Answer: Your basic idea was sound, but as you noted you were getting duplicate splits. The obvious and simplest correction is to record every split you compute and check each new split computed against those already generated. Of course, the most efficient way to record and test splits is to keep them in a set:
import itertools

def split(myList):
    assert len(myList) % 2 == 0
    s = set(tuple(myList))
    seen = set()
    for combination in itertools.combinations(myList, len(myList) // 2):
        A = list(combination)
        A.sort()
        A = tuple(A)
        if A in seen: # saw this split already
            continue
        B = list(s - set(A))
        B.sort()
        B = tuple(B)
        if B in seen: # saw this split
            continue
        seen.add(A) # record that we have seen this split
        seen.add(B) # record that we have seen this split
        yield (A, B) # yield next split

for s in split(['a', 'b', 'c', 'd']):
    print(s)

Prints:
(('a', 'b'), ('c', 'd'))
(('a', 'c'), ('b', 'd'))
(('a', 'd'), ('b', 'c'))


Change image size with JavaScript

Question: I'm trying to change the size of an image with JavaScript. The jS file is separate from the HTML page.
I want to set the height and width of an image in the JS file. Any good ways on doing this?
Answer: Once you have a reference to your image, you can set its height and width like so:
var yourImg = document.getElementById('yourImgId');
if(yourImg && yourImg.style) {
    yourImg.style.height = '100px';
    yourImg.style.width = '200px';
}

In the html, it would look like this:

Comment: You have to make sure the javascript is executed after the page is finished loading.  You can either do this by putting it in an onload event, or putting the script at the bottom of your page, just before the closing body tag.
Comment: Is there any way to change the actual height `yourImage.height = 100` after the style change and not have the image cropped?
Comment: Sure, if you want to readjust only one dimension later on, and maintain the aspect ratio of the image, you can use `auto` for the value you're not explicitly setting (e.g. `yourImg.style.height = '500px'` and `yourImg.style.width = 'auto'`).  Here's a quick example I put together: http://codepen.io/patheard/pen/aEwfn
Comment: @Pat so we can put it in the onload event ;) <body  onload="MyFunction()"
Comment: @Pat In my opinion no need (if condition) a browser has 2 options (Supports Javascript / Not Supports) i think there is no option 3
Answer: You can change the actual width/height attributes like this:
var theImg = document.getElementById('theImgId');
theImg.height = 150;
theImg.width = 150;

Comment: Doesn't seem to work if the image's width and height were set via CSS
Answer: If you want to resize an image after it is loaded, you can attach to the onload event of the  tag. Note that it may not be supported in all browsers (Microsoft's reference claims it is part of the HTML 4.0 spec, but the HTML 4.0 spec doesn't list the onload event for ).
The code below is tested and working in: IE 6, 7 & 8, Firefox 2, 3 & 3.5, Opera 9 & 10, Safari 3 & 4 and Google Chrome:

Answer: Changing an image is easy, but how do you change it back to the original size after it has been changed? You may try this to change all images in a document back to the original size:

var i,L=document.images.length;
for(i=0;i<L;++i){
 document.images[i].style.height = 'auto'; //setting CSS value
 document.images[i].style.width = 'auto'; //setting CSS value
// document.images[i].height = ''; (don't need this, would be setting img.attribute)
// document.images[i].width = ''; (don't need this, would be setting img.attribute)
}
Answer: you can see the result here
In these simple block of code you can change the size of your image ,and make it bigger when the mouse enter over the image , and it will return to its original size when mouve leave.
html:

js file:
var b=0;
function fifo() {
       if(b==0){
            document.getElementById("f").width = "300";
           b=1;
          }
       else
          {
         document.getElementById("f").width = "100";
          b=0;
        }
   }

Answer: Direct manipulation
HTML tag declaration for image:

Handling html tag by direct access to object image:
const myImg = document.getElementById("my-img");

// Set a new width and height
myImg.style.width = "800px";
myImg.style.height = "450px";
// Or set a new width and height by attribute
// This option is not advisable because the attribute has a
// low priority over the style property.
myImg.setAttribute("width", 800);
myImg.setAttribute("height", 450);

Functions for manipulation
Using the updateImageSizeWithWidth or updateImageSizeWithHeight method below, you can increase or decrease any image without having to explicitly specify the exact width and height, you only need one value out of these two to update the image size.
/**
 * Update image size using width
 *
 * param {HTMLImageElement} img
 * param {number} newWidth
 */function updateImageSizeWithWidth(img, newWidth) {
  // Getting the width and height of the current image
  const oldWidth =  Number.parseFloat(getComputedStyle(img).width || img.getAttribute("width"));
  const oldHeight = Number.parseFloat(getComputedStyle(img).height || img.getAttribute("height"));
  // Getting proportional height with new width
  const newHeight = (newWidth * oldHeight)/oldWidth;
  // Setting dimensions in the image
  img.style.width = `${newWidth}px`;
  img.style.height = `${newHeight}px`;
}

/**
 * Update image size using height
 *
 * param {HTMLImageElement} img
 * param {number} newHeight
 */
function updateImageSizeWithHeight(img, newHeight) {
  // Getting the width and height of the current image
  const oldWidth =  Number.parseFloat(getComputedStyle(img).width || img.getAttribute("width"));
  const oldHeight = Number.parseFloat(getComputedStyle(img).height || img.getAttribute("height"));
  // Getting proportional height with new width
  const newWidth = (newHeight * oldWidth)/oldHeight;
  // Setting dimensions in the image
  img.style.width = `${newWidth}px`;
  img.style.height = `${newHeight}px`;
}

updateImageSizeWithWidth(myImg, 800);
// Or
updateImageSizeWithHeight(myImg, 450);

Answer: //  This one has print statement so you can see the result at every stage if     you would like.  They are not needed

function crop(image, width, height)
{
    image.width = width;
    image.height = height;
    //print ("in function", image, image.getWidth(), image.getHeight());
    return image;
}

var image = new SimpleImage("name of your image here");
//print ("original", image, image.getWidth(), image.getHeight());
//crop(image,200,300);
print ("final", image, image.getWidth(), image.getHeight());

Comment: Try describing what you're doing in your answers, instead of just pasting naked source code. It almost invariably helps the asker a lot more if you do.
Answer: You can do this:

.html file:

.js file:

document.getElementById("yourImgId").style.height = "heightpx";

The same you can do with the width.

Change image size with JavaScript


simple hook function not working

Question: This is a function that fires after the user submits a gravity form in wordpress. Ive talked to their support team, and have gone thru adding a custom log inside the function, and from the systems report, the can tell the action is firing fin, but not the log inside the function. and i cant seem to find what is wrong with it.
I've tried adding the action inside an mu plugin, I've tried uninstalling all plugins, even tried a fresh install with only the gravity form plugin, and my modifications to the functions file.
Its a pretty straight forward function:
<code>function survey_done( $entry, $form ) {
   $user_id = get_current_user_id();
   add_user_meta( $user_id, 'survey_complete', 'control' );
}
add_action( 'gform_after_submission_2', 'survey_done', 10, 2 );
</code>
Answer: If you are trying to insert the function you have shown then it might be due to the plugin loading first then gravity form plugin.
So, your hook will not be fired until the Gravity form plugin is loaded.
Comment: ive added the same exact code inside the function somewhere else and it works just fine.
Comment: the last option is for meta_value, doesnt just have to be true or false
Comment: anyways, i tested your code just in case, and it still didnt work. thanks for your help tho

simple hook function not working


Whats happening to my off shore money?

Question: I know some edicts cost you money from your Swiss Bank Account, but no matter what I do when I start a new level in a campaign (if I save and exit the game before hand) I end up with less money in my Swiss Account.   I know I'm loosing money as I've done plenty of the campaign and sandbox missions, and at various times peaked over half a mission, but I seem to keep dropping to around ~100K.
I am more than half way through the campaign so:

 I have completed the mission where you are forced out and have to get a new identity, so I guess you do drop money there (as it says you lose your fortune) but I wouldn't expect this to carry on.
Answer: No answer, it seems offshore fluctuates depending on the mission.

Whats happening to my off shore money?


How to install symform.deb?

Question: I've an updated Ubuntu 13.10 and I want to install the .deb from Symform (a cloud NAS service). But I'm having problems when I download the .deb and installing it from their website http://www.symform.com/download/.
Is there an apt-get for Symform in any repo?
Why is the .deb giving the following error when I sudo dkpg -i Symform.deb? It keeps on printing the certificate...
alvas@ubi:~/Downloads$ sudo dpkg -i Symform.deb
[sudo] password for alvas:
Selecting previously unselected package symform.
(Reading database ... 598899 files and directories currently installed.)
Unpacking symform (from Symform.deb) ...
Setting up symform (3.19.7-1) ...
Mono Certificate Manager - version 22.214.171.124
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 18.104.22.168
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 22.214.171.124
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 184.108.40.206
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 220.127.116.11
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 18.104.22.168
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 220.127.116.11
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 220.127.116.11
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 184.108.40.206
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 18.104.22.168
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 22.214.171.124
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 188.8.131.52
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 188.8.131.52
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 126.96.36.199
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 126.96.36.199
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 184.108.40.206
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 184.108.40.206
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 184.108.40.206
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 220.127.116.11
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 184.108.40.206
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 184.108.40.206
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 18.104.22.168
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 188.8.131.52
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 18.104.22.168
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 184.108.40.206
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 220.127.116.11
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 22.214.171.124
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

1 certificate(s) added to store Trust.
Mono Certificate Manager - version 188.8.131.52
Manage X.509 certificates and CRL from stores.
Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed.

^Cdpkg: error processing symform (--install):
 subprocess installed post-installation script was interrupted
Errors were encountered while processing:
 symform

Comment: I believe it's a problem with their package postinst script. Is a real pain to debug it. They should fix their stuff. You can try and check the output of `sh -x /var/lib/dpkg/info/symform.postinst configure` but I don't make promises. As I said before, this is a problem with their package, a bug more accurately, and should be fixed by them.
Answer: It appears that you entered ^C to exit the process.  It may work if you let it run for a while.  The "1 certificate(s) added..." blocks are normal for the Symform install and the result of adding certificates to the mono cert store one at a time.  This will take a little time as there are many of them.
Comment: There are changes in the pipeline to eliminate "one at a time" nature and speed up the install time drastically.  They will be available in an update in the near future.
Comment: yes, you were right =)

How to install symform.deb?


How to use python on webserver for web pages

Question: I have  read in the documentation that there are 4 or 5 ways in which i can python for web pages. Like

With CGI
Mod_python : mod_python does have some problems. Unlike the PHP interpreter, the Python interpreter uses caching when executing files, so changes to a file will require the web server to be restarted
FastCGI and SCGI
mod_wsgi

SO which way should i go . does it means that python is not for webistes if there are too many problems while using it
I have to build the live business website with thousands of users so i should not use it if that has many probelms
Answer: I believe mod_python is deprecated so you shouldn't use it.
see http://blog.dscpl.com.au/2010/05/modpython-project-soon-to-be-officially.html
mod_wsgi is mentioned as a replacement.
Comment: And 'http://blog.dscpl.com.au/2010/06/modpython-project-is-now-officially.html'. Is now officially dead.
Comment: I wish I knew of a suitable replacement.  mod_wsgi is great for dynamic web pages, but as far as I know, it can't hook apache handlers like mod_python can.
Comment: The mod_wsgi module can hook certain stuff in Apache, ie., host access control, authentication and authorisation providers. That covers most of what people actually want out of mod_python as far as hooking Apache.
Answer: I am a big fan of cherrypy.  Yes there are a lot of choices out there.
Comment: IS cherrypy different from Django
Comment: Yes it is, and both are full frameworks in their own right, though some people mix n match, running Django apps on top of a CherryPy WSGI server layer.
Answer: You could also use Google App Engine with Python and Django
Comment: sorry i could not fully understood , what google has to do with running Python websites.you mean i have to install it for making python websites
Comment: @Mirage: No, you do not have to. Google App Engine (GAE) is a product made by Google (the company), which you MAY choose to use for hosting Python web apps. It is one option among many.
Comment: So it mean i can host my python website using GAE and i don't need to install anything else on server. Can you explain more . That looks good
Comment: Yes, you install and run the code in Google's GAE servers. They provide all the hosting, database, storage, servers, etc.
Answer: Personally I use CGI or the Python *HTTPServer modules. CGI is very easy and seems a reasonable "unixy" approach. The *HTTPServer modules are minimal, and easy to extend if you're familiar with HTTP.
I've heard very good things about mod_wsgi, and hope to learn to use it sometime. My vote then is that you go with mod_wsgi, it's not even specific to just Python.
Answer: The important thing is that whatever you use to develop your Python web application, that it support the WSGI (http://www.wsgi.org) interface for hosting. So long as you do that, it can be hosted with any of options 1-4, albeit that CGI/WSGI bridge would only be used for small scripts and not large frameworks because of fact that new process has to be created for each request.
So, don't worry about the hosting mechanism as many exist and not just those above. Instead, start looking at the various framework and toolkits available. The most mainstream of these for Python is Django (http://www.djangoproject.com).
Comment: I am thinking of using PiP i.e  python in PHP , IF i use frameworks , can ibe able to use that. i mean call from python functions inside php
Comment: Yes you could, but I think you'd find that approach inconvenient and maybe slow. Give it a try, compare it to something like using Django natively from a template down through to data models, and see which you like better!
Answer: I think those problems are not strong enough to say Python is not for websites. And Python syntax is very clear and easy read. You should try Django for web development. It can reali speed up your development process.


Open a file and copy its contents into another file

Question: In this example, the contents of the style.css file are not being written to the output string. What am I doing wrong?
<code>$openFile = get_theme_root() . "/" . get_template() . "/myfile.css";
$customcss = fopen($openFile, 'w');
$customcss.=file_get_contents(get_bloginfo('template_directory')."/styles/test/style.css");
fwrite($openFile, $customcss);
fclose($openFile);
</code>
Comment: why not use file_put_contents instead of fopen, fwrite, fclose?
Comment: Why not just [`copy`](http://php.net/copy) the file?
Answer: I see the following error:
At the line 2, you put a resource in <code>$customcss</code> (according to the documentation). Then you tried to append a string to it (line 3) which is a non-sense. So, just change the var at line 2.
Comment: Thanks, I believe file_put_contents is what I'm looking for.


Auto Refresh a div in PHP and AJAX

Question: I'm stuck with my auto refresh function in my web course assignment. I always put my code like this :
navigation.php :

     .... ALL STYLE AND JS .....

          ...... ALL MY WEB MENU .......

index.php :
<?php
  include "navigation.php";
  function A(){
    global $variable_functionA;
    .... FUNCTION TO CALL API X BY cURL .....
  }
  function B(){
    global $variable_functionB;
    .... FUNCTION TO CALL API Y BY cURL .....
  }
?>

    ...... MY WEB CONTAINER ........

       <?php
           include "auto_refresh_data.php"; //Success when first load, failed to load style, js, etc at the second load
       ?>

<?php
  include "footer.php";
?>

footer.php :

 <scrpt>..... ALL MY JS SCRIPT.....</script>

My ajax code :

auto_refresh_data.php :

  <?php
   function A($variable1);
   function B($variable2);

  ... OPERATION FOR GLOBAL VARIBLE RESULT FROM function A and function B ....
  ?>

I want to make an auto refresh data in the middle of my container. Then I made it in ajax like this : How do i auto refresh my div class content? . It failed because of some php variable, style, js, function, etc placed before the auto refresh div element.
So the question is how to make it my data become auto refresh if my code design is like that?
Thankyou
Comment: None of what you posted here will help.  We need to see the `setInterval()` function in your JavaScript.
Comment: Show the _exact_ code that you're using instead of just linking to other questions and showing us placeholders.
Comment: Hi @JayBlanchard , I've edited for more details
Answer: I think there are a couple things you should be doing to fix this, but the main problem are your functions:
1) Move your functions somewhere else, like into their own files:
/functions.php
<?php
function A()
{
    global $variable_functionA;
    .... FUNCTION TO CALL API X BY cURL .....
}

function B()
{
    global $variable_functionB;
    .... FUNCTION TO CALL API Y BY cURL .....
}

2) Include the functions in the main file where it's used on load:
/index.php
<?php
include("functions.php");
include("navigation.php");
?>

    ...... MY WEB CONTAINER ........

       <?php include("auto_refresh_data.php") ?>

<?php include("footer.php") ?>

3) On the auto_refresh_data.php page, you need to include the functions again, but use include_once instead of include so you don't get a declaration error:
<?php include_once("functions.php") ?>

  <?php
  # Presumably you want to run these functions?
  A();
  B();

  ... OPERATION FOR GLOBAL VARIBLE RESULT FROM function A and function B ....
  ?>

4) Since you aren't really doing anything special with the ajax, I would just use .load():

Further to this, I would probably look at using setTimeout() recursively vs setInterval() just because if you get a delay in response, you may get those responses out of time. Using setTimeout will fire after the response is returned as opposed to every 5 seconds whether the response has come back yet or not.
Comment: if you want to share a value throughout your site then it makes sense to save this token into the session. That is easy to pull from the ajax
Comment: Hi @Rasclatt. I've tried your suggestion but it seems auto_refresh_data.php still failed to load some variable from another include files. For example, in navigation.php I set token variable based on session. But in auto_refresh_data.php can't read this token variable in second load, but run perfectly in the first load. The next question is how to pass variable between navigation.php, index.php, functions.php, etc? Thankyou

Auto Refresh a div in PHP and AJAX


Vent kitchen hood vent to roof turbine vent?

Question: I had a contractor install a hood vent.  He ran a foil pipe up towards the roof and tie it @ 6 in below the turbine vent (whirley birds).
Is this adequate for all the fumes to escape out?  Is this ok?
He told me to run it out through the roof it would cost more money.
Comment: It always costs more in the short term to do it right, but in the long term, you could have costly problems.  My house's clothes dryer vent goes partway into the attic, no where near a vent, so I get free flammable lint insulation nearby.
Comment: When you say "foil pipe" do you mean flexible metal duct, like with corrugations and can be expanded by pulling out?
Answer: TL;DR:

It is explicitly not to code to exhaust into the attic or to use foil pipe
It's a bad idea anyway because it puts smoke, grease and warm humid air into your attic which can cause mold growth

2015 International Residential Code, Chapter 15:

M1501.1 Outdoor discharge.
The air removed by every mechanical exhaust system shall be discharged to the
  outdoors in accordance with Section M1506.3. Air shall not be exhausted into an
  attic, soffit, ridge vent or crawl space.

Foil pipe is also not allowed:

M1503.2 Duct material.
  Ducts serving range hoods shall be constructed of galvanized steel, stainless
  steel or copper.

I'd also say aside from the material, foil pipes don't meed the requirement of having a "smooth interior surface":

SECTION M1503 RANGE HOODS
M1503.1 General.
Range hoods shall discharge to the outdoors through a duct. The duct serving the
  hood shall have a smooth interior surface, shall be air tight, shall be equipped
  with a back-draft damper and shall be independent of all other exhaust systems.
  Ducts serving range hoods shall not terminate in an attic or crawl space or
  areas inside the building.

Also note that range hoods are very explicitly not allowed to exhaust into an attic, though there is an exception for hoods that are specifically built to exhaust elsewhere:

M1503.1 Exception: Where installed in accordance with the manufacturer's
  instructions, and where mechanical or natural ventilation is otherwise
  provided, listed and labeled ductless range hoods shall not be
  required to discharge to the outdoors.

This of course can vary by jurisdiction (eg: your jurisdiction may follow a different version of IRC, have their own amendments, or not follow it at all), and the final call is up to the AHJ (Authority Having Jurisdiction, aka inspector). You can likely call your local building permits department to be sure.
Answer: I don't know where you live, but something to consider is that you're dumping warm, moist air into a potentially cold zone. So some of that air can/will condense in there in winter. Since attics tend to be filled with untreated wood, that means you're creating all the necessary conditions for mold to grow. That can potentially negatively affect your home air quality.
Code or not, I'd get it vented out of the roof.
Comment: Besides which,  a kitchen hood is venting smoke and grease, neither of which is something you want collecting in the attic or in the roof vent.


How can I get the values from this file?

Question: How can I grep the values from this file?
[myfile.file]
documentation            My Documentation
test                     testvalue
test for my var          123
test_var2                this is my second var
test_bool                false

For example I want to get the value "123" for the key "test for my var" or the value "this is my second var" for the key "test_var2. Between the keys and the values (in the file) are a lot of spaces. In my bash variable I just want to have the value without these spaces.
My current approach is not working.
#!/bin/bash
value=$(cat /tmp/myfile.file | grep '^test:' | awk '{print $2}')

Comment: Your approach is not working because you searched for a `:` which is not in the file.
Comment: What are your delimiters? Or is the file fixed width?
Comment: Use the delimiter (`\t` or a fixed (?) amount of spaces) Paul Hodges asked you to specify?
Comment: When I use '^test', I get all values back where the keys start with test.
Answer: You may use this awk that splits fields on 2+ whitespaces:
awk -v s='test for my var' -F '[[:blank:]]{2,}' '$1 == s {print $2}' file
123

awk -v s='test_var2' -F '[[:blank:]]{2,}' '$1 == s {print $2}' file
this is my second var

Comment: This works with gawk (GNU awk). My distro came with a different edition of awk. The same may apply to you.
Comment: There is nothing gnu specific. This worked on my mac (BSD) awk as well
Comment: Using the `{2,}` regex syntax in the FS did not work with `mawk` (Debian ships with it afaik now)
Comment: I don't have access to `mawk` but POSIX awk works fine with above pattern


How to format a number into decimal in php

Question: I have the below simple number, $total = 1060;, that i need to format as below using PHP

10.60

What i tried
$total = 1060;
number_format($total, 2)

But the result showing is 1,060.00 instead of the below 10.60
Plus I need it to be a dot . and not a comma , as the separator
Comment: From what I remember from the math classes in school, `1060` is 100 times bigger than `10.60`. [`number_format()`](http://php.net/manual/en/function.number-format.php) knows how to do it, if you provide it the correct value.
Answer: All you need to do is divide by 100 in before you format it. That makes it 10.6 (because the second decimal is zero, it's not needed and stripped away), and then you format it to have two decimal places.
$total = 1060;
number_format($total/100, 2); // 10.60

Live demo


Spring MVC Stack Overflow Error - trying to get data from database

Question: I have a form that inserts into a database however before I preform the insert I check if there are existing records. I am unable to insert the record and I am getting a StackOverflow Error.
Can someone tell me what causes this error and what I can do to get rid of it? If I remove the check hasRecords the code preforms fine. Its almost like the code doesn't want to access the database at this point. I have created different types of function to preform he check here for records but at this point I keep getting the same error StackOverflow
Code
com.crimetrack.service.MonitoringManager.getMonitoringStDate(MonitoringManager.java:60)
public String getMonitoringStDate(Integer crimeRecNo,
            Integer socialSecurityNumber) throws Exception {

        return this.getMonitoringStDate(crimeRecNo, socialSecurityNumber);
    }

DAO for getMonitoringStDate
public String getMonitoringStDate(Integer crimeRecNo, Integer socialSecurityNumber){

    //select the minimum start date in event there is several records although this will not be allowed
    String sql = "select IFNULL(min(monitoringStDate),'0') as monitoringStDate from tblmonitoring where crimeRecNo = ? and socialSecurityNumber = ?";

    String monitoringStDate = (String)getJdbcTemplate().queryForObject(sql, new Object[]{crimeRecNo,socialSecurityNumber}, String.class);

    return monitoringStDate;
}

I also have the following listeners registered:
Listeners
 <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>

     <listener>
         <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

Code
DAO
public boolean hasMonitoringRecord(Integer crimeRecNo, Integer socialSecurityNumber){

        //select a count of monitoring records there should be only one monitoring record
        String sql = "select count(*) as monitoringStDate from tblmonitoring where crimeRecNo = ? and socialSecurityNumber = ?";

        Integer count = (Integer)getJdbcTemplate().queryForObject(sql, new Object[]{crimeRecNo,socialSecurityNumber}, Integer.class);

        if(count > 0 ){

            return true;
        }else{
            return false;
        }
    }

Controller
if(result.hasErrors()){

    myMonitoringTypeList.put("monitoringTypeList",this.monitoringTypeManager.getListOfMonitoringType());
    model.addAttribute("icon", "ui-icon ui-icon-circle-close");
    model.addAttribute("results", "Error: Unable to Save Record!");
    model.addAttribute("monitoringType",myMonitoringTypeList);
    model.addAttribute("monitoring",monitoring);
    model.addAttribute("records", session.getAttribute("records"));
    model.addAttribute("crimeRecNo",session.getAttribute("crimeRecNo"));

    //return the user to the page they were on initially not the first page but the one with the error
    return new ModelAndView("monitoringList","page",session.getAttribute("page"));
}else{

    int crimeRecNo = monitoring.getCrimeRecNo();
    int socialSecurityNumber = monitoring.getSocialSecurityNumber();

        logger.info("No errors going to process records");
        logger.info("CrimeRecNo is " + monitoring.getCrimeRecNo());
        logger.info("SocialSecurity Number  is " + monitoring.getSocialSecurityNumber());
        //check if a record already exists. if one exist do an update else do an insert
        //to check if the record exists we can simply get the start date
        String dbMonitoringStDate = monitoringManager.getMonitoringStDate(crimeRecNo,socialSecurityNumber);

        logger.info("The dbMonitoringStDate is " + dbMonitoringStDate);

        if(monitoringManager.hasMonitoringRecord(crimeRecNo, socialSecurityNumber)){
            logger.info("Has monitoring record");
            //do an update

            monitoringManager.updateMonitoringRecord(monitoring);
            model.addAttribute("icon", "ui-icon ui-icon-circle-check");
            model.addAttribute("results", "Record Was Updated");
        }else {
            logger.info("Does not have monitoring record");
            //do an insert
            monitoringManager.saveMonitoringRecord(monitoring);
            model.addAttribute("icon", "ui-icon ui-icon-circle-check");
            model.addAttribute("results", "Record Was Saved");
        }

Error
7035 [http-bio-8084-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet  - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@6f138f45
7035 [http-bio-8084-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet  - Could not complete request
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.StackOverflowError
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:972)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.StackOverflowError
    at com.crimetrack.service.MonitoringManager.getMonitoringStDate(MonitoringManager.java:60)
    at com.crimetrack.service.MonitoringManager.getMonitoringStDate(MonitoringManager.java:60)
    at com.crimetrack.service.MonitoringManager.getMonitoringStDate(MonitoringManager.java:60)
    at com.crimetrack.service.MonitoringManager.getMonitoringStDate(MonitoringManager.java:60)
    at com.crimetrack.service.MonitoringManager.getMonitoringStDate(MonitoringManager.java:60)

Comment: Show us the relevant code. As the stack trace indicates, the error is in com.crimetrack.service.MonitoringManager.getMonitoringStDate(), at line 60.
Comment: @JBNizet question was updated
Answer: Look at your method definition:
public String getMonitoringStDate(Integer crimeRecNo,
                                  Integer socialSecurityNumber) throws Exception {
    return this.getMonitoringStDate(crimeRecNo, socialSecurityNumber);
}

The only thing this method does is calling itself. So obviously, you have an infinite recursion loop.


Problems making radial gradient in arcs using javascript, d3 with data from json file

Question: I'm using javascript and d3 (v6) and working towards making a sunburst type plot
or at least a plot with arcs at different radial distances where each arc has potentially its own gradient (a radial gradient from center to periphery). At this point I've followed some examples (e.g. here, here) where I set up a set of radialGradient elements and then use the ids from that to generate the fill in my actual arcs. But I am generating my arcs and gradients from data from a json file, and this makes it different from previous questions because the svg element generation is within the d3.json call (e.g. here).  I have two problems. (1) The gradient setups have lines like:
grads.append("stop")
        .attr("offset", "0%").style("stop-color", "white")
        .attr("offset", "100%").style("stop-color", "green");

but these don't seem to actually get added to the grads elements (when I look at the inspector in the webpage).
(2) The link to the arcs doesn't seem to work, although perhaps that is because of the first problem.
JAVASCRIPT (can be found here)
var width = window.innerWidth,
    height = window.innerHeight;

var body = d3.select('body')

// append svg to the DIV
chart = d3.select(".chart");

const svg = chart.append("svg:svg")
    .attr("width", width)
    .attr("height", height);

///////////////////////////////////////  Global variables controlling the arc appearance //////////////////
const arcMin = 30;
const arcWidth = 45.5;
const arcPad = 1;
///////////////////////////////////////////////////////////////////////////////////////////////

d3.json('dataExample.json')
    .then(function (data) {

        const grads = svg.append("defs").selectAll("radialGradient").data(data.sequences);
        grads.enter().append("radialGradient")
            .attr("gradientUnits", "objectBoundingBox")
            .attr("cx", 0)
            .attr("cy", 0)
            .attr("fr", (d, i) => arcMin + (d.pulse-1) * (arcWidth))
            .attr("r", (d, i) => arcMin + d.pulse * (arcWidth))
            .attr("id", function (d) {
                return "grad" + d.code;
            });
        grads.append("stop")
            .attr("offset", "0%").style("stop-color", "white")
            .attr("offset", "100%").style("stop-color", "green");//eventually this gradient will go between two colors that are functions of the data that is read in from the json file

        console.log(grads);

        var arc = svg.selectAll('path.arc-path')
            .data(data.sequences);
        arc.enter()
            .append('svg:path')
            .attr('d', d3.arc()
                .innerRadius((d, i) => arcMin + (d.pulse - 1) * (arcWidth) + arcPad)
                .outerRadius((d, i) => arcMin + d.pulse * (arcWidth))
                .startAngle(function (d, i) {
                    ang = (i * 30) * Math.PI / 180;
                    return ang;
                })
                .endAngle(function (d, i) {
                    ang = ((i + 1) * 30) * Math.PI / 180;
                    return ang;
                })
            )
            .attr("class", ".arc-path") // assigns a class for easier selecting
            .attr("transform", "translate(600,300)")
            //.style('fill',(d) => `rgb(${d.code * 10},${d.code*20},${255 -d.code * 7})`); this works - but doesn't use the gradients
            .style("fill", function (d) {return "url(#grad" + d.code + ")";})

    })

JSONFILE (called dataExample.json above) can be found here
{"type":"sequenceData","sequences":[{"pulse":1,"code":0},{"pulse":1,"code":1},{"pulse":1,"code":2},{"pulse":2,"code":3},{"pulse":2,"code":4},{"pulse":2,"code":5},{"pulse":2,"code":6},{"pulse":2,"code":7},{"pulse":2,"code":8},{"pulse":2,"code":9},{"pulse":2,"code":10},{"pulse":3,"code":12}]}

index.html (can be found here)
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Gradient arc test</title>
    </style>

And if there are other problems or bad coding practices you notice, please let me know since I'm new to this.
Thanks.
(edited)
Based on Ruben Helsloot's comment I made some jsfiddles with the various parts.  There are 4 fiddles. They differ in 2 aspects:  (1) how the json file is read in and (2) how the fill is generated. I'll note that for my final purpose I need to be able to read the json file from a file - either local or from a URL
(1) jsfiddle Version 1 Attempts to read json from a URL and attempts to use gradients for the fill. I think there is a problem reading from the url as well as a problem with the gradient filling.
(2) jsfiddle Version 2 Attempts to read json from a URL but does not use gradients for the fill.  This has problems with reading the URL.  When I do this on my local machine reading the json from a local file, this version does generate an output (although not gradients).
(3) jsfiddle Version 3 This puts the json in a local variable called data and then uses that.  It also tries to use the gradients for filling.
(4) jsfiddle Version 4 This puts the json in a local variable called data and then uses that. It does not use gradients for filling.  This is the only one of the 4 that gives the output on jsfiddle.
Comment: Please turn your code into a runnable [mre], it will help us see what's going on. YOu can host your JSON file on github or just store it as the variable `data` and remove the `d3.json` call
Comment: I edited the post with links to 4 jsfiddles with variants that show the problem.  There is a problem reading from the URL using d3.json.  Ultimately, I need to be able to read from a file or URL instead of having the data in the javascript file itself. I also posted the index.html, arcExample.js, and dataExample.json file at gitlab (links in the question) for local testing.
Answer: You should learn basic SVG 1.1 specification first and then how to add elements (not attributes) to the correct SVG structure.
Below is fixed code though I don't know exactly what gradient do you want to achieve. You can try to change the gradientUnits attribute back to objectBoundingBox but first experiment with the r attribute as well.

var width = window.innerWidth,
    height = window.innerHeight;

var body = d3.select('body')

// append svg to the DIV
chart = d3.select(".chart");

const svg = chart.append("svg:svg")
    .attr("width", width)
    .attr("height", height)
    .attr("xmlns", "http://www.w3.org/2000/svg")
    .attr("xmlns:xlink", "http://www.w3.org/1999/xlink");

///////////////////////////////////////  Global variables controlling the arc appearance //////////////////
const arcMin = 30;
const arcWidth = 45.5;
const arcPad = 1;
///////////////////////////////////////////////////////////////////////////////////////////////

var data = {"type":"sequenceData","sequences":[{"pulse":1,"code":0},{"pulse":1,"code":1},{"pulse":1,"code":2},{"pulse":2,"code":3},{"pulse":2,"code":4},{"pulse":2,"code":5},{"pulse":2,"code":6},{"pulse":2,"code":7},{"pulse":2,"code":8},{"pulse":2,"code":9},{"pulse":2,"code":10},{"pulse":3,"code":12}]};

        const grads = svg.append("defs").selectAll("radialGradient").data(data.sequences);
        gradsWrap = grads.enter().append("radialGradient")
            //.attr("gradientUnits", "objectBoundingBox")
            .attr("gradientUnits", "userSpaceOnUse")
            .attr("cx", 0)
            .attr("cy", 0)
            //.attr("fr", (d, i) => arcMin + (d.pulse-1) * (arcWidth))
            //.attr("r", (d, i) => arcMin + (d.pulse-1) * (arcWidth))
            .attr("fr", "0%")
            .attr("r", "25%")
            .attr("id", function (d) {
                return "grad" + d.code;
            })
        gradsWrap.append("stop")
            .attr("offset", "0%")
            .attr("stop-color", "white");
        gradsWrap.append("stop")
            .attr("offset", "100%").attr("stop-color", "green");//eventually this gradient will go between two colors that are functions of the data that is read in from the json file

        console.log(grads);

        var arc = svg.selectAll('path.arc-path')
            .data(data.sequences);
        arc.enter()
            .append('svg:path')
            .attr('d', d3.arc()
                .innerRadius((d, i) => arcMin + (d.pulse - 1) * (arcWidth) + arcPad)
                .outerRadius((d, i) => arcMin + d.pulse * (arcWidth))
                .startAngle(function (d, i) {
                    ang = (i * 30) * Math.PI / 180;
                    return ang;
                })
                .endAngle(function (d, i) {
                    ang = ((i + 1) * 30) * Math.PI / 180;
                    return ang;
                })
            )
            .attr("class", ".arc-path") // assigns a class for easier selecting
            .attr("transform", "translate(" + width/2 + "," + height/2 + ")")
            .attr('stroke', 'white')
            .style('stroke-width', '2px')
            .attr("fill", function (d) {
              //return "red";
              return "url(#grad" + d.code + ")";
            })

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <title>Gradient arc test</title>

Comment: Based on your code and the example I based my code on [here](https://stackoverflow.com/a/32566727), I also tried removing the semicolon after `const grads = svg.append("defs").selectAll("radialGradient").data(data.sequences)` and going straight into the `.enter().append("radialGradient")...` part instead of adding the additional gradsWrap variable and it worked as well. This clarifies a lot.
Comment: Sure, you just have to distinguish if you are adding the attributes or subelements to one SVG element. In the later case and often requiring several subelements the way to define a "wrapping" (variable) element is practical.


php RegEx extract values from string

Question: I am new to regular expressions and I am trying to extract some specific values from this string:

"Iban: EU4320000713864374\r\nSwift: DTEADCCC\r\nreg.no 2361 \r\naccount no. 1234531735"

Values that I am trying to extract:
EU4320000713864374

2361

This is what I am trying to do now:
preg_match('/[^Iban: ](?<iban>.*)[^\\r\\nreg.no ](?<regnr>.*)[^\\r\\n]/',$str,$matches);

All I am getting back is null or empty array. Any suggestions would be highly appreciated
Answer: The square brackets make no sense, you perhaps meant to anchor at the beginning of a line:
$result = preg_match(
    '/^Iban: (?<iban>.*)\R.*\R^reg.no (?<regnr>.*)/m'
    , $str, $matches
);

This requires to set the multi-line modifier (see m at the very end). I also replaced \r\n with \R so that this handles all kind of line-separator sequences easily.
Example: https://eval.in/47062
A slightly better variant then only captures non-whitespace values:
$result = preg_match(
    '/^Iban: (?<iban>\S*)\R.*\R^reg.no (?<regnr>\S*)/m'
    , $str, $matches
);

Example: https://eval.in/47069
Result then is (beautified):
Array
(
    [0]     => "Iban: EU4320000713864374
Swift: DTEADCCC
reg.no 2361"
    [iban]  => "EU4320000713864374"
    [1]     => "EU4320000713864374"
    [regnr] => "2361"
    [2]     => "2361"
)

Comment: @Pavel: See the update. And see my comment about the square brackets. I don't know why you put them there in the first place.
Comment: `preg_match` return `bool`, not **matches**
Comment: @Mpol: It returns `$result` as bool|int (false, 0, 1) *and* `$matches` as byref parameter.
Answer: preg_match("/Iban: (\\S+).*reg.no (\\S+)/s", $str, $matches);

There is a specific feature about newlines: dot (.) does not match newline character unless s flag is specified.

php RegEx extract values from string


use of the word "object"

Question: I have a nit-picky question about how the word "object" (as in "mathematical object") is generally used/understood. I'll ask by way of a simple, specific example.
Consider 1) the set of permutations of $n$ things, and 2) the set of bijective functions mapping $n$ things to $n$ things. If you separately explain 1) and 2) to someone with no prior knowledge, it's not immediately obvious that they are basically the same thing (otherwise I've chosen a bad example).
Would you say,

and 2) are two equivalent objects

and 2) are two different ways of looking at the same object

or,

both the above usages are ok, depending on what you want to emphasize?
Comment: What do you mean by permutations of $n$ things?
Comment: Presumably the three "$n$ things" can be three different (but fixed) objects?  Also, you should perhaps specify which of the (equivalent) definitions of "permutation" you are using.
Comment: Isomorphic objects in the category of groups. (Or equal objects, depending on your definition of permutation.)
Answer: Your question is pretty vague, but that's ok since you are merely looking for intuition. Some of the comments answer your question, but I will try to give some more details.
First of all if you talk about an object you want to be very precise what it is, then you should carefully define what you are talking about.
In you example you could define permutation as
1) A permutation is a bijection of a finite ordered set on itself, or
2) A permutation is a sequence containing each element of a finite ordered set once, and only once.
There are probably more definitions but for now these will suffice.
Now note that the first definition here just defines the first object you want to talk about as the second object you mention. So they are virtually the same.
If we take the second definition, then you can talk about this object without knowing your second object. But obviously the definitions are equivalent - or two different ways to look at the same object.
To be completely precise we have to specify what we mean by equivalent. In particular we need a world in which we can compare these objects. One way to do this is to understand both objects as groups. Then they are isomorphic as groups which usually as good as being equal for all that matters.
Edit: @celtschk's comment shows that the question is actually deeper. Above I am talking about finite ordered sets. If we work without this extra condition then the two objects aren't even isomorphic as groups. However if we understand these objects as categories, 1) as a category with one object and bijection as morphisms and 2) as a category with one object for each choice of an ordering, and the sequences and additionally a unique isomorphism between any two object as morphisms, then the two categories are equivalent.
Remark: Since I assume that this answer is maybe above the OP's head the moral answer is: Depnding on your definition these objects are either equal, equivalent or not even equivalent. To say what we mean by equivalent we have to fix a universe to work in, which might change whether they are equivalet or not.
Comment: Actually the two are only equivalent if you also have an order on your finite set. Or else, how do you determine if the sequence $[a,\alpha,\aleph]$ or the sequence $[a,\aleph,\alpha]$ is the identity permutation?
Comment: Thanks @celtschk, this comment revealed that the question is actually even deeper than I initially expected.

use of the word "object"


Can't install any packages on Ubuntu 16.04

Question: I have just bought a new digital ocean Ubuntu droplet and configured it as an Apache server but when I was installing phpmyadmin package my ssh session suddenly shut down and so the download and install was interrupted. Since then whenever I try to download anything using apt i get this error
The following packages have unmet dependencies:
 sendmail : Depends: sendmail-base but it is not going to be installed
            Depends: sendmail-bin but it is not going to be installed
            Depends: sendmail-cf but it is not going to be installed
            Depends: sensible-mda but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I tried to install aptitude to fix this problem but then i received this error
Package aptitude is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'aptitude' has no installation candidate

I tried all the commands of
apt-get update , apt-get upgrade
I would be glad to know how to solve this as I really need to install send mail
My question isn't like the others as it is asking about the version 16.04 of Ubuntu and i tried all the possible answers
Comment: This certainly sounds strange. Can you copy and paste the commands you've been typing to try to solve the problem, including the apt-gets?
Comment: apt-get update and apt-get upgrade and apt-get -f install and sudo apt-get update --fix-missing and dpkg --get-selections | grep hold
which gave no output and
Comment: it is added in the title as 16.04
Comment: I tried all the answers in the link supplied and they all failed to solve the problem
Comment: Are you able to rebuild the server? It's a little bit of an evolution of 'try switching it off and on again' but if there's nothing critical on there, this might be your quickest and most lasting fix option. Also, have you tried rebooting the server?
Answer: Just completely remove the the broken apache2 and reinstall.
sudo apt-get purge apach2* && sudo apt-get update && sudo apt-get install apache2
Comment: well actually i tried this and it broke my server as the problem isn't with Apache it got removed but when trying to install it back he says it has no installation candidate
Comment: If its apache you want to install, have you tried wget the dpkg from apache download and installing via dpkg?
Comment: Apache is not the target but after this answer i had to delete Apache and cant reinstall it
Comment: i tried using dpkg but it also fails
Comment: And the final one before i delete my answer. Have you restarted your server? have you tried installing some other package and it works?
Comment: and this ?? `sudo apt-get -f install`
Comment: i tried all of this and all of them failed
Comment: Do you mean you could not install any other applications as well?
Comment: yes and i even can't update anything


external java script file not working

Question: I'm doing a project for school and so far it's been a lot of copy this script and paste it here to make things "work".  I don't really have any idea what I'm doing besides comparing one line of code to another and looking for the differences.
I've got javascript that is returning some values to me and it works fine when it's in a simple webpage format but when I insert it into a more complicated page it stops working.
At the very end of the page it should give a line of numeric values and be updated every 1000 milliseconds but what happens is it just sits there displaying Temp()...
I've checked the data.xml and those values are being updated when I push buttons and stuff on my PIC protoboard.
I'm using the same ajax.js file for both the simple webpage and the complicated page.
I'm thinking it is something simple like a missed
 or
 tag but my eyes don't seem to see it.
Could some take a look at the code and see what I've missed?  Thanks!
ajax.js
        var xhr;

        function getXMLHttpRequest(){

        try { return new ActiveXObject("Msxm12.XMLHTTP"); } catch(e){};
        try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){};
        try { return new XMLHttpRequest(); } catch(e){};

        return null;
        }

        function parseHttpResponse(){

            if(xhr.readyState == 4){

                if(xhr.status == 200){

                document.getElementById("T0").innerHTML=xhr.responseText;
                }
                else
                {

                }
            }
        }

        function getTemp(){
        xhr = getXMLHttpRequest();

        xhr.open("GET", "data.xml", true);
        xhr.onreadystatechange = parseHttpResponse;
        xhr.send(null);
        }

        setInterval("getTemp()", 1000);

Simple webpage - this works great

        <title>Ajax test - index1</title>

Headline

Paragraph

Loading Temp0...

"Complicated" webpage - when this is used I get no joy
                <!DOCTYPE html>

            <title>Elex267-Webpage</title>

            <link rel="stylesheet" href="myStyle.css" type="text/css" >

Elex 267 Web Demo

            Microchip TCP/IP Stack v3.02

Home

Features

About

            Welcome to the Elex 267 Demo Web Server for [Name Here].

            This web page is being run on the NM101 NorthMicro Pic Prototype Board with the LCD/Keypad and Network modules.

            This web page refreshes the data every 3 seconds.

                Pot RA0:   1022

                Pot RA1:   223

                Switch RA2:

                LEDs:  RB6     RB5

            Commands

            <button align="left" type="button" onclick="alert ('RB5 Activated')">Toggle RB5</button>

            <button align="left" type="button" onclick="alert ('RB6 Activated')">Toggle RB6</button>

Loading Temp0...

Comment: "I'm thinking it's something simple like a missed /p or /div but my eyes don't seem to see it." That's why you better use a code editor like Netbeans or Eclipse. I suppose you are using notepad++ or something. And use a web debugger like Google inspector or Firebug. Your getTemp() is called twice, one from onload, one from setInterval could cause unexpected behavior
Comment: Don't know what your problem is but did you check the console for errors? Are you sure you ajax request was made, because this could be a problem of asynchronous loading.
Comment: It works fine if the simple webpage is being used. It just stops when the more complex page is loaded into my PIC.
Comment: put your getTemp() in a script tag at the end of your file (right before the ending body tag.

At expressed here http://stackoverflow.com/questions/10494620/when-does-a-body-onload-gets-called, the onload trigger your function after everything is loaded (image included). Maybe it does get trggerd, but at the wrong time.
Comment: as mentioned by Thanh Trung, there is great tools meant to be used. They are free too and open-sources as well.
Comment: @LouisLoudogTrottier The location of the getTemp() *declaration* is irrelevant; `onload` code will not be executed until the document has been loaded, so always after the declaration. The problem is the location of the getTemp() *call*.
Comment: onload will trigger after all dom elements are ready, img included, maybe he's just not waitng long enough for the pic to show up.... as the script tag at the end will trigger when readed... I've tested and i have an 600ms difference bewteen an ending script tag and my onload trigger (without img)
Comment: i agree that it might not be his issue here but it can help finding where (or WHEN) it breaks
Comment: @LouisLoudogTrottier `onload` code will be triggered after the document code has been parsed. Resources like images may be finished later. This is implementation-dependent. As for the time difference: Again, that is interesting but irrelevant. Whether you *declare* the function in the document head or in the body has no bearing on the availability of the function in `onload` code or in `load` event listeners in general. You must be confusing this with something else.
Comment: Quoted from: https://developer.mozilla.org/en-US/docs/DOM/window.onload
"The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

There are also Gecko-Specific DOM Events like DOMContentLoaded and DOMFrameContentLoaded (which can be handled using element.addEventListener()) which are fired after the DOM for the page has been constructed, but do not wait for other resources to finish loading." w3school don'T say the same thing tho... :S
Comment: @LouisLoudogTrottier There is more to Web development than quoting documentation, particularly a wiki like *Mozilla* Developer Network. AISB, it is implementation-dependent and has nothing to do with function declaration. Delete W3Schools from your bookmarks while you are at it.
Comment: W3Schools is crap?!  So THAT'S my problem...friggin' instructor is telling us to go there for the tutorials and muddle our way through things. Such a lame instructor.
Comment: sorry but i wans't trying to be a b. I just remembered seeing this article when i was having simlar issues.Stopped using onload with ajax since. and yes w3school is not a reliable sources.
Comment: I am afraid that while the intention of W3Schools may be good, there is too much misinformation there to be useful, particularly to beginners who necessarily cannot easily tell nonsense apart. IMHO, the amount of unlearning you would have to do is not worth it. (It is _not_ W3C.) You should start at MDN; but take everything in this field, particularly on the Web, with a handful of salt. Do not rely on what you read, test it yourself, in as many environments as possible (because implementations differ). I can also strongly recommend reading `comp.lang.javascript`; but it is not for the timid.
Answer: setInterval("getTemp()", 1000);

does not make sense at this line, and it might be the cause of your problems. This call causes getTemp to be called every second, starting from after this call as returned.  In the getTemp function you are reusing the xhr variable, creating a new XMLHttpRequest instance each time. That alone is not necessarily a problem (aside from the "Msxm12.XMLHTTP" which appears to be wrong; should probably be "Msxml2.XMLHTTP").
But in each call of getTemp you are issuing a new request, regardless if the previous request has received a response (the third argument being true means asynchronous request-response handling).  Consider this: The readystatechange listener might not have been called (or its readyState == 4 part has not be executed) because the client is waiting for the server to respond. Now your one-second timer kicks in, calls getTemp again and thus overwrites the xhr value that is to be used in the listener code.  There is a closure, xhr is a bound variable, and therefore there is a race condition already.
Further, an HTTP client SHOULD NOT (per RFC 2616), and a well-designed Web browser will not, keep more than a specified number of persistent HTTP connections (default: 2 to 8) open to the same server or proxy. So the more complex the document, and the more resources need to be loaded in parallel, the more likely that this approach will fail.
You should remove the setInterval(…) call and add a getTemp() call below the line where you update the innerHTML property (when the request was successful, status == 200), so that only then a new request is issued.  You should at least wait for the readyState to become 4 (FINISHED) before you issue a new request.  Since you want to wait one second before the next call, use window.setTimeout("getTemp()", 1000).
It should help your understanding if you pretty-print that code, that is, indent function body and block content with a reasonable amount of white-space, and add some white-space, for example between ) and {.  There are editors like Eclipse JavaScript Development Tools which can automate much of the code formatting.
Afterwards you should learn to use a debugger (use Firebug for Firefox, newer versions of other browsers have one built-in) and set breakpoints in your code, particulary in getTemp and parseHttpResponse. Step through the code (caveat: step over send(), then continue so that execution halts at the breakpoint in parseHttpResponse) to see what is going on. Good luck.
Comment: Do not pass a string to `setInterval` or `setTimeout`.
Comment: Why? We do not need another closure here, so I saw no good reason to complicate the original code for this beginner. I sincerely hope that was not the reason for the downvote.
Comment: Proper syntax is `setTimeout(getTemp, 1000);`.  How is that more complicated?
Comment: Utter nonsense. Have you read this in one of the many bad books on this topic? *Both* forms are possible (none of them is standardized, because the method itself is proprietary to date); the string argument is more compatible (although it is slightly slower). And `setTimeout(…, 1000)` is _not_ equivalent to `setTimeout("…", 1000)` in all cases. The string argument was in the original code, and it did no harm whatsoever. So I left it that way in my answer, avoiding further confusion.
Comment: For further reference, the most complete documentation on this method:  [window.setTimeout at MDN](https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout) (CAVEAT: It's a wiki.)
Comment: I took the time to read *your reference* on MDN. In the **Notes** of *your reference* under the title 'Passing string literals' it says what you have done is 'incorrect'.
Comment: That's why I pointed out that MDN is a *wiki*. It's of course *not incorrect* to pass a string (it says at the top that that is *not recommended*, and why). The example at MDN is bogus at best (I might fix that later). As you can read there, the rationale for not passing a string value is that it is slow as `eval()`. However, speed does not matter here (it would e.g. for an animation). And *again*, the *original code* already used strings, and actually there are cases when it is *better* to pass a string. But that is well beyond the scope of this question, so would you *please* give it a rest.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/19719/discussion-between-pointedears-and-shaun5)

external java script file not working


WebStorm show errors for relative paths with SCSS files

Question: WebStorm can't find the relative path in SCSS files in a React app and show the errors below.
The import is working, but WebStorm can't recognize the relative path and show these errors.
Application was created with cra and baseUrl: src was included in the tsconfig file. So everything is working, but the errors remain and autocomplete for the paths are not working.
Cannot resolve directory 'styles'
Cannot resolve file 'variaveis'
Cannot resolve directory 'assets'
Cannot resolve directory 'cardapio'
Cannot resolve file 'header.png'
Element 'padding-horizontal' is resolved only by name without use of explicit imports
Element 'padding-horizontal' is resolved only by name without use of explicit imports

Cardapio.module.scss
@import "styles/variaveis";

.menu {
  padding: 20px $padding-horizontal;
}

.header {
  background-image: url('/assets/cardapio/header.png');
  background-size: cover;
  background-repeat: no-repeat;
  height: 300px;
}

I expect WebStorm to recognize the relative path and make autocomplete work properly.
For now what I did was disable the inspection just to get rid of the messages.
Here's my tsconfig file and the errors.
tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": "src"
  },
  "include": [
    "src"
  ]
}

Is there some config to make in tsconfig, package.json or even in WebStorm?
Answer: baseurl ffrom tsconfig.json is not respected when resolving paths in SASS; related ticket: WEB-57018, feel free to upvote it to get notified on any progress.
As a workaround, I'd suggest marking the src folder as Resource root (Mark Directory As/Resource Root in folder right-click menu).


Python XML: 'TypeError: SubElement() argument 1 must be xml.etree.ElementTree.Element, not Element'

Question: I have a list of child elements from another part of the xml that I am trying to insert as shown here:
import xml.etree.ElementTree as et
import xml

defs_element = xml.etree.ElementTree.Element('ns0:defs')
for pc_def in pc_defs_list:
    et.SubElement(defs_element, 'path', pc_def.attrib)

But when I try I get this error:
TypeError: SubElement() argument 1 must be xml.etree.ElementTree.Element, not Element

Other methods produce similar must be an Element, not Element errors. How do I get this element that is not an element?
Comment: Slimming this down to something I can run, `e=et.Element('foo');et.SubElement(e, 'bar')` works. Can you post something that reproduces the problem?
Comment: Thank you for your patience. When I pull the code out and run it in a Jupyter cell, it works fine. Should I just delete this question?
Comment: That's a good question. If you can still reproduce this in your original environment, we'd have to figure out what's different. If you can get a minimal running program failing in one environment - plus a description of that environment - then its worth keeping. If its just not reproducable by anybody out here, its less useful.
Answer: There are two possible problems:

Does the problem go away if you remove the namespace ns0: prefix?  Creating a namespaced element in ElementTree is not as simple as just prefixing with the prefix.  See the top answers in Emitting namespace specifications with ElementTree in Python to show how namespace might work:

et.register_namespace('ns0',"http://ns0.namespaces.org")
defs_element = xml.etree.ElementTree.Element('{http://ns0.namespaces.org}:defs')

You're not explaining where pc_defs_list comes from.  Is it possibly loaded in another file?  ElementTree in its C version is very picky about the exact class that is being passed in.  So that if the elements come from a file loading the python version of ElementTree, you can't insert them in your ElementTree.  Even if they're both loading the C-version of ElementTree (cElementTree before Python 3.3), if they're not loading from the same binary file (one is inside the virtual environment, one is outside, for instance), then this message appears (formerly the even more cryptic argument 1 must be Element, not Element message).  This seems less likely to be the case here because you're creating a new SubElement rather than appending an existing element directly.

In a Django environment once, I even had problems with:
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element

root = Element('root')
hi = ET.Element('hi')
root.append(hi)

with a complaint that they were incompatible objects
Answer: Something like this works:
defs_xml_str = '<defs>'
for path_str in path_strs_list:
    defs_xml_str += path_str
defs_xml_str += '</defs>'
legend_1_xml.insert(0, et.fromstring(defs_xml_str))