Should I use a captcha in my sign up form?

Question: I have created a sign up form for a job finding website:

Should I add a captcha to separate humans from robots when registering for the site?  What are its benefits and what effects could this have on the user experience?
Comment: As this is a User Experience site, then the answer is a definitive NO. Has any user ever said "Oh cool, I've got to solve this little puzzle before I can sign in!"
Comment: ok in that case why some sites put captchas in their sign up form ? is is for security reasons ?
Comment: @jonW Oh, i got this. its to prevent spams, but is that new captcha which makes users only to check that box user friendly?
Comment: Any form of CAPTCHA is less user-friendly than no CAPTCHA at all. What takes less time to do for you - typing your name in a box and hitting OK, or typing your name in a box, ticking a box and hitting OK?
Comment: The way I discuss this topic with clients: For every hurdle you put in the way of the user's task, you will lose some number of potential users/customers. How many are you willing to lose?
Comment: @JonW I don't entirely agree with your standpoints, as CAPTCHA's are out there for a reason, though your 2nd comment is really true: it takes "only 1 second" to tick that checkbox.. but that's 1 second too much and takes "more effort" than not having to tick that box.
Comment: @EdwinLambregts Captcha's are there for a reason, yes. But that reason is not UX. It's like saying to your users *"We have a spam problem, so instead of dealing with it technically we're going to push the burden onto you, the user, instead"*. Sure, users are used to them, but that doesn't mean that a captcha is good UX compared to the alternative of no captcha.
Comment: Try using a CAPTCHA on a mobile device then come back and tell us that is not a hindrance to users. Know anyone that uses a mobile device?
Answer: No, you should not use CAPTCHA.
You should focus on technical ways of solving your problems rather than shifting the technical burden onto your users.  As a simple example, you are asking for an email address, so you could validate the email address (which you should do anyway) as a substitute for CAPTCHA.
Someone could still write a script to generate many user accounts, but there is no incentive to do this if they don't have an easy way to spam people with user accounts.
Comment: exactly - even just asking for an email address and password can be a barrier to entry.  make it easy for people to get in and then verify that they are a legitimate user later with a simple verification email.
Answer: First, you should find out why CAPTCHAs are placed in websites. CAPTCHA is a way to filter the requests from suspicious visitors (robot). So the reason is about "security" itself.
And then about UX concern, "Does it provide a good experience?" The answer is NO. It's very frustrating when I visit a register page at first time, I have to solve the CAPTCHA. Sometimes users are difficult to solve the text, or user mistakenly types the text. It can decreases your "conversion" for your next step.
So, combining the UX and security concern, let follow how Google & Facebook did. They're very user friendly. When login/register, there are no CAPTCHA displayed. But when you're trying to submit the form brutally or you failed to login using password, it shows the CAPTCHA. So the CAPTCHA is showed when an unusual activity detected. It's your security time. The conclusion what they did is: User-friendly:  ✓ YES, Secure: ✓ YES


Android TextInputLayout with EditText in ScrollView hides hint on focus

Question: if I focus a EditText within a ScrollView this happens (thats fine):

Then, I focus the EditText below and refocus EditText from picture one, then this happens:

The hint is not shown or badly (depending on scrollview).
Part of the solution:
The Scrollview sees that I want to focus the EditText but not the surrounded android.support.design.widget.TextInputLayout element. Therefore it does not care if the hint is being shown.
How to fix?
My XML (basically a scrollview with some linearlayouts containing android.support.design.widget.TextInputLayout with EditTexts):
<ScrollView
            android:layout_width="match_parent"
            android:fadeScrollbars="false"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:orientation="vertical"
                android:layout_height="match_parent">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:orientation="horizontal"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:weightSum="9"
                    android:descendantFocusability="beforeDescendants"
                    android:layout_height="match_parent">

                    <TextView
                        android:layout_width="0dp"
                        android:layout_weight="1"
                        android:text="1"
                        android:gravity="center"
                        android:layout_height="match_parent" />

                    <android.support.design.widget.TextInputLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="4">

                        <EditText
                            android:layout_width="match_parent"
                            android:layout_weight="1"
                            android:maxLines="1"
                            android:hint="hint1.1"
                            android:inputType="numberDecimal"
                            android:layout_height="match_parent" />

                    </android.support.design.widget.TextInputLayout>

                    <android.support.design.widget.TextInputLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="4">

                        <EditText
                            android:layout_width="match_parent"
                            android:maxLines="1"
                            android:inputType="number"
                            android:hint="hint1.2"
                            android:layout_height="match_parent" />

                    </android.support.design.widget.TextInputLayout>

                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:orientation="horizontal"
                    android:weightSum="9"
                    android:layout_height="match_parent">

                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:text="2"
                        android:gravity="center"/>

                    <android.support.design.widget.TextInputLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="4">

                        <EditText
                            android:layout_width="match_parent"
                            android:layout_weight="1"
                            android:maxLines="1"
                            android:hint="hint2.1"
                            android:inputType="numberDecimal"
                            android:layout_height="match_parent" />

                    </android.support.design.widget.TextInputLayout>

                    <android.support.design.widget.TextInputLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="4">

                        <EditText
                            android:layout_width="match_parent"
                            android:layout_weight="1"
                            android:maxLines="1"
                            android:hint="hint2.2"
                            android:inputType="number"
                            android:layout_height="match_parent" />

                    </android.support.design.widget.TextInputLayout>

                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:orientation="horizontal"
                    android:weightSum="9"
                    android:layout_height="match_parent">

                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:gravity="center"
                        android:text="3"/>

                    <android.support.design.widget.TextInputLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="4">

                        <EditText
                            android:layout_width="match_parent"
                            android:hint="hint3.1"
                            android:maxLines="1"
                            android:inputType="numberDecimal"
                            android:layout_height="match_parent" />

                    </android.support.design.widget.TextInputLayout>

                    <android.support.design.widget.TextInputLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="4">

                        <EditText
                            android:layout_width="match_parent"
                            android:layout_weight="1"
                            android:hint="hint3.2"
                            android:maxLines="1"
                            android:inputType="number"
                            android:layout_height="match_parent" />

                    </android.support.design.widget.TextInputLayout>

                </LinearLayout>

            </LinearLayout>

        </ScrollView>

Comment: try this code..
`your_scrollview.post(new Runnable() {
            @Override
            public void run() {
                your_scrollview.smoothScrollTo(0, your_EditBox.getBottom());
            }
        });`
Comment: i think it is shown, but you can't see cuz scroll view is scrolled.
Comment: Yes. Is there a way to make the scrollview scroll properly?
Comment: I wrote that code based on your answer and it works like a charm!
Thank you, @sourabh!
`EDITTEXT.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    scrollView.post(new Runnable() {
                        @Override public void run() {
                            scrollView.smoothScrollTo(0, textInputLayout.getTop());
                        }
                    });
                }
            }
        });`
Answer: Use this code to scroll to proper position of your edittext view,
your_scrollview.post(new Runnable() {
@Override
 public void run() {
       your_scrollview.smoothScrollTo(0, your_EditBox.getBottom());
 }
});


connecting to a transfer switch

Question: I have a 35KW Wacker diesel generator. It has 3 x 240V 3 prong - 10, 20 and 30 amp service. it also has a 4 wire 3 prong 125/250 locking (center ground) outlets of 50 amp.
My question is how do I connect that to my 20K transfer switch (240V 4 prong) inlet. At 50 amps, the most I can get out of 240V is 12KW, right? I'm thinking to rewire the generator with 100 amp service - is that feasible.  I need the whole 20KW to drive our electrical needs.  Peak is actually a bit more than that...
Comment: At 35kw the generator should be able to supply ~145 amps the question is this the peak load of the generator? I would think it should be able to provide 100a but cord and cap for the most part are limited to 30a this is probably why it is wired this way. A permanent wiring method would allow for the larger wiring you need.
Comment: Would using a suitably rated pin and sleeve connector and inlet pair be an option for such a fat hookup? (NEMA plugs being limited to 50A as they are)
Answer: For a generator of that size, the primary connection would not be through those convenience outlets, but rather directly to lugs sized for the cables required. If this wasn't the primary use of the generator, and you wanted an easily detachable connection, and 50 amps was sufficient, then you could use the 4-conductor receptacle with a cable.
Your model sounds like the G50. See page 34 of that manual:

3.13
  Connection Lugs
See Graphic: wc_gr002611
The customer connection lugs (r) are located on left at the bottom of the panel behind a hinged door. The lugs provide connection points for attachment of outside loads.
  A large label like the one shown in section Terminal Connections is attached to the inside of the terminal door. It shows the correct terminal connections for selected voltages.
  Connections to the lugs should be made by running the power cables up under the lug door in the bottom of the panel and into the lug. Use a 3/8 in. Allen wrench to tighten cable connections in place.
Answer: I'm confused as I thought all 240 volts had 4 prongs.  I'm thinking you may be receiving power from one power leg rather than both, something to look into.  If you get the correct connector straight, you may want to consider an Interlock rather than a transfer switch.  I originally was going with a Transfer Switch but decided on an Interlock.  With a simple Interlock device, you power whatever you wish in your breaker panel by turning the breakers on, careful not to overload the generator, plus it's less expensive.  The Interlock prohibits you from having the Main Breaker on when generator is on.  With Transfer Switch, you power only the selected breakers that are wired to it.  Lastly, when running 240 volts, the generator should be balanced, that is, not excessive wattage on one power leg versus the other.  Just bought a watt meter to help with the balance, and the watt meters are also available at Reliance.  I got the one for 30 amps and couldn't locate one any place else.  Special order for exterior use but mine was shipped same day ordered.
Comment: There is lots of good stuff here, but it doesn't really answer the question the OP asked....

connecting to a transfer switch


JTable : how to align data in the center or how to set row background color alternate

Question: How can I set the row background color in  JTable and also align the data to the center.The JTable1 is dynamic. JTable uses defaultTableModel for setting the data. I want to if i%==0 than background color is #Color.GRAY else #Color.WHITE I read about render class but can not understand about renderer class
import java.awt.Dimension;
import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

class FacultyList extends JPanel {

