When does C++ perform deep copying and shallow copying?

Question: I wonder when C++ does deep copying, and when it does shallow copying.
For example:
int find()
{
    int n=5;
    return n;
}

In order to delete n after moving out of the function, it must create a temporary variable n, and return it back to the caller. As a result, that's shallow copy, is that right?
Comment: For a single scalar value, what do you think the difference is between shallow and deep copying? How would it get any deeper? Also note, "delete" when it comes to function local, plain old data types is not a very useful concept; nothing is "deleted" typically, it's just left lying around as the stack is unwound, and the memory is probably reused in some later function call without being cleaned up in any meaningful way.
Comment: The "Shallow problem" happens with pointers; the address is copied but the content of the memory at that address is not copied. You have to manually copy it!
Comment: every copy is "shallow" unless you do something extra, in the sense that only the value is copied, but not anything that may be associated with it. Eg copying the pointer to the first element of an array does not copy the array. For your `int` there is absolutely no difference between shallow or deep copy
Comment: I've never heard of a language that does deep copies on its own.
Comment: @molbdnilo I really wanted to rock up and dazzle you with a counter-example, but I'm stumped!
Answer:
As a result, that's shallow copy, is that right?

A shallow copy keeps referring to whatever the original object† referred to. A deep copy refers to a copy of the referred resource†† (this new copy of the resource must be created by the copy constructor). That distinction is meaningful only if the copied object† is referential i.e. it refers to some resource.
int type does not refer to any object, so as far as the type system is concerned, it is not referential. However outside of the type system, one can give it referential meaning. It is quite typical for example, for an integer to represent identity of a resource such as an entity stored in a database. You need to consider whether that is the case for your integer. In object oriented design, such identifiers are typically wrapped into a class††† (which can be specified to support deep copies).
The copy of a non-class type is always shallow. Only copy constructor†††† can perform a deep copy. If 5 identifies some resource, then a copy of 5 also refers to that same resource.
Examples of referential types for which deep and shallow copy are relevant: References, pointers, classes which have referential members. Examples of usch classes: smart pointers, wrappers of referential identifiers†††. Of these, pointers and references are copied shallowly, since they aren't classes. Copy of a class instance may be shallow or deep, depending on the implementation of the copy constructor.
Then there is move construction. Move construction is a shallow copy, which modifies the original object in a way that enforces any class invariants that would be violated by a trivial shallow copy. For example, the move constructor of a unique pointer would shallowly copy the internal pointer, and set the original pointer to null, so that the uniqueness of pointer ownership is maintained.

† I say object for simplicity, but this applies to copies of a reference types - which are not objects - too.
†† A resource might be another object in memory, or for example a file descriptor, or a thread of execution.
††† Example: std::thread which wraps a lower level identifier provided by the OS.
†††† Any function can perform a deep copy, but a copy constructor is the only function that is invoked by copy initialisation.
Answer: The terms "shallow copy" and "deep copy" are generally understood to relate to types that themselves indirectly encapsulate some objects.
So, for example, a class with a pointer (that we assume points to something):
struct Foo
{
   Bar* ptr;
};

When you copy a Foo, is the Bar it points to copied as well (deep)? Or does the new Foo merely share the original pointer to the original Bar (shallow)?
This will depend upon how the copy is performed — usually your Foo will have a copy constructor, and it is the code in this copy constructor that makes the distinction.
For example, all standard C++ containers (e.g. vector) are internally made up of a bunch of pointers to some allocated buffers, but they have copy constructors that ensure the whole buffer is copied when the vector is copied, so that each vector has its own, independent buffer. This is a deep copy.
But the example I gave above, without any copy constructor or other lovely code, will simply perform a shallow copy when assigned, because I didn't tell it to do anything except to copy over the value of ptr.
As for your case: an int is just a value and so we can make no such comparison. You just have a value copy, plain and simple. The internal details of how many (if any) temporaries are required to implement that functionality are irrelevant (and unimportant); it's meaningless to talk about shallow vs deep copies in this case because there is literally no encapsulated, indirectly-held object owned or not-owned that can be deemed shallow or deep or anything copied. And we can generally say this about any non-class type.
Answer: int is not a referential type and so there is no question of shallow or deep copy. Its just a copy.
We can understand Deep and shallow copy as follows :
Deep Copy
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.
Shallow Copy
Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied, not the actual objects.
Comment: Mostly true, although saying that a shallow copy is "a bit-wise copy of an object" is not really (at least not necessarily) correct in C++. You can still have high-level copy semantics without deep copying all your members. In fact unless you're doing a `memcpy` (or `std::copy` over an aliased `char[]`) that's pretty much always the case.
Answer: Your description of the behaviour of your code is consistent with the source code that you present but the compiler might not do that.
C++ compilers are allowed to implement an as-if rule: i.e. your source specifies your intentions not the form of the final executable.
In other words, the compiler could replace your entire function call with 5.
In short, a deep copy creates duplicates every byte in your source object that's pertinent to that object. Any lesser copy than that is a shallow copy. Unless you overload = in some way, = takes a shallow copy.


Why does a GroupLayout not having a result as per requirement

Question: Here I want to add buttons as per 4-3-3 formation in football but i am getting 3-3-3. how can i put 4 buttons in one row??
I have been referral to this site: https://weblogs.java.net/blog/tpavek/archive/2006/02/getting_to_know_2.html
Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import static javax.swing.GroupLayout.Alignment.*;

class Abc extends JFrame
{
JButton b[];

Abc()
{
b=new JButton[11];
JPanel jp=new JPanel();
for(int i=0;i<b.length;i++)
{
b[i]=new JButton();
}
GroupLayout layout=new GroupLayout(jp);
jp.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);

layout.setHorizontalGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(LEADING)
.addComponent(b[0])
.addComponent(b[1])
    .addGroup(layout.createSequentialGroup())
    .addComponent(b[2])
    .addComponent(b[3]))
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(b[4])
.addComponent(b[5])
    .addGroup(layout.createSequentialGroup())
    .addComponent(b[6]))
.addComponent(b[7])
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(b[8])
.addComponent(b[9])
    .addGroup(layout.createSequentialGroup())
    .addComponent(b[10]))
);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(BASELINE)
.addComponent(b[0])
.addComponent(b[4])
.addComponent(b[8]))

.addGroup(layout.createParallelGroup(BASELINE)
.addComponent(b[1])
.addComponent(b[5])
.addComponent(b[9]))
.addGroup(layout.createParallelGroup(BASELINE)
.addComponent(b[2])
.addComponent(b[3])
.addComponent(b[6])
.addComponent(b[10]))

.addComponent(b[7])
);
setTitle("kuvh b");
setSize(1000,1000);
for(int i=0;i<11;i++)
{
add(b[i]);
}
add(jp);
pack();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel(
                                  "javax.swing.plaf.metal.MetalLookAndFeel");
                                //  "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                                //UIManager.getCrossPlatformLookAndFeelClassName());
                } catch (Exception ex) {
                    ex.printStackTrace();

           }
                new Abc().setVisible(true);
            }
        });
    }
}

I want to make a structure of 4-3-3 formation with this. Please help me
The code is resulting in 3-3-3 formation. there are 3 buttons on third row but i want 4 how can i do this please help
See the output:
[1]:

https://i.stack.imgur.com/1NnDz.jpg

i hope i will find my solution as far as possible
Comment: Your desired output is not clear.  You say you want "4-3-3 as in football", but I don't know what that means.  You don't say whether you want the 4 to be a row or a column, or on which end.  You say you are getting 3-3-3, but you actually have 10 buttons on the output.  You don't say what you've tried, or which buttons you want where.  Most of us don't want to just poke around hoping we accidentally land on the answer that you want, so look at your question from the standpoint of someone who does not already know what you're after, and describe it.
Comment: i want a output that consists of 4 rows and 3 columns
Comment: first row consists of 3 buttons Second row is same as first one and third row contains 4 buttons and at last 4th row contains one button in center
Comment: Ok, I was going to get further into this, but I've run out of time to spend on it now.  First figure out what you want your 4-button-row to look like -- are the first three buttons lined up with the three buttons on the first two rows, or do you want all four buttons spread out and centered on their own?  That will tell you whether to put the first three buttons of those rows in the same vertical groupings as the buttons in the first two rows.  Each grouping corresponds to either a vertical or horizontal row. Try posting a picture of what you want.
Comment: http://newsimg.bbc.co.uk/media/images/41705000/gif/_41705434_4_3_3_416.gif
Answer: I've found two ways to do something like you want; centering the buttons turns out to be something that Swing does not make as easy as it might, but then centering components is probably not as common as other alignments.
You can center components in a FlowLayout; the disadvantage in a FlowLayout is that, if the user shrinks the window to the point the components no longer fit, the layout wraps the components.  This is very useful for some things, but not for your football players.  I've wrapped my example in a scrollpane so this won't happen.
The other way to center components is with GroupLayout, but GroupLayout is not good for the overall layout you are trying to achieve.  GroupLayout is intended for use where you have overall rows and columns in which to line things up, and your four lines of football players are not lined up that way vertically, only horizontally.  But you can use the centering characteristic of GroupLayout to do the horizontal centering, and make a separate GroupLayout for each line.
My example uses FlowLayout for the first line, and GroupLayout for the second, just to show how it could be done.  I did not address the problem of the gap that appears between the players' lines when the window is made large enough.  Especially for examples, I do not use the style of tacking method invocations onto other method invocations and constructors; I think the deeply nested parentheses and non-straightforward logic of this style makes it more difficult to figure out (or keep track of) what's going on.
You can use GridBagLayout to center things, also, but I don't use it at all if anything else will do what I need.
I hope this answers your question.
package grouplayout;

import java.awt.FlowLayout;

