How to add textBox to Winform dataGridView cells

Question: I want to add textBox to my column cells by for loop...
My code:
DataTable dt = new DataTable();

DataColumn dc;
dc = new DataColumn("No");
dt.Columns.Add(dc);
dc = new DataColumn("Item");
dt.Columns.Add(dc);
dc = new DataColumn("Available Stock");
dt.Columns.Add(dc);
dc = new DataColumn("Quantity");
dt.Columns.Add(dc);
dc = new DataColumn("Price");
dt.Columns.Add(dc);

// Define  rows
for (int i = 0; i < count; i++)
{
    string no = dtr.Rows[i][0].ToString();
    string item = dtr.Rows[i][2].ToString() + " " + dtr.Rows[i][1].ToString();
    string A_qty = dtr.Rows[i][3].ToString();
    string price = dtr.Rows[i][4].ToString();

    dt.Rows.Add(no, item, A_qty,"[i want to add text box here] " ,price);
}

dataGridView1.DataSource = dt;

I want to add textBoxes to 4th column and I want access that one by one.
Comment: It should already be leveraging the `TextBoxColumn`. What are you getting?
Comment: Its not working there's an error
Comment: The details of that error are pretty important to solving this, clearly. Edit your question with the error.
Answer: You can add textBox column to DataGridView instead and loop through DataGridView like
DataTable dt=new DataTable();

dt.Columns.Add("No",typeof(int));

dt.Columns.Add("Item",typeof(string));

dt.Columns.Add("quantity",typeof(int));

dt.Columns.Add("Price",typeof(decimal));

//Add row to the datatable

for (int i = 0; i < count; i++)
{

//Not Sure what dtr is you looping through

    string no = dtr.Rows[i][0].ToString();
    string item = dtr.Rows[i][1].ToString() + " " + dtr.Rows[i][1].ToString();
    string A_qty = dtr.Rows[i][2].ToString();
    string price = dtr.Rows[i][3].ToString();

    dt.Rows.Add(no, item, A_qty, price);
}

//Create New DataGridViewTextBoxColumn
DataGridViewTextBoxColumn textboxColumn=new DataGridViewTextBoxColumn();

//Bind DataGridView to Datasource
dataGridView1.datasource=dt;

//Add TextBoxColumn dynamically to DataGridView
 dataGridView1.Columns.Add(textboxColumn);

//Loop through DataGridView
 foreach (DataGridViewRow row in dataGridView1.Rows)

{

     //Do your task here
      string fourthColumn = row.Cells[4].Value.toString();

   }

Answer: Not sure. But hope this code will help you. Just add column of type textbox to your datatable.
DataTable table = new DataTable();
DataColumn col = new DataColumn("Name", typeof(TextBoxBase));
table.Columns.Add(col);


Testing a React Hooks component with Jest / Enzyme & Axios

Question: I have a react component that uses Axios to fetch data that is HomePage.js and Post.js to render it on the screen. I'm trying to write test cases for both of them. But everytime i try its failing could someone help me understand what i'm doing wrong in the test cases. Thanks
I'm new to testing and I know for the testing of components Any advice would be appreciated!
HomePage.js
import React, { useState, useEffect } from 'react';
import Post from '../../Components/Post/Post';
import axios from 'axios';

const HomePage = () => {

    const [posts, setPosts] = useState('');

    const url = 'https://jsonplaceholder.typicode.com/posts/1/comments';

    useEffect( () => {
        AllPosts();
    }, []);

    const AllPosts = () => {
        axios.get(`${url}`)
        .then((response) => {
            const allPosts = response.data;
            setPosts(allPosts);
        })
        .catch( error => console.error(`Error: ${error}`));
    }
    return (

            <Post className ="Posts" posts = {posts}/>

    )
}

export default HomePage;

HomePage.test.js

import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Post from './Post';

configure ({adapter: new Adapter()});

describe('<Post />', () => {
    it('Should render all the posts ', () => {
        const wrapper = shallow(<Post />);
        expect (wrapper.length).toBe(1);
    });
});

Post.js

import React from 'react';
import './Post.css';

const Post = (props) => {

    const displayPosts = (props) => {
    const  { posts } = props;

    if ( posts.length > 0) {
        return(
            posts.map( (post) => {
                return(

Name : {post.name}

 Email : {post.email}

 Body :{post.body}

                )
            })
        )
    }
}
    return (

            { displayPosts(props) }

    )
}

export default Post;

Post.test.js

import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Post from './Post';

configure ({adapter: new Adapter()});

describe('<Post />', () => {
    it('Should render all the posts ', () => {
        const wrapper = shallow(<Post />);
        expect (wrapper.find(Email)).toHaveLength(3);
    });
});

Comment: shallow ignores useEffect and shouldn't be used for this. A promise that axios returns isn't waited. Real requests shouldn't be performed in unit tests. Enzyme is inferior for testing functional components, React Testing Library makes better job.
Answer: i tried using mount and mocking get method not working as expected to get 100% coverage,
export default function HomePage (){}

it('axios mock', async () => {
    let wrapper;

    axios.get = jest.fn()
    jest.mock('Axios');

    const data = [
        {
          "userId": 1,
          "id": 1,
          "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
          "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
        }
      ]

      await act(async ()=> {
        await axios.get.mockImplementationOnce(()=> Promise.resolve(data))
        wrapper = mount(<HomePage />)
      })

    await expect(axios.get).toHaveBeenCalledTimes(1);
    wrapper.update();
    await expect(axios.get).toHaveBeenCalledWith('https://jsonplaceholder.typicode.com/posts?_limit=5')
    await expect(wrapper.find("Post").at(0)).toHaveLength(1)
    expect(toJson(wrapper)).toMatchSnapshot();

  })


How can I fix a cold and damp extension room?

Question: We recently bought our first house, a rather old 3-bed terraced house. The adjacent house has been empty for 4 years. The 3rd bedroom in my house is a single room extension I'm using as an office and it's always cold. We didn't get a survey (inspection). Our agent told me the house to his knowledge has never failed a survey. We did have specialists (contractors) evaluate & quote for free so have had full electrical safety check, roof inspection, damp inspection in extension & ground floor.
I've pushed some insulation into the corners of the roof/ceiling (slanted roof). There is a small plastic vent in the top of the room which says "do not cover." I've put glue along the PVC window frame as there were some holes in the paint and I wondered if this was creating a draft. When the heat is on, the rest of the house will be warm but when it cycles off within an hour my hands are numb. The wall next to the empty house in the extension sounds real hollow when I knock on it. We already had to damp-proof the ground floor wall on the empty house side as we had rising damp in that wall
Whilst in the attic I noticed on the back wall there are gaps in the mortar through which you can see outside. The bricks are very black where the wall ends between our attic and the empty house and some crumbled bricks have fallen out of an inner partial layer of bricks. Some bricks seemed a bit damaged. It's also possible to get around the end wall into the neighbouring attic (which isn't very well insulated) and obviously that house isn't being heated whilst vacant. Some of the beams have mould, and the roofer who came over had a look and said it will dry out after roof repair.
Should I replace and re-mortar the bricks? Could the empty neighbouring house be causing some of our insulation issues? If so, should I put up some kind of barrier or cover the gap between the walls of the attic, or are they supposed to have a gap between them? And is there a cheap way of making the extension warmer?
Comment: The wall between the two houses probably not insulated that well since they expected both to be heated, instead of one cold.  The attic floor should have good/better insulation, but the deck of the roof should open and have ventilation(outside air moves from bottom to top).  Would get second opinion on the mould, hoping it will go away does not make sense.
Comment: Wow, there are a lot of questions in here. If you'll take the [tour], you note that questions that focus on one thing at a time are the preference. Nobody will complain if you post multiple, focused questions.
Comment: A single room extension would also have 1 or 2 outside walls & be directly under its own separate roof space, if I'm reading this correctly. That's going to need a whole different level of insulation compared to the body of the house which has neighbours to both sides. Depending on age & style of terrace, your adjoining wall may only be a single brick, not doule course, no airgap, no insulation.
Comment: BTW, ***never*** trust an estate agent who claims no survey is needed. They want to sell the house, they don't give a monkey's if it falls down after that. It was **your** responsibility to get the survey & now you'll be paying for that lack of foresight. Surveys don't have a 'pass or fail', they have a list of remedial &/or preventative work on current or future concerns; which you use as leverage on the selling price.
Comment: Is it possible that the extension is the old sheds, coal storage areas very commonly found on the back of English terrace houses? If so, they might not be very thick walls and not insulated. I've seen 'finished' rooms which turned out to be half brick thick walls.
Answer: It sounds like you have at least two problems that contribute to the warmth (or lack of warmth) of a room.
First, this extension room needs to be connected to your heating system and it's unclear from the description whether this is the case. Older homes (based on spelling I'm guessing you're in the UK) probably have a boiler and radiator system, so you should have a radiator in this room (and place one there, if there isn't one yet).
Second, this room does not have a proper envelope - the brickwork, vapor barrier, insulation and finishing that helps houses keep the climate inside different than outside.

(Image taken from short video https://youtu.be/8VLX_dqybpA)
From the outside to the inside, this wall has bricks, an insect screen (optional), a damp drainage mat, house wrap, then metal studs with insulation between, then gypsum board for the wall surface. If there are holes in your bricks and mortar, those should be patched first before upgrading the wall insulation. All walls and the ceiling and roof of your extension need to be properly built and insulated, including the shared wall adjacent to the vacant house.
You can seek out an insulation contractor with a thermal camera, they will be able to pinpoint the spots in the wall and ceiling that need addressed because they show a different color on a thermal image. Such a contractor should also be able to recommend a type and R-value of insulation for your specific situation.


Getting the length of an array - Prints incorrect value

Question: I have an Array called arr. I am adding items to it ( arr.push(val) ) and it prints the value as 1 (arr.length) - It prints 1 when i add only 1 item.
but, when i add 2 values/items (arr.push(val)), i still get the result as 1 and not 2.
var arr=[];
arr.push(val);
console.log(arr.length);
console.log(arr);

When i add 1 value i get the output for console.log(arr); as One
When i add 2 value i get the output for console.log(arr); as One,Two (But the Length is printed as 1)
Why is this ? and how can i resolve this.
UPDATE
checkBox: function (val) {

var arr=[];
arr.push(val.name);
console.log(arr.length);
console.log(arr);

}

Comment: How do you "*add 2 value*"? Post the exact code.
Answer: You are re-instantiating your array every time you call that function. Thus it will only have the current value in. You should try:
var arr      = [],
    checkbox = function(val) {
        arr.push(val);
        console.log(arr.length);
    };

checkbox('hello');
checkbox('moto');

Comment: According to the problem description this is not causing the  issue because he can see both values...
Comment: Just looking at the lower source code section provided, I'm pretty sure that must be happening. In the upper case, you're right, arr only is initialised once.

Ideally a full copy of the code in context would be nice.
Comment: When i add 2 value i get the output for console.log(arr); as One,Two (But the Length is printed as 1) - doesn't sound to me like a reinstantiating error;)
Comment: Yes but the lower source code cannot be what is happening then, because if you try it, arr gets reset to [] each time, so there must be something slightly different going on, and for that we need the source code in the context of how it is used.
Answer: Probably you are pushing a string or an array into that array!
The following works:
arr.push("one","two"); // -> arr =["one","two"]

this will work too, but put only one element into the array
arr.push("one,two"); // -> arr =["one,two"] <- the first element is a string "one,two"

this would work in the same way as pushing a string into the array:
arr.push(["one","two"]); // arr = [["one","two"]] <- the first element is an array ["one,two"]

If it's a string, you need to split it first (e.g. when it's a name) and put the values into the first array using concat()
var a = [];
var name = "John Doe";
var b = name.split(" "); // creates an array ["John","Doe"]
a.concat(b);