    static DefaultTableModel dm;
    JTable table;
    JScrollPane jsp_table;
    static Connection conn;
    static Statement stmt;
    static ResultSet rs;

    public FacultyList(Connection c) {
        conn = c;
        String col_name[] = {"S.No.", "Name", "Father Name", "College ID",
            "Gender", "Date of Birth", "Branch", "Contact No."};
        dm = new DefaultTableModel(null, col_name);
        table = new JTable(dm);
        table.getTableHeader().setFont(new Font("Goudy Old Style", Font.BOLD, 15));
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.getColumnModel().getColumn(0).setPreferredWidth(50);
        table.getColumnModel().getColumn(1).setPreferredWidth(150);
        table.getColumnModel().getColumn(2).setPreferredWidth(150);
        table.getColumnModel().getColumn(3).setPreferredWidth(125);
        table.getColumnModel().getColumn(4).setPreferredWidth(50);
        table.getColumnModel().getColumn(5).setPreferredWidth(125);
        table.getColumnModel().getColumn(6).setPreferredWidth(225);
        table.getColumnModel().getColumn(7).setPreferredWidth(150);
        jsp_table = new JScrollPane(table);
        jsp_table.setPreferredSize(new Dimension(975, 520));
        addRowTable();
        add(jsp_table);
    }