import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Main2 extends JFrame
{
    public static void main(String ... arguments)
    {
        Main2 main2 = new Main2();
        main2.createUI();
        main2.setVisible(true);
    }

    public void createUI()
    {
        JPanel wingPanel = new JPanel();
        FlowLayout flowLayout = new FlowLayout();
        flowLayout.setHgap(35);
        wingPanel.setLayout(flowLayout);

        JButton btnone = new JButton("Lwing");
        JButton btntwo = new JButton("center");
        JButton btnthr = new JButton("Rwing");
        wingPanel.add(btnone);
        wingPanel.add(btntwo);
        wingPanel.add(btnthr);

        // -------------------------------------------

        JButton mid1 = new JButton("mid1");
        JButton mid2 = new JButton("mid2");
        JButton mid3 = new JButton("mid3");
        JButton mid4 = new JButton("mid4");
        JPanel midfieldPanel = new JPanel();
        GroupLayout groupLayout = new GroupLayout(midfieldPanel);

        GroupLayout.SequentialGroup horizontalGroup = groupLayout.createSequentialGroup();
        groupLayout.setHorizontalGroup(horizontalGroup);
        horizontalGroup.addComponent(mid1);
        horizontalGroup.addComponent(mid2);
        horizontalGroup.addComponent(mid3);
        horizontalGroup.addComponent(mid4);

        GroupLayout.SequentialGroup verticalGroup = groupLayout.createSequentialGroup();
        groupLayout.setVerticalGroup(verticalGroup);

        GroupLayout.ParallelGroup midButtonGroup = groupLayout.createParallelGroup(GroupLayout.Alignment.CENTER);
        midButtonGroup.addComponent(mid1);
        midButtonGroup.addComponent(mid2);
        midButtonGroup.addComponent(mid3);
        midButtonGroup.addComponent(mid4);

        verticalGroup.addGroup(midButtonGroup);

        JPanel teamPanel = new JPanel();
        BoxLayout boxLayout = new BoxLayout(teamPanel, BoxLayout.PAGE_AXIS);
        teamPanel.setLayout(boxLayout);

        teamPanel.add(wingPanel);
        teamPanel.add(midfieldPanel);

        JScrollPane scrollPane = new JScrollPane(teamPanel);
        getContentPane().add(scrollPane);

        pack();

    }
}

EDIT: as requested, the below does the same thing with only GroupLayout.
There is no interaction between the two groups, because GroupLayout aligns things in columns, and your players are not in columns.
And yes, I suppose it is difficult -- GroupLayout, as I understand it, was really intended for use by GUI builder tools, not really for building UIs by hand.  I personally have a supporter class or two that allows GroupLayout UIs to be built with slightly simpler logic.  But in any event, I think you need to understand the building blocks:
GroupLayout allows - and requires - that you place each component in both horizontal and vertical row/column position independently; this is useful since so many UIs require rows and columns of mixed components and variable extra components.
A sequential group of components in dimension X is arranged sequentially in dimension X; a parallel group in dimension X is also arranged sequentially, but perpendicular to dimension X.
The layout maintains preferred sizes of components; row width and column height are set at the maximum preferred size of the constituent components.
The overall GroupLayout object has one vertical and one horizontal grouping; within that, sequential and parallel groups are created to create the overall layout desired.
I know the examples in the tutorial(s) I've read do not create separate variables to hold the internal sequential and parallel groups, preferring to use forms like new X().addComponent().addGroup() etc.  But I think that makes it harder to understand what the code is actually doing, not easier; and the nested parentheses become their own maintenance problem.  So I think this is a better way to do things, especially for those just getting started with this layout.
package grouplayout;

import java.awt.FlowLayout;

import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Main3 extends JFrame
{
    public static void main(String ... arguments)
    {
        Main3 main2 = new Main3();
        main2.createUI();
        main2.setVisible(true);
    }

    public void createUI()
    {
        JButton btnone = new JButton("Lwing");
        JButton btntwo = new JButton("center");
        JButton btnthr = new JButton("Rwing");

        JPanel wingPanel = new JPanel();
        GroupLayout wingGroupLayout = new GroupLayout(wingPanel);

        GroupLayout.SequentialGroup wingHorizontalGroup = wingGroupLayout.createSequentialGroup();
        wingGroupLayout.setHorizontalGroup(wingHorizontalGroup);
        wingHorizontalGroup.addComponent(btnone);
        wingHorizontalGroup.addComponent(btntwo);
        wingHorizontalGroup.addComponent(btnthr);

        GroupLayout.SequentialGroup wingVerticalGroup = wingGroupLayout.createSequentialGroup();
        wingGroupLayout.setVerticalGroup(wingVerticalGroup);

        GroupLayout.ParallelGroup wingButtonGroup = wingGroupLayout.createParallelGroup();
        wingButtonGroup.addComponent(btnone);
        wingButtonGroup.addComponent(btntwo);
        wingButtonGroup.addComponent(btnthr);

        wingVerticalGroup.addGroup(wingButtonGroup);

        // -------------------------------------------

        JButton mid1 = new JButton("mid1");
        JButton mid2 = new JButton("mid2");
        JButton mid3 = new JButton("mid3");
        JButton mid4 = new JButton("mid4");
        JPanel midfieldPanel = new JPanel();
        GroupLayout groupLayout = new GroupLayout(midfieldPanel);

        GroupLayout.SequentialGroup horizontalGroup = groupLayout.createSequentialGroup();
        groupLayout.setHorizontalGroup(horizontalGroup);
        horizontalGroup.addComponent(mid1);
        horizontalGroup.addComponent(mid2);
        horizontalGroup.addComponent(mid3);
        horizontalGroup.addComponent(mid4);

        GroupLayout.SequentialGroup verticalGroup = groupLayout.createSequentialGroup();
        groupLayout.setVerticalGroup(verticalGroup);

        GroupLayout.ParallelGroup midButtonGroup = groupLayout.createParallelGroup(GroupLayout.Alignment.CENTER);
        midButtonGroup.addComponent(mid1);
        midButtonGroup.addComponent(mid2);
        midButtonGroup.addComponent(mid3);
        midButtonGroup.addComponent(mid4);

        verticalGroup.addGroup(midButtonGroup);

        JPanel teamPanel = new JPanel();
        BoxLayout boxLayout = new BoxLayout(teamPanel, BoxLayout.PAGE_AXIS);
        teamPanel.setLayout(boxLayout);

        teamPanel.add(wingPanel);
        teamPanel.add(midfieldPanel);

        JScrollPane scrollPane = new JScrollPane(teamPanel);
        getContentPane().add(scrollPane);

        pack();

    }
}

Comment: Its little bit difficult for me. Although it seems like its fine. Can you give me the same result with only GroupLayout.
Comment: I am not as good as you are in java. Sir, please give me a easy method to solve my problem
Comment: is there any solution by which i could merge different layouts and gets the required result???
Comment: I think I've done enough programming for you. There may be a simpler way of doing this, but I don't know of one offhand.  If this is beyond your current programming capabilities, the answer is not necessarily easier programming.  A standard layout manager may not be the right tool for your job; their purpose is easier creation of standard UIs -- windows and dialogs with buttons, text fields, drop-downs, etc. --  and it appears you don't have that. Also be aware that SO is great at providing answers to specific technical questions, but that you seem to be expecting something else.


v1 deg out = zero?

Question: My Attempt
Yes it is true. There is one directed edge between two vertices and you can see that there is one vertex that the out-degree is zero. If you want to fix that, you can add a vertex and a directed edge between the new and old vertex that have out-degree zero. But if you keep repeating this, you running into the same problem.
The other option is to connect the vertex with outdegree zero to an existing vertex. But if you do that then u can create a directed cycle.
Answer: Suppose all vertices have outdegree greater than zero. Let $v_{1}$
be an arbitrary vertex. By the assumption, it follows that we can
find $v_{2}$ such that $v_{1}\rightarrow v_{2}$. Continue this process
to obtain a path of the form $v_{1}\rightarrow v_{2}\rightarrow\cdots$.
Since the number of vertices are finite, it follows by the pigeon
hole principle that $v_{i}=v_{j}$ for some $i\neq j$, and hence
we have a cycle.

v1 deg out = zero?


script skipping user input in nested case statement

Question: I am trying to create a nested case statement in which user input is expected (Y/N). However, the system never waits for the input and always goes to the third option, "Please answer yes or no". Can anyone tell me what I am missing?
Here is the case statement
#!/bin/bash
STATUS=status