Answer: Adding two elements to an array should always properly update it's length property, regardless of whether you add them one at a time or in a group.
The only way you could get a discrepency with the length is if you add the two values as an array or a single string, in which case there would only be 1 element in the original array, and that element would be an array containing 2 elements or a single string.
var blah = [];
blah.push('foo');
blah.push('bar');
console.log(blah.length); // 2

var boo = [];
boo.push('foo', 'bar');
console.log(boo.length); // 2

var baz = [];
baz.push(['foo', 'bar']);
console.log(baz.length); // 1

http://jsfiddle.net/EcHtU/


JS: using capturing with onclick

Question: I know when using addEventListener, you can add in another argument of true to tell it to not bubble and to use capturing instead.  Can this you tell onclick to use capture as well when using it instead of addEventListener?
Answer: Properties of elements like onclick are called IDL attributes. See the specification. When its setter is invoked, it adds the assigned function to the event handler map of the element. That precise name has a very specific meaning here: "event handlers" are:

Many objects can have event handlers specified. These act as non-capture event listeners for the object on which they are specified.

They always listen in the bubbling phase, never in the capturing phase. So, what you're looking for isn't possible.
In contrast, addEventListener adds an event listener, which has a slightly different official definition and can be either capturing or bubbling.
If you want to add a listener for the capturing phase, you must use addEventListener.

JS: using capturing with onclick


Android: User location without locationListener

Question: I would like to know if its possible to get the users location without the use of a LocationListener.
The reason why i ask is that my locationListener events are not being called.
public class LocationActivity extends Activity implements LocationListener{

    private LocationManager m_locationManager;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        LinearLayout content = new LinearLayout(this);
        content.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        content.setOrientation(LinearLayout.VERTICAL);
        content.setBackgroundColor(Color.TRANSPARENT);

        TextView infoLabel = new TextView(this);
        infoLabel.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        infoLabel.setTextSize(20.0f);
        infoLabel.setText("Initializing...");
        content.addView(infoLabel);

        try{
            m_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

            String provider = null;

            if ( m_locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
                provider = LocationManager.GPS_PROVIDER ;
                Log.d("Unity", "Using GPS");
                m_locationManager.requestLocationUpdates(provider, 0, 0, this);
            } else if(m_locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                provider = LocationManager.NETWORK_PROVIDER;
                Log.d("Unity", "Using Netword");
                m_locationManager.requestLocationUpdates(provider, 0, 0, this);
            } else {
                Log.d("Unity", "Provider Not available");
            }

        }catch(Exception ex){
            Log.d("Unity", "locatons error " + ex.getMessage());
        }

        setContentView(content);

    }

    public void onLocationChanged(Location location) {
        Log.d("Unity", "UserLocation Lat:" + location.getLatitude() + " Long:" + location.getLongitude());
    }
    public void onStatusChanged(String provider, int status, Bundle extras) {Log.d("Unity", "onStatusChanged");}
    public void onProviderEnabled(String provider) {Log.d("Unity", "onProviderEnabled");}
    public void onProviderDisabled(String provider) {Log.d("Unity", "onProviderDisabled");}
}

See this post for more info:
Android: Can't create handler inside thread that has not called Looper.prepare()
Modified to reflect mmeyer comments
Answer: First, you can check the last known location when you select the provider with LocationManager.getLastKnownLocation(provider) and see if it's not null and not too old.
Beyond that your code looks adequate. I suspect the issue might be that the 3rd param in your call to requestLocationUpdates says to only send updates if the location has changed by more than 100 meters. For most situations where youre running in debug and watching logcat, moving a hundred meters a second seems unlikely.
From the API docs:

The frequency of notification may be controlled using the minTime and
  minDistance parameters. If minTime is greater than 0, the
  LocationManager could potentially rest for minTime milliseconds
  between location updates to conserve power. If minDistance is greater
  than 0, a location will only be broadcasted if the device moves by
  minDistance meters. To obtain notifications as frequently as possible,
  set both parameters to 0.
Comment: Hmmm, I cant see how unity would muck with this given that it's still and Android Activity. I have code that does pretty much the same thing with no issues. The only real difference I see is that I ask for location updates from the onResume phase rather than onCreate...cant see how that would matter, but worth a quick hack to see.
Comment: So getLastKnownLocation is not null but still no updates. Are you aware of any other way i can get the current position with out using locationListener? Or is it the only way it can be obtained?
Comment: No, I dont think there is another way. getLastKnownLocation just gives you a fast way to get a location before you get any update, so the UI/user doesnt have to wait. But, I do still think the reason youre not getting updates is because your params ask for updates only when location has changed by more than 100 meters. What happens when you change the 3rd param to 0?
Comment: Modifying both parameters to 0 does nothing and getLastKnownLocation is over 24 hours old. Im calling this from the Unity Game engine. So its obviously screwing the the events some how. The view is open correctly it just those events are not firing. Thanks for your help with this.


Am I correctly finding the standard matrix?

Question:
Question:
Let $F: \Bbb R^3 \to \Bbb R^3$ be the linear transformation satisfying
  $F(1,0,1)=(-3,-3,1)$,$F(0,1,0)=(0,1,1)$, and $F(0,1,1)=(2,-2,1)$. Find
  the standard matrix $A$ of $F$.

My Approach:
I used a method that I haven't been taught, so I'm not sure if I am correct and allowed to do this. Can you guys see if this is acceptable.
Since:
$$F\begin{pmatrix}1\\0\\1\end{pmatrix}=\begin{pmatrix}3\\-3\\1\end{pmatrix}$$
$$F\begin{pmatrix}0\\1\\0\end{pmatrix}=\begin{pmatrix}0\\1\\1\end{pmatrix}$$
$$F\begin{pmatrix}0\\1\\1\end{pmatrix}=\begin{pmatrix}2\\-2\\1\end{pmatrix}$$
We want to find:
$$\text{standard matrix:}F\begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix}=?$$
So what I did was:

$$\therefore \text{standard matrix:}F\begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix}=\begin{pmatrix}3&0&2\\-1&0&-1\\-2&1&-1\end{pmatrix}$$
Is this method correct?
Comment: @JessePFrancis Is it better now? :)
Comment: @JessePFrancis Did that as well :)
Comment: @MSE, please consider converting image to text (the question, mainly), or it will not be searchable/may be flagged to close.
Comment: @JessePFrancis I don't know how to write that picture in latex, where there are two boxes beside each other. I have put the stuff I can in latex.
Comment: Just use array with {ccc|ccc} param for double matrices.
Comment: I found out what you calculated.
Answer: Your matrix does not map $(0,1,0)^t$ to $(0,1,1)^t$, so I believe it is wrong.
Instead you could use
$$
A X = Y \iff \\
A = Y X^{-1}
$$
where $X$ has the given argument vectors and $Y$ the corresponding image vectors, assuming the argument vectors are linear independent.
Applying the above I get
$$
X =
\left(
\begin{array}{rrr}
1 &0 & 0 \\
0 &1 & 1 \\
1 &0 & 1
\end{array}
\right)
\quad\quad
Y=
\left(
\begin{array}{rrr}
 3 & 0 &  2 \\
-3 & 1 & -2 \\
 1 & 1 &  1
\end{array}
\right)
$$
which leads to
$$
A=
\left(
\begin{array}{rrr}
1&0&2\\
0&1&-3\\
1&1&0
\end{array}
\right)
$$
The matrix you calculated is $B = X^{-1} Y$. It solves $X B = Y$.
Comment: +1 Hey, Did you mean F(A) ? how do I test my matrix?
Comment: okay ummm. First off all, is my method correct?
Comment: My book definition: Let $F:\Bbb R^n \to \Bbb R^m$ be a L.T. Then the standard matrix A for F is the unique m x n matrix such that: $$F(x)=Ax$$.
Answer: Let's check your solution,
So you got $T(1,0,0)=(3,-1,-2)$, $~T(0,1,0)=(0,0,1)$ and $~T(0,0,1)=(2,-1,-1)$
Now $T(1,0,1)=(3,-3,1)$
also $~T(1,0,1)=T(e_1+0.e_2+e_3)=Te_1+Te_3=(3,-1,-2)+(2,-1,-1)=(5,-2,-3) \not=(3,-3,1).$


How to stop Maybe from being passed into another function in Haskell

Question: I have already looked at this answer, but it is unclear to me how to apply it in my situation.
I have the following function:
designC :: DesignC -> Maybe CDef -> String
designC FirstString _ = "first_string"
designC SecondString _ = "second_string"
designC UnknownString c = getName c

The getName function takes a CDef as it's argument. However the above code will not work and has the following error:
No instance for (getIdea (Maybe CDef))
arising from a use of 'getName'
In the expression: getName c

I tried:
designC UnknownString c = getName (Just c)

but the error shows that this made things worse
No instance for (getIdea (Maybe (Maybe CDef)))

How can I pass just the CDef to getName?
Comment: What do you expect `designC` to do if the `Maybe CDef` is `Nothing`? Should it throw an error, propagate the `Nothing` along or return a default value?
Comment: Are we supposed to know what `getName` and `getIdea` [sic] are? Anyway, I don't. Show us their definitions, please.
Comment: What value exactly do you want `designC UnknownString Nothing` to return?
Answer: You have to handle a situation when your Maybe is Nothing.
Either provide some default value
defaultValue = ""