    public static void addRowTable() {
        try {
            int a = dm.getRowCount();
            int i = 0;
            while (i < a) {
                dm.removeRow(0);
                i++;
            }
            String fac = "Faculty";
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
            rs = stmt.executeQuery("SELECT NAME, FNAME, CLG_ID, GANDER, "
                    + "DOB, BRANCH, CONTACT FROM PROFILE "
                    + "where I_AM = '" + fac + "'");
            int count = 1;
            while (rs.next()) {
                String s[] = new String[8];
                s[0] = "" + count;
                s[1] = rs.getString(1);
                s[2] = rs.getString(2);
                s[3] = rs.getString(3);
                s[4] = rs.getString(4);
                s[5] = rs.getString(5);
                s[6] = rs.getString(6);
                s[7] = "" + rs.getLong(7);
                count++;
                if (i % 2 == 0) {
                } else {
                }
                dm.addRow(s);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Comment: please where did you read about Renderer - (I read about rander class but can not understand about rander class)
Comment: on this site or java oracle doc
Answer:
on this site or java oracle doc

TableCellRenderer is just about painting, is statics painting based on settings in XxxTableCellRenderer, isn't interactive, is about painting illusion,
painting in XxxTableCellRenderer is quite intesive and is invoked from all key and mouse events, methods implemented in rellated APIs
it could be separate definition for JTable or separate class thats returns rulles, painting definitions for JTables view
JDBC isn't good place to set or define the Renderer, about add a new data from database to DefaultTableModel,
ResultSet.CONCUR_UPDATABLE could not be set for JTable, is snapshot from ResultSet, it hasn't any action back to database
why is returns from JDBC restricted to String s[] = new String[8];, set data typed correctly by override getColumnClass
set alignment in Renderer (data typed returns alingment by default), e,g, by cast to JLabel, then all methods implemented in JLabels API can be used there
by default there are used prepareRenderer, getTableCellRendererComponent, both for whole JTables view and many various attempts for Renderer applied just for the concrete Columns
Answer: You could use a custom renderer to do this. It can be done as follows :
 table1 = new JTable(){

public Component prepareRenderer(TableCellRenderer tcr, int row,
    int column) {
    Component c = super.prepareRenderer(tcr, row, column);

    if (isRowSelected(row)) {

        c.setForeground(getSelectionForeground());
        c.setBackground(getSelectionBackground());

    } else {

        c.setForeground(getForeground());
        c.setBackground((row % 2 == 0) ? getBackground()
            : Color.lightGray);
    }

    int rendererWidth = c.getPreferredSize().width;
    TableColumn tableColumn = getColumnModel().getColumn(column);
    tableColumn.setPreferredWidth(Math.max(rendererWidth
        + getIntercellSpacing().width,
        tableColumn.getPreferredWidth()));

DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(SwingConstants.CENTER);
table1.getColumnModel().getColumn(column).setCellRenderer(rightRenderer);
return c;
    }

  };;

Comment: why collection of prepareRenderer and DefaultTableCellRenderer, can be confortly done in one of them, could be very CPU intensive to combine two XxxRenderers for one JTable, Column, Cell ...


Intuitively, why is the Euler-Mascheroni constant near $\sqrt{1/3}$?

Question: Questions that ask for "intuitive" reasons are admittedly subjective, but I suspect some people will find this interesting.
Some time ago, I was struck by the coincidence that the Euler-Mascheroni constant $\gamma$ is close to the square root of $1/3$. (Their numerical values are about $0.57722$ and $0.57735$ respectively.)
Is there any informal or intuitive reason for this? For example, can we find a series converging to $\gamma$ and a series converging to $\sqrt{1/3}$ whose terms are close to each other?
An example of the kind of argument I have in mind can be found in Noam Elkies' list of one-page papers, where he gives a "reason" that $\pi$ is slightly less than $\sqrt{10}$. (Essentially, take $\sum\frac1{n^2}=\pi^2/6$ as known, and then bound that series above by a telescoping series whose sum is $10/6$.)
There are lots of ways to get series that converge quickly to $\sqrt{1/3}$. For example, taking advantage of the fact that $(4/7)^2\approx1/3$, we can write
$$
\sqrt{\frac{1}{3}}=(\frac{16}{48})^{1/2}
=(\frac{16}{49}\cdot\frac{49}{48})^{1/2}=\frac{4}{7}(1+\frac{1}{48})^{1/2}
$$
which we can expand as a binomial series, so $\frac{4}{7}\cdot\frac{97}{96}$ is an example of a good approximation to $\sqrt{1/3}$. Can we also get good approximations to $\gamma$ by using series that converge quickly, and can we find the "right" pair of series that shows "why" $\gamma$ is slightly less than $\sqrt{1/3}$?
Another type of argument that's out there, showing "why" $\pi$ is slightly less than $22/7$, involves a particular definite integral of a "small" function that evaluates to $\frac{22}{7}-\pi$. So, are there any definite integrals of "small" functions that evaluate to $\sqrt{\frac13}-\gamma$ or $\frac13-\gamma^2$?
Comment: Also, [this link](http://en.wikipedia.org/wiki/Wikipedia:Reference_desk/Archives/Mathematics/2013_March_6) might prove helpful.
Comment: For the same reason that $2\pi+e$ is so clsoe to $9$. :-)
Comment: Thank you for the link. Unfortunately, it's short on details, and I still don't fully understand how to conclude that $\gamma\approx\sqrt{1/3}$. I assume the Gaussian quadrature mentioned is the one that approximates $\int_{-1}^1 f(x)dx$ with $f(\sqrt{1/3})+f(-\sqrt{1/3})$ (rescaled as appropriate). I can use these ideas to approximate $\gamma$ with a series, but not one that is obviously close to $\sqrt{1/3}$.
Comment: @Lucian For attempts at why $2\pi+e$ is so close to $9$ please visit https://math.stackexchange.com/questions/1711437/an-integral-for-2-pie-9
Answer: From the continuous fraction expansion, the seventh convergent is
$$\gamma \approx \frac{15}{26}$$
From the limit definition
$$\begin{align}
\gamma
&=
\lim_{n \to \infty} {\left(2H_n-\frac{1}{6}H_{n^2+n-1}-\frac{5}{6}H_{n^2+n}\right)} \\
&=
\frac{7}{12}+\sum_{n=1}^{\infty}\left(\frac{2}{n+1}-\frac{1}{3n(n+1)(n+2)}-\sum_{k=n(n+1)+1}^{(n+1)(n+2)}\frac{1}{k}\right) \\
&=\frac{7}{12}-\frac{1}{180}+\sum_{n=2}^{\infty}\left(\frac{2}{n+1}-\frac{1}{3n(n+1)(n+2)}-\sum_{k=n(n+1)+1}^{(n+1)(n+2)}\frac{1}{k}\right) \\
&=\frac{26}{45}+\sum_{n=2}^{\infty}\left(\frac{2}{n+1}-\frac{1}{3n(n+1)(n+2)}-\sum_{k=n(n+1)+1}^{(n+1)(n+2)}\frac{1}{k}\right) \\
\end{align}
$$
so
$$\gamma \approx \frac{26}{45}$$
Multiplying both approximations,
$$\gamma^2 \approx \frac{1}{3}$$
The origin of this limit definition is improving the convergence of Macys formula from $o(n^{-2})$ to $o(n^{-4})$ downweighting the last term, without additional fractions (https://math.stackexchange.com/a/129808/134791)
In fact, the convergent approximation is not necessary.
Given $$\gamma \approx \frac{26}{45}$$
we have
$$3\gamma^2\approx3\left(\frac{26}{45}\right)^2=3\frac{676}{2025}=3\frac{676}{3\cdot675}=\frac{676}{675}\approx 1$$
which also yields
$$\gamma^2 \approx \frac{1}{3}$$
Towards proving that $\gamma < \frac{1}{ \sqrt {3} }$, we may take one more term out of the summation:
$$\gamma \approx \frac{7}{12}-\frac{1}{180}-\frac{1}{2310}=\frac{4001}{6930}<\frac{1}{\sqrt{3}}$$
Answer: I have an interesting approach. The Shafer-Fink inequality and its generalization allow to devise algebraic approximations of the arctangent function with an arbitrary uniform accuracy. By a change of variable, the same holds for the hyperbolic arctangent function over the interval $(0,1)$ and for the logarithm function over the same interval. For instance,
$$ \forall x\in(0,1),\qquad \log(x)\approx\frac{90(x-1)}{7(x+1)+12\sqrt{x}+32\sqrt{2x+(x+1)\sqrt{x}}}\tag{A} $$
and $\approx$ holds as a $\leq$, actually. We have
$$ \gamma = \int_{0}^{1}-\log(-\log x)\,dx \tag{B}$$
hence:
$$ \gamma\leq 1-\log(90)+\int_{0}^{1}\log\left[7(x+1)+12\sqrt{x}+32\sqrt{2x+(x+1)\sqrt{x}}\right]\,dx\tag{C}$$
where the RHS of $(C)$ just depends on the (logarithms of the) roots of $7 + 32 x + 12 x^2 + 32 x^3 + 7 x^4$, which is a quartic and palindromic polynomial. The numerical approximation produced by $(C)$ allows to state:
$$ \gamma < 0.5773534 < \frac{\pi}{2e}.\tag{D}$$
Actually $(A)$ is not powerful enough to prove $\gamma<\frac{1}{\sqrt{3}}$, but we can achieve that too by replacing $(A)$ with the higher-order (generalized) Shafer-Fink approximation.


Will I have the option of allowing dual boot during installation?

Question: Heard about this, and immediately decided to get Ubuntu. I'm not interested in running Ubuntu alongside Windows, 'cause yeah. I just had one doubt, I'm currently downloading Ubuntu 11.10 32 bit. I've seen around the internet, that there's an option to dual boot. I've never done any of this in my life, and obviously, first time chills. So when I download Ubuntu, I understand I'm supposed to put it on a CD or a USB? Then try out this CD, etc etc etc. The question is, in all of this process, will I ever have the option of allowing dual boot? Or do I have to go around downloading what I see is called "Wubi" too?
Deeply appreciated.
One more minor thing, after installing Ubuntu and living happily ever after, will everything I have currently in my laptop get deleted? Pictures, data, games, everything? Or transformed to be supported on Ubuntu?
Thanks, if answered.
Happy new year!
Comment: I'm confused with your question. You said you don't want to run Ubuntu alongside Windows, then you ask if you will have the option to dual boot? Well the answer is yes, you will have this option if you install Ubuntu alongside Windows, even if you don't want to do that...
Comment: **Also**. If you're looking for "zero commitment" installation of Ubuntu (ie it can be uninstalled easily from Windows), you should definitely use the [windows installer (nicknamed "Wubi"](http://www.ubuntu.com/download/ubuntu/windows-installer).
Comment: When you install Ubuntu via CD or USB, it will ask you whether you want to install alongside Windows. All files and apps on your Windows partition will still be there. You'll just be asked whether to use Ubuntu or Windows at boot time. **As for the question**, it seems to be a duplicate of [this one](http://askubuntu.com/q/1366/24694). No detailed answers to that question, unfortunately...
Comment: desgua is right. I was just typing an answer, when I encountered the same problem.
Answer: Yes, the graphical installer will present you with an option to keep Windows. What will happen is that you're asked how much space of the harddisk Windows should have access to, and how much Ubuntu should use. That's just a slider and you can choose 50%, for instance. You should be aware that while Windows is not capable of reading Ubuntus data, Ubuntu is capable of reading and writing to Windows' file system.
The difference between Wubi and a normal install in that regard, is that Wubi installs do not resize the Windows file system, but creates a folder in it where Ubuntu can be "installed". If you've heard of ISO images that's used instead of CD-ROM discs, that is the same type. Instead of simulating a CD-ROM in a file, wubi simulates a harddisk for Ubuntu to use. But this also means Wubi installs usually are less efficient and might also be less stable. A normal install is preferred, and is very easy to do. Just follow the onscreen instructions and you shouldn't have any difficulties.
But please do pay attention. For instance, if you choose not to keep windows, it cannot be undone afterwards. So make sure before you click. :)
Comment: Your personal files will **only** be kept and not be deleted if you chose an *"Intallation alongside Windows"*.
Comment: You could back up your files.
Answer: Installing from a CD or USB stick will still allow you to install side-by-side with Windows if you want.  There are instructions here:
http://www.ubuntu.com/download/ubuntu/download
If you click "Show me how" under Step 4 ("Install it!") you will see that one of the questions asked during install is whether or not to erase the entire disk or install alongside an existing operating system.
Some settings can be imported from a Windows partition if you perform a side-by-side install with Windows, but your documents and files will not be copied or moved automatically.  You should back up your important files and copy them to your new Ubuntu installation once it is completed.


NoMethodError in PublicBundlesController#show

Question: In my web app a public_bundle has_many cards and a card belongs_to a public_bundle. I added the associations for this however, when I try to create a new public bundle I get a nothemod error saying undefined method 'cards' for the public_bundle.
Models:
class User < ActiveRecord::Base
   has_secure_password
   has_many :cards, through: :public_bundles
   has_many :cards, through: :bundles
   has_many :bundles
   has_many :public_bundles
end

class PublicBundle < ActiveRecord::Base
   has_many :cards
   belongs_to :user
end

class Card < ActiveRecord::Base
   belongs_to :user
   belongs_to :public_bundle
   belongs_to :bundle
end

Controllers:
class CardsController < ApplicationController
def new
    @card = current_user.public_bundles.cards.new
end

def create
    @card = current_user.public_bundles.cards.new(card_params)
    if @card.save
        redirect_to '/'
    else
        render @public_bundle
    end
end

private
def card_params
    params.require(:card).permit(:name, :description, :image)
end

class PublicBundlesController < ApplicationController

def show
    @public_bundle = current_user.public_bundles.find(params[:id])
    @public_bundle_edit = current_user.public_bundles.find(params[:id])
    @card = current_user.public_bundles.cards.new
    @cards = @public_bundle.cards.all
end

private
def public_bundle_params
    params.require(:public_bundle).permit(:name)
end

View:

        <%= form_for @card do |x| %>
            <%= x.text_field :name, :placeholder => " New Card Name", :style => "height:30px; width:530px; border:#ff4d4d solid; margin-top:14px; padding:5px; margin-left:14px; background-color:#eff5f5;" %>
            <%= x.text_field :image, :placeholder => " New Card Image (Optional)", :style => "height:30px; width:530px; border:#ff4d4d solid; margin-top:14px; padding:5px; margin-left:14px; background-color:#eff5f5;" %>
            <%= x.text_area :description, :placeholder => " New Card Description", :style => "height:30px; width:530px; border:#ff4d4d solid; margin-top:14px; padding:5px; margin-left:14px; background-color:#eff5f5;" %>
            <%= x.submit "✔", :style => "height:40px; width:40px; margin-top:10px; border-radius:100%; font-size:20px; background-color:#cce0ff; cursor:pointer; margin-left:270px;" %>
        <% end %>

Comment: Add the error stack trace please.
Comment: I'm sorry I'm not familiar with that term @ArupRakshit
Answer: When you generate a new @card instance variable that way, Rails doesn't know which public bundle is going to be associated with the new card.
I'm sure there's a more efficient way to do this, but you could try this in the cards controller:
def new
  @public_bundle = PublicBundle.find(params[:id])
  @card = @public_bundle.cards.build
end

def create
  @public_bundle = PublicBundle.find(params[:id])
  @card = @public_bundle.cards.build(card_params)
  @card.user_id = current_user.id
  if @card.save
    redirect_to '/'
  else
    render @public_bundle
  end
end


Knockout.JS: Bind change event of select to another UI attribute

Question: I'd like to make the following inputs visible only if the database property is selected (on Bootstrap change event). Is there an elegant and effective solution in Knockout JS to do it inside HTML and if not then what would be the JavaScript way?
<select id="db" class="form-control" data-bind="value: database, valueUpdate: 'change'">
    <option disabled selected> -- select an option -- </option>
    <option>MySQL database format</option>
    <option>PostgreSQL database format</option>
    <option>Other format</option>
</select>

Address :
<input type="text" class="form-control" id="address" data-bind="visible: database">
Port :
<input type="text" class="form-control" id="port">

I'm thinking about using something like data-bind="visible: typeof database != 'undefined'", but such expressions with trying to access database throw Uncaught ReferenceError: database is not defined. Approach with jQuery doesn't work either.
Answer: Store your options in an array and bind them to the select input via the options binding. To store the selected value, use (your existing) database observable. Based on that observable, you can show your form fields when the database observable has an selected option (or hide them, if not).
also, use the optionsCaption binding to show a "please choose" option. otherwise, you need to manually deal with filtering that dummy option out.

function viewModel(){
  this.databaseOptions = ko.observableArray(["MySQL database format", "PostgreSQL database format", "Other format"]);
  this.database = ko.observable();
}

ko.applyBindings(new viewModel());

<select id="db" class="form-control" data-bind="options: databaseOptions, optionsCaption: ' -- select an option -- ', value: database">

</select>

  Address :
  <input type="text" class="form-control" id="address" data-bind="visible: database">
  Port :
  <input type="text" class="form-control" id="port">


How to get response from server after posting data using RxJava

Question: I am trying to post data on server using retrofit2 and rxjava2 after data posted successfully on server I want to get response from server.I am using kotlin so how can I get server response in my app.
This is what I have done so far:
AddHero.kt
class AddHero : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_add_hero)

    addHero.setOnClickListener {

        if(hero.text.toString().equals("")){

            Toast.makeText(applicationContext,"Enter superhero name",Toast.LENGTH_SHORT).show()
        }
        else if(movie.text.toString().equals("")){

            Toast.makeText(applicationContext,"Enter movie name",Toast.LENGTH_SHORT).show()
        }
        else{

            saveData()
        }
    }

}

private fun saveData() {

    RetrofitClient.create().saveHero(hero.text.toString(),movie.text.toString())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe()

   }
}

RetrofitClient.kt
object RetrofitClient {

fun create():ApiService{

    val okHttpClient = OkHttpClient.Builder()
                       .connectTimeout(12,TimeUnit.SECONDS)
                       .readTimeout(12,TimeUnit.SECONDS)
                       .writeTimeout(12,TimeUnit.SECONDS)
                       .build()

   val retrofit = Retrofit.Builder()
               .baseUrl("https://www.example.com")
               .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
               .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
               .client(okHttpClient)
               .build()

    val service = retrofit.create(ApiService::class.java)
    return service
   }

}

ApiService.kt
interface ApiService {

@POST("createHero")
@FormUrlEncoded
fun saveHero(@Field("name") name:String,
             @Field("movie") movie:String):Observable<Hero>

}

Hero.kt
data class Hero (

        @SerializedName("name")
        val name:String,

        @SerializedName("movie")
        val movie:String
)

Someone please let me know what I am doing wrong or missing. Any help would be appreciated.
THANKS
Comment: So, you subscribed to the event, but you want to `doOnNext` if you are wanting to observe the response
Comment: So how can I Observe an event.
Comment: Have you looked at the RxJava docs on Observables? Something like `saveHero(..).onNext(...).subscribe()`
Comment: ``onNext()`` method is call under subscribe.
Comment: I'm not seeing that in your question
Answer: Your ApiService saveHero function returns Observable<Hero>, you should get your response in subscribe(onNext, onError), like this:
RetrofitClient.create().saveHero(hero.text.toString(), movie.text.toString())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ hero -> Log.d("AddHeroTag", hero.toString()) },
                { error -> Log.e("AddHero", error.message, error) })