find /etc/init.d/* -name '*' -print0 | while IFS= read -r -d '' FILE;
do
if [ "$FILE" != "." -o "$FILE" != ".." ]; then
OUTPUT=$($FILE $STATUS)
case "$OUTPUT" in
    *disabled* )
        echo "Do you wish to start $FILE ?"
        read  yn
        case $yn in
         [yY] | [yY][Ee][Ss] )
                $FILE start
                ;;
         [nN] | [n|N][O|o] )
                ;;
        * )
        echo "Please answer yes or no.";;
        esac
        ;;
       * )
        echo "App $FILE is running"
;;
esac
fi
done

Running under Ubuntu 14.04 LTS
Sample output
App /etc/init.d/reboot is running
App /etc/init.d/resolvconf is running
App /etc/init.d/rsync is running
App /etc/init.d/rsyslog is running
App /etc/init.d/samba is running
App /etc/init.d/samba-ad-dc is running
Do you wish to start /etc/init.d/saned ?
Please answer yes or no.

Comment: I am trying with certain ubuntu init scripts. updating the full  script
Comment: It's still a generic programming question. The fact that you're using it for Ubuntu init scripts doesn't make it an Ubuntu-related question. Please post it on [StackOverflow](http://stackoverflow.com/), as it's off-topic to this site.
Answer: You're piping find output to the while loop. The inner read command is reading a line from find's output, not from stdin.
You can restructure like this: send the find output to the while loop on a different file descriptor. This leaves stdin free for the inner read.
while IFS= read -u3 -r -d '' FILE; do
    if [ "$FILE" != "." -o "$FILE" != ".." ]; then
        OUTPUT=$($FILE $STATUS)
        case "$OUTPUT" in
            *disabled* )
                read -p "Do you wish to start $FILE ?" yn
                case $yn in
                    [yY] | [yY][Ee][Ss] ) $FILE start ;;
                    [nN] | [nN][Oo] ) ;;
                    * ) echo "Please answer yes or no.";;
                esac
                ;;
            * ) echo "App $FILE is running" ;;
        esac
    fi
done  3< <(find /etc/init.d/* -name '*' -print0)

This uses a process substitution, instead of a pipe, to read from find
Answer: The context this time provides the answer. You are piping the output of find into the entire while loop, and that includes your inner read as well... meaning, your "read yn" will also read from the very same output that "find" provides, as opposed to from your keyboard.
I also dislike your general handling of looping over files. A simple:
for file in /etc/init.d/*; do
   echo Processing $file
done

usually works well nowadays, even for larger amounts of files.
If you really must use find, you could perhaps wrap your handler inside another script, and call it for each file with:
find /etc/init.d -type f -perm +111 -exec myhandlerscript.sh {} \;

This will find all files with executable permissions, and call myhandlerscript.sh for each one with the name as argument. Inside the script, the file name will appear inside the $1 special variable.
If it really must be in the same file, wrap the code inside a function, export it with "export -f myfunction", and use "-exec bash -c 'myfunction "$0"' {} \;" as a parameter to find.
Answer: Your usage of the "read" command doesn't seem to be quite right.
read -p "Do you wish to input data ?" yn

The -p switch expects a string right next to it, which will be used as the Prompt. Thus it thought that "yn" was something to display, rather than the variable to store the answer in.
Comment: With this, there would be no need for the `echo -n "Do you wish to input data ?"` otherwise it would show that twice. An alternative would be just to have `read yn` without the `-p` option that is causing the problem.
Comment: @Wilf , I tried both,somehow both doesnot work. Its always jumping the input. Updated with the full script I am trying to create.
Comment: Does it skip the echo as well, or just the read? Does it ever even enter the "disabled" case branch?
Comment: @Whyte: Yes it does. The output I get is: `App /etc/init.d/reboot is running
App /etc/init.d/resolvconf is running
App /etc/init.d/rsync is running
App /etc/init.d/rsyslog is running
App /etc/init.d/samba is running
App /etc/init.d/samba-ad-dc is running
Do you wish to start /etc/init.d/saned ?
Please answer yes or no.
`


Mandrill Issue Setup

Question: When I do the sudo tar --strip-components 1 -C /usr/local/Mandrill -zxf Mandrill.tar.gz command I get an error of
tar: components; invalid number of elements.
I am not sure what I did wrong I verified all my directories any ideas?
Answer: You just need a = symbol after the --strip-components option, so your command would be:
sudo tar --strip-components=1 -C /usr/local/Mandrill -zxf Mandrill.tar.gz

The man page gives the clue in the description of the --strip-components option:

--strip-components=NUMBER
            strip NUMBER leading components from file names on extraction

You can use the man tar command to read the manual for the tar command.
Comment: So now I am getting the following error:

`tar(child): Mandrill.tar.gz: Cannot open No such file or directory`
`tar(child): Error is not recoverable: exiting now`
`tar: Child returned status 2`
`tar: Error is not recoverable: exiting now`

This makes not sense because all the directories exist I double checked them.
Comment: Here is my workflow:
`git clone https://github.com/wollardj/Mandrill.git`

`cd Mandrill`
`git checkout tags/`git tag -l | tail -n 1``

`sudo mrt bundle Mandrill.tar.gz `# updated from wiki

`sudo mkdir /usr/local/Mandrill`
`sudo tar --strip-components 1 -C /usr/local/Mandrill -zxf Mandrill.tar.gz`

Mandrill Issue Setup


response.sendRedirect() does not running - Servlet

Question: When run the below code and the output I receive is "in", but the response .sendRedirect() does not run. The two  java servlet files "Class1" and "Servlet1" are in the same folder.
public class Class1 extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws IOException, ServletException {

       response.setContentType("text/html; charset=ISO-8859-7");
       PrintWriter out = new PrintWriter(response.getWriter(), true);

       ArrayList list2 = (ArrayList)request.getAttribute("list_lo");

       if (list2 == null || list2.isEmpty() ) {
          out.println("in");
          response.sendRedirect("Servlet1");
          return;}
       }

}

Comment: You cannot send redirect once you start returning any output. I'm not sure if merely getting the writer through response.getWriter() counts, try putting the redirect logic at the very beginning of the method (that is a good thing to do anyways). And remove the `out.println("in");` as this will mean printing output for sure and thus prevent you from doing the redirect.
Comment: I think you have missed configuring the web.xml file for url mapping
Comment: Could you kindly post your `web.xml` excerpt where you have configured this?
Comment: Yes, I have configured the web.xml
Comment: @Jiri Tousek thank you. The println was the problem.
Comment: @JiriTousek      it's not correct! You can do it, you have to make sure that you set the status code correctly too. I have this working on my system all the time, no problems.....the OPs issue is not this...
Comment: @nancy I've made it a full answer.
Comment: @ha9u63ar if we're talking about classic redirect using 302 header, it cannot be used after response body is started - see my answer for reason behind this. The only possible way it might work for you I can think of is that your started response is still in some buffer and wasn't actually sent to the client - don't rely on this!
Answer: You cannot send redirect once you start returning any output.
You need to put the logic handling any possible redirects before any output is started (e.g. out.println() in your example). Putting the redirect logic at the very beginning of the method is a sensible thing to do anyways, since it should be the first thing you decide.
The reason why redirecting after output is started lies in the HTTP protocol itself - redirect is transmitted using response headers, which are separated from response body by a blank line. Once you start writing the response body, there's no way to transmit any more headers anymore (apart from the started output being still in buffer if you're lucky).
Answer: Try to put the name of the file with the extension instead of the class name, sometimes happened to me, and just by doing this worked


Composition of permutations left to right or right to left?

Question: I'm a bit confused about permutation groups. I was reviewing for a test and a problem we had was, let τ,o both be in S3. And o(1)=1 and τ(i)=1. Show that if
γ ∈ τo$τ^{-1}$ then γ(i) = i.
I started off from right to left, i.e first I evaluated $τ^{-1}$(i) and then took o($τ^{-1}$(i)) and so on. I got the question wrong, and looking at the solutions it makes more sense to go from left to right, i.e to first evaluate τ(i) and then o(1) and so on.
But I thought when you compose permutations you go from left to right? So if you had, A, B as permutations in cycle notation with A=(1,2,3) and B= (1,2) And you took AB wouldn't you first evaluate it as, 1 goes to 2 under B then 2 goes to 3 under A, thus we would have AB=(1,3) with 2 going to itself? When do you evaluate from right to left and vice versa?
Answer: Unfortunately, both conventions are in use: some people evaluate from left to right, some from right to left. You simply have to know which convention is in use. In the exam problem you can actually infer the convention from the question. You need to evaluate $\gamma(i)$; depending on which convention is in force, this means evaluating either $\tau(i)$ first or $\tau^{-1}(i)$ first. The information given in the problem doesn't tell you what $\tau^{-1}(i)$ is, but it does tell you that $\tau(i)=1$. Thus, you can be pretty sure that the convention in force here is left-to-right composition: perform $\tau$ first, then $o$, and finally $\tau^{-1}$. And of course when you do, everything works out just right: $\tau(i)=1$, $o(1)=1$, and then $\tau^{-1}(1)=i$, so $\gamma(i)=i$.
(By the way, you seem to be reversing left and right: in your $AB$ example you're actually doing right-to-left evaluation, since you're applying $B$ first.)


Ruby - Downcase on string values in a hash that also contains nil values

Question: Currently attempting to adjust all the string values of a hash to lowercase. This hash contains multiple value types (nil, string, integer) so running across the entire hash with downcase spits out an error due to the nil values in the hash.
NoMethodError: undefined method "downcase!" for nil:NilClass

I'm pretty brand new to Ruby and I wasn't sure how best to run through this hash and skip the nil or integer values. I've attempted to use .map to convert every value to string and then downcase the values, but I'm either not seeing any difference in the end result or I get an error.
testHash = testHash.map(&:to_s)
testHash.map(&:downcase!)
(I've also attempted testHash.each {|k,v| v.downcase!}

I'm sure most of this is me just not knowing how to write this out in Ruby correctly. Please let me know if you need additional info and thank you.
Answer: Check if the value is a valid string before downcasing
testHash.each { |k, v| v.downcase! if v.is_a?(String) }

Comment: You could also use `v.downcase! if v.respond_to?(:downcase!)` which is slightly more duck-typish. It's sometimes better to ask what a thing can *do* rather than what a thing *is*.
Comment: I've ran this and it goes through with no error. But when calling on one of the values I know has an uppercase letter in it, I'm still seeing it capitalized. Any idea why it's not actually adjusting, even with the ! at the end of downcase?
Comment: Laura, this should work. Can you edit your question to show an example hash where this doesn't work? Include just a few keys in the example, perhaps two or three.
Comment: When I make a test hash, it works but running it against the code I have is not working so I realize this is an issue with my existing data. It doesn't seem to be working against this CSV I am hashing. Still trying to figure out this issue.
Comment: I realize my hash is actually an array of hashes, which is why this isn't working for me.
Answer: h = {a: nil, b: "Someword", c: 1}
h.map {|k,v| v.downcase! if v.is_a? String}
puts h #=> {:a=>nil, :b=>"someword", :c=>1}

This will work. I am mapping through the hash and check for values that are strings, and then running the downcase! method.


Removed front closet doors and hardwood below is a different color

Question: After removing the door rails on this closet, the hardwood underneath is quite different. Is there any way of "fixing" it or getting it close to the rest of the flooring?
Any advice would be greatly appreciated!

EDIT: By the way, this is the semi finished product. We will eventually add a threshold, but right now just leaving it!
Comment: That's a shame that someone took a lazy shortcut there. I'd do a little careful wiping with some paint thinner. You might just get enough of that heavy stain line to dissolve that you can blended it onto the lighter strip.
Answer: The rest of your floor has been stained a darker color and has also weathered with exposure to air.
You have a few choices of how to handle this, listed here from hardest to easiest:

Refinish the entire floor and then it will all be bright and shiny like that strip. (This will be both time-consuming and expensive).
Find the correct stain to match the rest of the floor and carefully fill in the space, applying one light coat at a time until you have matched the existing color. (This will not be expensive, but it might be difficult to find the correct color, will be time-consuming, and a small mistake making it too dark will probably call for stripping and starting again. You will probably also have to strip a little finish right along the work area because the lines are so sharp.)
(Suggested by @Ack) Strip the existing finish from inside the closet only, then refinish the entire closet floor (including this strip). If it's not the same color, it will look like it was meant to be that way to define the closet space. It should probably be a darker color than the main floor.
Nail a threshold to the floor over the spot. You can get a wood threshold and stain it to match (the floor or the rest of the doorway trim) or deliberately leave it contrasting to mark the edge of the closet, or a metal or plastic one.

If it were me, I'd do option #3 or #4. Since the closet is already an obvious doorway, having some difference on the floor (whether threshold or stain) would not be out of place.
Comment: Re #3: to avoid any item -on the floor- an option could be to stain the line and the closet a darker color to contrast the main floor which would give the illusion that it was done on purpose as a design choice. I would sand the closet floor first so that the floor takes the stain the same or there will be a difference in the closet and at the line
Comment: @Ack great idea! I added it as another option. For future readers, what Ack says is #3 is now #4 because I added the suggestion as a new #3.
Comment: That's what's known as a "H@ack"!
Comment: @Mazura There was no previous threshold. At the bottom of the photo you can see the rails that the closet was on. Those were screwed into the floor
Comment: #4: **threshold** (*put the candle BACK*), +1. You didn't throw it away did you?
Answer: The darker color is probably due to light, unless you have had ammonia gas in there for decades :).  (Look up fuming oak).
The floor probably has a finish over the stain, probably polyurethane, and stain won't penetrate that. You would need to sand it off for the stain to penetrate, run a strip of tape on each side of the strip to prevent oversanding.  I would also test a corner first to see how much work it is and how it looks with the stain you choose.  Remember that the final coat of finish (polyurethane) will darken it slightly.
Another solution is to celebrate the line as if it was on purpose.  I think it's kind of cool.
Comment: I kind of like that last idea.... maybe run a pair of black pinstripes along the color change and give it an "inlay" look... Heh. It might be cool. "Fake it...and make it look like you meant to do that..." is sometimes excellent DIY advice...


Validate several controls with CustomValidator

Question: I am building a feature for users to change their passwords. So this means I have three text fields that need to be validated (is current == actual current, and is new == repeat). So I'm trying to build a custom validator for the first time, and am not sure how to do this. From another example I've seen, the validator is tied to one input field only, which means the ControlToValidate property is rather self-explainatory. But now, though?
I'm trying to do this:
var passwordValidator = new CustomValidator()
            {
                Display = ValidatorDisplay.None,
                ValidationGroup = "PasswordValidationGroup"
            };

passwordValidator.ServerValidate += ChangePasswordServerValidate;

ValidationPlaceHolder.Controls.Add(passwordValidator);

But I'm not getting the results I'm after. The validator does get executed when expected, and debugging shows it follows the if/else-structure as expected, but the error message never does get set. So how do I set it to validate three controls? Is it related to ValidationGroup somehow? I just set that property similarly to how it was in that other custom validator.
private void ChangePasswordServerValidate(object sender, ServerValidateEventArgs e)
        {
            var validator = sender as IValidator;
            var user = SessionManager.Get<OrderFacade>(SessionKeys.OrderFacade).User;

            if (CurrentPasswordTextBox.Text == "" || NewPasswordTextBox.Text == "" || RepeatPasswordTextBox.Text == "")
            {
                validator.ErrorMessage = SiteTextResources.CreateAccount_YourEmailAddressEmpty;
                e.IsValid = false;
            }
            else if (!NewPasswordTextBox.Text.Equals(RepeatPasswordTextBox.Text))
            {
                validator.ErrorMessage = SiteTextResources.CreateAccount_YourEmailAddressEmpty;
                e.IsValid = false;
            }
            else
            {
                ResolveClient<IUserClient>().TryPassword(user.UserName, CurrentPasswordTextBox.Text, passwordSuccessfullyChanged =>
                {
                    e.IsValid = passwordSuccessfullyChanged;
                    validator.ErrorMessage = String.Empty;
                }, error =>
                {

                });
            }
        }

Answer: The error message doesn't get set because you are setting the display to None. Change it to Static or Dynamic. From the documentation:

None -   The validation message is never displayed inline.
Static - Space for the validation message is allocated in the page
layout.
Dynamic -    Space for the validation message is dynamically added to the
page if validation fails.

As for the validation details, if you need to check the contents of 3 controls, do it inside the ChangePasswordServerValidate method and set the e.IsValid accordingly. The ControlToValidate property is not relevant here.
Comment: I did remove the ControlToValidate a little while ago, after stumbling across some forum post. But the error message still isn't displaying. Changing Display to Static or Dynamic didn't help either :( (fwiw, all other validators have "None" set).
Comment: @ChristoferOlsson add the code for the ChangePasswordServerValidate method please


Has one formula the different results in server side and client side?

Question: I have wrote a function to calculate the payment fee in my website but it gives different results in javascript and php.
You should copy this code to a htm/html file.
the code in bug.php :

original number	phpToFixed()	jsToFixed()	phpCalc	jsCalc

Any one can figure out?
Comment: http://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem might be helpful
Answer: When dealing with currency, ALWAYS use integer mathematics. For example, if your currency is US Dollars, ALWAYS calculate prices in cents.
Floating point numbers CANNOT represent 0.01 exactly. It's no surprise, therefore, that you're getting issues.
Whereas, integers CAN represent 1 exactly, and when you're done calculating you can just divide by 100 and round to two decimal places - any FP errors would be too small to have any effect.
Comment: Can't agree enough. Avoid floats when dealing with currency calculations as much as possible.
Comment: Often even 4 digits are used. E.g. exchange rates are always published with 4 decimal digits.


Meaning of the asterisk symbol in Java

Question: Is it possible to change the meaning of the asterisk symbol (multiplication operator) in Java?
I want to do this:
int ex = 600 * 0.98;

It fails because you can't convert from double to int.  Can I make it so that I'm able to convert the double to an integer? Or does the
asterisk only have one meaning that can't be changed?
Comment: What do you mean? ints are just numbers. They can't have asterisks in them.
Comment: Why do you want to do that?
Comment: Do you want to store `*` in a variable, and use it? If yes, Why on earth would you want to do that?
Comment: Multiplication is the only possible meaning of `*` in this context.
Comment: Your question is confusing. Could you explain what you're trying to accomplish?
Answer:
I just want the OPERATION in math, not a string.

To have an operation, you must have code.  One way of doing this is to have a method like
public static double ex(double factor) {
    return factor * 0.98;
}

or if the factor is a field
private double factor = 600;

public double ex() {
    return factor * 98 / 100;
}

public static void main(String... ignored)  {
    Main m = new Main();
    System.out.println("factor: "+m.factor+" ex: "+ m.ex());
    m.factor = 700;
    System.out.println("factor: "+m.factor+" ex: "+ m.ex());
}

prints
factor: 600.0 ex: 588.0
factor: 700.0 ex: 686.0

As you can see ex() is re-evaluated each time it is used.
Why do I * 98 / 100? I do this as each value can be represented exactly however 0.98 is not represent exactly and can have a small error.
System.out.println(new BigDecimal(0.98));

prints the closest representable value to 0.98
0.979999999999999982236431605997495353221893310546875

If you want to store text you need to do something like
String ex = "600 * 0.98";

An int value is for storing a whole number which is a 32-bit signed value, nothing else.
Comment: @Mattcejpa: If you just want the calculation and not the result, then `anything * anything else` won't work.  You'll need an object containing a function that does the calculation and returns the result.  There's no way to redefine `*` to do something other than what it does -- and what it does, is multiply two numbers right then and there.
Comment: I meant if how to have the operator asterisk like in real math, not the word, my question was how to have an asterisk operation.
Comment: @Mattcejpa It's really not clear what you want. What do you mean by an "asterisk operation", considering that in the question you say you don't want multiplication? What should the variable `ex` contain as a result?
Comment: @Juhana i want to have friction in my game, so if i have a variable asterisk 0.98 it would have the finishing operation. In math class they have question like 100 * 1 or something. I just want the OPERATION in math, not a string.
Comment: @Mattcejpa See my updated answer above.  A variable has a fixed value but a method can return a different value each time it is used based on a formula.
Answer: Uhhh.
The short answer is that you can't do that. A variable of type int can only store an integer value. The expression you assign to the int has to evaluate to an integer.
What integer value do you want assigned to ex?
int ex = 588;  // 600 * 0.98

What meaning are you associating with the asterisk between two numeric values that is not multiplication?
If you want to store an array of characters, then:
char[] ex = "600 * 0.98".toCharArray();

Meaning of the asterisk symbol in Java


Who to map through a nested object and delete a key value pair in JavaScript

Question: I have an array of objects and I am trying to create a new object but with out a particular key:value pair in it. Here is my object.

{
  "versionRoomPoolList": [{
      "pmsRoomType": ["CITY"],
      "versionRoomTypeAttributeList": [{
          "attributeDisplayId": 2,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "CV",
          "attributeDescription": "City View"
        },
        {
          "attributeDisplayId": 6,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "HF",
          "attributeDescription": "High Floor, 8th floor and above"
        },
        {
          "attributeDisplayId": 4,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "KN",
          "attributeDescription": "1 King Bed"
        },
        {
          "attributeDisplayId": 5,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "NE",
          "attributeDescription": "Near Elevator"
        },
        {
          "attributeDisplayId": 7,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "RF",
          "attributeDescription": "Mobile Lock"
        },
        {
          "attributeDisplayId": 3,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "SB",
          "attributeDescription": "Sofabed"
        },
        {
          "attributeDisplayId": 1,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "SU",
          "attributeDescription": "Alpine Guest Room"
        },
        {
          "attributeDisplayId": 8,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "TS",
          "attributeDescription": "Separate Shower and Bathtub"
        }
      ],
      "roomTypeDisplayId": 31,
      "roomTypeId": 21,
      "roomTypeStatus": "NOCHANGE",
      "roomPool": "CITY",
      "maxOccupancyStatus": "NOCHANGE",
      "newMaxOccupancy": 4,
      "currentMaxOccupancy": 4,
      "capacityStatus": "NOCHANGE",
      "newCapacity": 12,
      "currentCapacity": 12,
      "guaranteed": 9,
      "minAvailability": 1,
      "premium": false,
      "eliteAvailability": false,
      "isROH": false
    },
    {
      "versionRoomTypeList": [{
          "pmsRoomType": ["HOSP"],
          "versionRoomTypeAttributeList": [{
              "attributeDisplayId": 2,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "CV",
              "attributeDescription": "City View"
            },
            {
              "attributeDisplayId": 5,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "HF",
              "attributeDescription": "High Floor, 8th floor and above"
            },
            {
              "attributeDisplayId": 1,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "HS",
              "attributeDescription": "Hospitality Suite"
            },
            {
              "attributeDisplayId": 4,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "KN",
              "attributeDescription": "1 King Bed"
            },
            {
              "attributeDisplayId": 6,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "RF",
              "attributeDescription": "Mobile Lock"
            },
            {
              "attributeDisplayId": 3,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "SB",
              "attributeDescription": "Sofabed"
            },
            {
              "attributeDisplayId": 7,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "TS",
              "attributeDescription": "Separate Shower and Bathtub"
            }
          ],
          "roomTypeDisplayId": 34,
          "roomTypeId": 24,
          "roomTypeStatus": "NOCHANGE",
          "roomPool": "HOSP",
          "maxOccupancyStatus": "NOCHANGE",
          "newMaxOccupancy": 4,
          "currentMaxOccupancy": 4,
          "capacityStatus": "NOCHANGE",
          "newCapacity": 1,
          "currentCapacity": 1,
          "guaranteed": 1,
          "minAvailability": 1,
          "premium": true,
          "eliteAvailability": false,
          "isROH": true
        },
        {
          "pmsRoomType": ["HOSP"],
          "versionRoomTypeAttributeList": [{
              "attributeDisplayId": 2,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "CV",
              "attributeDescription": "City View"
            },
            {
              "attributeDisplayId": 6,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "HF",
              "attributeDescription": "High Floor, 8th floor and above"
            },
            {
              "attributeDisplayId": 1,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "HS",
              "attributeDescription": "Hospitality Suite"
            },
            {
              "attributeDisplayId": 4,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "KN",
              "attributeDescription": "1 King Bed"
            },
            {
              "attributeDisplayId": 5,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "NE",
              "attributeDescription": "Near Elevator"
            },
            {
              "attributeDisplayId": 7,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "RF",
              "attributeDescription": "Mobile Lock"
            },
            {
              "attributeDisplayId": 3,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "SB",
              "attributeDescription": "Sofabed"
            },
            {
              "attributeDisplayId": 8,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "TS",
              "attributeDescription": "Separate Shower and Bathtub"
            }
          ],
          "roomTypeDisplayId": 35,
          "roomTypeId": 25,
          "roomTypeStatus": "NOCHANGE",
          "roomPool": "HOSP",
          "maxOccupancyStatus": "NOCHANGE",
          "newMaxOccupancy": 4,
          "currentMaxOccupancy": 4,
          "capacityStatus": "NOCHANGE",
          "newCapacity": 1,
          "currentCapacity": 1,
          "guaranteed": 1,
          "minAvailability": 1,
          "premium": true,
          "eliteAvailability": false,
          "isROH": false
        }
      ],
      "roomPoolDisplayId": 4,
      "roomPoolStatus": "NOCHANGE",
      "roomPoolCode": "HOSP",
      "miosSRC": "YD",
      "sna": "N",
      "maxOccupancyStatus": "NOCHANGE",
      "newMaxOccupancy": 4,
      "currentMaxOccupancy": 4,
      "capacityStatus": "NOCHANGE",
      "newCapacity": 2,
      "currentCapacity": 2,
      "premium": true,
      "eliteAvailability": false,
      "excludeAlways": false,
      "excludeOverAuth": false,
      "propertySellOnly": false
    },
    {
      "pmsRoomType": ["HOSP"],
      "versionRoomTypeAttributeList": [{
          "attributeDisplayId": 2,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "CV",
          "attributeDescription": "City View"
        },
        {
          "attributeDisplayId": 5,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "HF",
          "attributeDescription": "High Floor, 8th floor and above"
        },
        {
          "attributeDisplayId": 1,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "HS",
          "attributeDescription": "Hospitality Suite"
        },
        {
          "attributeDisplayId": 4,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "KN",
          "attributeDescription": "1 King Bed"
        },
        {
          "attributeDisplayId": 6,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "RF",
          "attributeDescription": "Mobile Lock"
        },
        {
          "attributeDisplayId": 3,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "SB",
          "attributeDescription": "Sofabed"
        },
        {
          "attributeDisplayId": 7,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "TS",
          "attributeDescription": "Separate Shower and Bathtub"
        }
      ],
      "roomTypeDisplayId": 34,
      "roomTypeId": 24,
      "roomTypeStatus": "NOCHANGE",
      "roomPool": "HOSP",
      "maxOccupancyStatus": "NOCHANGE",
      "newMaxOccupancy": 4,
      "currentMaxOccupancy": 4,
      "capacityStatus": "NOCHANGE",
      "newCapacity": 1,
      "currentCapacity": 1,
      "guaranteed": 1,
      "minAvailability": 1,
      "premium": true,
      "eliteAvailability": false,
      "isROH": true
    }
  ]
}

So what I am trying to do is remove the pmsRoomType in each of the objects.
Here is what I wrote as part of a bigger method I wrote to try and address this.

var data = {
  versionRoomPoolList: array.map(roompools, function(roompool) {
    roompool = lang.mixin({}, roompool);
    delete roompool.numAttributeChars;
    delete roompool.pmsRoomType;
    delete roompool.versionRoomTypeList[0].pmsRoomType;
    return roompool;
  })
};

However I keep getting the following error:
Uncaught TypeError: Cannot read property '0' of undefined

I am assuming I need to write another .map method but I am stuck on how to do that or is that the correct way?
Comment: It looks like not every object in the array has a `versionRoomTypeList` property, hence the error.
Answer: You data is not an array, it is an object with versionRoomPoolList field.
map function calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.
I think this is what are you looking for: Create new object (data) with versionRoomPoolList as key and an new array as value.
var rawData = {
  "versionRoomPoolList": [
    {
      "pmsRoomType": [
        "CITY"
      ],
      "versionRoomTypeAttributeList": [
        {
          "attributeDisplayId": 2,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "CV",
          "attributeDescription": "City View"
        },
        {
          "attributeDisplayId": 6,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "HF",
          "attributeDescription": "High Floor, 8th floor and above"
        },
        {
          "attributeDisplayId": 4,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "KN",
          "attributeDescription": "1 King Bed"
        },
        {
          "attributeDisplayId": 5,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "NE",
          "attributeDescription": "Near Elevator"
        },
        {
          "attributeDisplayId": 7,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "RF",
          "attributeDescription": "Mobile Lock"
        },
        {
          "attributeDisplayId": 3,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "SB",
          "attributeDescription": "Sofabed"
        },
        {
          "attributeDisplayId": 1,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "SU",
          "attributeDescription": "Alpine Guest Room"
        },
        {
          "attributeDisplayId": 8,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "TS",
          "attributeDescription": "Separate Shower and Bathtub"
        }
      ],
      "roomTypeDisplayId": 31,
      "roomTypeId": 21,
      "roomTypeStatus": "NOCHANGE",
      "roomPool": "CITY",
      "maxOccupancyStatus": "NOCHANGE",
      "newMaxOccupancy": 4,
      "currentMaxOccupancy": 4,
      "capacityStatus": "NOCHANGE",
      "newCapacity": 12,
      "currentCapacity": 12,
      "guaranteed": 9,
      "minAvailability": 1,
      "premium": false,
      "eliteAvailability": false,
      "isROH": false
    },
    {
      "versionRoomTypeList": [
        {
          "pmsRoomType": [
            "HOSP"
          ],
          "versionRoomTypeAttributeList": [
            {
              "attributeDisplayId": 2,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "CV",
              "attributeDescription": "City View"
            },
            {
              "attributeDisplayId": 5,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "HF",
              "attributeDescription": "High Floor, 8th floor and above"
            },
            {
              "attributeDisplayId": 1,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "HS",
              "attributeDescription": "Hospitality Suite"
            },
            {
              "attributeDisplayId": 4,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "KN",
              "attributeDescription": "1 King Bed"
            },
            {
              "attributeDisplayId": 6,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "RF",
              "attributeDescription": "Mobile Lock"
            },
            {
              "attributeDisplayId": 3,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "SB",
              "attributeDescription": "Sofabed"
            },
            {
              "attributeDisplayId": 7,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "TS",
              "attributeDescription": "Separate Shower and Bathtub"
            }
          ],
          "roomTypeDisplayId": 34,
          "roomTypeId": 24,
          "roomTypeStatus": "NOCHANGE",
          "roomPool": "HOSP",
          "maxOccupancyStatus": "NOCHANGE",
          "newMaxOccupancy": 4,
          "currentMaxOccupancy": 4,
          "capacityStatus": "NOCHANGE",
          "newCapacity": 1,
          "currentCapacity": 1,
          "guaranteed": 1,
          "minAvailability": 1,
          "premium": true,
          "eliteAvailability": false,
          "isROH": true
        },
        {
          "pmsRoomType": [
            "HOSP"
          ],
          "versionRoomTypeAttributeList": [
            {
              "attributeDisplayId": 2,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "CV",
              "attributeDescription": "City View"
            },
            {
              "attributeDisplayId": 6,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "HF",
              "attributeDescription": "High Floor, 8th floor and above"
            },
            {
              "attributeDisplayId": 1,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "HS",
              "attributeDescription": "Hospitality Suite"
            },
            {
              "attributeDisplayId": 4,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "KN",
              "attributeDescription": "1 King Bed"
            },
            {
              "attributeDisplayId": 5,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "NE",
              "attributeDescription": "Near Elevator"
            },
            {
              "attributeDisplayId": 7,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "RF",
              "attributeDescription": "Mobile Lock"
            },
            {
              "attributeDisplayId": 3,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "SB",
              "attributeDescription": "Sofabed"
            },
            {
              "attributeDisplayId": 8,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "TS",
              "attributeDescription": "Separate Shower and Bathtub"
            }
          ],
          "roomTypeDisplayId": 35,
          "roomTypeId": 25,
          "roomTypeStatus": "NOCHANGE",
          "roomPool": "HOSP",
          "maxOccupancyStatus": "NOCHANGE",
          "newMaxOccupancy": 4,
          "currentMaxOccupancy": 4,
          "capacityStatus": "NOCHANGE",
          "newCapacity": 1,
          "currentCapacity": 1,
          "guaranteed": 1,
          "minAvailability": 1,
          "premium": true,
          "eliteAvailability": false,
          "isROH": false
        }
      ],
      "roomPoolDisplayId": 4,
      "roomPoolStatus": "NOCHANGE",
      "roomPoolCode": "HOSP",
      "miosSRC": "YD",
      "sna": "N",
      "maxOccupancyStatus": "NOCHANGE",
      "newMaxOccupancy": 4,
      "currentMaxOccupancy": 4,
      "capacityStatus": "NOCHANGE",
      "newCapacity": 2,
      "currentCapacity": 2,
      "premium": true,
      "eliteAvailability": false,
      "excludeAlways": false,
      "excludeOverAuth": false,
      "propertySellOnly": false
    },
    {
      "pmsRoomType": [
        "HOSP"
      ],
      "versionRoomTypeAttributeList": [
        {
          "attributeDisplayId": 2,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "CV",
          "attributeDescription": "City View"
        },
        {
          "attributeDisplayId": 5,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "HF",
          "attributeDescription": "High Floor, 8th floor and above"
        },
        {
          "attributeDisplayId": 1,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "HS",
          "attributeDescription": "Hospitality Suite"
        },
        {
          "attributeDisplayId": 4,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "KN",
          "attributeDescription": "1 King Bed"
        },
        {
          "attributeDisplayId": 6,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "RF",
          "attributeDescription": "Mobile Lock"
        },
        {
          "attributeDisplayId": 3,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "SB",
          "attributeDescription": "Sofabed"
        },
        {
          "attributeDisplayId": 7,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "TS",
          "attributeDescription": "Separate Shower and Bathtub"
        }
      ],
      "roomTypeDisplayId": 34,
      "roomTypeId": 24,
      "roomTypeStatus": "NOCHANGE",
      "roomPool": "HOSP",
      "maxOccupancyStatus": "NOCHANGE",
      "newMaxOccupancy": 4,
      "currentMaxOccupancy": 4,
      "capacityStatus": "NOCHANGE",
      "newCapacity": 1,
      "currentCapacity": 1,
      "guaranteed": 1,
      "minAvailability": 1,
      "premium": true,
      "eliteAvailability": false,
      "isROH": true
    }
  ]
}

var data = {
  versionRoomPoolList: rawData.versionRoomPoolList.map(function(roompool) {
    roompool = Object.assign({}, roompool);
    delete roompool.numAttributeChars;
    delete roompool.pmsRoomType;
    // make sure `versionRoomTypeList` is existed
    roompool.versionRoomTypeList && delete roompool.versionRoomTypeList[0].pmsRoomType;
    return roompool;
  })
};
console.log(data)

Comment: I cannot use rawData because I am getting this data from an endpoint. So can you adjust the method.
Comment: Set your response to a variable called `rawData`, or you can warrap my logic to a function by yourself.
Answer: You can try something like this:

const data = {
  "versionRoomPoolList": [{
      "pmsRoomType": ["CITY"],
      "versionRoomTypeAttributeList": [{
          "attributeDisplayId": 2,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "CV",
          "attributeDescription": "City View"
        },
        {
          "attributeDisplayId": 6,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "HF",
          "attributeDescription": "High Floor, 8th floor and above"
        },
        {
          "attributeDisplayId": 4,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "KN",
          "attributeDescription": "1 King Bed"
        },
        {
          "attributeDisplayId": 5,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "NE",
          "attributeDescription": "Near Elevator"
        },
        {
          "attributeDisplayId": 7,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "RF",
          "attributeDescription": "Mobile Lock"
        },
        {
          "attributeDisplayId": 3,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "SB",
          "attributeDescription": "Sofabed"
        },
        {
          "attributeDisplayId": 1,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "SU",
          "attributeDescription": "Alpine Guest Room"
        },
        {
          "attributeDisplayId": 8,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "TS",
          "attributeDescription": "Separate Shower and Bathtub"
        }
      ],
      "roomTypeDisplayId": 31,
      "roomTypeId": 21,
      "roomTypeStatus": "NOCHANGE",
      "roomPool": "CITY",
      "maxOccupancyStatus": "NOCHANGE",
      "newMaxOccupancy": 4,
      "currentMaxOccupancy": 4,
      "capacityStatus": "NOCHANGE",
      "newCapacity": 12,
      "currentCapacity": 12,
      "guaranteed": 9,
      "minAvailability": 1,
      "premium": false,
      "eliteAvailability": false,
      "isROH": false
    },
    {
      "versionRoomTypeList": [{
          "pmsRoomType": ["HOSP"],
          "versionRoomTypeAttributeList": [{
              "attributeDisplayId": 2,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "CV",
              "attributeDescription": "City View"
            },
            {
              "attributeDisplayId": 5,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "HF",
              "attributeDescription": "High Floor, 8th floor and above"
            },
            {
              "attributeDisplayId": 1,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "HS",
              "attributeDescription": "Hospitality Suite"
            },
            {
              "attributeDisplayId": 4,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "KN",
              "attributeDescription": "1 King Bed"
            },
            {
              "attributeDisplayId": 6,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "RF",
              "attributeDescription": "Mobile Lock"
            },
            {
              "attributeDisplayId": 3,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "SB",
              "attributeDescription": "Sofabed"
            },
            {
              "attributeDisplayId": 7,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "TS",
              "attributeDescription": "Separate Shower and Bathtub"
            }
          ],
          "roomTypeDisplayId": 34,
          "roomTypeId": 24,
          "roomTypeStatus": "NOCHANGE",
          "roomPool": "HOSP",
          "maxOccupancyStatus": "NOCHANGE",
          "newMaxOccupancy": 4,
          "currentMaxOccupancy": 4,
          "capacityStatus": "NOCHANGE",
          "newCapacity": 1,
          "currentCapacity": 1,
          "guaranteed": 1,
          "minAvailability": 1,
          "premium": true,
          "eliteAvailability": false,
          "isROH": true
        },
        {
          "pmsRoomType": ["HOSP"],
          "versionRoomTypeAttributeList": [{
              "attributeDisplayId": 2,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "CV",
              "attributeDescription": "City View"
            },
            {
              "attributeDisplayId": 6,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "HF",
              "attributeDescription": "High Floor, 8th floor and above"
            },
            {
              "attributeDisplayId": 1,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "HS",
              "attributeDescription": "Hospitality Suite"
            },
            {
              "attributeDisplayId": 4,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "KN",
              "attributeDescription": "1 King Bed"
            },
            {
              "attributeDisplayId": 5,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "NE",
              "attributeDescription": "Near Elevator"
            },
            {
              "attributeDisplayId": 7,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "RF",
              "attributeDescription": "Mobile Lock"
            },
            {
              "attributeDisplayId": 3,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "SB",
              "attributeDescription": "Sofabed"
            },
            {
              "attributeDisplayId": 8,
              "attributeStatus": "NOCHANGE",
              "attributeCode": "TS",
              "attributeDescription": "Separate Shower and Bathtub"
            }
          ],
          "roomTypeDisplayId": 35,
          "roomTypeId": 25,
          "roomTypeStatus": "NOCHANGE",
          "roomPool": "HOSP",
          "maxOccupancyStatus": "NOCHANGE",
          "newMaxOccupancy": 4,
          "currentMaxOccupancy": 4,
          "capacityStatus": "NOCHANGE",
          "newCapacity": 1,
          "currentCapacity": 1,
          "guaranteed": 1,
          "minAvailability": 1,
          "premium": true,
          "eliteAvailability": false,
          "isROH": false
        }
      ],
      "roomPoolDisplayId": 4,
      "roomPoolStatus": "NOCHANGE",
      "roomPoolCode": "HOSP",
      "miosSRC": "YD",
      "sna": "N",
      "maxOccupancyStatus": "NOCHANGE",
      "newMaxOccupancy": 4,
      "currentMaxOccupancy": 4,
      "capacityStatus": "NOCHANGE",
      "newCapacity": 2,
      "currentCapacity": 2,
      "premium": true,
      "eliteAvailability": false,
      "excludeAlways": false,
      "excludeOverAuth": false,
      "propertySellOnly": false
    },
    {
      "pmsRoomType": ["HOSP"],
      "versionRoomTypeAttributeList": [{
          "attributeDisplayId": 2,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "CV",
          "attributeDescription": "City View"
        },
        {
          "attributeDisplayId": 5,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "HF",
          "attributeDescription": "High Floor, 8th floor and above"
        },
        {
          "attributeDisplayId": 1,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "HS",
          "attributeDescription": "Hospitality Suite"
        },
        {
          "attributeDisplayId": 4,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "KN",
          "attributeDescription": "1 King Bed"
        },
        {
          "attributeDisplayId": 6,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "RF",
          "attributeDescription": "Mobile Lock"
        },
        {
          "attributeDisplayId": 3,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "SB",
          "attributeDescription": "Sofabed"
        },
        {
          "attributeDisplayId": 7,
          "attributeStatus": "NOCHANGE",
          "attributeCode": "TS",
          "attributeDescription": "Separate Shower and Bathtub"
        }
      ],
      "roomTypeDisplayId": 34,
      "roomTypeId": 24,
      "roomTypeStatus": "NOCHANGE",
      "roomPool": "HOSP",
      "maxOccupancyStatus": "NOCHANGE",
      "newMaxOccupancy": 4,
      "currentMaxOccupancy": 4,
      "capacityStatus": "NOCHANGE",
      "newCapacity": 1,
      "currentCapacity": 1,
      "guaranteed": 1,
      "minAvailability": 1,
      "premium": true,
      "eliteAvailability": false,
      "isROH": true
    }
  ]
}

const myFunction = data => ({
  ...data,
  versionRoomPoolList: data.versionRoomPoolList.filter(i => {
    delete i.pmsRoomType;
    return i;
  }),
});

console.log(myFunction(data))
Comment: I've updated my code with a code snippet where you can test it. The example will remove all pmsRoomType key from each object.
Comment: Unfortunately I can't use this because I am cannot use a tool like `babel` to transpile my code. This particular functionally has to support `IE7` and `IE8` for an internal business application.
Answer: Your code is mostly correct and as Felix Kling commented on your post, you just need to safeguard against properties that don't exist. This can be as simple as:
if (roompool.versionRoomTypeList && roompool.versionRoomTypeList.length) {
  // delete
}

That said... I'm suspecting that you just have a typo and you should change versionRoomTypeList to versionRoomTypeAttributeList :-P


Add result of php function to WP database

Question: I have the following function to create a member_id:
add_action('user_register', 'generate_member_id');
function generate_member_id($user_id){
    $unique_id = 1000 + get_current_user_id();
    $chapter_id = fetch_chapter();
    $member_id = "FAL-" . $chapter_id . "-" . $unique_id;

    return $member_id;
}

It appears to work fine and I can call the function from a shortcode and get the correct value.
Now I want to add the returned value to a database and have tried using

update_user_meta()
$wpdb->update
$wpdb->insert
$wpdb->query
all with necessary arguments but nothing seems to work.

I expected this to do it, but it just generates a generic error that I am not able to debug (I have a problem with error logging):
global $wpdb;
$users = $wpdb->get_results( "SELECT ID FROM $wpdb->users" );
$generated_id = generate_member_id()
if( $users ) {
    foreach ( $users as $user ) {
        update_user_meta( $user->ID, 'member_id', generate_member_id() );
    }
}

However if I change generate_member_id() to a string like 'memberId', it works and the database is updated. So I don't know what I'm doing wrong. Why can't I add' the result of the generate_member_id() function and to a WP database?
EDIT
add_action('user_register', 'fetch_chapter');
function fetch_chapter(){
    $current_user = wp_get_current_user();
    $current_user_id = $current_user->ID;
    global $wpdb;
    $result = $wpdb->get_results('SELECT meta_value FROM usermeta WHERE meta_key = \'chapter_name\' AND user_id = '. $current_user->ID .' LIMIT 1');
    if ($result[0]->meta_value == 'Peregrine') {
           $result[0]->meta_value = 'PG';
    }elseif ($result[0]->meta_value == 'Barbary') {
           $result[0]->meta_value = 'BB';
    }
     return $result[0]->meta_value;
}

Answer: There are a few things I notice that could cause problems:

You have this line that (1) has no ; at the end and (2) it doesn't look like you need it anyway - you don't use $generated_id anywhere:

    $generated_id = generate_member_id()

You are not passing the user_id into generate_member_id for your users in the loop calling update_user_meta...

... but even if you did pass in the user_id, generate_member_id isn't using it anyway - it is using the current user id. That is the wrong value for the users in your loop.

You need to fix your generate_member_id function to work with the user_id parameter. I assume you want this function to work without one too, so it still gets the get_current_user_id is no user id is passed in:
add_action('user_register', 'generate_member_id');
function generate_member_id($user_id){

    // If no user_id is passed in, use the current user id
    if (!$user_id) $user_id = get_current_user_id();

    $unique_id = 1000 + $user_id;
    $chapter_id = fetch_chapter_id();
    $member_id = "FAL-" . $chapter_id . "-" . $unique_id;

    return $member_id;
}

And then remove the erroneous $generated_id... line and pass the user_id to the generate_member_id in your update_user_meta:
global $wpdb;
$users = $wpdb->get_results( "SELECT ID FROM $wpdb->users" );
if( $users ) {
    foreach ( $users as $user ) {
        update_user_meta( $user->ID, 'member_id', generate_member_id($user->ID) );
    }
}

Comment: `$generated_id = generate_member_id()` leftovers from trying all kinds of statements! Thanks @FluffyK, I think the second issue you mentioned was what had kept me running in circles. It works a treat now.
Comment: @eneimi I thought that might be the case :) FYI I just noticed I was missing a `;` myself so I've edited the code in my answer to fix it.
Comment: I have a situation now where the $member_id displayed in the frontend is accurate (specific for that user), but the member_id stored in the database is always using $chapter_id from admin (I am logged in as admin). I think I've mixed up $user and $current_user. Any thoughts @FluffyK ?
Comment: @eneimi Yes it does sound like you are getting the current user data instead of the "member" user.  You haven't included the `fetch_chapter_id` function here (I assume that's where you get $chapter_id for the user)  so I can't see what you're doing. However you have the `$user_id` now when you call `fetch_chapter_id` so you can pass it in to the function. If you need help more with it, you should ask a new question - each question on Stack Overflow should be about one single problem. If I'm on the site I'll take a look! but if I'm not, someone else might help :)


Second LED bulb in each fixture burns out, what should I replace?

Question: We have a number of inexpensive light fixtures in our house, each of which takes two bulbs.  Most, but not all of these, are on newer dimmer switches (two with sliders, one with remote).  We're having a consistent problem where one (but only one) of the bulbs in each of at least 4 different fixtures fails every 1 to 4 months.  The other bulb will continue working, at least for the 2 years since we installed them.
Since LED bulbs are supposed to last for 5-10 years, and are difficult to dispose of, this bulb burnout is kind of a problem.  So we're looking for advice on what is most likely to be the problem, and what I need to fix/replace to stop burning out bulbs.
Here's what the bulbs & fixtures have in common:

The fixtures are all inexpensive "home depot" models.
Because of their shallow profile, the fixtures are effectively fully enclosed (do LED bulbs overheat?).
All bulbs are supposed to be dimmable
The LED bulbs are on the more inexpensive end, most having been purchased from CostCo.
Bulbs are from 9.5W to 13W
Dimming works fine, up until the bulbs fail
The electrical wiring in the house is mostly from the late 1980's, but some of it may date back to the 50's.

Here's what they don't have in common:

The two slider dimmers are older (made for incandescents), but the dimmer with the remote is new and supposedly LED-compatible
The one in the dining room tends to flicker for a while before it dies, but in other fixtures the bulb just burns out.
Burnout (again, one bulb only) has also happened in one fixture that does not have a dimmer.
There are two different designs/models of fixture involved.
The dead bulbs did not show any strong evidence of damage from arcing, as (presumably) they would if not making contact was an issue.

So, ideas/suggestions?  What is the most likely cause of this one-of-two bulb burnout, and what's the first thing to try replacing?
Comment: LEDs are easy to dispose of.  You throw them in the trash.  They don't have anything toxic in them, not even lead.   *You're thinking of CFLs aka twistys aka screwballs.Take those to Home Depot*.  But if you're throwing away LEDs, something is wrong...  Since you are buying at CostCo you are almost certainly buying Feit Electric, and that's your problem right there.  Try Cree, GE or believe it or not Ikea.
Answer: Older dimmer switches are not necessarily compatible with "dimmable" LED lamps. Replace the dimmers with those designed for LED's, or replace with a standard wall switch, and use remotely-controlled lamps.
BTW, there is no problem disposing of "dead" LED lamps -- most should comply with RoHS and contain little or no hazardous material. While the emitters may contain tiny amounts of arsenides, they're well sealed in plastic. Perhaps you're confusing LED's with fluorescent lamps, which have small amounts of metallic mercury.
Answer: Your comment about the fixture being fully enclosed is probably the key. Indeed, LED bulbs (actually, the driver electronics in the base) are heat sensitive and can die from overheating. Probably, once one dies, the heat level reduces enough that the other can survive.
If you look carefully at the packaging for the bulbs, you'll probably find something like "not for enclosed fixtures". You need to look for ones that don't say that.
BTW, it's my belief that the clear bulbs that look like old-fashion filament bulbs do not have significant drive electronics and do not have this issue. These are what I use in enclosed fixtures.
Comment: Just had one die in front of me, and when I checked it the base of it was HOT.  So this is likely the problem.


In Python, how can I get the Unix timestamp of the day before?

Question: I'm in PST time.  I want to get 2 timestamps:

the beginning of yesterday
the end of yesterday

These timestamps should be the same no matter what time it is currently.
How can I do this with Python?
Do I have to use the datetime object, and then transform it to timestamp?
Comment: And by "end of yesterday" do you mean "beginning of today"? Or do you mean one (second?/millisecond?/nanosecond?) before midnight?
Comment: @MattJohnson: He's saying the pair of timestamps returned at any given time should be the same as the pair of timestamps returned at any other time in the same day. Not the same as _each other_.
Comment: You don't _have_ to use a `datetime` object, but… why would you not _want_ to?
Comment: How could the timestamps be the same if they are for two different points in time?
Comment: What do you mean by "beginning of yesterday"
Comment: @MattJohnson: For your first question, I don't think there's anything unclear: the timestamps will be different if the _day_ changes, but at different times in _the same day_ they will always be the same. For the second, if he wants a half-open range here, I don't think he needs to state so explicitly, since that's what Python uses consistently, and what people usually use for faking continuous time ranges with discrete time values.
Comment: @abarnert - I'm still confused.  Maybe it's just the wording.  I understand about half-open intervals.  I just don't understand how two different points in time (one at the beginning of the day, one at the end) can be expected to have the same exact timestamp.
Comment: @abarnert - Thanks, that makes sense now.  So we're looking for "midnight to midnight" of the prior day in the local time zone, as long as midnight is valid.  Yes?
Comment: Do you have to deal with the days when the clocks spring forward and fall back?  They complicate what is otherwise doable because mostly you add 86399 seconds to the start time to get the end time, except when you need to add 86399±3600 seconds.  You might do better with an end time that is the start of the next day (86400±3600), and write your code to exclude the end time.  It avoids awkward questions about what happens during the last second before midnight.
Comment: @JonathanLeffler: I already suggested using a half-open range, both a few comments back and in my answer, because there's no other way to define a continuous time range, and DST doesn't really affect that. DST also doesn't affect you when you use a high-level time library—but if you try to do it with something low-level built on timestamps, you do have to take care of it. Again, that's explained in my answer.
Answer: To get yesterday I guess you can do this:
>>>import datetime
>>>yesterday = datetime.date.today() - datetime.timedelta(1)
>>>unix_time= yesterday.strftime("%s") #Second as a decimal number [00,61] (or Unix Timestamp)
>>>print unix_time
'1372737600'

Comment: Caution should be given that this returns a *string* despite looking exactly like the  'number' it should be.
Comment: On python 2.7 this does not work for me.  It give a error with unix_time= yesterday.strftime("%s") and 00 with unix_time= yesterday.strftime("%S")
Answer: The obvious way to do this is with datetime. But you apparently want to avoid that for some strange reason. Well, you can use time or calendar, or various third-party libraries, or custom code instead.
Here it is with time:
import time

def yesterday():
    now = time.time()
    yday = time.localtime(now - 86400) # seconds/day
    start = time.struct_time((yday.tm_year, yday.tm_mon, yday.tm_mday, 0, 0, 0, 0, 0, yday.tm_isdst))
    today = time.localtime(now)
    end = time.struct_time((today.tm_year, today.tm_mon, today.tm_mday, 0, 0, 0, 0, 0, today.tm_isdst))
    return time.mktime(start), time.mktime(end)

If you run this during a leap second, on a platform that tracks leap seconds, it will give today instead of yesterday. You can check for that easily (basically, if today == yesterday, subtract another day), but I don't think it's worth it.
Also, if you run this during DST crossover in a timezone where the crossover happens between midnight and 01:00 or 23:00 (depending on your hemisphere), it will get the wrong day. For example, in Brazil, if you ran this code during the second 23:00-00:00 hour on 16 February 2013, it would return the start of the day that includes the time 24 hours ago… which is today, rather than yesterday. The same workaround works here.
Comment: Yes, there are time zones that transition as you described.  For example, [Brazil](http://www.timeanddate.com/worldclock/clockchange.html?n=45).
Comment: 1) [time.gmtime](http://docs.python.org/2/library/time.html#time.gmtime) takes one argument: seconds, not year, month, day. 2) If you state that the only correct answer is a half open range, this includes the 'off the end' value of the first moment of today. This is correct for `start < time_yesterday < end` but incorrect for any logic one may want to use using `end` and the named tuples of yesterday, like `end.tm_mon end.tm_day` etc 3) The OP did not say specifically he did not want to use datetime 4) Your logic will be off by the fraction of the second returned by `time.time()`
Comment: @MattJohnson: It looks like you're right; in Brazil, during the second 23:00-00:00 on 16 February, this code will return today instead of yesterday (assuming `is_dst` works right). Let me edit the answer. Thanks.
Comment: @thewolf: 1) sorry, that should be `struct_time`; fixed. 2) No, a half-open range is `start <= time < end`, not `start < time`. 3) The OP said "Do I have to use the DateTime object?" That implies that he doesn't want to use it. But, just in case I've inferred wrong, the very first sentence is "The obvious way to do this is with `datetime`." 4) If you mean the microsecond portion, no, that can't make any difference; HH:MM:SS.999999 is always on the same day as HH:MM:SS.000000. If you mean that `time.time()` doesn't run instantly… then so what?
Comment: @thewolf: Also, note that nobody's using `end`; he explicitly wants a _timestamp_, which is just a number, so that's what I'm returning. A pair of timestamps has to be interpreted as a half-open range; the only other alternative would be to return the previous real number to midnight of today, and there is no such thing as "the previous real number" by definition.


List functions in fish config file?

Question: How can I list all the functions I have saved in the config file?
I tried functions | cat, but that listed a bunch of functions that are not in my config folder.
Comment: You have to parse config files, fish usually  finds them in ./config/fish/functions and in /usr/share/fish/config.fish . Perhaps there is way to run with with only one config file and execute `functions -n` from ot
Answer: Iterate over the known function names then use functions -details $f to get the file it was defined in and filter on that info.
for f in (functions)
    if string match '*/.config/fish/config.fish' (functions --details $f)
        echo $f
    end