designC :: DesignC -> Maybe CDef -> String
designC FirstString _ = "first_string"
designC SecondString _ = "second_string"
designC UnknownString (Just c) = getName c
designC UnknownString Nothing = defaultValue

-- or shorter
designC UnknownString c = maybe defaultValue getName c

Or raise an exception
data MyException = VeryNastyError

designC :: MonadError MyException m => DesignC -> Maybe CDef -> m String
designC FirstString _ = pure "first_string"
designC SecondString _ = pure "second_string"
designC UnknownString (Just c) = pure $ getName c
designC UnknownString Nothing = throwError VeryNastyError


Create custom User Control for Acumatica

Question: I am attempting to create a custom User Control that is usable in the Acumatica Framework. Documentation is very limited so I was hoping someone may have some experience/examples of how best to implement?
It appears possible by creating a WebControl derived from PXWebControl and creating a global JS function with a matching name.
Comment: This question is too broad; [questions asking only for generic examples are off-topic for Stack Overflow](//meta.stackoverflow.com/a/291259/2747593). Instead, start writing code, and come back when you have a more specific problem. Be sure to show us [what you have tried](http://whathaveyoutried.com) and include a [Minimal, Complete, Verifiable Example](//stackoverflow.com/help/mcve).
Comment: I can provide you an example of how to work with a pure HTML/JS control and have it interact with the graph, but as far creating an ASP.NET control that will seamlessly work with the Acumatica framework, it's not something I've seen before. I tried it a while ago but wasn't able to figure out how to have my global JS functions loaded - didn't try very hard however. Will be watching this question with great interest!
Answer: To create a custom User Control in an easy way, you need to:

Open Customization of your project (System - Customization - Customization Project)
On the left side, you can see your screens in your customization. Find screen that needs or add needed screen. Go to the necessary view.
Select add controls and add your needed control.

You can see in an image provided below.
Comment: @HuguesBeauséjour technically any custom asp.net control can be used with Acumatica Framework. The other question is that the Layout Editor won't automatically show or manage that control with drag&drop. But the question is not specific to Layout Editor.
Comment: The product doesn't really support custom control (no option for that in Add Control tab). On the other hand JavaScript is correctly highlighted as the closest you can get to a custom control..
Comment: Correct, this is a possibility when creating new pages.
Comment: I'm not sure you can customize existing pages with any asp.net control. The customization parser will likely break on unknown controls.


Counter Strike Source map rotation based on time of day

Question: I am admin and owner of a Counter Strike Source server. We have a decent number of people on and off but we are still sort of new and have a bit of a fracture in what the people who play want and what will draw more traffic.
We largely only play DE and CS maps but some people want more stock maps and think a rotation of mostly if not exclusively stock maps. Some people think we should just run the server with the stock maps we like and a whole host of other custom maps and people who don't like it can deal with it.
What I want to know is are there any server plugins you know that allow map rotation to be changed based on the time of day or number of players currently on the server.
So far I've only found this plugin, but it hasn't been supported since 2008 it seems and based on the comments it would appear it works at times but has some issues with some of the variables.
Comment: This is the kind of thing where a SourceMod plugin would be excellent.  If I wasn't so rusty, I could probably write it myself.  If you're willing to invest a small amount of money, or you ask reaaaal nice, you might find someone on the AM forums who would be willing to write you something.
Answer: I can't find any, but requesting a plugin from some forums is always an option. One forum that I found is pretty good. Click Here to go to the website.


Javascript confirmbox + form inside it

Question: I'm having a PHP/MySQL giftlist and people can click "reserve"-button to reserve one piece of gift. Thing is that in that list there is gift which has been wished like 10 times. So to reserve all 10 pieces of certain gift one has to click the reserve-button 10 times  and javascript always  confirm if one is willing to reserve one piece of that gift.
What I'm now after is that change that javascript confirm to confirm+form which will send data to action.php.
In HTML it would look like this:

How many piece of gift are you willing to reserve?

<form action="action.php" method="post">
    <input type="text" name="giftammount" />
</form>

And when confirm returns true it will submit the answer and action.php will do the magic for MySQL table.
So, is this even possible technically? Not that i've tried, i've spent several hours wondering this but can't figure this out.
Comment: you could use something like ajax or jquery for an easy way to do it.
Comment: Ok..! I can try google it. Still a newbie with javascript, ajax etc. so I'm trying to learn it via examples..
Comment: You can perfectly use a confirm for this, you place the quantity in the form and bind the confirm to the submit event, and there return confirm(...);
Answer: If you're using jQuery UI then the dialog widget could be just what you need:

Use a modal dialog to require that the user enter data during a multi-step process. Embed form markup in the content area, set the modal option to true, and specify primary and secondary user actions with the buttons option.

Take a look at the jQuery UI page for an example and basic code
Answer: Javascript confirm box and a form are two totally different things.
One way you can solve this, is creating a modal box and simulating a confirm box + confirm dialog effect.
Few other functions like alert(), confirm() and prompt() only take text but not HTML
Comment: Ok, its good to get this straight. No way to get this work that fit html form to javascript confirm box. It's just not a way it should be done. So thanks for the heads up towards modal box. I try to look in that.
Answer: The following might help
If the function confirmAction returns true the form will be submitted and else the form will not. If the confirm process requires ajax , you can use jquery ajax function with asnc:true
function confirmAction(){
  //return true or false
}

<form action="action.php" onsubmit="return confirmAction()" method="post">
    <input type="text" name="giftammount" />
</form>

Javascript confirmbox + form inside it


Is the proposed solution to this masonry project okay?

Question: We will going to build long interior, round(little bit) shaped staircase (similar to this) from concrete, and I needed to get instructions
with physics that it will possible to make it without any middle pillar that 12ft long staircase. So because of that We suppose
to burrow the ground and concrete the base about 2-3ft tall where stair going to start.
I do not have particularly deep knowledge about staircase masonary. After a consulting mason, that he doesn't have a good
alternative. If those solutions aren't reasonable, is there anything we can do that without making middle pillar??
How can we convince him??
Comment: You will need a welded metal (iron rebar) internal structure to support the concrete.
Comment: Google "self supporting stairs" for lots of examples.
Answer: If you had an professional engineer design the whole unit as an assembly it may be possible to have the railings and metal concrete reinforcing members in the steps and risers work as a trussed span structure that was only supported at the bottom step and at the top step.
This is definitely not a project for any local neighborhood handyman, general masonry contractor or DIY type work. Also do not expect this type of project to be low cost.
Answer: I'd like to echo that if you intend to have an unsupported cast concrete staircase, the amount, size, and placement of rebar is likely essential.  This is entirely a question for an engineer.
As a design alternative, you may find that using steel as the structure and adding concrete as treads may be more cost effective.  If you google, I think you can find curved steel staircase manufacturers quite easy.  They may have stock designs that allow you to avoid custom engineering work.
Again, don't expect this to be cheap.


If all directional derivatives of $f$ in point $p$ exist, is $f$ differentiable?

Question: I am a little bit confused by the various theorems concerning the differentiability of a multivariable function.
Let $f : D \subseteq R^n \to R$ have all directional derivatives in point $p$. Does it directly imply that $f$ is differentiable in $p$? I know that the opposite is true: If $f$ were differentiable, it would imply that it has directional derivatives.
Comment: @Dog_69 You are wrong. If $f\colon\mathbb{R}\longrightarrow\mathbb{R}$ is defined by $f(x)=x^2\sin\left(\frac1x\right)$ if $x\neq0$ and $f(0)=0$, then $f'$ is discontinuous at $0$. However, $f$ is differentiable there.
Comment: The function $f$ is differentiable at $0$ because the limit $\lim_{x\to0}\frac{f(x)-f(0)}{x}$ exists (it is equal to $0$). And, no, being differentiable does *not* require continuous derivatives.
Comment: No. For $f$ to be differentiable you need that all the partial derivatives exist AND are continous. The converse is also true.
Comment: @JoséCarlosSantos, why is $f$ differentiable in $0$? I am pretty sure that the definition of differentiability requires continuous derivatives.
Comment: @JoséCarlosSantos: Yes, you are right.Thanks. If all the partial derivatives of $f$ exist AND are continuous then $f$ is defferentiable. BUT, there are differentiable functions which do not have continuous partial derivatives.
Answer: No, this is not true. Take, for instance$$\begin{array}{rccc}f\colon&\mathbb{R}^2&\longrightarrow&\mathbb{R}\\&(x,y)&\mapsto&\begin{cases}\frac{x^2y}{x^4+y^2}&\text{ if }(x,y)\neq(0,0)\\0&\text{ otherwise.}\end{cases}\end{array}$$You can check that, at $(0,0)$, every directional derivative exists. However, $f$ is not differentiable there.
Comment: @HansLundmark I've edited my answer. Thank you.
Comment: $$f_x(0,0)=\lim_{h\to0}\frac{f(h,0)-f(0,0)}h=\lim_{h\to0}\frac0h=\lim_{h\to0}0=0.$$
Comment: The directional derivatives all exist at the origin (which is what was required), but they are not all zero.
Answer: Ler $$f(x,y)=\begin{cases} 1 & x^2< y < 2x^2\\ 0 & {\rm otherwise}\end{cases}$$ The directional derivatives are equal $0.$ The function is not continuous at $(0,0).$


My Canister ceiling light bulbs, LED 65, BR30 burn out too quickly

Question: Have kitchen canister fixtures. The bulbs 65 watt BR30 Flood, burn out too quickly - one at a time in about 3 months. Ceiling (attic) heavily insulated
Comment: Are the can lights new or old?
Comment: 65 **actual** watts, or "65 watt replacement LED" - ie, typically 7-12 watts depending how well/poorly the thing is built?
Answer: Heavily insulated can lights are a Bad, Bad thing for LED bulbs - LED bulbs are already compromised in their cooling ability by being forced to fit in an envelope that is similar in shape to an incandescent bulb. Stick it in an IC can fixture with no airflow and insulation all around, and it gets hot. Heat kills LEDs and heat also kills LED power supplies (what turns 120/240 VAC into DC current and voltage proper for the LED module itself.)
Given the price of LED bulbs, you are probably not saving money .vs. using incandescent bulbs that can take the heat, or somewhat more efficient halogen bulbs that LOVE the heat if you are killing a bulb avery 3 months.
A non-bulb-shaped LED retrofit module can have somewhat better cooling designed in. One of those might last longer, though I note that ones I have specify a life of 35,000 hours in IC fixtures and 50,000 in ventilated fixtures, so even there it's definitely hurting the life.
Replacing the entire fixture with a designed-from-the-ground-up LED fixture that has effective cooling built in is the best option for long LED life. If you are not going to do that, I'd suggest looking for Halogen incandescent bulbs and not killing any more LED bulbs in these fixtures.
Comment: CFL's have come a long ways color-wise these past few years. They might also prove a good replacement for overheating LED's.
Comment: @WayfaringStranger Heat is not terribly kind to the ballasts (cute pile of electronics in the base of) CFLs, either. Base-up in an insulated can is very hard service for those.
Comment: Yes, there can be problems, but I've heard good things about the latest generation of spotlight style CFLs, designed for canisters. Granted, until I have one running for 6 years myself, that good word might just be marketing, but they're more energy efficient than tungsten or halogen, and far cheaper than LED.
Answer: This maybe something for every one who is having this problems with screw in type of fixtures and this may or may not be your problem. In the socket of a can light (recessed lighting) or lamp, you have two basic parts on the inside. The socket interior, the ring of metal that makes the most connect with the lamp, is the neutral and the little metal tab, at the bottom of the socket, is the hot. The biggest thing here is that people usually tighten the lamp down to hard and the little tab at the bottom gets bent down. With the tab bent down it will not make a good connection but will light the lamp until it is to much for the lamp and it burns out. The way to fix is simple, turn of the breaker, or unplug the fixture and check to make sure it is off. With it off using a small hard flat plastic object lift the tab back out just a little(Do not Force it or it will break). With tab back in position, screw in the lamp with the tips of your fingers and stop from screwing it in to tight. Turn on the break, or plug it back in, and see if that fixed it. Another problem maybe coming from your power company. A lot of home owners in the US thinks that the power is set and it stays that way and that is not true. I have been in house where the power can go from 108v to 135v, so when you turn on the light switch or turn the knob on a lamp, you get a inrush on high voltage and the 120v lamp pops. To fix this go to a lighting supply store and ask for 130v lamps or led that should help a lot also.
Comment: So why is this a negative?  If you do not like a answer let me know why.


Is this board solvable?

Question: Can anyone tell me an answer to this Minesweeper problem. I have to find just 2 mines from 4 spaces. What I really want to know is the sure shot way to solve puzzle (no guessing)

I have found all but 2 mines in lower right corner position.
I want an explanation to the answer. I am not obsessed with Minesweeper, but with the solution. Also if answer involves some mathematics, I will try to understand that.
Answer: The original problem
X31
X??
X4?
12?

Possible answers:
X31    X31    X31    X31
X4X    X5X    XX2    XX1
X42    X4X    X4X    X42
12X    121    121    12X

Each of the tiles have equal probability of being a mine (50/50).
There is a wrong move, which is to try the corner or the tile next to the corner.  If you try those lower tiles, you do not reveal enough information to avoid a second guess (odds of winning = 1/4).  If you try either of the two higher tiles and win, there will be no second guess (odds of winning = 1/2).
Comment: This situation actually happens fairly frequently in Minesweeper.  It's a bit of a flaw in the puzzle, if you expected it to behave in a manner that can be solved using reasoning only.
Comment: If you choose an upper tile, either you lose, or you don't.  If you didn't lose, you'll know whether the tile next to the corner is a mine or not, so you won't have to guess about the corner or its neighbor.  You can see this in the answer because the upper tiles change values based on the position of the lower tile mine.
Comment: "if you expected it to … be solved using reasoning only".  Losing on the first click should help break that expectation.
Comment: I'm confused on how the odds of winning this are 50/50 if you choose one of the upper tiles. Can you explain please?
Answer: The board isn't solvable, since there are multiple valid solutions.

Assuming you're playing the Windows Phone version of the game, there are various power ups which you can use to reveal where the final two mines are.
Comment: That 2nd one was the answer. My brother used all his luck for the day to uncover those :D
Comment: Yeah, but I am using the ones which finalizes all flagged position against possible mines. Bad choice here :D
Answer: There is no one possible solution for this puzzle. It's a matter of luck now.
Every box is a possibility for every number.
Comment: No! This! Is! Minesweeper!
Comment: It is not just luck, there are still 2 locations where you should not gamble for. Keep thinking.
Comment: Now that is bad
Comment: That is nonsense. There is no way to solve that position applying logic, without any gambling. There are two completely independent ways of satisfying the 3 and the 2, and both of them satisfy the 4.
Answer: Yes, it is solvable without guessing.
First, you can reduce the 3 to a 1, the 4 to a 2, and the 2 to a 1 making the board look like this.

11
XX
2X
1X

Then, you can further reduce the two to a one because you know that one of the mines have to be on the upper side.
After that, you basically got an 1-1 situation at the bottom. Then your board will look like either one of these:

11    -----------  11
X1    -----------  X2
2X    -----------  2X
1X    -----------  1X

Depending of which one of these two, you can find out the answer without guessing
Comment: How did you - without guessing - determine that the upper-right unknown couldn't be a mine?

Is this board solvable?


Should we stop using "Home" in navigation?

Question:
Possible Duplicate:
Home button vs Logo link?

The following must be true for most (if not all) websites:
Clicking the logo or website name leads to the homepage (/index.html).
But the question is, would most people (preferably all) know to click it if there was no "Home" in the nav?

One can assume that the navigation would contain the usual suspects: About, Services, Blog, Contact, etc.
How many users would comfortably click the logo/name to get to the homepage?
How many would not know what to do?
How many would know, but hesitate and be frustrated by the website, or develop a negative association?

Different websites would have a different demographic of visitors - I wonder how this is for people wealthier in years (40-60 or more).
Is it better to leave "Home" where it is?
Answer: There was a good discussion on this in another thread and the consensus was that it still bore relevance in usability and that it should stay.
For your particular case, however, it might be instructive to add a ?ref= param to your logo and home button link and look at your analytics to determine what your site visitors are actually doing.
You might be surprised how many people use the home link in the nav.
Comment: you could AB test this. show half of your uses one version and show the other half the other. mabey just for a week or until you see how people are using your site
Comment: Thanks Charles, the only issue with having both and seeing which users use more is that it's not possible to know whether those clicking "Home" would or would not have clicked the logo
Comment: True. Would also be interesting to know if anyone has done this already!
Comment: But another issue is that users now aren't necessarily users that, for example, SEO efforts are trying to bring in for the future. So it'd be best to quantify global web trends...


Split an arraylist of strings to its original strings elements

Question: So I have this Arraylist:
ArrayList<String> al = new ArrayList<String>();
for (int i = 0; i < arr1.length(); i++) {
JSONObject objectt = arr1.getJSONObject(i);
JSONObject triple = objectt.getJSONObject("triple");
String subject=triple.getString("s");
String predicate=triple.getString("p");
String value=triple.getString("o");
al.add(subject);
al.add(predicate);
al.add(value);
}

I wanna know if there is a way to split the arraylist "al" into the original strings (subject, predicate, value) outside the for loop?
Comment: They'll be every third element of the list, but why not put them into a object with subject, predicate, and value fields instead, and have a list of those objects?
Comment: @DavidConrad how?
Answer: Don't store the individual strings separately, store them in an object that has fields for subject, predicate, and value, like this:
public class Triple {
    private String subject;
    private String predicate;
    private String value;

    public Triple(String subject, String predicate, String value) {
        this.subject = subject;
        this.predicate = predicate;
        this.value = value;
    }

    /* getters, toString, equals and hashCode if necessary... */
}

// . . .
    List<Triple> al = new ArrayList<>();
    for (int i = 0; i < arr1.length(); i++) {
        JSONObject triple = arr1.getJSONObject(i).getJSONObject("triple");
        String subject = triple.getString("s");
        String predicate = triple.getString("p");
        String value = triple.getString("o");
        al.add(new Triple(subject, predicate, value));
    }

Then, if you want to use the values, call the getters:
// . . .
    for (Triple t : al) {
        String subject = t.getSubject();
        String predicate = t.getPredicate();
        String value = t.getValue();
        // do something with them
    }

Comment: and how to assign the values of subject, predicate, value that I've got inside the for loop after it into new variables?
Comment: @amine4392 By calling the getters of the Triple.


Continuity of the function $f(x,y)=\max\{x,y\}$ in $\mathbb{R}^2$.

Question: Continuity of the function $f(x,y)=\max\{x,y\}$ in $\mathbb{R}^2$.
I have seen the other proofs where the entries were themselves both functions of $x$, but I'm dealing with specific points and am not given a relation between $x$ and $y$. I know that in order for this to be continuous, then for all $\epsilon >0$
$|\max(x,y)- \max(a,b)| < \epsilon$ whenever $||(x,y)-(a,b)||< \delta$
I feel like this can be done by cases where $a=b$ and where $a<b$, but I'm not really too sure that this is correct or how to go about the second of those options.
Comment: Consider prooving cases of $x\le y$ and $x\ge y$. Then you'll have continuity everywhere.
Answer: You need to prove that $max(x, y) < max(a, b) + \epsilon$ and $max(x, y) > max(a, b) - \epsilon$, knowing that $x < a + \epsilon$ and $x > a - \epsilon$ and same with y and b
Making the cases as you suggest is a good idea, and I would encourage you to choose $\epsilon < b-a$ in the case $a < b$
Another way to see it : $max(x, y) = \frac{x + y}{2} + \frac{|x - y|}{2}$ so it is continuous
Answer: For any $\delta > 0$, if $\|(x, y) - (a, b)\| < \delta$, then $|x - a| = \|(x, 0) - (a, 0)\| \le \|(x, y) - (a, b)\| < \delta$, so that $x \in (a - \delta, a + \delta)$. Similarly, $y \in (b - \delta, b + \delta)$.
This gives $\max(x, y) < \max(a + \delta, b + \delta) = \max(a , b) + \delta$. Similarly, $\max(x, y) > \max(a, b) - \delta$. Therefore, given any $\epsilon > 0$, we can choose $\delta = \epsilon$.


Search for a little string in a huge one

Question: I'm working on a project in which I must search for a little string (about 40 chars) in a very very large string (we're speaking of about a hundred million chars). I'm searching the fastest way. I've tried several methods: these are the results of benchmarks:

Contains returned True in 248 ms;
IndexOf returned True in 671 ms (I would have never said that!);
Contains using an array instead of a string returned True in 48 ms only;

Even though the Contains inside an array seemed to be the best method, I've had a look at some search algoritms too (Knuth–Morris–Pratt, Rabin-Karp and Boyer-Moore), but none of them seems to be suitable for my scenario
My question is: is there a faster way to search a little string in a very big string?
Thanks,
PWhite
Comment: How does the "Contains using an array" case look?
Comment: Trying to optimise this suggests that you will be doing it more than just once. Will you be searching the same huge string for more than one word? Is there anything more that you can tell about what the huge string is, how it is created, or why you are searching it, that can help in finding a way to search other than just brute force?
Comment: This just begs the question, how are you getting the very large string in the first place?...
Comment: [Contains just call IndexOf](http://stackoverflow.com/a/498722/130611), your result seems stange. Are you running in multi thread?
Comment: @the_lotus `Contains` calls `IndexOf` with the  `StringComparison.Ordinal` comparison type, that is probably why it is faster.
Comment: Hi all, thanks for your answers. @Guffa: I'm searching a little string in a huge textual database of clothes and, yes, I'm doing this more than once subsequently; @Magnus: I read the file with `File.ReadAllLines` instead of `File.ReadAllText`.  My question is: is there a faster method that `Contains` (with `ReadAllLines`) or shall I use it? Thanks! _FWhite_
Answer: If you have a fixed, gigantic string that you want to search repeatedly for very small substrings, you may want to search for a library that implements a suffix tree or suffix array. Once you've done the preprocessing work to build the suffix tree or array, the runtime of searching for a pattern of length P is O(P) for the suffix tree and O(P + log T) for the suffix tree, where T is the length of the long text string. That's likely to be significantly faster than what you're seeing now, though you'll need heavierweight libraries to do this.
On the other hand, if you have a fixed set of pattern strings and a rotating cast of large strings to search in, you may want to use the Aho-Corasick string matching algorithm, which can scan for all occurrences of a fixed set of patterns in a string of length T in time O(T + z), where z is the number of matches. This is typically very fast in practice.


Does MATLAB perform common subexpression elimination?

Question: Does MATLAB's optimizer perform common subexpression elimination on MATLAB code? For example:
if max(val) > minVal && max(val) < maxVal
    maxVal = max(val)
end

How often is max(val) evaluated there? Does it make sense to store the intermediate value in a temporary variable (assuming the repeated calculation is expensive) or does MATLAB handle this automatically?
Answer: Pretty sure the answer is no to subexpression elimination and yes to storing intermediate values. Example:
>> x = rand(10000, 1);
>> tic;
for i = 1:100000
  y = max(x) + max(x);
end
toc;
Elapsed time is 4.297135 seconds.
>> tic;
for i = 1:100000
  m = max(x);
  y = m + m;
end
toc;
Elapsed time is 1.074672 seconds.

Even built-in operations like + don't seem to be optimised; a similar test showed that
z = (x + x);
y = z + z + z;

is faster than:
y = (x + x) + (x + x) + (x + x);

Comment: The latter is a different situation. In floating point arithmetic z+... Yields a different result than x+...


Xamarin Sharing A Base Android and iOS Project with multiple Android and iOS apps

Question: I have a project set up so that I can have a different styled app for each of our clients and i'm trying to stream line our design.
Currently it is set up so we have our PCL and then an Android and an iOS project for each client. This means that if we change anything on the app side code we have to change it manually across each project.
I have been attempting to change it so we have our PCL and a base Android and iOS project which has the platform specific interface code which each of the other projects with their individual colour styling, images and bundle identifiers can then inherit.
e.g.

PCL Poject (shared code, Forms, etc)
Android.Shared (shared resources/localisations for the android apps/platform specific code)
Android.Client1Theme (custom resources (logos, colors, etc) for Client1)
Android.Client2Theme (custom resources (logos, colors, etc) for Client2)
iOS.Shared (shared resources/localisations for the android apps/platform specific code)
iOS.Client1Theme (custom resources (logos, colors, etc) for Client1)
iOS.Client2Theme (custom resources (logos, colors, etc) for Client2)

I have gotten this to work for Android simply by creating a new android project and adding a reference to the shared android project and PCL.
I am having trouble getting to work for iOS in the same way. It's close, the iOS app compiles as a new app with the correct styling however the DependencyService crashes whenever it tries to access an interface method.
DependencyService.Get<ISystemFunctions>().ToggleTorch();
exception thrown on iOS interface access
Below is the code of my interface in my shared project, however i don't think this is the issue but rather the DependencyService cant find it.
[assembly: Dependency(typeof(SystemFunctions_iOS))]
namespace SharedApp.iOS.iOS_Interfaces
{
    public class SystemFunctions_iOS : ISystemFunctions
    {
        public SystemFunctions_iOS()
        {   }

        public void ToggleTorch()
        {
            var device = AVCaptureDevice.GetDefaultDevice(AVMediaTypes.Video);
            if (device == null)
                return;

            device.LockForConfiguration(out NSError error);
            if (error != null)
            {
                device.UnlockForConfiguration();
                return;
            }
            else
            {
                device.TorchMode = device.TorchMode == AVCaptureTorchMode.On ? AVCaptureTorchMode.Off : AVCaptureTorchMode.On;
                device.UnlockForConfiguration();
            }
        }
    }
}

Let me know if there is anything else i can share to help with this.
Comment: The same `DependencyService.Get()` method did work in your Android project ?
Comment: Yeah it works fine on iOS. I found the solution to my problem which I am posting below
Comment: * It works fine on android i mean.
Answer: Found the solution to my problem
In the AppDelegate for iOS.Shared remove the line
[Register("AppDelegate")]
//[Register("AppDelegate")]   NEEDED TO REMOVE THIS
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        global::Xamarin.Forms.Forms.Init();
        LoadApplication(new App());

        return base.FinishedLaunching(app, options);
    }
}