And don't forget to check if your object is non-null
Comment: and also don't forget to make the api call a Single because it makes no sense for it to be an Observable
Comment: I want to know why you have added ``hero.toString()`` in ``Log.d`` statement will it get response from server I am sending response like ``Data added`` from server..
Comment: I added Log just for example, you don't need it, all you have to do is check your `Hero` object for nullability and do what you want with it
Comment: @Dig If your API only returns a String, you'll need to change `Observable` to a `Observable`


simultaneous pageloads: queries one by one?

Question: I use a PHP script which modifies a mysql database with multiple PDO queries. I was wondering, if two users load a page exactly the same time, will mysql first handle all the queries from user one in one go, or is there a risk that some queries from user one are handled, after which some queries from user two and then some more from user one?
I hope my question is clear. Many thanks in advance ;-).
Answer: Unless you use locks or transactions, you can't guarantee the order of execution of queries.  If you have multiple PHP scripts that are executed simultaneously, They will interact with the database unaware of each other.
For example, if a script is executed twice simultaneously and has two queries with a few seconds of space between them, script one's query 1 could be executed by the database before script two's query one, but script two's query 2 could be executed before script one's query 2.
From a higher level perspective, all of the queries are executed at the same time, but if there is something in the code that depends on the queries being executed in a specific order, you'd need to use a lock or transaction to make sure everything goes well.


Unable to install anything on Ubuntu 14.04

Question: Whenever I try to run any apt-get command, it gives me this error message:

dpkg: error: corrupt info database format file '/var/lib/dpkg/info/format'
E: Sub-process /usr/bin/dpkg returned an error code (2)

Please advice how to rectify this.
Comment: Is this a duplicate? It sounds like the error is happening in different files, which would mean that the fix could be completely different.
Comment: possible duplicate of [How do I rebuild a corrupt dpkg status file?](http://askubuntu.com/questions/4834/how-do-i-rebuild-a-corrupt-dpkg-status-file)
Comment: Try `sudo dpkg --configure -a`
Answer: Delete that "format" file, or if you're paranoid, back it up (move it to the RAM disk):
sudo mv /var/lib/dpkg/info/format /dev/shm

Mine only contains the number 1 and a carriage return (\n), resulting in a two byte file. You can create this from the command line:
sudo printf "1\n" > /var/lib/dpkg/info/format

If it fails, then simply restore your backed up "format" file over the top of the new one you created.
sudo mv /dev/shm/format /var/lib/dpkg/info/

Comment: Are there any risks with doing this? Could you [edit] to include them, and a rm command so that we are less likely to delete the wrong file?
Comment: If you're paranoid, then do this: sudo mv /var/lib/dpkg/info/format /dev/shm which will move the "format" file into the RAM disk, then create a new file using your favourite text editor (type in 1 then enter, then save your file). If it fails, then simply mv /dev/shm/format /var/lib/dpkg/info/ which will restore your backed up "format" file over the top of the new one you created.
Comment: Nope, I am not able to edit this file.

>mewtomat@MewtoMat:~$ sudo mv /var/lib/dpkg/info/format /dev/shm
>[sudo] password for mewtomat:
>mewtomat@MewtoMat:~$ sudo printf "1\n" > /var/lib/dpkg/info/format
>bash: /var/lib/dpkg/info/format: Permission denied
>mewtomat@MewtoMat:~$ sudo mv /dev/shm/format /var/lib/dpkg/info/
>mewtomat@MewtoMat:~$
Comment: Do "sudo nano /var/lib/dpkg/info/format" and then when the editor appears, type in "1" then Enter, then press CTRL+X, then "Y" and then Enter to save your changes.


ViewState issue

Question: We are using our website on Windows server 2003 with IIS 6 and also have a test server 2003 with IIS 5.
When I tested the page with ViewState on test server, it worked fine. But we tested on other server which is running IIS 6.It gave error. I compared web configuratioin file, it looked the same. There was the machine key and maximum length for view state. I've been spending couple days and still don't find it. Somebody can help me.
This error doesn't happen all the time. So I think the source code is not the problem.
Here is my error
[SerializationException: Member '_name' was not found.]
   System.Runtime.Serialization.SerializationInfo.GetElement(String name, Type& foundType) +7608149
   System.Runtime.Serialization.SerializationInfo.GetString(String name) +24
   SD.LLBLGen.Pro.ORMSupportClasses.EntityBase2..ctor(SerializationInfo info, StreamingContext context) +69
   PV.Data.Standard.EntityClasses.ClinicEntity..ctor(SerializationInfo info, StreamingContext context) +26

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle._SerializationInvoke(Object target, SignatureStruct& declaringTypeSig, SerializationInfo info, StreamingContext context) +0
   System.Reflection.RuntimeConstructorInfo.SerializationInvoke(Object target, SerializationInfo info, StreamingContext context) +108
   System.Runtime.Serialization.ObjectManager.CompleteISerializableObject(Object obj, SerializationInfo info, StreamingContext context) +273
   System.Runtime.Serialization.ObjectManager.FixupSpecialObject(ObjectHolder holder) +49
   System.Runtime.Serialization.ObjectManager.DoFixups() +223
   System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) +188
   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) +203
   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream) +12
   System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader) +968
   System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader) +291
   System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader) +392
   System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader) +404
   System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader) +392
   System.Web.UI.ObjectStateFormatter.Deserialize(Stream inputStream) +135

[ArgumentException: The serialized data is invalid.]
   System.Web.UI.ObjectStateFormatter.Deserialize(Stream inputStream) +199
   System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +297
   System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
   System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +37
   System.Web.UI.HiddenFieldPageStatePersister.Load() +113

[ViewStateException: Invalid viewstate.
    Client IP: 10.0.51.92
    Port: 51267
    User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; BRI/1)
    ViewState: /wEPDwUJODUyMDU5NzIxDxYOHgpQcmFjdGljZVBrKClYU3lzdGVtLkd1aWQsIG1zY29ybGliLCBWZXJzaW9uPTIuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OSRlMzE4OTAzNy0xOWY3LWRmMTEtOGQwNC0wMDFlMGI2ZTE4MWEeCENsaW5pY1BrKCsEJGQyYzg3OWI4LTE5ZjctZGYxMS04ZDA0LTAwMWUwYjZlMTgxYR4IUHJhY3RpY2UFBFBDTFAeBkNsaW5pYwUKVy4gUk9CSU5TTx4M..]

[HttpException (0x80004005): The state information is invalid for this page and might be corrupted.]
   System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +106
   System.Web.UI.ViewStateException.ThrowViewStateError(Exception inner, String persistedState) +14
   System.Web.UI.HiddenFieldPageStatePersister.Load() +217
   System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +105
   System.Web.UI.Page.LoadAllState() +43
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6785
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +242
   System.Web.UI.Page.ProcessRequest() +80
   System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21
   System.Web.UI.Page.ProcessRequest(HttpContext context) +49
   ASP.clinicinfo_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\9ca5f508\2be4cd8e\App_Web_sqt6xlmv.2.cs:0
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