end

List functions in fish config file?


TCL - read a file, extra line

Question: I have written the script below, and for some reason it output an extra 3rd line (top out.txt & name ). How do I stop it from outputing the last 2 line to the output file.
I think is because of this line but not too sure: set lines [split [read $list] "\n"]
Input put file - a.txt
**********************
abc
bcd

Output
*******
top out.txt
name abc
top out.txt
name bcd
top out.txt
name

set outfile      [open "out.txt" w]
set list         [open "a.list" r]
set dir         "[glob a.txt]"

    foreach ddd $dir {
        set lines [split [read $list] "\n"]
        foreach line $lines {
                puts $outfile "top $dir"
                puts $outfile "name $line"
        }
    }
close $list
close $outfile

Comment: Try `read -nonewline $list` -- check the [read man page](http://www.tcl-lang.org/man/tcl8.6/TclCmd/read.htm)
Comment: Or use `gets` in a loop instead of reading the entire file in one go.
Comment: Also, how do you get `out.txt` from `glob abc.txt`? Why are you even using glob here anyways? It'll only return at most one file with that pattern since there aren't any wildcards... And if that outer `foreach` does manage to run more than once, you'll only reading `a.list` the first time because it'll be at the end of the file the subsequent times....
Answer: The core of the issue is that split works with field separators and not field terminators; this is where you see the difference between the two.
If we look at the characters of your file, we'll see this:
a b c \n b c d \n. (Technically, the \n might instead be \r \n or \r; Tcl auto-adapts to that by default for text files.)
If we split those characters at the \n, we get these substrings: abc, bcd, and the empty string for the characters after that final \n. This means that when we join the strings with \n (as the joiner string) between all the elements, we get the original string back again.

You've got a few options for dealing with this. My favourite is to add code to ignore blank lines; versions of this are particularly useful for all sorts of human-written lists (as it's fairly easy to also add in comment skipping):
    set lines [split [read $list] "\n"]
    foreach line $lines {
        if {$line eq ""} continue
        puts $outfile "top $dir"
        puts $outfile "name $line"
    }