In the AppDelegate for iOS.ClientThemeX add the line
var systemFunctions_iOS = new iOS.Shared.iOS_Interfaces.SystemFunctions_iOS();
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        global::Xamarin.Forms.Forms.Init();
        LoadApplication(new App());

        // DO NOT REMOVE THIS. It breaks without it. Don't know why
        // but a similar row will need to be added for each interface added to the project
        var systemFunctions_iOS = new SharedApp.iOS.iOS_Interfaces.SystemFunctions_iOS();

        return base.FinishedLaunching(app, options);
    }
}

removing the AppDelegate register from the shared project makes sense, but i'm not sure why i needed to declare a new object with my interface to work.
This interface constructor, as in the question, is empty.
If anyone could shed any light on this still it would be appreciated, or if there is any advice for a much simpler way of doing this.


Google Drive API syncing randomly

Question: I have set up a Change Subscription to a Drive file, this is the way it is set:
public SyncChangeListener(Context context) {
    apiClient = new GoogleApiClient.Builder(context)
            .addApi(Drive.API)
            .addScope(Drive.SCOPE_APPFOLDER)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    apiClient.connect();
}

@Override
public void onConnectionSuspended(int i) { ... }

@Override
public void onConnectionFailed(ConnectionResult connectionResult) { ... }

@Override
public void onConnected(@Nullable Bundle bundle) {
    Query query = new Query.Builder().addFilter(Filters.eq(SearchableField.TITLE, "Sync.bak")).build();
    Drive.DriveApi.query(apiClient, query).setResultCallback(querycallback);
}

final private ResultCallback<DriveApi.MetadataBufferResult> querycallback = new ResultCallback<DriveApi.MetadataBufferResult>() {
    @Override
    public void onResult(@NonNull DriveApi.MetadataBufferResult result) {
        if (!result.getStatus().isSuccess()) {
            Log.i("SyncChangeListener", "Status NOT SUCCESS");
            return;
        }

        if (result.getMetadataBuffer().getCount() > 0) {
            DriveResource dr = result.getMetadataBuffer().get(0).getDriveId().asDriveResource();
            dr.addChangeSubscription(apiClient);
        }

        result.getMetadataBuffer().release();
    }
};

I have also set up the DriveEventService extended class
public class SyncChangeEventService extends DriveEventService {

    @Override
    public void onChange(ChangeEvent event) {
        // ...
    }
}

And I have set it in the manifest:
<service
    android:name=".sync.SyncChangeEventService"
    android:exported="true">
    <intent-filter>
        <action android:name="com.google.android.gms.drive.events.HANDLE_EVENT"/>
    </intent-filter>
</service>

The problem is that the change event is randomly getting fired. I'm testing this app on two different devices. When one device makes changes to the synced file, the other device sometimes gets the change event, but more than often it doesn't, or it does with huge delay.
So, the change subscription is working, but something is wrong because syncing is not guaranteed. I don't know where the problem is, or even if there's one. Where should I look to fix this issue?
Answer: You may want to check these links:

Introducing the Google Drive Android API
Google Drive Android API

Per links given above, Google Drive Android API temporarily uses a local data store in case the device is not connected to a network and will automatically and transparently be stored in the Google Drive cloud by Android's sync scheduler when connectivity is available.
Also, user files are automatically synced between different devices (provided the app has the same namespace and is signed with the same key).
Comment: I'm testing on two different devices, the first with debug key, the second with release key. This means they have not only different apk signing keys, but also they refer to different google api keys. Still it is partially working as the main post says. But I'll be empirical till the end and I'll test with the same apk on both devices.
Comment: I have just tried. It works the same way as before. The only viable way to make it always work is to occasionally do a `Drive.DriveApi.requestSync(mGoogleApiClient)`. But I really hate this for two reasons: 1) What is the purpose of setting a ChangeSubscription if I still have to force a sync? Why doesn't it just work as expected from Google API Docs? 2) Doing an occasional sync request causes a wakelock on the device. It causes a slight battery drain which I absolutely want to avoid.

Google Drive API syncing randomly


How to handle users typing without input focus