Comment: Different database? Doesn't look ViewState related.
Comment: What are you doing with the viewstate in your code? I sense shenanigans and fraggles. Are you able to display any of your code at all? What happens if you take the maximum length off the ViewState in your config?
Comment: It is the same whether I put the maximum lenth..
Answer: I guess it's too obvious to say that your test server might serve it's purpose better if it ran on the same version of windows and IIS that your production server uses...  (so that's actually one suggestion...)
Otherwise, without digging into all of the possible issues that could be causing this, you can use IIS5 compatibility mode in IIS6.

R-click your website in IIS Manager
Service
check-mark the IIS 5 Isolation mode checkbox
Answer: Has the SD.LLBLGen.Pro.ORMSupportClasses.EntityBase2 class ever had a member named _name? Is there load balancing involved here?
It looks like the ViewState was created on a machine where the SD.LLBLGen.Pro.ORMSupportClasses.EntityBase2 class had a _name_ member, and then the ViewState is being interpreted on a machine where that class does not have a_name` member.
Comment: If the _name member is not there, the error has to happen all the time. But my problem is that it sometimes happens and sometimes doesn't happen.
Comment: Please edit your question to include this fact, and please include the full exception you see when the `_name` variable is not there.

ViewState issue


How to make ESLint understand that function is used in vue pug template?

Question: I have following vue component.
<template lang="pug">
button(@click="onLogout") Logout
</template>

When I run linter. Linter complains Warning:(9, 10) ESLint: 'onLogout' is defined but never used. (@typescript-eslint/no-unused-vars)
How do I make ESLint aware that onLogout function is used in the template?
Answer: you can use eslint-plugin-vue-pug. This plugin extends eslint-plugin-vue to support pug templates. After installing you must add the plugin to your eslint config:
module.exports = {
  extends: [
    'plugin:vue/vue3-recommended',
    'plugin:vue-pug/vue3-recommended'
  ]
}

The plugin only supports pug syntax that directly corresponds to html syntax. Some more details you can find on the description of rule no-pug-control-flow.
Comment: Do you know if this only works with Vue3? I tried to add `plugin:vue-pug/strongly-recommended` and it didn't seem to work.
Comment: it works well with my vue3 project!


How to decode incorrectly encoded data in mysql

Question: I have mysql table with "latin1_swedish_ci" collation. The table is used to store strings in multiple languages (russian, english, latvian). As a result, the strings stored in the table are incorrectly encoded.
For example: Двери is stored as Двери
I spent hours trying to find coding, which would allow me to properly store strings in new table with "utf8_general_ci" collation.
I used python to guess the decoding for the incorrect strings. I ran through tens of different encodings and the closest I got was
print "Двери".decode("latin1")
gives me ÐвеÑи, which is close but not exactly Двери
I was wondering if there are some variations in latin1 encoding, which would give me a proper encoding? And I would greatly appreciate if someone would suggest a way how to resolve similar problems in general?
Thanks.
Answer: When the coding used in the stored data doesn't match the coding defined for the column, you can first switch to a binary type, then back to the text type with the appropriate character set. For example, after backing up your database,
ALTER TABLE table MODIFY col varbinary(...);
ALTER TABLE table MODIFY col varchar(...) CHARACTER SET utf8;

Make sure your client also uses UTF8 for its connection to the server by (e.g.) issuing a SET CHARACTER SET utf8 command.
See also:

Changing character sets with ALTER TABLE (from the MySQL manual, §12.1.7. ALTER TABLE Syntax)
Converting Character Sets
Turning MySQL data in latin1 to utf8
Converting Database Character Sets
Answer: It's the very-similar-yet-different CP1252.
>>> print u'Двери'.encode('cp1252').decode('utf8')
Двери

Comment: Thanks a lot Ignacio. If I have a dump file and I want to perform the transformation you showed me on the whole file, how would I do that?
Comment: Depends on the charset used in the dump. If it's CP1252 then just read it as UTF-8 instead. If it's UTF-8 then just decode as UTF-8, encode as CP1252, then read it in as UTF-8.
Comment: I ran 'file dump.sql' to make sure that utf8 is used in the dump. after that I ran 'iconv -f utf8 -t cp1252 dump.sql'.
After successfully converting first few lines, iconv chokes: 'iconv: dump.sql:7:32: cannot convert'. Is it possible that some of the characters are corrupted, i.e. cant be properly converted from cp1252?
Comment: Yes, it may be entirely possible that the data within the database has been goofed around enough for it to actually be using multiple encodings. You will have to handle it line by line in that case.
Comment: Ignacio, so the only way to resolve this is just basically guessing the set of encodings, which could return correct string?
But how does browser handles this? if I just run a query and output the result, my web page (with charset set to utf8) renders perfectly fine.
Comment: Not for *everything* in the database. The things that don't, are in a different encoding.
Comment: Do you have ideas what similar codings could be used (other than cp1252)?
For string `пеноплаÑтовые потолочные плитки, изолÑциÑ, клеÑ` iconv returns `пенопла?
iconv: categories_dump.sql:1:15: cannot convert` for cp1252 and `пеноплас?
iconv: categories_dump.sql:1:16: cannot convert` for latin1. while it the proper string would be `пенопластовые потолочные плитки, изоляция, клея`

I am getting despaired here, because our database has around 4000 items.
Comment: That one is Latin-1. `>>> print u'пенопластовые потолочные плитки, изоляция, клея'.encode('utf-8').decode('latin1')`
`пеноплаÑÑовÑе поÑолоÑнÑе плиÑки, изолÑÑиÑ, клеÑ`


How to get the email message body with ActionMailer

Question: I am sending an standard email with Rails like this
<code>@mail = mail(to: registration.user.email, subject: "Registration Confirmation: #{@site.name}")
</code>
Now i need to get the message body (or html in this case) from the email. I tried the following but it does not work since it returns not the rendered email but rather the template (including ERB and Haml).
<code>@mail.body
@mail.body.raw_source
@mail.body.encoded
</code>
It seems surprisingly difficult to do this. I need the result that a persons sees when receiving the email.
Update
The ERB and Haml i saw was an HTML comment, that's why in the logs it looked like it logged ERB instead of a rendered tempalte. So @mail.body.encoded works fine.
Comment: If you simply want to have a look at the email body, I think you could use gems like [letter opener](https://github.com/ryanb/letter_opener).
Answer: I tried the accepted answer but it is showing the HEADER along with HTML. To get the HTML tags only I've used below code:
<code>@mail.html_part.body.decoded
</code>
Comment: This is better than the accepted answer. First it shows how to use `html_part` (and `text_part`) to get just one or the other. Second it shows `decoded` instead of `encoded`. If you're sending in emails in, say, Japanese, `encoded` gives you Base 64 gibberish, but `decoded` lets you write tests matching against Japanese text.
Answer: How about <code>@mail.body.encoded</code> (which should give you the result for which you seek)?
Comment: That still returns ERB and HAML in it instead of a rendered email. Like ""<!-- %h1= event_banner_text(@site)"
Comment: @TK-421 Is there a way to get the HTML content only without the header ? I can write a few lines to do so, but if a property exists it will be cleaner.


Do touch screens have a harmful psychological effect on people?

Question: The touch screen is a radical change in the control of machines. For centuries, machines were operated by physical buttons. Perhaps the most important aspect of user experience for a physical device is the sense of touch. Because physical controls offer tactile feedback at all steps of the process, allowing the user to know when they are about to activate a function, when they are activating the function, and when they have finished activating it, a major cognitive load is removed from the conscious mind.
In layman's terms, you know when your finger is on the button. You know when your finger is pushing the button down. You know when the button is down all the way and the button's inherent function is activated. There's a sense of security in knowing that only with a conscious effort to depress a button or flip a switch, will a machine begin a function. The touch screen turns all of this on its head.
I can rest my fingers on a keyboard and know that the keyboard won't suddenly start typing letters. I can put my finger on the trigger of a gun and not worry that it will accidentally discharge. I can rest my foot on the gas pedal without wondering if the car will suddenly lurch forward into the sap in front of me. I cannot run my fingers across an iPad to feel for buttons.
In fact it's worse than simply not having the sense of touch to guide me to the right button. Because today's touch screens do not have pressure sensitivity, even the slightest contact between my finger and the screen could end up sending a dirty joke to my boss instead of my friend or dial someone's number at 3AM. And this is where the real issue lies. Is this combined lack of tactile feedback and hyper-sensitive control making me a nervous wreck?
We spend so much time holding and using our smartphones and tablet computers that they inevitably condition our behavior in the rest of our life. If I am spending hours a day constantly on edge gingerly making sure my fingers daintily dance across the finnicky screen lest I do something disastrous, is it subtly sapping my sense of physical assertiveness? Such a device won't let you hold it the way you'd hold an old school phone or a hammer or a Glock, all of which invite sturdy, assertive grips. I have to make sure the ball of my hand doesn't accidentally hit something. I have to twinklefinger all of the controls rather than mashing my fingers to the right buttons.
To put it another way, if you live in a creaky old building and you have to constantly tiptoe around the house to avoid disturbing roommates, that's absolutely going to have an effect on the way you comport yourself physically elsewhere. Where you may have once confidently strutted, you now tentatively mince around. And research absolutely bears out the fact that your body language affects your confidence and emotions (smiling makes you feel happy, standing in a space-occupying way boosts your confidence while curling up makes you feel weak). There's no way this isn't having a similar effect.
Is there research that vindicates this theory? I'd love to get some substantial statistics to counter what I see as a pernicious trend.
Comment: "I can put my finger on the trigger of a gun and not worry that it will accidentally discharge."  I have to object to this example because it's endorsing something that you should never do.  Putting your finger inside the trigger guard before you're ready to fire violates one of the most important rules of firearm safety.
Comment: So when you want to select an icon on screen the ability to actually use your finger and touch that icon itself is *less* usable that having to hold a big soap-bar sized blob that is several feet away from the icon that moves a small arrow-sized item around on the screen and requires to to then press a piece of that soap-bar to register what you're interested in?
Comment: If this had been posted yesterday I would have thought it was a joke.
Comment: @NicolasBarbulesco: Yes, I removed it intentionally in an attempt to salvage the question away from being an angry rant and into more of an answerable question.
Comment: Ah, yes, the edit shows the original post is merely a rant. Voting to close.
Comment: @NicolasBarbulesco: No, that final line takes all credibility away from the question and was completely unnecessary.
Comment: I don;t think pressing buttons are centuries old, I can't think of how they would work without large mechanical advantage or electricity so difficult for me to see before mid 1800s. This [slide show](http://www.slideshare.net/billder/history-of-the-button-at-sxsw) suggests 1895. So buttons are a new way of interaction anyway
Comment: @Jon — In a way, yes. Especially when your finger is big and the icon is small.
Comment: @NicolasBarbulesco: In that case I would say the blame lies with the badly developed UI rather than the whole concept of Touch.
Comment: "subtly sapping my sense of physical assertiveness" = wut?
Comment: [The first edit by @JonW](http://ux.stackexchange.com/posts/37461/revisions) strongly denatures the message of @JClaussFTV.
Comment: @DA01 — Certainly not. The original message is a long and detailed question asking for research, concluding by one sentence of opinion.
Comment: @NicolasBarbulesco that one line changes the entire intent of the post, IMHO.
Comment: And 'rant' is perhaps not entirely accurate. Given the abuse of the thesaurus in this question, I'm thinking it's a clever troll post. ;)
Comment: Hmmm - if I'd seen that line I wouldn't have answered!
Comment: +1 for using the word "comport", but -1 for an overly-discursive question.
Comment: There are plenty of non-touch devices out there that could suit you. Personally I've been using touch-screen devices for years now and don't suffer from any of the problems you mentioned. Provided you're careful and precise in their operation, there is nothing wrong with touch devices.
Comment: "For centuries, machines were operated by physical buttons." - No, no they weren't. For less than a century were machines largely operated by physical buttons. Before that it was levers, wheels, etc because most machines used daily were very basic and powered almost completely by the operator.
Comment: Are we men or soap-bar shaped things?
Answer: There is little doubt that for most people a touch device has positive psychological effects.  Watch a small child using a tablet vs a computer, or even better, watch an autistic person interact with a tablet.  Watch their faces as it opens a new world to them, and you will be convinced.
Touch screens allow people to interact more naturally with devices as there is less of a separation between what you are seeing and what your interaction is. However there are some things that aren't as easy for advanced users to do on a touch screen than on a physical device.  And that is pretty much anything for which tactile feedback is important.
It is likely that safety switches will remain as physical switches for a long time, as it is much harder to accidentally activate one.  The same applies to keyboards where (for example) I type without looking at my keyboard, but I am slow and clumsy on a tablet screen keyboard as I have to look at it to see what I am typing.
Answer: Touch screens are really still at an early stage in the life and history of mobile devices, but touch (or haptic) feedback is at an even earlier stage of development (despite probably having been around for longer!), largely due to lack of funding, cost of prototyping and risk of non-widespread take up.
Rachel Hinman (currently at Nokia) is a thought leader in the world of mobile devices and natural user interfaces (NUIs), and she also mentions in her excellent book The Mobile Frontier that designers are much less proficient with touch/tactile feedback as a design language compared to say sight/sound as a design language.
There's certainly research going into haptics for mobile: Mobile hapticons - changing the surface of a smartphone to reflect emotions and, of course, in devices that do not even need touch at all like the Google Glass project - using voice as a NUI
We already have plenty of gestural input available and companies like Mitsubishi and Apple and others are researching detecting proximity of the digits without necessity for touch, to reintroduce hover to mobile devices, or interaction though other material layers, but again, it's still early days.
So there's no doubt that touch and tactile feedback is a desirable sensory input and that their introduction should help to improve interaction where it makes sense to do so.
But I don't think the current generation's interaction with flat glass is so frequent, long-lasting, or exclusive as to be conditioning or detrimental to human development and evolution (excepting the possibility of the rarest and most extreme of cases). Certainly I don't feel concerned having watched my own kids take to touch screens like ducks to water.
The larger question as to the effect of using mobile devices in a social environment and in preference to other tools, from a young age is however, quite a different matter, as outlined in an article in the New York
 Times a couple of days ago.
Comment: "Reintroduce" hover to mobile devices?
Answer: The basic premise of the question lies in the fact that phones have changed (almost instantly) from the tactile monsters to touch beings and that brings about a drastic shift in how people interact with them and they suddenly require more attention (idea very nicely put in the question).
Phones used to be our usual machines with tactile feedback at the core of their functionality (in the form of keypads). Now does this have a psychological effect? I guess it does. People need to be more aware of what they are doing on their phones than they used to be (due to plethora of features these days and touch aspect) and consequently less focused towards other activities they are performing at the same time. They lose the benefit that a tactile feedback used to give them. They used to learn certain combination of key-presses and perform them almost unconsciously sometimes.
There was certain aspect of perfect, no-nonsense, confidence involved in those activities and they knew at all times what they were doing.
This is no longer so. They need to see the screen to know what they are actually doing, and the phone is suddenly taking 100% of their attention while they are working on it. The more they are into their phones, the less they are available for their surroundings. Can you imagine having a touch based brakes or accelerator in a car and what would that do to a driver's psyche even if both of those tools are directly in front of his eyes?
Human psyche is programmed to be inquisitive about tools, learn to handle those tools, expect some feedback from them, and almost do all that in a passive manner. We are not programmed to look into those tools all the while we are using them, rather look outside them and see what effect they are having. This is not to say that we cannot be programmed to be reliant on touch in the coming generations, we definitely could be but touch will have to prove to be as efficient, as unobtrusive, and as reliable a tool as were its tactile forefathers.
That is one of the primary reasons I think that even today, all the major platforms still have some kind of a one-stop tactile button (on the side or bottom or top) in their phones so that people know what they need to press & where they need to press when they really need to. That button is meant to give those people a (psychological) peace of mind.
Answer: Starting with 'Direct Manipulation' a term coined in the 1980s by Shneiderman and then later redefined to be more appropriate for 'UX', states that DM's intention is to

Allow a user to directly manipulate objects presented to them, using actions that correspond at least loosely to the physical world.

This is made quite literal by the touch interfaces. You are touch the things you want to interact with, removing the cognitive overload of maneuvering peripherals like mouse and pointers and calibrating them. It is more natural, leading to the domain of NUI like Roger pointed out. I would not call the touch interface like tablets and phones NUI in the hardcore sense, but they are getting us a step closer.
John brought up an interesting point of autistic individuals using touch devices. I have spent quite some time with autistic individuals and can verify then interfaces like touch devices have the least amount of learning curve, again due to the implicit direct manipulation in the interaction.
I am not aware of any psychological implications/studies per se, but we can bring up the hardcore BB fanbase into consideration here. They are a group which prefer the hardware keyboard over the fancy touch keyboard, rendering it a question of choice rather than ability (on the other hand, people from the same group have migrated to touch devices and are happy too.)
And there is also the current movement going on for bringing haptic feedback to touch devices. The one pioneer whose work I like it Hiroshi Ishii from Media labs, he is the proponent of radical atoms movement. He is working on displays and interfaces which change in touch and feel, from soft and spongy to hard, etc. People will keep on working in different domains to keep exploring new modalities.
Touch tablets were first brought into academic circle by Mark Weiser and group at Xerox Parc in the 1989-1991, they introduced how we can use tablets and smart (phone) like devices. Going by that trajectory, you can imagine you will be using something radically different in the next 10 years :)
Answer: This psych effect is true, I have observed it… on me. I am reticent to having a touch screen phone, especially because my ear would touch it — the problems Apple had with its first iPhones prove me right. Sometimes, albeit rarely, my iPad clicks "on her own". So now I am more careful — and more nervous — with my iPad. I hold it with keeping my fingers far from the screen…
This is without doubt a negative side-effect of the touch interface.
Touch user interfaces have to be designed specifically to counter this side-effect. This is the case of the iPad, to a certain extent. Touch user interfaces have to give more feedback, visual and audio, about the buttons and the actions. They have to respect even more the sacred rule of UI which says that any user action must be easily cancellable.
Comment: @John — That would not prove anything. There many products having negative psych effects and being sold successfully. Telephones, computers, drugs, alcohol…
Comment: Individual people will have good and bad experiences, but I'd be wary of assuming that just because some individuals (yourself included) have issues thats means the same is true for a significant majority. Touch is a new technology in comparison with other interfaces, there will be teething problems, but that doesn't mean these issues are inherant in the whole premise.
Comment: @NicolasBarbulesco I think the massive sales in touch devices would prove your assumption incorrect.
Comment: "especially because my ear would touch it" = wut?
Comment: @JonW — "A significant majority" ? ;-)
Answer: I think it's indisputable that something is lost in eliminating tactile feedback completely; the market for tactile control surfaces for music-making and games testifies to this.  When you use an on-screen keyboard or control pad, you're constantly expending a certain amount of cognitive effort to control the position of your hands, which would be reduced or eliminated by tactile feedback from physical controls.  It's not unreasonable to assume that when you're making this effort, you can't engage quite as fluidly in the activity you're doing, and it may detract from how well you can perform that activity.
But then, if you want to perform a given activity at a virtuoso level, you can add the $20-$100 cost of the relevant peripheral to the cost of a tablet.  There are lots of specialist peripherals designed with this in mind, and the reason those peripherals exist is because the iPad market is so big, which in turn is because it isn't specialised.  It doesn't include any physical controls, but (unlike a notebook) it can do an entry-level impersonation of thousands of different physical controls, including ones that don't exist yet.
I do agree, though, that designers should be more mindful of the different physical reality of using a touchscreen.  It's still extremely common to see apps with too-small controls, poor consideration of where the user's hands will be, and (on phones) design that requires two hands where one should suffice.  An iPhone is still a physical object-- sometimes the problem is designers failing to understand that.
Answer: I was interested particularly on the effects on children and brain development. As you mentioned studies are hard to come by. Longitudinal studies take time and touch devices have only recently become commonly available.
The studies that have been done seem to vary in their responses. My understanding was overall research shows no significant benefit on children's development of using touch screen devices - and that they may take away time from other activities that have been shown to increase brain development.
Some potential benefits on development of touch/technology include:

Using technology to play learning games that can increase certain
areas of cognitive development/learning.
Children grow up with familiarity with digital.
Can allow children to explore and develop their personality.

Some of the potential negative impacts include:

Taking time away from other tasks that have an positive developmental impact.
tactile touch/play/social interaction Effect on attention: Some games
are created to encourage regular releases of dopamine, which could
effect attention on tasks that do not have the same effect.
Effects on the perception focusing on a screen flat screen that has little tactile feedback.

References:

No statistically significant difference between toddlers scores, but
those that played non-educational games had lower verbal test scores:
http://www.forbes.com/sites/robertglatter/2014/05/06/do-touch-screen-devices-have-an-adverse-effect-on-cognitive-development-in-toddlers/
http://online.wsj.com/news/articles/SB10001424052702304363104577391813961853988
http://www.wjla.com/articles/2013/12/tablet-study-brain-development-delays-in-kids-98512.html
http://www.bristol.ac.uk/sps/news/2010/107.html
http://www.sensomotorische-integratie.nl/CrisRowan.pdf
Comment: "but those that played non-educational games had lower verbal test scores" Lower than who? Lower than those who played educ games? Lower than those who played no games at all?
Comment: Only evidence I can find in the article states: "compared to children who engaged in other types of touch screen device games." Although the exact definition of "other" isn't provided.


What does it mean to XOR graph edges

Question: This question might be a bit trivial, but what does it mean to XOR graph edges? I can't seem to find anything on Google to describe how to XOR graph edges.
Given a Bipartite graph, what happens when I XOR the edge?
Thanks in advance.
Comment: Can you provide some context where you heard this term? Are you asking about graph theory, or computer graphics?
Answer: I've heard this term in relation to taking the product of two graphs. You end up taking an edge if it appears in exactly one of the two graphs. This is analogous to the Exclusive OR operation.
Look at the Alon paper: http://research.microsoft.com/en-us/um/people/eyal/papers/xor4.pdf

What does it mean to XOR graph edges


bad operand types for binary operator '>' in JAVA

Question: I get this error on my program and can't figure it out.
 public static void main (String[] args)

    int x = Integer.parseInt(args[0]);
    int y = Integer.parseInt(args[1]);
    int z = Integer.parseInt(args[2]);
    boolean isOrdered;
    System.out.println(x);
    System.out.println(y);
    System.out.println(z);
    asc = x<y<z;
    dec = x>y>z;
      If (asc || dec);
            isOrdered = true;
            System.out.println(isOrdered);
            Else
 isOrdered = false;
 System.out.println(isOrdered);

Comment: Is this really JAVA Code ? (It doesn't look like , for me) [The syntax is wrong and even note that Java is case-sensitive]
Comment: i just started learning java
Answer: you can't do this in java:
asc = x<y<z;
dec = x>y>z;

< and > accept only two operands.
instead, you should use:
boolean asc = x<y && y<z;
boolean dec = x>y && y>z;

EDIT: adding the correct if-else syntax:
  if (asc || dec) {
        isOrdered = true;
        System.out.println(isOrdered);
  } else {
        isOrdered = false;
        System.out.println(isOrdered);
  }

Comment: cannot find symbol
  symbol:   variable asc
  location: class Ordered
Comment: I just copied it from your original code, you don't declare asc and dec before that segment? if not, add `boolean` before both rows. also - take a look at the comments you got on your questions, there are some other java syntax errors in your code
Comment: i have a problem with the ''else'' now cannot be used without ''if'' but i wrote if
Comment: take a look at my last edit - your if-else statement was wrong (use {} and not ; and should have it lowercase)
Comment: didn't knew it was case sensitive. Thank you for the help it worked!
Answer: change
asc = x<y<z;
dec = x>y>z;

to
asc = (x < y && y < z);
desc = (x > y && y > z);

check the case of if and else, use {} for case and loops
Comment: cannot find symbol
  symbol:   variable asc
  location: class Ordered
the same for des


Proper way to plug in generator cord?

Question: I recently purchased a Champion portable 5500W generator for use with my home's existing transfer switch. It has the familiar 30A L14-30R circular twist lock connector on it, that I use with a 40ft male->female power cord. Recently when I had my local electrician over, he plugged it in for me, we test fired it and it worked well.
But now that I'm going to be using it on my own, I'm obsessed about safety, particularly the steps you take to connect it to the house. This is what the electrician did:

Plug female end of cord into power inlet box on house
Start generator, and let it come up to speed
Plug male end into generator
Go to transfer switch - make sure all branch breakers being fed by transfer switch are off (this will prevent sudden loads when moving mains to GEN position)
Flip main breakers, one at a time, to GEN position, from LINE
Flip branch breakers being fed by transfer switch, one at a time, to ON position

My concern really lies with steps 1-3, as there seems to be a lot of conflicting information on the net. My generator manual clearly states NOT to start the generator with loads connected. However, there is a warning in the box for the power cord that I got to connect the cord BEFORE starting the generator! So this information seems contradictory...
There is also a YouTube video here with a guy plugging in the cord BEFORE he starts the generator: https://www.youtube.com/watch?v=3_6ZpziBF-4
I'm actually starting to think either way may be OK, as long as the transfer switch mains are in the LINE position, as that will cut power off from the inlet box, right? So there would be no chance of overloading the genny at startup.
Any help you can provide is greatly appreciated. There is so much misinformation out there it's ridiculous.
Answer: Since you have a proper transfer switch, you can safely connect the cord to both the inlet and the generator. As long as the switches on the transfer switch are in the LINE position, there should be no load on the generator.
Once you start switching from LINE to GEN, then the generator will start picking up the loads.

NOTE:
I'm not sure how your transfer switch is wired, but there should be no requirement to turn off the circuit breakers in service panel. The switches on the transfer device should handle that.  They should actually break the circuit when switching between LINE and GEN.  The switches will typically have three positions (LINE, OPEN, GEN), so that the circuit is always open before switching to one of the power sources.

Think of your transfer switch as having six contacts, with a shuttle that moves between two at a time.

When it's in the LINE position, the load is being supplied by the power company.

Since there's no load on the generator, you can plug it in and start it up.

As you switch to generator power, the transfer equipment will open the circuit as you switch.

When it finally reaches the GEN position, the generator will pick  up the loads.

So as long as the transfer switches are in the LINE or OFF position, you should be fine to start the generator with the cord connected.
Comment: Okay, this confirms what I thought - no loads as long as the switches are in the line position. I guess I'll start the generator with the cord connected from now on. My transfer switch has no "OFF" position - just LINE AND GEN. I think it's an older design...hopefully that's still legal?
Comment: @rk15000 If it doesn't have an OFF position, turning off the breakers in the main panel *may* be required.  I'd assume that the switch has an internal "OFF" position, but without knowing more about the specific equipment I can't say for sure.

Proper way to plug in generator cord?


What is a good way to attach vent covers to ceiling vents in my basement?

Question: I recently bought a house and the basement was newly renovated.
The furnace and air exchangers have vents all along the ceiling of the basement suite. However the vent covers have a tendency to fall off the ceiling and onto the floor. Is there a good way to attach them to the ceiling?
The vent covers are similar to this
Answer: You have the wrong register cover for a ceiling. The one you have is a floor register, it just sits in place. You need a register like this one that screws into the ceiling.

This will also distribute the heat more evenly.
Answer: If you want to keep the existing registers you have, the easiest thing to do is to modify it so it can be secured to the ceiling.  Drill a hole in either side of the register, and then put the register up in the ceiling and mark the holes with a pencil. Remove the register, drill holes at the marked locations, install drywall anchors, and then screw the register in place.
Comment: I think I'm going to do it this way. I have 5 of them and I think they will do the job if they would only stay in place.


Leaking flat roof

Question: We have a "flat roof" (actually a very slight pitch) which is made from lead with folded seams.
It is rectangular, with a slight slope toward one long side where there is a gutter with a downspout at either end.
We had our first proper rain in a while today, and it was torrential (and is still going, and forecast to be continuous for the next 24 hours). I quickly discovered that one of the aforementioned downspouts was blocked, and that the blockage was under the footpath between the bottom of the downspout and the outlet to the street gutter, so I detached the bottom of the downspout so that the water could freely run onto the footpath.
There are several leaks into the rooms underneath the flat roof. I think these are exacerbated by the fact that the downspout was blocked, but obviously they are not caused by that.
How can I find the cause of leaks in this roof? Some of the seams have been flattened by people walking on them over the years -- would that cause leaks? There are no other obvious signs of damage, but I'm not sure what I'm looking for.
Answer: Lead makes a good roof, but finding leaks in one (or any flat roof) can be a real bear as the leak below may be a long way from the leak above.
If the folded seams are (as I suspect from your description) standing up, except where walked on and flattened, then yes, the walked-on parts would be prime suspects for leakage. Sometimes the the seams are all folded down and soldered, but standing seams are not usually also soldered (it's a fair bit of fiddly torch work.)
Look very carefully for cracks right next to the flattened seams. If you don't see any cracks, run a torch over the flattened area (trying to anneal the metal before reworking it) and carefully stand the seam back up - look for cracks on the lower side as well. If there are cracks you (or a lead roof specialist you hire) can clean the area and solder them.
If there is a wall above the flat roof area, also look very carefully at the flashing where the wall joins the roof - likewise look very carefully around any penetrations in the roof.
Some folks will no doubt tell you to reroof, since lead is "old-fashioned" and therefore also "old" - depending on the shape the roof is in this might be the right thing to do, but both lead and terne-plate (lead coated steel) roofs can last for hundreds of years, so it is well worth trying to fix it first, IMHO.
Comment: Only if you go nuts with it. So "At all" - yes; "much" - no. Don't work the point of the inner cone of the flame too close to the surface. You might take a bottle of water with you - toss a few drops on the area you've been heating - if it boils away, that's enough (in just heating before reforming.) When/if soldering the solder (which melts before the lead will) will tell you where you are at.
Comment: This was the problem! I used careful heat and pliers to gently bend all the flattened seams back to standing up straight. There have been several heavy rains since with no leaks at all. Thanks!
Comment: Great - the roof should be good for another couple of centuries now.
Comment: Do I need to worry at all about possibly melting the lead with a torch?
Answer: I'd argue the blocked downspout could have caused the leak.  Roofs only work in one plane. If water has a way to go around that plane, it can defeat the roof even though the roof is working probably.  In some cases, that means you are missing a flashing you should have but it can just a fact of life of gutters.
An example:

ice damming on a metal roof into a gutter can then lift the metal panel (whether because it isn't adhered correctly or because the ice breaks those connections) and ice on top of the sheathing.  When the ice melts, it might well leak through cracks between sheathing panels.  The metal panel didn't really fail
I have a low slope (2%) EPDM roof.  I have one scupper that likes to ice dam under the right conditions.  If I then get the right conditions (high sun on the roof but cold enough to keep the north facing scupper frozen), the roof can melt into the scupper faster than the ice clogged scupper can drain.  Water will back up to unflashed connections that aren't designed to see water and a leak develops.

The point is just that I'd fix your gutter situation and see what happens before I spent a lot of energy on the roof.
Comment: Your answer is appealing because of Occam's Razor (the simplest explanation tends to be correct), but how far do you expect a leak at the gutter could travel uphill away from the gutter? The leaks are in a few spots throughout the area under the roof, some of which are quite far (and thus elevated) from the gutter. The slope isn't extreme, probably only 2%, but still…
Comment: I don't know.  But capillary action between two tight surfaces could move water against gravity a significant distance.
Answer:
How can I find the cause of leaks in this roof?

I use a water hose to find roof leaks. I run it slow to start, and find the lowest spot I want to test. Sometimes I get my wife to observe from inside, but you can also find something to prop up the hose and go inside yourself. Let it run for at least 5 minutes on that spot. And, wait another 5 minutes or so to allow for it to seep inside. Then move on repeating this process until you locate a leak. Fix it before attempting to locate any other leaks, and make sure it no longer leaks. Oh, one more thing, mark the exact spot of the leak or the next time you go up there you may not be able to find it.

Leaking flat roof


Java web applet fails to start in Java 1.7.0_21

Question: We have Java applets deployed that have worked fine up until now. Actually, they continue to run fine on 32 bit machines, but on 64 bit machines they stopped yesterday.
The last line of the error is...
Match: Running JVM args mismatch: have:<-Dsun.java2d.noddraw=true -Dsun.java2d.noddraw=true> !satisfy want:<>
Here is the .jnlp file
<?xml version="1.0" encoding="utf-8"?>
<jnlp href="app.jnlp">

<information>
<title>App via Web Start</title>
<vendor>School</vendor>
<homepage href="http://www.url.edu"/>
<description>Application</description>
<description kind="short">Application</description>
<offline-allowed/>
</information>

<security>
  <all-permissions/>
</security>

<resources>
<j2se version="1.5+"/>
<property name="sun.java2d.noddraw" value="true"/>

<jar href="v0.41/CC.jar" main="true"/>

<extension name="pCSDT-Core" href="../Core/v0.41/Core.jnlp" />

<extension name="java3d-latest" href="../media/java3d/webstart/release/java3d-latest.jnlp"/>
<extension name="jogl" href="../media/jogl/builds/archive/jsr-231-1.x-webstart-current/jogl.jnlp"/>
<extension name="gluegen-rt" href="../media/gluegen/webstart/gluegen-rt.jnlp" />
</resources>

  <applet-desc name="pCSDT Applet" main-class="CC.CCGui" width="1200" height="800">
  </applet-desc>

</jnlp>

Apparently, it's the properties tag above that is the problem. I've tried removing it and then I get a null error. I have read where the .jnlp file needs to be signed (by placing a copy of the .jnlp file in the .jar), that hasn't fixed it.
Comment: Can you please provide a link to the instructions to copy the .jnlp file into the jar?
Comment: Which os r u using. If mac then it will not run as oracle does not produce 32 bit vm now
Comment: Hi - thanks! On 32bit Windows os, applets still load fine. On 64bit Windows I get the error above. Here is the link that I found and used (didn't work however)....
Comment: Sorry, I can't find the original link (I've looked many places), but here's a link that talks about signing a .jnlp file...http://www.coderanch.com/t/554729/JNLP-Web-Start/java/Signing-JNLP-JNLP-INF-directory
Comment: Possible duplicate of [Cannot launch applet using Java 7u21](http://stackoverflow.com/questions/16083405/cannot-launch-applet-using-java-7u21) or [Java applet stopped working after update to JRE 7u21](http://stackoverflow.com/q/16084324/418556).  Please search before asking questions.
Answer:
First at all : Test if other applet run on the browser. Check the installation from the Java site (Oracle)
The test fail, the content of the applet doesn't come. It it means that none applet can run on this browser : you need to install the correct jvm for the browser. For firefox or chrome you need a 32bit jvm.
If you have a IE64 then you need to install jvm 64. You can install both 32 and 64 without problem. That's what I have done on my machine :
Download the java 64 bits version
There is no way to avoid this step !
The test is ok, then the problem is in your applet. I have no idea of the cause, you have to search, look at the possible duplicates in the comment.

ps.: Please if step 2 solve the problem tag my answer. But if you fail in case 3, don't add comment on this question. Make research, open a chat or make a new question, stackoverflow should not be interractive.
Comment: We have multiple applets that used to work, and now they don't, giving the error above. I've tested in Chrome, IE and FF (the problem seems to be limited to Windows 64bit 7 & 8.
Comment: Check if you have the correct install with this link http://www.java.com/fr/download/installed.jsp
Comment: Thank you mki. I think we're especially concerned that potential users of the software with 64bit machines, without 32bit browsers installed will try to use the software and have it not load, and then give up. It used to work on 64bit machines just fine, and now it doesn't.


Initializing Camera and uploading file in Android through a website

Question: I have a asp.net website on a public server and it has a form. The button on the form should initialize a camera and when capture is done, the image file should be uploaded on the server to save it in the database.
We implemented this for Iphone though a webapp called QuickPic. We call this application through the javascript. The link below has the javascript code for the same.
http://www.resolved-technologies.com/php/cliqcliq-quickpic-upload-for-php/
We are looking for the similar thing for Android. For now whatever forum I visited in relation, they all point to developing a java based web app e.g. PhoneGap which is not an option for us.
So I have two questions:
Is there any native AndroidAPI which can be called via Javascript and enable to interact with the Camera and upload an image?
or
Is there any Android APP which can be called via Javascript for intitializing camera and upload an image?
Thanks,
Vijay
Answer: Here is some native Java code that may help you:
Use this to initialize the camera:
Intent intent2 = new Intent(v.getContext(), CameraView.class);
startActivityForResult(intent2, 1);

Here is CameraView:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.content.ContentValues;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class CameraView extends Activity {
private static final String TAG = "CameraView";

private SurfaceView preview=null;
private SurfaceHolder previewHolder=null;
private Camera camera=null;
private boolean inPreview=false;
private ImageView takePicture;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cameraview);

takePicture = (ImageView)findViewById(R.id.take_picture);

preview=(SurfaceView)findViewById(R.id.preview);
previewHolder=preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder
    .setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

preview.setOnClickListener(new OnClickListener(){

    @Override
    public void onClick(View arg0) {
        takePicture.setEnabled(false);
        camera.autoFocus(myAutoFocusCallback);

    }

});

takePicture.setOnClickListener(new OnClickListener(){

    @Override
    public void onClick(View arg0) {

        camera.takePicture(null, null, photoCallback);
        inPreview=false;
    }

});

}

@Override
public void onResume() {
super.onResume();
try{
    if (camera==null) {
      camera=Camera.open();
      camera.setDisplayOrientation(90);
      Camera.Parameters params = camera.getParameters();
      params.set("rotation", 90);
      camera.setParameters(params);

    }
}catch (Exception e){
    finish();
}
}

@Override
public void onPause() {
if (inPreview) {
  camera.stopPreview();
}
if(camera != null)
    camera.release();
camera=null;
inPreview=false;

super.onPause();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.options, menu);

return(super.onCreateOptionsMenu(menu));
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.camera) {
  if (inPreview) {
    camera.takePicture(null, null, photoCallback);
    inPreview=false;
  }
}

return(super.onOptionsItemSelected(item));
}

private Camera.Size getBestPreviewSize(int width,
  int height, Camera.Parameters parameters) {
Camera.Size result=null;

for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
  if (size.width<=width && size.height<=height) {
    if (result==null) {
      result=size;
    }
    else {
      int resultArea=result.width*result.height;
      int newArea=size.width*size.height;

      if (newArea>resultArea) {
        result=size;
      }
    }
  }
}

return(result);
}

SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
  try {
    camera.setPreviewDisplay(previewHolder);
  }
  catch (Throwable t) {
    Log.e("PictureDemo-surfaceCallback",
        "Exception in setPreviewDisplay()", t);
    Toast.makeText(CameraView.this, t.getMessage(),
        Toast.LENGTH_LONG).show();
  }
}

public void surfaceChanged(SurfaceHolder holder,
    int format, int width, int height) {
  Camera.Parameters parameters=camera.getParameters();

    parameters.setPictureFormat(PixelFormat.JPEG);

    camera.setParameters(parameters);
    camera.startPreview();

    inPreview=true;
}

public void surfaceDestroyed(SurfaceHolder holder) {
  // no-op
}
};

Camera.PictureCallback photoCallback=new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {

      Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
      Constants.currImageURI = uriTarget;
      OutputStream imageFileOS;

      try {

       imageFileOS = getContentResolver().openOutputStream(uriTarget);
       imageFileOS.write(data);
       imageFileOS.flush();
       imageFileOS.close();

       Toast.makeText(CameraView.this, "Image saved: " + uriTarget.toString(), Toast.LENGTH_LONG).show();

      } catch (FileNotFoundException e) {
       e.printStackTrace();

      } catch (IOException e) {
          e.printStackTrace();

      }
      setResult(RESULT_OK);
      finish();

}
};
    AutoFocusCallback myAutoFocusCallback = new AutoFocusCallback(){

       @Override
       public void onAutoFocus(boolean arg0, Camera arg1) {
        // TODO Auto-generated method stub
        takePicture.setEnabled(true);
       }};

}

and this will help you get the image to the server:
    public String uploadUserPhoto(File image) throws FileNotFoundException, IOException {

    Bitmap resized;

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, bos);

    byte[] data = bos.toByteArray();

    ByteArrayBody bab = new ByteArrayBody(data, "mobileimage.jpg");

    DefaultHttpClient mHttpClient;
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    mHttpClient = new DefaultHttpClient(params);

    try {
        HttpPost httppost = new HttpPost("http://com.yourserver");

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        multipartEntity.addPart("userfile", bab);

        httppost.setEntity(multipartEntity);

        HttpResponse response = mHttpClient.execute(httppost);
        String responseBody = EntityUtils.toString(response.getEntity());

        Log.d(TAG, "response: " + responseBody);
        return responseBody;

    } catch (Exception e) {
       Log.d(TAG, e.getMessage());
    }
    return "";
}


How to expose client_address to all methods, using xmlrpclib?

Question: I create little SimpleXMLRPCServer for check ip of client.
I try this:
Server
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
server = SimpleXMLRPCServer(("localhost", 8000))
def MyIp():
    return "Your ip is: %s" % server.socket.getpeername()
server.register_function(MyIp)
server.serve_forever()
Client
import xmlrpclib
se = xmlrpclib.Server("http://localhost:8000")
print se.MyIp()
Error
xmlrpclib.Fault: :(107, 'Transport endpoint is not connected')">
How make client_address visible to all functions?
Answer: If you want for example to pass client_address as the first argument to every function, you could subclass SimpleXMLRPCRequestHandler (pass your subclass as the handler when you instantiate SimpleXMLRPCServer) and override _dispatch (to prepend self.client_address to the params tuple and then delegate the rest to SimpleXMLRPCRequestHandler._dispatch). If this approach is OK and you want to see code, just ask!
I'm not sure how you'd safely use anything but the function arguments to "make client_address visible" -- there's no client_address as a bare name, global or otherwise, there's just the self.client_address of each instance of the request handler class (and hacks such as copying it to a global variables feel really yucky indeed -- and unsafe under threading, etc etc).
Comment: I am using the same approach. Subclass of SimpleXMLRPCRequestHandler and appending client_address to parameters of calling function.