Another option is to use the -nonewline option to read to discard that final \n:
    set lines [split [read -nonewline $list] "\n"]
    foreach line $lines {
        puts $outfile "top $dir"
        puts $outfile "name $line"
    }

You could also string trimright before splitting, but that would strip multiple newlines from the end (if they're present).
    set lines [split [string trimright [read $list] "\n"] "\n"]
    foreach line $lines {
        puts $outfile "top $dir"
        puts $outfile "name $line"
    }

Finally, if you're using a machine-generated list, you could consider just getting that code to not put a newline at the end. Sometimes that's the easiest option of all.

TCL - read a file, extra line


Why VertexBuffer is faster than DynamicVertexBuffer

Question: I've been doing some XNA programming (DirectX) on Windows Phone 7 and noticed that the VertexBuffer class is 30 times faster than the DynamicVertexBuffer class. What's the difference between them anyways? Why the significant speedup when using VertexBuffer?
Answer: The MSDN entry for the DynamicVertexBuffer Class states:

" Use DynamicVertexBuffer for dynamic
  vertex arrays and VertexBuffer for
  non-dynamic vertex arrays...In
  situations where your game frequently
  modifies a vertex buffer, it is
  recommended that the buffer be
  instantiated or derived from
  DynamicVertexBuffer instead of the
  VertexBuffer class.
  DynamicVertexBuffer is optimized for
  frequent vertex data modification."

So, its presumably the usual tradeoff of something like a fixed allocated array representation versus a dynamic list.


How change selected value of radio buttons in R Shiny manually?

Question: I have an R Shiny UI component with radio buttons and would like to manually change the selected value from the code.
Let say, there are 3 values: "Stay here", "Do it", and "Go away". By selecting "Do it" the user sees the action button "Do it". I'd like to change the selected radio buttons value on "stay_here" after the user clicked on the action button "Do it". Here is the code.
library(shiny)

# UI
ui <- fluidPage(
  fluidPage(
    fluidRow(uiOutput("rbtn_test")),
    fluidRow(uiOutput("uo_stay_here")),
    fluidRow(uiOutput("uo_do_it")),
    fluidRow(uiOutput("uo_go_away"))))

# SERVER
server <- function(input, output) {

   # 1. Radio buttons
   output$rbtn_test <- renderUI({

     # 1.1. Values
     actions_values <- c("stay_here", "do_it", "go_away")
     names(actions_values) <- c("Stay here", "Do it", "Go away")

     # 1.2. Selected value
     action_selected <- "stay_here"

     # 1.3. UI element
     radioButtons(
       "rbtn_test_selected", "Actions",
       choices = actions_values,
       selected = action_selected,
       inline = TRUE)
   })

   # 2. 'Stay here'
   output$uo_stay_here <- renderUI({
     if(input$rbtn_test_selected == "stay_here") {
       tags$div(tags$p("Stay here ..."))
     }
   })

   # 3. Process 'Do it' action
   output$uo_do_it <- renderUI({

     if(input$rbtn_test_selected == "do_it") {
       actionButton("btn_doit", "Do it")
       # TBD: Change selected value in radio buttons on 'stay_here'
     }

   })

   # 4. 'Go away'
   output$uo_go_away <- renderUI({
     if(input$rbtn_test_selected == "go_away") {
       tags$div(tags$p("Go away ..."))
     }
   })

}

# Run the application
shinyApp(ui = ui, server = server)

Thanks!
Answer: You can add an observeEvent on "Do it" action button which will change the selected value on click.
 observeEvent(input$btn_doit, {
    updateRadioButtons(session, "rbtn_test_selected", selected = "stay_here")
  })

Complete code -
library(shiny)

# UI
ui <- fluidPage(
  fluidPage(
    fluidRow(uiOutput("rbtn_test")),
    fluidRow(uiOutput("uo_stay_here")),
    fluidRow(uiOutput("uo_do_it")),
    fluidRow(uiOutput("uo_go_away"))))

# SERVER
server <- function(input, output, session) {

  # 1. Radio buttons
  output$rbtn_test <- renderUI({

    # 1.1. Values
    actions_values <- c("stay_here", "do_it", "go_away")
    names(actions_values) <- c("Stay here", "Do it", "Go away")

    # 1.2. Selected value
    action_selected <- "stay_here"

    # 1.3. UI element
    radioButtons(
      "rbtn_test_selected", "Actions",
      choices = actions_values,
      selected = action_selected,
      inline = TRUE)
  })

  # 2. 'Stay here'
  output$uo_stay_here <- renderUI({
    if(input$rbtn_test_selected == "stay_here") {
      tags$div(tags$p("Stay here ..."))
    }
  })

  # 3. Process 'Do it' action
  output$uo_do_it <- renderUI({

    if(input$rbtn_test_selected == "do_it") {
      actionButton("btn_doit", "Do it")
    }
  })

  observeEvent(input$btn_doit, {
    updateRadioButtons(session, "rbtn_test_selected", selected = "stay_here")
  })

  # 4. 'Go away'
  output$uo_go_away <- renderUI({
    if(input$rbtn_test_selected == "go_away") {
      tags$div(tags$p("Go away ..."))
    }
  })

}

# Run the application
shinyApp(ui = ui, server = server)

Comment: Thank you very much for this sophisticated answer!