Question: An issue I repeatedly observe with novice web users is that they will occasionally begin typing without first properly selecting (focusing) an input field. A typical pattern I see is this: the user clicks just outside of the input field, and will start typing in a hunt-and-peck fashion -- they will only learn that their text hasn't been inputted when they return to look at the screen. I guess there are various reasons this problem arises: poor mouse control or poor motor control seem to be the most significant.
I wanted some opinion on what you think the best strategy of dealing with this issue is. Should it simply be ignored, or should the application take a proactive step to deal with it?
Comment: I'd advise against jumping to a text field when keys are pressed. Flickr does this, jumps to comments when you hit "c" and jumps to the search when you hit "s". With my setup, "s" scrolls down, and "c" closes a tab. And flickr breaks that configuration. Users might have a reason to be hitting keys outside of a text field.
Comment: "With your setup"? Sounds pretty unusual - what is it?
Answer: Best strategy is to place the cursor in the first expected input field as soon as the page loads. Remove the need for selecting the field completely. However, if the user can have more than one alternatives, you should avoid auto selecting since it can lead to confusion.
As for the next fields, use a proper tab-navigation to allow a mouse free typing experience.
eg: Look at facebook and gmail login pages, as soon as the page loads the cursor is already in the username field.

If you want to annoy the users who left their speakers on, you can start making error beeps when the user starts mashing keys outside of the input fields. (Problem is, it messes with the browsers keyboard navigation shortcuts)
Comment: Having helped many folks fill forms out at the library, I can say with confidence this will ONLY help with the very first field in your form. Most people who don't know to check if the field has focus, also don't know how to tab between fields. And as soon as they click 3 pixels off of the field no field will have focus.
Comment: This can be annoying for users that want control over their cursor--especially for those using assistive technologies. As such, I strongly recommend against this. The one exception, as noted, would be incredibly simple one-task pages such as the login page (where USERNAME would be an obvious bit of content to initially focus on since it's the only thing you can do on that page).
Comment: @rk on the web the goal is often to make the page accessible in general--not have to design specifically for assistive technology.
Comment: But that's the problem. It will announce the field you are focused on. In a lot of cases, this will be completely disorientating. On a login form, maybe not.
Comment: @DA01 Even those users need to fill up the form and you can announce the location of the cursor on page load. It is not bad usability, it is a case of how the implementation is handled.
Comment: @DA01 I would assume that forms which are specifically designed with accessibility in mind will have better solutions. This is particularly for helping the capable users who are inattentive.
Comment: @DA01  Hence 'expected input field', it is all about the judgement of the designer. If there are multiple flows, this solution does not work.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9231/discussion-between-da01-and-rk)
Answer: I would take a proactive approach that does not annoy the user through beeping or auto-focusing.
If users are clicking just outside of the field, it is possible to provide some progressive enhancement to the input fields via JavaScript that might help with this issue. The input field could be surrounded by a < div >, or other element, that provides some clickable white space. When the input field's parent element is clicked, which JavaScript can listen for, then the element's input field child would gain focus.
Statistically, this may not yield worthwhile results, but if you're seeing that same problem a lot, it may be worthwhile because the development shouldn't take too long. I've heard of similar implementations on buttons, where the click area is slightly larger than the visual button itself.
Comment: The  should actually be a  tag.  Selecting the label puts the cursor into the field.  You can wrap the input field in the  tag, but that may prove to be more challenging from a layout perspective.
Answer: Auto focus is less than ideal. It can make sense in some very simple single-task pages, such as a login screen, where the ONLY two fields are username and password.
But on a page that is any more complex than that, it can be a huge accessibility hurdle. If, for example, you have a large complex form on a page with the first field being, say, 'ID' then a person using a screen reader would load the page and hear "Form. Field: ID". Which gives absolutely not context as to what this page is about. Ideally, they'd be able to first read things like the title of the page, introductory content, etc.
Some more reading on this: http://www.brucelawson.co.uk/2009/the-accessibility-of-html-5-autofocus/
As for usability, many people prefer to keep control over their own cursor. So while autofocus might be a usability enhancement for some, it can be a usability problem for others. So another reason to avoid the auto-focus route.
To go back to your question, note that you are dealing with hunt-and-peck computer users. They certainly exist. And we need to accomodate them. But not at the detriment of other users. ;)
What I would suggest is simply create a larger target area for them to focus into. Make the fields bigger.
Instead of the top 'standard', style it like the bottom.

download bmml source – Wireframes created with Balsamiq Mockups
And added bonus is that this makes things a lot easier for those using touch devices.
Comment: One of the key benefits of the `@autofocus` attribute in HTML5 is that it can conceivably be suppressed by the UA/accessibility tools (e.g. Mobile Safari ignores it because it zooms the page and brings up the keyboard without any user input). It's significantly better than JavaScript-based autofocusing which is user hostile for a bunch of users, regardless of assistive tech.
Answer: Depending on your page layout and its purpose, auto-focusing a field could help.
Note that if the main point of the page isn't to fill in an input, then it might not be a good idea.
Also, if the field in question isn't near the top of the page, then don't do this. I've found that when auto-focusing a field that isn't at the top, the page loads partially scrolled down (to the input) which is quite odd behavior if you don't understand why.
Another solution (assuming you're working with HTML) could be to wrap the input inside a corresponding label tag. Then with CSS you can pad the label out a bit. That way, clicking in or anywhere near to the input will focus the field. I haven't ever actually tried this method, but it is valid HTML according to W3.
Comment: There should already be a valid label tag associated with the field, which can help if laid out appropriately as suggested.
Answer: I would agree with rk. A proactive approach seems to be overkill such as beeping on typing outside of text field focus.
Just to echo rk., understanding where the users are most likely to start typing when they launch into your site is crucial to the strategy of auto focus on page load though. If people are used to this, and the wrong field is in focus, it would just be an annoyance and not a large issue. But if you have analytics wired up, you could see how many people focus outside of your auto focused field before performing any other actions on the page to see for sure what people are doing.


Insulate rigid rectangular duct

Question: The problem
My vented attic in Virginia has a straight 28ft of 12" x 8" rigid rectangular trunk duct with seven 6" branches. The insulation is quite low around R-4, and also has many tears and rips, and the ducts need to be air sealed. I would like to replace the insulation with R-8.
After reinsulating all ducts to R8, I plan to bury them in blown cellulose insulation, based on the report Compact Buried Ducts in a
Hot-Humid Climate House.
This question is related to a previous question.
Standard solutions
From what I've read, there are two standard solutions recommended. The first is to wrap the duct in something like Owens Corning SOFTR Duct Wrap FRK, but it can only be purchased from HVAC supply houses that usually don't sell direct to homeowners. They also sell only in 50 ft rolls for 3" R-8, and for 2016 run around $100 a roll. Wrapping the ducts would entail disconnecting all the branch lines, air sealing with mastic, lifting the duct up to pull the insulation underneath, cutting holes for all the branch starting collars, then sealing the seams with UL181 foil tape. Lifting the duct and cutting the holes just right I feel would be rather difficult.

The second solution is to encase the ducts in 2-part spray foam. This has the advantage of air sealing and doesn't require a thick layer, but it is very expensive even if done yourself, requires special safety precautions, and it would be very difficult to seal the bottom of the ducts. At around $1 per board foot (1 sq ft 1 in thick, about R6), this would require about 150 bd ft, and DIY kits come in 200 bd ft for about $300.

Proposed solution
Surround the ducts with 1.5" (R-9.6) polyisocyanurate rigid foam insulation board. These run about $30 for a 4x8ft board, and only four would be needed for my installation with very little waste. As the duct is all the same dimensions and straight, the cuts would be very simple and could be done outside the attic. The seams would be sealed with UL181 foil tape, perhaps with some caulk or construction adhesive where the boards overlap at the corners. If needed the foam board could be cut to fit around the starting collars without even taking off the branch ducts. Near the plenum where it might be difficult to lift the duct, the foam board could be cut to fit between the joists, with simple spray foam or caulk sealing where it meets the joists.

Questions
Fiberglass duct wrap would be pressed right against the duct, but the foam would leave a slight and variable gap. Is there any problem with this? I suppose there could be some convection, but if the ducts are sealed and the insulation is sealed, how could this be a problem?
Are there any problems with my proposed solution?
Answer: Your plan to use polyiso foam board will work, but you must be absolutely sure to perfectly air-seal the insulation so that humid summer air cannot reach the cold metal duct surface. The only advantage of the spray foam approach is that it's easier to get this air seal. But you can get it with foam board using canned foam, tape, and caulk, it's just harder.
Comment: Turns out a friend could get me material from an HVAC supply house, so I ended up getting the duct wrap at about half the cost of the polyiso, plus I'll have 20 ft left over if needed elsewhere. Thinking about all the seams needed sealing with polyiso didn't seem very easy after all.
Answer: A previous owner used the SOFTER duct wrap, it looks terrible with age as the backing has been punctured leaving the fiberglass to hang out, so I'd advise against it.
Polyiso is going to talk a long time to hang and seal, but will leave you with a nice smooth and paintable surface, so is probably preferred in any area there might be a lot of eyeballs.
If you don't mind the texture and value your time more than the extra $ expanding foam seems like a clear winner.
Alternatively, as recommended to me in my similar question, you can also get foil backed peel-n-stick neoprene. I imagine if you are careful and have straight runs and rectangular ducts, this might look okay as well. However the previous owner of my house used this on a curve and thus had many overlapping patches making it look almost as bad as the fiberglass wrap.

Insulate rigid rectangular duct


Why use image load / stores instead of FBOs

Question: One example of Image Load / Stores that I have seen could be done using framebuffers instead of Image Load / Stores.  Framebuffers have been available longer in OpenGL and so my question is:
Why would you use Images instead of Framebuffers?
What advantages do they offer?
The referenced example says:

Note that this demo can also easily be imlemented using Framebuffer Objects. But with Framebuffer Objects you cannot write to arbitrary locations in a texture, though.

I am not exactly sure what is meant here. My understanding is that you can write to whatever pixel coordinates you want in an FBO.  Am I mistaken here?
Answer:
Why would you use Images instead of Framebuffers?

Image Load/Store is not intended to replace framebuffers. It's a feature that allows (relatively) arbitrary reading and writing to memory. So you would use images when you need to arbitrarily read and write to memory. You would use framebuffers when you're rasterizing primitives for rendering purposes.
The fact that you can build scenarios where you would use the latter in place of the former does not mean that this is the purpose of the feature.

What advantages do they offer?

Again, it's not meant to replace framebuffers. But the comparison is pretty simple.
A particular FS invocation cannot:

Choose what framebuffer texel(s) to write to. An FS invocation will only ever write outputs to the framebuffer texel(s) that map to its current fragment location. gl_FragCoord is an input value; it is non-modifiable. An FS's outputs will either be discard or written to the framebuffer texel(s) corresponding to gl_FragCoord.xy.
Yes, through point rasterization, you can select which fragment is being generated. But it isn't the fragment shader itself that's deciding this; it's whatever process wrote the vertex to the buffer that it's being read from. That is not under the direct control of the FS invocation itself.
Choose to write to multiple distinct framebuffer texel(s) locations. A fragment cannot cover multiple texels.
Choose which output attachments in the framebuffer to write to. The decision of which fragment shader outputs will be written is made by the write mask state, which the FS has zero control over. An FS can choose to be discarded, but that discards all of its outputs.
Choose to read from the current framebuffer texel(s) it is writing to. Blending is done by a fixed-function stage; the FS has zero control over this. The closest you can get is to employ some texture barrier gymnastics, but that's not something the FS can directly control.
Choose to read from framebuffer texel(s) other than the one it's writing to. Even with texture barrier gymnastics, you cannot read from other people's texels.

Now granted, image load/store doesn't exactly make read/modify/write passes easy, due to incoherent memory access rules.
Of course, image load/store cannot handle (easily):

Depth testing. Or at least, not in any way that is nearly as efficient as the rasterizer. The read/modify/write nature of the depth test makes this exceedingly tricky with image load/store. With a regular depth buffer however, this is trivial.
Simple blending. Again, you can do it, but it's really hard, and far less efficient than the normal rendering process.
Answer: To write to an arbitrary location in a FBO you need to do rasterization of point primitive at that location. This is significantly more costly than a single imageStore because it involves invoking the vertex shader, the ROP units, and possibly rasterizing a whole 2x2 quad or more for just a single pixel.† With imageLoad/imageStore you have greater flexibility and finer control of where you read and write, including atomics, barriers, etc... Since you skip the ROP and give up the API-order guarantee, such direct writes might be faster even for filling triangles.

† I'm not sure about this last point, but since the screen-space derivatives are still available in the fragment shader, and point primitives are typically used for larger sprites, it means that the implementations are more likely to just go the typical rasterization route used for lines and triangles.
Answer: The documentation quickly sum up the idea with:

The idea with image load/store is that the user can bind one of the
  images in a Texture to a number of image binding points (which are
  separate from texture image units). Shaders can read information from
  these images and write information to them, in ways that they cannot
  with textures.

Aside for the simplicity of usage, from An introduction to OpenGL 4.2 | Daniel Rákos Blog at the section ARB_shader_image_load_store you can perform more complex operations and algorithms in GLSL to a single level of a texture (which is called an image) and from any shader stage.
I am also curious about the implementation of the example with FBO since I don't understand why you cannot write to a specific pixel coordinate too.


Unable to restore cloud sql backup

Question: I followed this link to restore my backup
https://cloud.google.com/sql/docs/mysql/backup-recovery/restoring
and i've tried restoring on multiple instances too
but in every instance's this error comes up in logs
Couldn't repair table: mysql.general_log
Failed to write to mysql.general_log: Incorrect key file for table 'general_log'; try to repair it
Answer: First, address the error. Your general query log is enabled, but the install default is disabled. If you do not need the table enabled, then once everything is working, disable it.  I would suggest take a fresh backup and then:
A. Repair the table using the mysqlcheck -r YourDB general_log command. (If this is an ISAM table use myisamchk instead.)
B. If that does not repair the table, first try mysqlcheck -r YourDB to repair the whole database (sometimes more than just the table needs to be repaired.)
C. If the restore still doesn't work than there are a couple of possibilities: the database may be corrupted or the backup file is corrupted. You don't mention any other errors, so I do not suspect the whole database is corrupted.
D. To check on the corrupted file, you can create a fresh database instance and try your restore there.  If that does not work you can try restoring a data table to confirm if the backup file is usable.
Be prepared for the possibility your backup file is corrupt.

Unable to restore cloud sql backup


Cassandra 2.0 - CQL3 schema changes not propagated through rest of cluster even after 30+ minutes

Question: I created a table in CQL 3.0 / Cassandra 1.2 a few months ago with a pretty simple table structure that included a couple of columns with CQL3 collections.
Today I rolled out an update to the schema for that table on our development C* cluster, which has since been upgraded to Cassandra 2.0 running CQL 3.1.
I ran the following command via cqlsh on one of the 4 nodes in our ring today:

ALTER TABLE ExistingTable DROP OldColumn1;
ALTER TABLE ExistingTable DROP OldColumn1_; --used for DSE Search solr indexing; no longer needed
ALTER TABLE ExistingTable ADD NewColumn set<uuid>;

However, after 30 minutes I was seeing some failing tests from our application and was pretty surprised to see that while the node I ran these changes on had the correct schema, none of these changes were ever propagated to its peers in the ring. I've been using Cassandra for a year and a half and have never seen this before.
How can I fix this and what caused the issue?
Edit
This might help explain what's going on. Got the following error when I tried to kick off a nodetool repair:
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/cassandra/tools/NodeCmd : Unsupported major.minor version 51.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
        at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: org.apache.cassandra.tools.NodeCmd.  Program will exit.
Comment: Yeah, but your node tool definition has a JDK7 issue.
Comment: In case anyone asks, the Cassandra servers themselves are running fine. Haven't had any issues with them until now AFAIK. It's also not an obvious JDK7 issue - at least not with Cassandra itself, given that DSE is running properly.
Answer: I followed Christopher's suggestion and fixed my JDK issue with nodetool / dse tool. Cassandra worked because looks for a symbolic link to the "java" command, which was correctly set to JRE 7 during the upgrade to Oracle JDK7, and uses that to run its jars. All of the command line tools except for cqlsh, however, all depend on the JAVA_HOME environment variable, which was incorrectly set to Java 6. That's why Cassandra 2.0 could run but nodetool could not.
After fixing that issue my schema replicated instantly to other nodes once I re-applied my schema changes to a different node.
Answer: You're code was compiled for JDK 7, and you are running on JDK 6.
Comment: DSE 4.0.3 / Cassandra 2.0.7 runs fine on that machine, and it also has to target JDK7. IIRC, NodeTool gets updated along with the Cassandra / Solr / Hadoop bits. What would have gone wrong here?
Comment: Are you sure you are even invoking the Cassandra 2.0.7 nodetool?
Comment: So it looks like there's a definite JDK issue with Nodetool. Cassandra's pointing at JDK7, but the JAVA_HOME path variable is still pointing at JDK6. I'll fix that, but it doesn't explain the CQL schema issue.


How to implement content assist's documentation popup in Eclipse RCP

Question: I have implemented my own editor and added a code completion functionality to it. My content assistant is registered in source viewer configuration like this:
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
    if (assistant == null) {
        assistant = new ContentAssistant();
        assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
        assistant.setContentAssistProcessor(getMyAssistProcessor(),
                MyPartitionScanner.DESIRED_PARTITION_FOR_MY_ASSISTANCE);
        assistant.enableAutoActivation(true);
        assistant.setAutoActivationDelay(500);
        assistant.setProposalPopupOrientation(IContentAssistant.PROPOSAL_OVERLAY);
        assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
    }
    return assistant;
}

When I press Ctrl + SPACE inside the desired partition, the completion popup appears and works as expected.
And here's my question.. How do I implement/register a documentation popup that appears next to completion popup? (For example in java editor)
Answer: Well,
I'll answear the question myself ;-)
You have to add this line
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));

to the configuration above. Then when creating CompletionProposals, the eighth (last) parameter called additionalProposalInfo of the constructor is the text, which will be shown in the documentation popup.
new CompletionProposal(replacementString,
                          replacementOffset,
                          replacementLength,
                          cursorPosition,
                          image,
                          displayString,
                          contextInformation,
                          additionalProposalInfo);

More information about can be found here.
Easy, isn't it.. if you know how to do it ;)
Answer: For the styled information box (just like in JDT).

The DefaultInformationControl instance need to received a HTMLTextPresenter.
import org.eclipse.jface.internal.text.html.HTMLTextPresenter;

public class MyConfiguration extends SourceViewerConfiguration {

    [...]
    public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
        if (assistant == null) {
            [...]
            assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
        }
        return assistant;
    }

    @Override
    public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) {
        return new IInformationControlCreator() {
            public IInformationControl createInformationControl(Shell parent) {
                return new DefaultInformationControl(parent,new HTMLTextPresenter(false));
            }
        };
    }
}

Proposals can then use basic HTML tags in the string from method getAdditionalProposalInfo().
public class MyProposal implements ICompletionProposal {
    [...]
    @Override
    public String getAdditionalProposalInfo() {
        return "Hello World!";
    }
}


How to get the Salvage Droid stages for the least bux?

Question: I had about 650+ bux, but blew through them playing the Salvage Droid slots trying to get those stages. I think Kashyyyk was in the 2nd slot (at 15 bux a pop), and I must have wasted 345 bux but only have 2 wookies to show for it (not counting all the other crappy prizes).
I then used what remaining bux I had to rescan until Endor showed up in the 3rd slot (25 bux a pop), and I managed to get one of the Endor levels from there, along with 2 Ewoks and a rabbit-like creature.
I then saved my bux and had 75 when Endor showed up in the 3rd slot again. This time, in 3 spins, I got the remaining Endor level.
I'm still lacking the 2 Kashyyyk levels and the 2 Csilla levels, and since it's soooooo hard to get bux nowadays and so many places to spend it (dream jobbers holding out bux on you, and Decorator Droids not wanting to show up unless you bribe them), I would like to stretch my bux and know what's the most cost-efficient way to get those stages?
Also, does Kashyyyk still show up on your scans? Because I've only gotten Endor nowadays. I don't believe this is a limited event so I think Kashyyyk and Csilla should show up again, but they haven't for a while now and I'm getting a little worried.
So, for those who had gotten the Salvage Droid levels, how much bux did you spend (ballpark figure) to get them? What kind of Salvage Droid or which slot? Personally, I think spending bux anywhere but the last slot is a waste or maybe it was just dumb luck that i got those levels within a few spins...
Answer: If you're willing to "cheat" and spend some time on it, you can get all the levels for 25 bux apiece (or less if you're willing to spend more time).  I initially blew through 800 bux without getting a level so I got frustrated and started googling.  Here are instructions for Android based on what I found (sorry, you're on your own with iPhone).
Get the planet you want in the 25 bux slot (see note below), then:

Exit Tiny Death Star
Put your phone in Airplane Mode
Start Tiny Death Star
Send the 25-bux salvage droid and wait for return
Open the cargo.  If it's a level, goto step 6, otherwise goto step 7
Yay, you got something you wanted!

Collect the item
Press and hold power button and turn Airplane Mode off
Play for 5 min to resync with online servers
Goto step 1

Boo, you got junk!

Open the "Recent Apps" screen on your phone
Swipe TDS away
Turn Airplane Mode off and wait for Wifi or data to reconnect
Start TDS
You should get screen asking you to pick local or online, choose online
After game finishes loading, goto step 1 (or just re-enable Airplane and goto step 4)

So if you get a level, you continue playing and lose the 25 bux you spent. Otherwise you restore to your earlier state and it's like it never happened. :-) Of course you can also choose to keep the special bitizens or other cargo if you think they are worth 25 bux to you.
Note that you can use a similar process to rescan (using either the free scan or 5 bux) until you get the planet you want in the 25 bux slot.  You can also do this with the other slots but the chances of getting a level are a lot less so you just have to go through this more times.  Even at 25 bux, it will take you several hours to get all the levels this way.
Comment: Any iOS users have any luck with the above method? Pls post here if you successfully get the stages (for iOS users)
Comment: I thought I should let people know that this technique seems to have stopped working for me.  I am no longer given the choice of "local or on-line" when I restart the app with airplane mode off. The developers must have changed how things are handled when you play with no network connection.
Answer: Kashyyyk will still show up, but honestly the way to get things for the least Bux is not to play their game; be patient, wait for the free rescans to put something useful in the highest slot, and send your one free droid a day. Nothing about this appears to be limited-time only, so don't let gambler's fallacies impoverish you.
I have received characters from the highest slot, only one level so far (from one of the other slots), and all manner of nonsense. But when you get the "You already have this prize" message, you should at least make a Bux profit if it's from the highest slot...
Answer: I can confirm that the Kashyyyk level still shows up on the scans.  I just had it appear in the 25 Bux level so I spent 50 bux and received cooling coils and a Supply Officer.  I have yet to receive any of the levels from the Salvage Droid activity and I have spent over 600 bux just like you.
Answer: I've seen all the areas show up in all three slots but I never get anything from them, blew 1800 now and refuse to purchase any more from the store, nothing but useless stuff from the probe droids, it's pure luck to get anything, at least the decorator droid quest is proving much more satisfying and haven't had to spend real money on that one.


Footer element displays on top of page with IE

Question: Working on a page for a nonprofit. The content is finished, working on cross-browser rendering. Huge problem with IE. I did get the content to mostly diplay correctly, but the footer element of the site, which should be at the bottom of the page, is displaying on the top of the site. How can I fix this? By the way, this is not the only display problem, just the topic for this question. I do not want to use any scripting.
Here is the website: http://www.ncalhn.org/testing/ncdba/events.html
Footer displays on the top of the page on IE only. I'm assuming IE doesn't recognize the footer element yet so looking for code to make IE understand the footer should be displayed at the bottom of the page. code currently using:
CSS:
footer {
    width: 100%;
    margin-top: 90px;
    margin-left: 20px;
    text-align: center;
    position: absolute;
}

.foot {
    padding: 20px;
}

html:

Follow us on social media!

Tried adding bottom:0; and then again with margin-bottom: 0px; and neither worked. Also tried changing between position:relative; and position:absolute; - makes no difference.
Answer: Well you have your footer position: absolute, but no positional values.
Try adding bottom: 0; at least to the footer.
Comment: Thanks! I'll try that one. Would that be margin-bottom: 0;?
Comment: No literally just bottom: 0;  When you say position: absolute, you tell it where to go in relation to any parent that has position: relative. You do this by saying left: 13px, top: 5%, bottom: 0, etc
Comment: Tried that both literally and as margin-bottom and neither worked.


JMenu submenu items not displayed properly

Question: I'm tyring to add 2 JRadioButtonMenuItems as sub menu items to a JMenuItem, but the sub menu items are not getting displayed correctly.
This the code I have tried so far
 private void setupEditMenu() {

    editMenu = new JMenu("Edit");

    // some code..

    tabSpaceMenuItem = new JMenuItem("Tab Length");
    editMenu.add(tabSpaceMenuItem);

    ButtonGroup tabSpaceButtonGroup = new ButtonGroup();
    JMenuItem fourSpacedTabMenuItem, eightSpacedTabMenuItem;

    fourSpacedTabMenuItem = new JRadioButtonMenuItem("4 spaces");
    fourSpacedTabMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            editor.setTabSize(4);
        }
    });
    tabSpaceButtonGroup.add(fourSpacedTabMenuItem);
    tabSpaceMenuItem.add(fourSpacedTabMenuItem);

    eightSpacedTabMenuItem = new JRadioButtonMenuItem("8 spaces");
    eightSpacedTabMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            editor.setTabSize(8);
        }
    });
    tabSpaceButtonGroup.add(eightSpacedTabMenuItem);
    tabSpaceMenuItem.add(eightSpacedTabMenuItem);

    if(editor.getTabSize() == 4)
        fourSpacedTabMenuItem.setSelected(true);
    if(editor.getTabSize() == 8) {
        eightSpacedTabMenuItem.setSelected(true);
    }
}

Current Output

Expected:
Edit
 |-Find
 |-Font
 |-Tab Length
    |- 4 spaces
    |- 8 spaces

What am I missing?
Answer: JMenuItem isn't a container for other JMenuItems.  Instead, change tabSpaceMenuItem to JMenu instead...
tabSpaceMenuItem = new JMenu("Tab Length");

Comment: My bad, I wonder how I missed that, BTW, Thanks for the help :)
Comment: Welcome to the forest, watch out for the trees ;)


(Re?)Install Ubuntu on a Dell laptop that had Ubuntu preinstalled

Question: I have Dell Laptop that is 15 5567 7th Generation. So it was maybe pre-installed as Dell says and I can see in the product information that this laptop is Ubuntu built in and based not Windows.
So I want to get my Ubuntu OS again. How can I do that?
Comment: do you mean you are looking for an Ubuntu .iso file that came pre-installed with your laptop?
If yes, kindly edit your question so that we can assist accordingly.
Comment: See if https://askubuntu.com/questions/926204/whats-the-difference-between-vanilla-ubuntu-and-the-dell-oem-version helps.
Comment: Its edited and set properly.
Answer: I believe that laptop comes with ubuntu 16.04 to download that OS see this   download page you will probably want the "ubuntu-16.04.4-desktop-i386.iso" but you will have to decide that based on your needs and computer.
To install the OS see this tutorial there are many other tutorials online if you prefer a different one.
Edit:
It looks like there is some confusion over whether Dell uses its own version of Ubuntu or not (see comments). Either way, they have a Ubuntu iso 12.04 on their website see 12.04-OSP1
Edit2:
OP just wants to install Ubuntu.
To set up just Dual-Boot just follow this guide: How to Install Ubuntu Alongside With Windows in Dual-Boot | tecmint.com
To just Install Ubuntu see.
How do I install Ubuntu?
Comment: Although OP didn't make it clear in the question, I'm pretty sure OP's looking for Dell OEM Ubuntu iso tailored for their "Dell Inspirion 1567 7th Gen", not the generic Ubuntu iso.
Comment: @pomsky While I think you are correct according to the [Dell forms](https://www.dell.com/community/Linux-General/Inspiron-15-3521-DELL-OEM-Ubuntu-image/td-p/4057902) "we do not have a special OEM release of Ubuntu 12.04 LTS". I assume this applies to whichever Ubuntu OP has.
Comment: It seems the tech-support person who made the comment is not at all well-informed. I found a customised 12.04 iso just after a few minutes of googling: http://linux.dell.com/files/ubuntu/precise/12.04-OSP1/dell-12.04.2_20130822_0809.iso
Comment: Interesting, looks like you might right, I wonder if that is just the same OS or if they actually have it optimized for Dell laptops.  I guess OP can use it either way. Though that file looks like it has not been updated since 2013.
Comment: I am really confused guys, I don't know which Ubuntu to install in my Dell laptop. See the main question guys its been updated by me.
Comment: @MohammadAli do you want to have the exact same Ubuntu? If you are just a typical desktop user you can install any version of Ubuntu and you probably won't notice a much of a difference if any. There won't be any problems running a generic version of Ubuntu on your computer (i'm running 16.04 on my Dell PC I could just as easily run 12.04).  If there is a reason you would like the old version that came on your computer please explain why.

Bottom line, your computer can run pretty much any version of Ubuntu. I suggest the latest stale version unless you need your old version.
Comment: Well the things is I just found in my Support Drivers and Tools of my laptop there that is it supports Drivers for Windows 10, 64 bit and Ubuntu 16.04. So does it mean that my laptop had Ubuntu 16.04 as original?
Comment: @MohammadAli No it does not mean that. My understanding is that that is there because on Windows 10 Microsoft enables users to use the Linux command line in Windows (which is awesome). It is not enabled by default but there are lots of guides on how to do this.  I'm surprised that Ubuntu appears on the system before it's enabled but it seems to be the case.
Comment: @MohammadAli Have you used Ubuntu desktop on this laptop?
Comment: No. I didn't use.
Comment: @MohammadAli do you want to have the Desktop Ubuntu or do you just want the text-based command line access?
Comment: I think the best one is Desktop Ubuntu right?
Comment: @MohammadAli it is not a matter of best, it's a matter of your use case. But I'm certain you want the desktop version.
Comment: Desktop then bro. Give me the links and instructions as well.
Comment: @MohammadAli you have 2 options, create a Dual-Boot setup which would allow you to pick if you want to run windows or Ubuntu every time your computer starts.  OR you can destroy your windows install and just have Ubuntu.  For your use I would suggest having the Dual-Boot setup. if that's what you want follow this guide. https://www.tecmint.com/install-ubuntu-16-04-alongside-with-windows-10-or-8-in-dual-boot/
Comment: That is for downloading Ubuntu 16.04 so its the latest Ubuntu? And I should select the 64bit right the "64-bit PC (AMD64) desktop image" ?
Comment: @MohammadAli 16.04  is not the latest but it is what  I suggest you use. If you have a 64-bit computer download the 64-bit option.
Comment: Well can I run softwares like, Adobe CC, Google Chrome, Skype etc in ubuntu?
Comment: @MohammadAli yes but you should google search what you are looking for.  if you can't find an answer then post another question here.  a quick google for "skype ubuntu" returns https://askubuntu.com/questions/775087/how-to-install-skype-in-ubuntu-16-04

If you feel I have answered your original question please accept this answer. as getting reputation for answering questions is what keeps this site going. (accept this answer by selecting the check mark next to the above answer)