Phase curve of $\ddot{x}=-x,\ddot{y}=-y$

Question: Rewriting the ODE in the title, we get
$$\dot{x_1}=x_2,\dot{x_2}=-x_1, \dot{x_3}=x_4, \dot{x_4}=-x_3.$$
It is easy to show that
$$x_1=A\cos(t)+B\sin(t),x_2=B\cos(t)-A\sin(t),\\x_3=C\cos(t)+D\sin(t),x_4=D\cos(t)-C\sin(t).$$
In Ordinary Differential Equations by V. I. Arnold, there are several problems on this equation. For example, it can be shown that each phase curve is on a 3-sphere, and is a great circle of that.
The next problem is more difficult: show that the phase curves on a given 3-sphere form a 2-sphere.
I attempt to find out which 3-dimensional subspace the 2-sphere lies in, but in vain.
And the last question is about the linking number. Since 3-sphere can be regarded as $\mathbb R^3\cup \{\infty\}$, a partition of 3-sphere into circles determines a partition of $\mathbb R^3$ into circles and nonclosed circles. Show that any two of the circles of this partition are linked with linking number 1.
I am not sure how to visualize this partition, and what the circles stand for.
Can anyone give some advice? Thanks in advance.
Comment: I'm not an expert on this, but it seems to be connected with the so called Hopf fibration; see here:  http://en.wikipedia.org/wiki/Hopf_fibration
Comment: It seems that **every** property you are interested in derives from the fact that each solution of this differential system stays on a surface $$[x_1^2+x_2^2=a^2,\,x_3^2+x_4^2=b^2],$$ which, in turn, is included in the 3-sphere $$x_1^2+x_2^2+x_3^2+x_4^2=r^2$$ for some suitable $r$.
Comment: The two-sphere (the set of orbits) turns out not to be embedded in the three-sphere. It may help to introduce complex coordinates $z_{1} = x_{1} + ix_{2}$, $z_{2} = x_{3} + ix_{4}$; the flow of your system is $$(t, z_{1}, z_{2}) \mapsto (e^{it}z_{1}, e^{it}z_{2}).$$The three-sphere is invariant (see also Did's comment), and the quotient of $S^{3}$ by this circle action is the Hopf map (see Christian's comment); the quotient space is the [set of complex lines through the origin](http://math.stackexchange.com/questions/447567/flag-manifold-to-complex-projective-line/448316) of $\mathbf{C}^{2}$.
Comment: By __not__ rewriting the ODE we find that:
$$
x=A\cos(t)+B\sin(t)\\
y=C\cos(t)+D\sin(t)
$$
Solving for $\cos(t)$ and $\sin(t)$ and summing the squares of these then yields a Lisajous Ellipse, degenerated eventually (if $AD-BC=0$):
$$
\left(\frac{Cx-Ay}{AD-BC}\right)^2+\left(\frac{Dx-By}{AD-BC}\right)^2 = 1
$$
That's all "interesting" I can see. What more is there to be said?
Comment: @Amzoti Yes, and I have edited it.
Comment: Why did you rewrite the ODE in the title? Seems to me that it doesn't simplify but has become more complicated instead.
Comment: What you see is the projection of the phase curve to the plane $Ox_1x_3$, with my notation. And I want to know the structure of the phase curve itself.
Comment: @user86418 I agree with what you said, although I haven't deal with Hopf map before. Do you know something about the other question?
Comment: @EclipseSun: Hmm, seems that I do not know what a "phase curve" is good for and what it is.
Comment: @EclipseSun: It's "well known" that any two fibres of the Hopf map have linking number one, but this is one of those factlets whose proof (i) depends on your definition of linking number, (ii) may be difficult to track down on the web, and (iii) may be messy to establish from scratch. (Because $S^{3}$ itself is a group, it suffices to take one fibre to be the $z$-axis in $\mathbf{R}^{3}$; it's "fairly apparent" geometrically that every other fibre projects (in the $(x, y)$-plane) to a curve winding once around the origin, see also Han's comment about Lissajous ellipses.)
Comment: @user86418 Would you mind writing an answer? An outline will be appreciated.
Answer: $\newcommand{\Cpx}{\mathbf{C}}\newcommand{\Proj}{\mathbf{P}}$This answer introduces well-known constructions (the equivalence of the complex projective line with the Riemann sphere, and the Hopf map from the $3$-sphere to the $2$-sphere) that are accessible given the presumed background of readers of Arnol'd, but may or may not occur naturally in the course of approaching this problem about pairs of harmonic oscillators.
The Riemann Sphere: For present purposes, the Riemann sphere is the holomorphic curve obtained by taking two copies $U_{0}$ and $U_{1}$ of the complex line, with respective coordinates $z$ and $w$, and identifying $w$ in $U_{1}$ with $z = 1/w$ in $U_{0}$. The origin ($w = 0$) in $U_{1}$ is regarded as the point at infinity in $U_{0}$, and vice versa.
The Complex Projective Line: If $z_{0}$ and $w_{0}$ are complex numbers, not both zero, the complex line they determine is the set of (complex) scalar multiples of $(z_{0}, w_{0})$. Throughout, the term "line" refers to a complex line through the origin in $\Cpx^{2}$. (A complex line is an oriented, real $2$-plane. However, most real $2$-planes through the origin of $\Cpx^{2}$ are not complex lines.)
Every non-zero vector in $\Cpx^{2}$ lies on a unique line. Two non-zero vectors $(z_{1}, w_{1})$ and $(z_{2}, w_{2})$ lie on the same line if and only if there exists a complex number $\lambda$ (necessarily non-zero) such that
$$
(z_{2}, w_{2}) = \lambda (z_{1}, w_{1}).
$$
The set lines is, by definition, the complex projective line, $\Cpx\Proj^{1}$. This space acquires the structure of a holomorphic curve, equivalent to the Riemann sphere $\Cpx \cup \{\infty\}$, as follows: A complex number $z$ in $U_{0}$ corresponds to the line through $(z, 1)$. A complex number $w$ in $U_{1}$ corresponds to the line through $(1, w)$. If $w \neq 0$ and $z = 1/w$, then
$$
(1, w) = w(1/w, 1) = w(z, 1) \sim (z, 1);
$$
that is, each non-zero number $w$ in $U_{1}$ is identified with $z = 1/w$ in $U_{0}$. This is precisely the gluing that defines the Riemann sphere.
The Hopf Fibration: Define a (holomorphic) mapping $\Pi:\Cpx^{2} \setminus\{(0, 0\} \to \Cpx\Proj^{1}$ by sending each (non-zero) pair $(z, w)$ to the line through $(z, w)$. The restriction of $\Pi$ to the $3$-sphere
$$
S^{3} = \{(z, w) : |z|^{2} + |w|^{2} = 1\}
$$
is the Hopf map $\pi:S^{3} \to \Cpx\Proj^{1}$. The preimage of each point is the intersection of $S^{3}$ with a line, a great circle called a Hopf fibre. Since $\pi$ induces a bijection between Hopf fibres and points of $\Cpx\Proj^{1}$, the set of Hopf fibres is a $2$-sphere.
To see that distinct fibres of the Hopf map link once inside $S^{3}$, note that if $L_{1}$ and $L_{2}$ are distinct lines, then $\Cpx^{2} = L_{1} \oplus L_{2}$. Projection to the second summand is surjective, and the Hopf fibre in $L_{2}$ "winds around" $L_{1}$ (since this circle winds around the origin in $L_{2}$).

Consider the first-order linear system
$$
\dot{x}_{1} = x_{2},\quad
\dot{x}_{2} = -x_{1},\quad
\dot{x}_{3} = x_{4},\quad
\dot{x}_{4} = -x_{3}.
$$
Introducing complex coordinates $z = x_{1} + ix_{2}$ and $w = x_{3} + ix_{4}$ (and therefore identifying $\mathbf{R}^{4}$ with $\Cpx^{2}$, the preceding system becomes
$$
\dot{z} = iz,\quad
\dot{w} = iw.
\tag{1}
$$
The solution of (1) with initial conditions $z(0) = z_{0}$, $w(0) = w_{0}$, is
$$
\left[\begin{array}{@{}cc@{}}
    z(t) \\ w(t) \\
  \end{array}\right]
= e^{it} \left[\begin{array}{@{}cc@{}}
    z_{0} \\ w_{0} \\
  \end{array}\right]
= \left[\begin{array}{@{}cc@{}}
    e^{it} & 0 \\
    0 & e^{it} \\
  \end{array}\right] \left[\begin{array}{@{}cc@{}}
    z_{0} \\ w_{0} \\
  \end{array}\right].
\tag{2}
$$
Since scalar multiplication maps each line to itself, each solution curve (2) is the Hopf fibre in the line determined by the unit vector $(z_{0}, w_{0})$. Since solutions of (1) are precisely Hopf fibres, the set of solutions is a $2$-sphere, and distinct solution curves link once in $S^{3}$.


List posts from taxonomy term

Question: I need to display posts assigned to taxonomy term. I can do it manually with no problem but I would like to have a loop to automaticall display posts from each taxonomy term so when user adds new term the posts from that term are displayed on the site.
You can see the live example on the following url;
<code>    184.108.40.206/~divesdes/shop
</code>
I am using Woocommerce to build an online store. Here is the code I am using to disply posts manually.
<code>    <?php query_posts('post_type=product&product_cat=striped-mats'); ?>
    <?php single_cat_title( ); ?>
    <?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>
    <?php the_content();?>
    <?php endwhile;
      wp_reset_query();?>
    <?php endif; ?>
</code>
Thanks to everyone who would want to help me with this...
Answer: First of all you can use this service that can write the code for you : http://generatewp.com/
This is a cool tool that allowing you to build the code for several parts of the WordPress theme.
Otherwise you can use the WP_Query class to create a query object like that:
<code>$products = new WP_Query(
    array(
        'post_type'              => 'product',
        'post_status'            => 'publish',
        'cat'                    => 'product_cat',
        'category_name'          => 'striped-mats',
    )
);

if($products->have_posts())
{
while($products->have_posts())
    {
        $products->the_post();
        // do something
}
}
else
{
// Np products found
}
</code>
Comment: Don't forget to add wp_reset_postdata() after you've looped through your query.
Answer: Thanks you for your time and effort to answer my question.
The thing is that I need a loop that will list terms and posts assigned to that terms but with prediction that user will add new terms. So in short if a user adds term and a post to that term it is displayed in the site.

List posts from taxonomy term


API for monitoring AWS lambda and other instances pricing in real time?

Question: I am looking for a programmatic way to monitor my lambda serverless environment cost in real time, or x hours retrospective. I am looking at the budget API but it seems like it always goes around a defined budget which is not my use case. The other way I thought might work is the count lambda executions and calculate according to lambda instance type. Any insight or direction how to go about this programmatically would be highly appreciated.
Answer: From Using the AWS Cost Explorer API - AWS Billing and Cost Management:

The Cost Explorer API allows you to programmatically query your cost and usage data. You can query for aggregated data such as total monthly costs or total daily usage. You can also query for granular data, such as the number of daily write operations for DynamoDB database tables in your production environment.

Cost Explorer refreshes your cost data at least once every 24 hours, so it isn't "real-time".


Performing a state persistance in Aurelia Store

Question: We have a basic app state that needs to be persisted upon the browser refresh. similar to vuex-state-persistance plugin. Here is the basic state code that needs to be persisted.
export const initialState = {
    user: {
        uuid: 'wedRfertYjsnjnakUiisdj878HBhsns',
        name: 'Kiran Maniya',
        scope: 'user'
    }
};

Is there anything that can be used directly as a plugin or I need to write a custom plugin that persists the state in localStorage asynchronously? Also, how do we modularise the state when we have a complex and large state to manage?
Comment: I did custom localStorage based solution.
Comment: Were you able to resolve this??
Comment: Could U add that as an answer here so we can benefit from it?
Answer: Aurelia Store provides a built-in mechanism to persist state in localStorage.
So, if your initialState goes initialized in main.ts or main.js something like this:
aurelia.use.plugin('aurelia-store', { initialState: initialState });

Then in app.ts or .js you should register the localstorage middleware and perform a rehydration.
So, in app constructor, you could write:
import { localStorageMiddleware, rehydrateFromLocalStorage, Store } from 'aurelia-store';
import { initialState, State } from 'state';
...
constructor(
    private store: Store<State>,
  ) {
    store.registerMiddleware(localStorageMiddleware, MiddlewarePlacement.After, { key: ¨someKey¨ });
    store.registerAction('Rehydrate', rehydrateFromLocalStorage);
}

Regarding modularization, maybe you should combine store and the EventAggregator to implement more complex scenarios.
Good luck
Comment: Can you extend your answer to show how U will then insert data into the store??
Comment: It's done by the middleware. The parameter **MiddlewarePlacement.After** means that after every state change, it is saved to localstorage under the specified key.


Composition of mulitvariable functions with different dimensions

Question: I have $\gamma : (0,\infty) \to \mathbb{R}^3\backslash\{0\}, \gamma (t) :=\begin{pmatrix} -t\\t \\ t^2 \end{pmatrix}$ and $f: \mathbb{R}^3 \backslash \{0\} \to \mathbb{R}^2, f(x)=\begin{pmatrix} \sin |x|_2 \\ |x|_2^3+1 \end{pmatrix}$. What is $f \circ \gamma : (0,\infty) \to \mathbb{R}^2$? I thought I could just add a $0$ to $f(x)=\begin{pmatrix} \sin |x|_2 \\ |x|_2^3+1 \\ 0 \end{pmatrix}$ and exchange the variables component-wise, but I guess this doesn't work out, since the output of $f\circ \gamma$ has to be two-dimensional.
Comment: typo in the first sentence
Comment: Thank you, edited.
Answer: You want to think of $\gamma (t)$ as $x.$ Thus
$$(f\circ \gamma) (t) =f(\gamma (t))= (\sin |\gamma (t)|, |\gamma (t)|^3+1).$$
Now note $|\gamma (t)|= (t^2 + t^2 + t^4)^{1/2}.$
Comment: Is $$(f\circ \gamma)'(1)=\begin{pmatrix} \sin(3)\\ 3\sqrt{3}\end{pmatrix}$$ correct?


How do I connect this cables to my surface socket australia

Question:
I know red go together and black cables go together.
But what do I do with yellow and there is copper out of one black red pair what is that where do I connect that, and this is going to my surface socket for dowlight..
Your suggestion is appropriated.
Thanks in advance.
Comment: Does the yellow wire have green stripes?
Comment: Are you sure your electrical codes don't require you to make those splices inside junction boxes? Is one of the cables going to a switch?
Comment: No yellow wire is full yellow.. And it is going to common in the switch.. If that helps
Answer: If you know how the old light was hooked up, connect it in the same way, and ensure that all cables are suitably restrained (e.g. pinclips near the socket, or cable ties).
If you don't know, then this is almost certainly electrician time. It's likely that what's been done is no longer common practice, and possibly no longer legal. It's unclear simply from wire colours how it's hooked up; one would need to not just trace out how it is wired, but understand why.


How to print a variable that is tied to a word Arduino?

Question: I need my Arduino code to print out random words that are substituted as a variable. So like I would have a random number generator the spits out random numbers that are tided to a word that then as a variable needs to be printed out. Here is my code now, sorry I am still a beginner to Arduino.
long randnumber = 0;

int aye = 1;
int sup = 2;
int boi = 3;
int bruv = 4;

void setup() {
  Serial.begin(9600); // Starts the serial communication

}

void loop() {
int randnumber = 0;
  randnumber = random(0,4);
  Serial.println(randnumber);

}

Answer: You need to put the words into an array:
const char *words[] = {"aye", "sup", "boi", "bruv"};

Then pick a random index and send the word at that index:
// Calculate the number of words. Better than hardcoding
// 4. If you add/remove words from array, this code
// won't have to change
int num_words = sizeof(words) / sizeof(words[0]);
randnumber = random(0, num_words);
Serial.println(words[randnumber]);

You should also seed the RNG else you will get the same results each time. On a PC, people often seed the RNG with the current time, but there is no clock on the Arduino so it is more difficult. Here's a good discussion on that: Getting a truly random number in Arduino.
Comment: the question you link is about getting true randomness as opposed to pseudo randomness, while picking a seed for a prng does not make it less pseudo. Not saying that you wrote anything wrong, just that it could be misunderstood as being able to get getting true randomness from a prng if you just pick a good seed
Comment: @user463035818 True. I just included the link since some of the answers address picking a good seed. `randomSeed(analogRead(0))` is probably sufficient for this application.
Comment: @JohnnyMopp Hey thank you so much for the quick and awesome answer. I posted this at 1 in the morning and when I woke up my question has been answered, soo awesome. Will try to implement it in my code now. ;-)))


Custom post meta list only the upcoming events

Question: I have created a custom post type called "Events". One custom field is the date of the event and I need to query the posts based on this date, and only show future events. I've gotten close, but can't seem to figure out how to integrate the filter with the code I've already written. This is my code. thanks,
<code>    $today = date('dd-MM-yy');
    $args = array(
            'post_type'         => 'events',
            'posts_per_page'    => 2,
            'meta_key'          => 'events_date',
            'orderby'           => 'meta_value_num',
            'order'             => 'ASC',
            'meta_value_num'    => $today,
            'meta_compare'      => '>'
        );

    $events = new WP_Query( $args );
</code>
Comment: I tried, It's not worked.
Answer: try this
<code>$today = date('dd-MM-yy');
$args = array(
        'post_type'         => 'events',
        'posts_per_page'    => 2,
        'meta_key'          => 'events_date',
        'orderby'           => 'meta_value',
        'order'             => 'ASC',
        'meta_query' => array(
           array(
             'key' => 'events_date',
             'value' => $today,
             'compare' => '>',
           )
        )
    );

$events = new WP_Query( $args );
</code>


Can I add onto a 15 amp circuit with 12 gauge wire?

Question: I have 14 gauge wire on a 15 amp breaker. I want to add a ceiling fan, so from the switch that's fed by 14 gauge wire. Should I continue to feed the fan with 14 gauge wire or would it be OK to feed the fan from the switch with 12 gauge wire?
Comment: The one thing I would caution is that it's possible that in the future someone might see the 12 gauge wire and assume it's a 20 amp circuit, so you may want to mark the wire somehow.
Answer: You can always up size wire from the minimum required by code, therefore yes, you can do your new wiring extension with #12 on a 15A breaker. Note that when you start getting into big wires, you run into issues with connectors, but at #12 & #14 size, standard wire nuts, Wagos, etc. will all work just fine.
There is a cost associated with going with bigger wire, so unless you've got some #12 sitting around, burning a hole in your pocket, #14 would be less expensive.
There are recommendations to add a label to the panel if you have a 15A breaker with #12 wire going to it and #14 wire elsewhere in the circuit, but in your case, with just one run of #12 between switch & fan, there shouldn't be any need to worry about that. Nobody will be confused when they open the panel and see #14 going into the 15A breaker.
If your fan also has a light and they can be run from a pair of switches (as opposed to either the lights or fan being controlled by a remote) and only has one neutral at the ceiling, you'll want to run a /3 cable (black, red, white, ground) so that you're not paralleling your neutral with two separate runs of /2 cable.


Two consecutive kernels or whole-grid cooperative group synchronization?

Question: Suppose I have two tasks to run on a GPU, the second of which relying on essentially all work by the first. Traditionally, I would essentially have to write these tasks as two separate kernels and schedule the second to run at some point after the first. But - with CUDA 9, I can now synchronize on the entire grid concluding its work on the first task - using the cooperative groups feature, then proceed to have the grid do its second-task work.
My questions are:

Can we provide a rule-of-thumb regarding when it is better, in terms of performance to write two kernels, and when to use whole-grid synchronization?
If so, what would it be?
If not - why is it difficult to determine which is preferable in which cases?
Answer: Making this a CW answer so others feel free to add their opinions and edit.
The grid-wide sync feature in cooperative groups carries with it a requirement to limit the thread complement (size of the grid) to whatever is the carrying capacity of the GPU you are running on.  This isn't a major performance limiter, but it requires you to write code that can flexibly use different grid sizes while still achieving max performance.  grid-stride loops are a typical component of such a coding strategy.
Therefore the grid-wide sync feature will often require careful coding and additional code overhead (e.g. use of the occupancy API) to achieve maximum performance, especially compared to simple or naive kernels.
To offset this possible reduction in programmer productivity, some possible benefits are:

In the situation where launch overhead is a significant portion of the overall runtime, then the cooperative grid-wide sync may afford significant benefit.  In addition to the fusion of 2 separate kernels, algorithms that may call kernels in a loop, for example jacobi iteration/relaxation, or other timestep simulation algorithms, may benefit noticeably, since the launch loop can effectively be "moved onto the GPU", replacing a loop of kernel launches with a single kernel call.
In the situation where there is a significant amount of on-chip "state" (e.g. register contents, shared memory contents), which is needed to be loaded before the grid-wide sync, and will be used after the grid-wide sync, then cooperative groups may be a significant win, saving the time in the kernel that would have followed that grid-wide sync, that would have been used to re-load state.  This appears to have been the motivation here (see section 4.3) for example.  I'm not suggesting they were using cooperative groups (they were not).  I'm suggesting they were motivated to seek a grid-wide sync, using makeshift methods available at the time, to eliminate both the cost of state reload, plus possibly the cost of kernel launch overhead.
Comment: How much "state" is significant A full shared-memory's worth? Less? More?


Is there a way to combine multiple powerbi api requests in to a single restapi call? Something like a batch request to get a collective response?

Question: I'm trying to reduce the api calls to fetch data out of powerbi rest api. when i call endpoint like /Groups, The response is straight forward in a single api call, I get all the groups. in order to get datasets,dashboards and reports i'll have to pass every group id to endpoints of reports,datasets.,etc.
eg.
GET https://api.powerbi.com/v1.0/myorg/groups/{groupId}/datasets
Is there a way to combine these requests, such a way that i send multiple group ids in a single api call to get all the datasets from their respective groups?
I have not found a way to combine it all together to make a single batch api call.
However, I tried a different endpoint found from MSDocs to avoid input of group id.
GET https://api.powerbi.com/v1.0/myorg/datasets
But the problem with this is, the response wont have information of which group the dataset belongs to. without group information,the retrieved data wont be useful for me.
https://learn.microsoft.com/en-us/rest/api/power-bi/datasets
Answer: You must use the admin part of the API. To get a list of all groups in your organization, call GetGroupsAsAdmin (you can filter what you want to get too). Similarly, call GetDatasetsAsAdmin to get list of datasets. Look at their webUrl property to find their group.
https://api.powerbi.com/v1.0/myorg/datasets wont return all datasets (or datasets from multiple groups) but will give you the datasets located in your own My workspace.
Comment: No, it's not possible. If you can provide a meaningful filter in the admin call, use it. Otherwise you need to call the API multiple times
Comment: Hi Andrey, I was aware of that. my question is more like.

how can i pass multiple ids in a single api call.. like
`
https://api.powerbi.com/v1.0/myorg/groups/{group 1}/datasets

https://api.powerbi.com/v1.0/myorg/groups/{group 2}/datasets
`

is it possible to send both group1 and group2 in a single api call. something like a batch request or something. so in a single response i get results of multiple groups.


How to use POST request to implement browser download EXCEL function .Or, should I not use POST?

Question: I have done some EXCEL file export functions before, but they are all implemented using GET requests. The method I use is like this

// export excel module
handleExportTemplate:_debounce(function(){
  window.location.href = process.env.BASE_API + `/export/excelDownload`
}),

I used the [window.location.href] method to let the browser download Excel automatically, but today the back-end engineer asked me to use a POST request and pass the parameters to him in the body. The data is similar to this:

data:{
userIdList:["1","2","3","4","5"],
ifShow:true,
ifDownLoadNow:true,
}

but using window.location.href, I don't know how to return these parameters to the backend engineer
In addition, I tried sending it to him using a normal POST request, and he did successfully return a file to me, but I couldn't get the browser to download it automatically through window.location.href
I tried to convince him to use GET request for this function, but he won't listen to me.
Is it really appropriate to use POST for download requests? Is he wrong or I know too little? If it's my fault, how can I complete the POST request and be able to download EXCEL?
Comment: why aren't you using forms with prefilled data attributes?
Answer: There is no problem in using a POST request to download a file. Especially when you create your file with many data. In that case, a get request is limited in length, where a POST is not.
I do not know any way to send a POST request using only window.location.href, but what you want can be achieved with JavaScript.
One way is to use the fetch API :

const resp = await fetch('/your/url',{ method : 'POST', body : { /**@ your data **/ } });
const fileContent = await resp.text();

And then, you can make the browser download the file by using a function like this :
function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

It will create an invisible link temporarily with the download attribute and automatically click it to download the in-memory file.


How to translate mouse movement to a rotation gizmo?

Question: I need to implement translation, scaling and rotation gizmos and I'm having trouble with the rotation gizmo. Basically I don't know how to translate the mouse movement to determine in which direction to rotate the object.
By rotation gizmo (widget) I mean something like the below:

For the translation and scaling gizmos, which are represented as 3 axes, I do the following: I make a vector of the difference between the previous and current mouse position in screen space. Then multiply this vector by the inverse of the view and projection matrices, which gives me a vector of the mouse movement in world space. Then I take the dot product of the vector in world space with the  selected axis. This allows me determine if the mouse movement is in line with the axis or away from the axis.
But I can't do the same thing for the rotation gizmo. The rotation gizmo is represented as 3 circles, each representing a rotation around an axis. Once a circle is clicked, I need to find some way to translate the mouse movement to determine which direction to rotate the object around the selected axis. I don't know how to do this. Please help.
It is important to note that I am using color picking and not raycasting to determine where the gizmo was clicked. This means that I don't have the point at which the ray hits the gizmo in world space to start from. I mention this because I've looked at examples that use raycasting like libgizmo and I don't think I can do the same thing.
Thanks in advance for any help.
Comment: It took me a second to understand what you meant by a rotation gizmo. I added an image of one in case it's helpful (i think you can't add images until you have more reputation sadly!).  If you have a more appropriate image in mind, feel free to let me know and i can change the image.
Comment: Thanks for adding the image Alan. You are right, I think it will make things clearer.
Comment: Fwiw I think you are right. Using color based selection isn't going to work for this.
Answer: Ratchet Freak's answer might work. I'm not sure, I didn't spend much time on it because I didn't know how to create the quaternion from the dot and cross product as described.
What we ended up doing was:

Project the center of the gizmo to screen space.
Get the angle between the vectors GizmoToLastMouse and GizmoToCurrentMouse using the dot product formula: acos(Dot(GizmoToLastMouse, GizmoToCurrentMouse) / (GizmoToLastMouse.Length() * GizmoToCurrentMouse.Length()))
Get the sign of the angle by taking the cross of the GizmoToLastMouse and GizmoToCurrentMouse and dotting it with the screen normal.
Get another sign (times 1.0f or -1.0f) based on the orientation of the gizmo, by taking the dot product between the rotated axis and a vector from the center of the gizmo to the camera
Apply the rotation based on the angle and the two signs to the appropriate axis

There might be a better way to do it, but this works pretty well for our needs.
Comment: a quaternion is built as `quat(cos(angle/2), axis*sin(angle/2))` and you know that the dot product us equal to cos(angle) times the product of the lengths and the cross product is the axis times sin(angle) times the product of the lengths. Normalize it and you can easily get the quaternion of the same rotation but with double the angle. To get the proper quaternion you can do `slerp(unit, quat, 0.5)` which after inlining ends up as `normalize(unit+quat);`
Answer: Map the mouse position to the circle by drawing an imaginary line between the mouse and the center of the gizmo on the plane of the current circle. Do this for the start and current positions.
Then you can easily get the quaternion rotation around the center from the start to the end by doing normalize(quat(1+dot(v_1, v_2), cross(v_1, v_2))).
This works because the dot product is the cos of the angle between the vectors and the cross is the vector perpendicular to the 2 vectors (aka the rotation angle) and has length of the sin of the angle between the vectors. This means that you can create the double quaternion out of them. Then you can nlerp that double quaternion with the unit quaternion to get the rotation you need.
However with that information you can do an arcball by projecting the mouse onto the ball that is the gizmo and using the start and end vectors that way.
Comment: THis answer really needs a picture


Can I plug my E27 bulb directly into my wall socket

Question: Assuming I have an E27 lightbulb such as this:
https://web.archive.org/web/20150928143146/http://www.wartena.com/en/light-bulbs/6-philips-spaarlamp-e27-14w-65w-8710163224138.html
and I have fixed it onto a E27 mount, and perhaps wire it to a plug that looks like this:

Can I just plug it directly into a wall socket?
I'm in Malaysia and we run 240V from the wall sockets.
I don't really know how voltage comes into play here for bulbs or if a transformer is required.
Like I notice that all our other electronics have transformers. E.g. our cellphone and laptop chargers have some intermediate box that does necesary conversions.
Answer: Compact Fluorescent Lightbulbs
So long as the lightbulb is rated for 240V (and not 110V or 120V) it will work when connected as you suggest. In countries with 240V household outlets, retailers will normally supply lightbulbs rated for 240V. Check the packaging and the lightbulb itself - the voltage will be marked on them.
There is a manufacturer's datasheet for the part with EAN code 8710163224138. It says "• Voltage: 220-240 V" - so this is OK.
A home-made light fitting of this sort may not meet your local electrical safety code (i.e. law). Normally there has to be an enclosure designed for the purpose. The enclosure provides mechanical protection to the lightbulb (especially any glass parts) and provides some protection against people inadvertently touching parts that carry live current or which might do so in a fault condition.
You also need to pay attention to earthing any metal parts that are accessible.
In particular, compact-fluorescent lightbulbs of that sort are relatively delicate and, if broken, will leak mercury - which is poisonous. It is prudent to provide some protection in case the luminaire is accidentally knocked over or bumped into.
Other lightbulbs
Some lightbulbs are designed for low voltage. For example some desk-lamps use halogen bulbs that require 12V DC. These desk-lamps are supplied with a suitable transformer. These lightbulbs should never be directly connected to 240V AC.
These type of lightbulbs will never be provided in a E27 fitting. In general, you can be sure that any commercial lightbulb with an E27 fitting supplied in a well-regulated country by a reputable vendor is suitable for your local household electrical supply (e.g. 240V AC)
Other appliances
As you note, phone "chargers" and similar items contain a transformer that typically convert the household electrical supply (e.g. 240V AC) to a voltage suitable for the small appliance (e.g. 5V DC).


Tapping Neutral in Service Entrance

Question: (Back to original message because tapping utility pole ground rod directly is not good idea because in our country, robbers like to steal wiring, so if they remove the neutral, and they form a series, they can get shock or worse...)
Background for the experts who have helped me so much in the past. This is my last question. I need to activate grounding before I do all the projects I have asked advices the past month.
In my country the Philippines. 99.9999% of homes don't have any grounding. This is because we never use neutral to produce 120v. We only use 240v. And we have the same split phase power system as the US because they created our ac power system. But after they left and to promote national patriotism, we outlawed use of any 120v so we won't rely on products from the US (this is what the utility company exactly told me).
Also in my country. Contractors omit the third grounding wire because all our appliances don't have any third grounding wire. Even Refrigerators have only 2 prong plug.
Now I need to tap the neutral outside the service entrance directly to my Siemens panel. This is for protection in case hot wire touches the enclosure (so it can trip the breakers. I know the reasons and the rules for grounding and only bonding it at the panel). I want to know what kind of metal connector that I can use to connect or tap a AWG 10 side by side with the AWG 0/1 neutral wire in the service entrance, one that will not rust even after exposed to sun and rains for decades. Is there such a connector? I won't connect them end to end but just tap the open wire at the middle body of it (see photo below). It is much larger than my AWG 10. What connector can do that?
This is our service entrance neutral wire hanging (not inserted into the service entrance).

Here all our apartments have 2 wire going into the conduit and my home is 20 meters inside the compound, therefore I need to connect the AWG 10 by attaching it outside the house frames on the way to the Siemens neutral conductor lugs. I can't do the usual way of wiring it via the service entrance and main panels because I can no longer insert the wires 20 meters away. See.
Answer: A split bolt connector would seem to be right for this. Use electrical joint compound (such as Burndy Penetrox) then tape over the joint.
However, you would have to separate the neutral/ground enough from the insulated conductors and then tape over the split bolt and maybe interpose a piece of plastic or rubber so that it would not over time wear a hole in the insulation and cause a short.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/86211/discussion-on-answer-by-jim-stewart-tapping-neutral-in-service-entrance).

Tapping Neutral in Service Entrance


Failing web.config transform when no value exists for a transform

Question: We had a bit of an incident today which has got me thinking. We have a project with a pretty standard web.config transform setup for our various configs. There is a section which controls access to our DAO services which looks like this:
<endpoint address="http://myserver/myservice1.svc/basicHttp"
binding="basicHttpBinding" contract="MyAssembly.IItem" name="DataAccessEndPoint"
kind="" endpointConfiguration="" />
<endpoint address="http://myserver/myservice2.svc/basicHttp"
binding="basicHttpBinding" contract="MyAssembly.IItem2" name="LoggingEndPoint"
kind="" endpointConfiguration="" />

And a transform like this:
<endpoint address="http://mytestserver/myservice1.svc" name="DaoEndPoint" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"  />
<endpoint address="http://mytestserver/myservice2.svc" name="LoggingEndPoint" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"  />

Hopefully you will have spotted the error here - the name for the DaoEndPoint doesn't match. Unfortunately the dev who created it didn't, and had also been locally debugging against the live services, which caused the test deployment to, yup, point to live. We luckily picked it up pretty quickly, but I'm sure you can see the potential for extreme pain here!
I got thinking about your intent when creating transform files and it seems to me that if you put in a transform that you intend to transform something. So it would be nice if the transform (and therefore the deploy) failed if there was a DaoEndPoint transform but no matching DaoEndPoint item in the main .config file.
So I'm sort of canvasing for people's opinions, is this something that would be useful? Is it plain overkill? Am I totally missing the point?
Also, is there anything out there that does this? I'm happy to dig about and develop a solution, but I'd be happier if someone had done the legwork for me ;)
Comment: Don't know anything that will cause an exception, though could be useful. Might want to just try leaving the value blank in the main web.config and if it doesn't get transformed, you'll quickly get an error in the application.  Not as helpful, but prevents any unintentional PROD access.
Comment: The problem with this is that you then can't debug locally without adding in a value, which takes us back to the original issue when the dev forgets to take that value out again...
Answer: See Sayed Ibrahim Hashimi's great answer to this question, which involves creating a custom class that inherits from Microsoft.Web.Publishing.Tasks.Transform. You could use the same technique but inherit from the Locator class instead, and then throw an exception when you are unable to match a target node.
I actually tested this myself and was able to have the exception thrown during publishing. However, my custom locator class (MyMatch) didn't actually do anything besides throw the exception. It might be a fair bit of work to override methods to mimic the Match class (which you can't inherit from) and then figure out the appropriate place to do a final check for a failure to match.
Anyway, I definitely think it would be useful to at least have an option that you could set where publishing would fail or give you a warning when your transform had no effect.
Comment: Brill, this is just the sort of thing I was looking for, I'll try and get something put together and posted on github in the next couple of weeks. (Apologies for late reply by the way, on vacation with no internet!)


Karma Jasmine: Same Function Name, Two different source files

Question: I have 2 source files to test:

a.js
b.js

They both have a function validate();
In writing bSpec.js and testing b.js's validate function, I find that a.js's validate is the one being called.  Do I have a way to specify which source file is the one to be tested?
both a.js and b.js are included in the karma-config via the files block using 'js_files/**/*.js'
Comment: What are the contents of these file?
Comment: I don't believe there is (In Javascript anyway, I'm not familiar with Karma/Jasmine so can't speak on behalf of that). What you can do though if `validate()` is being called in a.js instead of b.js then you can change the function name to `validateA()` or `validateB()`.
Answer: When importing both files try providing each with an alias and use that to run the method you want.
Something like:
import * as fileA from './a.js'
fileA.validate();


select distinct elements from two columns with comma separated in sql

Question: I have a table with two columns like this
col1     col2
 a        b
 b        a
 c        d
 d        a

I want to get distinct values of these two columns combined with comma separated.
Expected out put is like this
a,b,c,d

Comment: possible duplicate of [SQL group\_concat function in SQL Server](http://stackoverflow.com/questions/8868604/sql-group-concat-function-in-sql-server)
Answer: The following example concatenate row values into a variable
DECLARE @val nvarchar(max)
SELECT @val = COALESCE(@val + ',' + col1, col1)
FROM (SELECT col1
      FROM dbo.twoColumns
      UNION
      SELECT col2
      FROM dbo.twoColumns
      ) x
SELECT @val

Demo on SQLFiddle
Answer: try this , its very much easy i think
select group_concat(distinct(c)) as d
from
(
  select col1 c from your_table
  union
  select col2 c from your_table
) as d

Comment: I get the data correclty by this method ,but is not comma seperated :(
Comment: `group_concat` is only valid in MySQL and the question is tagged as SQL Server.


Android connect to database with password authentification using Kotlin

Question: I'm trying to program a simple android app with database connection, however I've only recently started with Kotlin and so far, even after several hours of searching, I haven't found an understandable tutorial that shows how to enter/read something into a database via Kotlin.... Can anyone help here or has a good tutorial?
I've tried SQLiteOpenHelper so far, since I haven't found an alternative for MySQL (both MySQL and SQLite are installed and set up on my server). However, with SQLiteOpenHelper, I can't seem to specify a password to authenticate with the database....
Answer: You should go for Room Database
As per android developer docs:

The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

Room Database is the best.
Also, has support for RxJava as well as LiveData and Flows.
I recommend using Flows.
Comment: First of all, thanks for taking the time to answer, but I think my question was a bit misleading; from what I've read Room Database is a local database on the respective Android device, but I need access to an external database as the data should be retrievable across devices, do you have a tutorial or similar on this as well, if possible using MySQL or SQLite in conjunction with a password for authentication? As I said, so far I have only found the SQLiteOpenHelper, which apparently can not pass a password and which apparently also only uses a local database...


Convert UTC date format into javascript format

Question: How can I convert a date from:
Thu, 1 July 2011 22:30:00 to '2011-07-01T13:51:50.417' using javascript.
I get the UTC format when I do a new date.
IE causes me issues when I first create a date object as it shows: NaN
Answer: You could generate a new Date-Object and then get the different parts:
var today = new Date();
var year = today.getFullYear(); // Returns 2012
var month = today.getMonth()+1; // Returns the month (zero-based)
...

Then you can create a new string like you need it.
Answer: possible duplicate try search next time
stackoverflow question
Try http://www.datejs.com/. It is a JavaScript Date Library with an extended Date.parse method and a Date.parseExact method, which lets you specify a format string. See DateJS APIDocumentation.
and then you can manipulate it as you want
Answer: The d3.js library has some very solid routines for date conversions. See https://github.com/mbostock/d3/wiki/Time-Formatting#wiki-parse.


Save and Restore Form Position and Size

Question: In a WinForms 2.0 C# application, what is the typical method used for saving and restoring form position and size in an application?
Related, is it possible to add new User scoped application settings AT RUNTIME? I totally see how to add settings at design time, that's not a problem. But what if I want to create one at runtime?
More details:
My application is a conversion of an existing Visual FoxPro application. I've been trying to read as much as I can about application settings, user settings, etc. and get myself clear on the .Net way of doing things, but there are still several things I am confused on.
In the Fox app, saved settings are stored in the registry. My forms are subclassed, and I have base class code that automatically saves the form position and size in the registry keyed on the form name. Whenever I create a new form, I don't have to do anything special to get this behavior; it's built in to the base class. My .Net forms are also subclassed, that part is working well.
In .Net, I get the impression I'm supposed to use User scoped settings for things like user preferences. Size and location of a form definitely seem like a user preference. But, I can't see any way to automatically add these settings to the project. In other words, every time I add a new form to my project (and their are 100's of forms), I have to remember to ADD a User scoped application setting and be sure to give it the same name as the form, i.e.,  "FormMySpecialSizePosition" to hold the size and position. I'd rather not have to remember to do that. Is this just tough luck? Or am I totally barking up the wrong tree by trying to use User scoped settings? Do I need to create my own XML file to hold settings, so that I can do whatever I want (i.e, add a new setting at runtime)? Or something else?
Surely this is very common and somebody can tell the "right" way to do it.
Comment: You might find a question I aksed a while ago useful. It has a partly complete solution for a form base you can inherit from to make a form persist its bounds and location. You would probably just need to make it store its settings in an xml file or something like that.
Answer: private void Form1_Load( object sender, EventArgs e )
{
    // restore location and size of the form on the desktop
    this.DesktopBounds =
        new Rectangle(Properties.Settings.Default.Location,
    Properties.Settings.Default.Size);
    // restore form's window state
    this.WindowState = ( FormWindowState )Enum.Parse(
        typeof(FormWindowState),
        Properties.Settings.Default.WindowState);
}

private void Form1_FormClosing( object sender, FormClosingEventArgs e )
{
    System.Drawing.Rectangle bounds = this.WindowState != FormWindowState.Normal ? this.RestoreBounds : this.DesktopBounds;
    Properties.Settings.Default.Location = bounds.Location;
    Properties.Settings.Default.Size = bounds.Size;
    Properties.Settings.Default.WindowState =
        Enum.GetName(typeof(FormWindowState), this.WindowState);
    // persist location ,size and window state of the form on the desktop
    Properties.Settings.Default.Save();
}

Comment: This solution has a problem if you close the window in a minized state.
Comment: This solution also doesn't work if you're not writing an application e.g. if you're writing a plugin. It also doesn't mention how to set up or configure Properties which isn't obvious and requires a documentation search.
Answer: There is actually a real lack of a single, "just works" solution to this anywhere on the internet, so here's my own creation:
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Win32;
using System.ComponentModel;
using System.Security.Cryptography;

namespace nedprod
{
    abstract public class WindowSettings
    {
        private Form form;

        public FormWindowState state;
        public Point location;
        public Size size;

        public WindowSettings(Form _form)
        {
            this.form = _form;
        }
        internal class MD5Sum
        {
            static MD5CryptoServiceProvider engine = new MD5CryptoServiceProvider();
            private byte[] sum = engine.ComputeHash(BitConverter.GetBytes(0));
            public MD5Sum() { }
            public MD5Sum(string s)
            {
                for (var i = 0; i < sum.Length; i++)
                    sum[i] = byte.Parse(s.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
            }
            public void Add(byte[] data)
            {
                byte[] temp = new byte[sum.Length + data.Length];
                var i=0;
                for (; i < sum.Length; i++)
                    temp[i] = sum[i];
                for (; i < temp.Length; i++)
                    temp[i] = data[i - sum.Length];
                sum=engine.ComputeHash(temp);
            }
            public void Add(int data)
            {
                Add(BitConverter.GetBytes(data));
            }
            public void Add(string data)
            {
                Add(Encoding.UTF8.GetBytes(data));
            }
            public static bool operator ==(MD5Sum a, MD5Sum b)
            {
                if (a.sum == b.sum) return true;
                if (a.sum.Length != b.sum.Length) return false;
                for (var i = 0; i < a.sum.Length; i++)
                    if (a.sum[i] != b.sum[i]) return false;
                return true;
            }
            public static bool operator !=(MD5Sum a, MD5Sum b)
            {
                return !(a == b);
            }
            public override bool Equals(object obj)
            {
                try
                {
                    return (bool)(this == (MD5Sum)obj);
                }
                catch
                {
                    return false;
                }
            }
            public override int GetHashCode()
            {
                return ToString().GetHashCode();
            }
            public override string ToString()
            {
                StringBuilder sb = new StringBuilder();
                for (var i = 0; i < sum.Length; i++)
                    sb.Append(sum[i].ToString("x2"));
                return sb.ToString();
            }
        }
        private MD5Sum screenconfig()
        {
            MD5Sum md5=new MD5Sum();
            md5.Add(Screen.AllScreens.Length); // Hash the number of screens
            for(var i=0; i<Screen.AllScreens.Length; i++)
            {
                md5.Add(Screen.AllScreens[i].Bounds.ToString()); // Hash the dimensions of this screen
            }
            return md5;
        }
        public void load()
        {
            using (RegistryKey r = Registry.CurrentUser.OpenSubKey(@"Software\" + CompanyId() + @"\" + AppId() + @"\Window State\" + form.Name))
            {
                if (r != null)
                {
                    try
                    {
                        string _location = (string)r.GetValue("location"), _size = (string)r.GetValue("size");
                        state = (FormWindowState)r.GetValue("state");
                        location = (Point)TypeDescriptor.GetConverter(typeof(Point)).ConvertFromInvariantString(_location);
                        size = (Size)TypeDescriptor.GetConverter(typeof(Size)).ConvertFromInvariantString(_size);

                        // Don't do anything if the screen config has since changed (otherwise windows vanish off the side)
                        if (screenconfig() == new MD5Sum((string) r.GetValue("screenconfig")))
                        {
                            form.Location = location;
                            form.Size = size;
                            // Don't restore if miminised (it's unhelpful as the user misses the fact it's opened)
                            if (state != FormWindowState.Minimized)
                                form.WindowState = state;
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
        public void save()
        {
            state = form.WindowState;
            if (form.WindowState == FormWindowState.Normal)
            {
                size = form.Size;
                location = form.Location;
            }
            else
            {
                size = form.RestoreBounds.Size;
                location = form.RestoreBounds.Location;
            }
            using (RegistryKey r = Registry.CurrentUser.CreateSubKey(@"Software\" + CompanyId()+@"\"+AppId() + @"\Window State\" + form.Name, RegistryKeyPermissionCheck.ReadWriteSubTree))
            {
                r.SetValue("state", (int) state, RegistryValueKind.DWord);
                r.SetValue("location", location.X.ToString() + "," + location.Y.ToString(), RegistryValueKind.String);
                r.SetValue("size", size.Width.ToString()+","+size.Height.ToString(), RegistryValueKind.String);
                r.SetValue("screenconfig", screenconfig().ToString(), RegistryValueKind.String);
            }
        }
        abstract protected string CompanyId();
        abstract protected string AppId();
    }
}

This implementation stores the position and size of a form in HKCU/Software/<CompanyId()>/<AppId()>/Window State/<form name>. It won't restore settings if the monitor configuration changes as so to prevent windows being restored off screen.
Obviously this can't handle multiple instances of the same form. I also specifically disabled restoring minimised but that's an easy fix of the source.
The above is designed to be dropped into its own .cs file and never touched again. You have to instantiate a local namespace copy like this (in Program.cs or your plugin main .cs file or wherever):
namespace <your app/plugin namespace name>
{
    public class WindowSettings : nedprod.WindowSettings
    {
        public WindowSettings(Form form) : base(form) { }
        protected override string CompanyId() { return "<your company name>"; }
        protected override string AppId() { return "<your app name>"; }
    }
    ....

Now you have a non-abstract instantiation in the main namespace. So, to use, add this to the forms you want saved and restored:
    private void IssuesForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        new WindowSettings(this).save();
    }

    private void IssuesForm_Load(object sender, EventArgs e)
    {
        new WindowSettings(this).load();
    }

Obviously feel free to customise to your own purposes. No warranty is expressed or implied. Use at your own risk - I disclaim any copyright.
Niall
Answer: I got this code from somewhere, but unfortunately at the time (long ago) didn't make a comment about where I got it from.
This saves the form info to the user's HKCU registry:
using System;
using System.Windows.Forms;
using Microsoft.Win32;

/// Summary description for FormPlacement.
public class PersistentForm : System.Windows.Forms.Form
{
    private const string DIALOGKEY = "Dialogs";

    ///
    protected override void OnCreateControl()
    {
        LoadSettings();
        base.OnCreateControl ();
    }

    ///
    protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
    {
        SaveSettings();
        base.OnClosing(e);
    }

    /// Saves the form's settings.
    public void SaveSettings()
    {
        RegistryKey dialogKey = Application.UserAppDataRegistry.CreateSubKey(DIALOGKEY);
        if (dialogKey != null)
        {
            RegistryKey formKey = dialogKey.CreateSubKey(this.GetType().ToString());
            if (formKey != null)
            {
                formKey.SetValue("Left", this.Left);
                formKey.SetValue("Top", this.Top);
                formKey.Close();
            }
            dialogKey.Close();
        }
    }

    ///
    public void LoadSettings()
    {
        RegistryKey dialogKey = Application.UserAppDataRegistry.OpenSubKey(DIALOGKEY);
        if (dialogKey != null)
        {
            RegistryKey formKey = dialogKey.OpenSubKey(this.GetType().ToString());
            if (formKey != null)
            {
                this.Left = (int)formKey.GetValue("Left");
                this.Top = (int)formKey.GetValue("Top");
                formKey.Close();
            }
            dialogKey.Close();
        }
    }
}

Answer: You could create a base form class with common functionality such as remembering the position and size and inherit from that base class.
public class myForm : Form {
protected override void OnLoad(){
    //load the settings and apply them
    base.OnLoad();
}

protected override void OnClose(){
    //save the settings
    base.OnClose();
}
}
then for the other forms:

public class frmMainScreen : myForm {
// you get the settings for free ;)
}
Well, something like that ;)
Answer: I'm in the same boat as you, in that I have a number of forms (MDI children, in my case) that I want to preserve the position and size of for each user.  From my research, creating application settings at runtime is not supported.  (see this blog entry)
However, you don't have to stick everything in the main settings file.  You can add a Settings file to your project (explained here in the MSDN) and use it via the Properties.Settings object.  This won't ease the pain of having to remember to create new settigns for each form, but at least it will keep them together, and not clutter up your main application settings.
As far as using the base class to retrieve the settings... I don't know if you can do it there.  What I would (and probably will) do is name each attribute , then use Me.GetType().ToString() (I'm working in VB) to composite the names of the attributes I want to retrieve in the Load() event of each form.
Answer: I just stream it out to a separate XML file - quick and dirty and probably not what youre after:
Dim winRect As String() = util.ConfigFile.GetUserConfigInstance().GetValue("appWindow.rect").Split(",")
Dim winState As String = util.ConfigFile.GetUserConfigInstance().GetValue("appWindow.state")

Me.WindowState = FormWindowState.Normal

Me.Left = CType(winRect(0), Integer)
Me.Top = CType(winRect(1), Integer)
Me.Width = CType(winRect(2), Integer)
Me.Height = CType(winRect(3), Integer)

If winState = "maximised" Then
    Me.WindowState = FormWindowState.Maximized
End If

and
Dim winState As String = "normal"
If Me.WindowState = FormWindowState.Maximized Then
    winState = "maximised"
ElseIf Me.WindowState = FormWindowState.Minimized Then
    winState = "minimised"
End If

If Me.WindowState = FormWindowState.Normal Then

    Dim winRect As String = CType(Me.Left, String) & "," & CType(Me.Top, String) & "," & CType(Me.Width, String) & "," & CType(Me.Height, String)
    ' only save window rectangle if its not maximised/minimised
    util.ConfigFile.GetUserConfigInstance().SetValue("appWindow.rect", winRect)
End If

util.ConfigFile.GetUserConfigInstance().SetValue("appWindow.state", winState)

Answer: Here are some relevant links to check out:
Saving out a Form's Size and Location using the Application Settings feature
Any good examples of how to use Applications settings
Exploring Secrets of Persistent Application Settings
Comment: Most of these links manages one set of settings, the location and size for one form. If you have multiple forms it gets worse and you would like to keep it simple in the base class for the form. This article handles multiple forms: http://www.code-magazine.com/article.aspx?quickid=0607031
Answer: Here's the code I used.
private void SaveWindowPosition()
{
    Rectangle rect = (WindowState == FormWindowState.Normal) ?
        new Rectangle(DesktopBounds.Left, DesktopBounds.Top, DesktopBounds.Width, DesktopBounds.Height) :
        new Rectangle(RestoreBounds.Left, RestoreBounds.Top, RestoreBounds.Width, RestoreBounds.Height);
    RegistrySettings.SetSetting("WindowPosition", String.Format("{0},{1},{2},{3},{4}",
        (int)this.WindowState,
        rect.Left, rect.Top, rect.Width, rect.Height));
}

private void RestoreWindowPosition()
{
    try
    {
        string s = RegistrySettings.GetSetting("WindowPosition", String.Empty) as string;
        if (s != null)
        {
            List<int> settings = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                  .Select(v => int.Parse(v)).ToList();
            if (settings.Count == 5)
            {
                this.SetBounds(
                    settings[1],
                    settings[2],
                    settings[3],
                    settings[4]);
                this.WindowState = (FormWindowState)settings[0];
            }
        }
    }
    catch { /* Just leave current position if error */ }
}

I also presented this code in my article Saving and Restoring a Form's Window Position.

Save and Restore Form Position and Size


Extra hidden characters when trying to use php curl to get and parse JSON

Question: Here's my code:
$target_url = "http://myserver.localhost/get-questions-json.php?id=".$this->variable;
$ch = curl_init($target_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$assess_json = curl_exec($ch);
curl_close($ch);

echo $assess_json displays:
[
    {
        "id": "345",
        "student": "19172",
        "question": "1031",
        "answer": "",
        "submitted": "0",
        "entry": "161235",
        "correct": "0"
    },
    {
        "id": "346",
        "student": "19172",
        "question": "1035",
        "answer": "",
        "submitted": "0",
        "entry": "161235",
        "correct": "0"
    },
    {
        "id": "347",
        "student": "19172",
        "question": "1052",
        "answer": "",
        "submitted": "0",
        "entry": "161235",
        "correct": "0"
    },
    {
        "id": "348",
        "student": "19172",
        "question": "1053",
        "answer": "",
        "submitted": "0",
        "entry": "161235",
        "correct": "0"
    },
    {
        "id": "349",
        "student": "19172",
        "question": "1050",
        "answer": "",
        "submitted": "0",
        "entry": "161235",
        "correct": "0"
    }
]

echo strlen($assess_json) displays 4078. If I copy and paste the string into PHP it says the length is 541.
json_decode($assess_json) is NULL while json_decode($pasted_str) is an object.
If I go directly to:
http://myserver.localhost/get-questions-json.php?id=, it shows the JSON string. The code is echo json_encode($questions);
So how can I get it to retrieve and parse the JSON properly?
Answer: Edit:
There are actually style and script tags in the string due to a PHP page that was included.
I used the following to fix it:
Remove everything within script and style tags
$assess_json = preg_replace('/(<(script|style)\b[^>]*>).*?(<\/\2>)/is', "", $assess_json);
Comment: I ended up putting  around the style and script tags for the PHP that was included so the original problem stopped


Removing Ubuntu 14.04 and re-install 12.04?

Question: I just upgraded to Ubuntu 14.04 LTS from 12.04 LTS and realised that it is simply not right for this particular computer (I do still plan to use 14.04 with my newer machines).  I wish to completely remove ver. 14.04 and replace it with 12.04... no roll-back or anything necessary. Happy just to restore/fresh reinstall 12.04 just as it was.
I am even using the exact same DVD that I used to install 12.04 originally when I sucessfully switched from Windows. When I try to boot from the DVD, it just seems to go no further than the screen that shows the word Ubuntu and the series of red dots below it (lighting in succession) to indicate "progress". Only thing is.. the led light on the CD/DVD-Rom drive stops flickering after a minute or two, as though it is no longer being read. For a long time.
The computer does not freeze, but is otherwise unresponsive. Could it be that it will just take a very long time to begin the process of (re)installing 12.04 (like "overnight" long) and we should be more patient - or am I simply going about this the wrong way?
Any advice, including the correct/conventional way to "downgrade" a version of Ubuntu would be greatly appreciated.
Thank you.
Answer: I would open the tray and reboot, preferably with alt-ctrl-del if possible. It should not take that long to load. But, if you have unlimit data, or even the .iso on a PC, you might want to try a fresh dvd, if that one shows signs of wear. I would completely understand if your on a machine with Rambus or something, but if you had it on your system, your system should be capable of loading the cd in a timely fashion.
getting a .iso of Precise can be done from:
http://releases.ubuntu.com/precise/
and it's the latest, so less time doing updates after install.
Answer: I just did this the other day on my Girlfriend's laptop. I had to uninstall 14.04 LTS because her usb wireless adpater ALFA AWUS036 was extremely slow (I suspected a driver problem). I put in a whole day trying to get it to work, but no dice. I'm thinking something is up with the Linux 3.13 Kernel. Anyways, I manged to so snag an .iso from http://releases.ubuntu.com/precise/ and from there I plugged in a 2GB USB Flash Drive and used Startup Disk Creator to make a Bootable USB Drive. From there it was just a matter of booting the usb key and re installing Ubuntu 12.04 LTS again.
Answer: You can reinstall ubuntu 12.04 by rebooting and press F3 to go to the boot option.
Enter 'C' to go to the command prompt and type "coreboot_boottime". You will see the familiar 12.04 menu to install ubuntu 12.04.
Comment: Wait, what? This makes no sense...


Two subplots Within a Single Plot in Pandas

Question: After a count operation in Pandas, I have the following dataframe:
Cancer                  No   Yes
AgeGroups Factor
0-5       w-statin     108     0
          wo-statin   6575   223
11-15     w-statin       5     1
          wo-statin   3669   143
16-20     w-statin      28     1
          wo-statin   6174   395
21-25     w-statin      80     2
          wo-statin   8173   624
26-30     w-statin     110     2
          wo-statin   9143   968
30-35     w-statin     171     5
          wo-statin   9046  1225
35-40     w-statin     338    21
          wo-statin   8883  1475
41-45     w-statin     782    65
          wo-statin  11155  2533

I am having a problem with my barchart. With the code:
ax = counts.plot(kind='bar',stacked=True,colormap='Paired',rot = 45)

for p in ax.patches:
        ax.annotate(np.round(p.get_height(),decimals=0).astype(np.int64), (p.get_x()+p.get_width()/2., p.get_y()), ha='center', va='center', xytext=(2, 10), textcoords='offset points', fontsize=10)

yielded me:

My target is to achieve two different subplots with two different factors (w-statin/wo-statin) with agegroups as my x-axis. It should approximately look like this:

I would appreciate any help provided. Thank you so much.
Answer: by_factor = counts.groupby(level='Factor')

k = by_factor.ngroups

fig, axes = plt.subplots(1, k, sharex=True, sharey=False, figsize=(15, 8))
for i, (gname, grp) in enumerate(by_factor):
    grp.xs(gname, level='Factor').plot.bar(
        stacked=True, colormap='Paired', rot=45, ax=axes[i], title=gname)
fig.tight_layout()

Comment: @Aceraceae so glad you asked... I didn't paste all the code... I really should get some sleep.  Will edit post.
Comment: First of all thank you piRSquared for your answer. At the first glance, I thought , I understood it. Could you please explain to me 'k' and 'by_factor' parameters ? Thank you so much for your time and help.
Comment: Okay. Take your time and thank you so much for replying.


Probability/Likelihood/Odds of Something Happening.

Question: Here's my question/situation.
Let's say there is a group of 100 people in a room and we are randomly picking one person in the group. Lets also assume that 10% of them are left handed. What's the likelihood or odds of a left handed person being picked 5 times in a row? Also how would you express that in a 1 in X format? That is, the likelihood of 5 left handed people being picked in a row has a 1 in X chance of happening.
Thanks so much for your help!
Comment: Does the chosen person go back into the pool of choices?  Or is he or she not replaced?
Comment: The chosen person would not go back into the pool of choices.
Answer: Since the chosen person doesn't go to the pool, the # of people will reduce each time.
You seem to be new to this field, so easiest way to understand it is
$Pr = \dfrac{10}{100}\cdot\dfrac{9}{99}\cdot\dfrac{8}{98}\cdot\dfrac{7}{97}\cdot\dfrac{6}{96} = \dfrac{1}{298,760}$


What is the purpose of a 6" base gravel layer in patio installation?

Question: All standard drawings for patio installation show a base gravel layer. What is the purpose of this layer? Depending on the answer, I am curious what this forum feels about this product as replacement for the base gravel layer: https://www.alliancegator.com/products/gator-base/
My thoughts.
A base  gravel layer (with different stone sizes, larger at the bottom) is clearly needed for permeable patios to absorb/hold the water. But the base layer was required before permeability/water runoff became a thing, so I wonder if there is an additional purpose? Or has water absorption to prevent pooling/runoff mitigation always been he reason in which case I don't see what problem his product solves.
Thanks,
Answer: It mainly serves two functions:

The density of the in-situ soil usually is uneven (due to voids) throughout the site, and difficult, if not impossible, to compact to the desired strength (eliminate/minimize the void spaces) to avoid uneven settlement that would lead to structural cracks. A 6" course of gravel fill solves that problem, as it is more rigid to work with.

For cold regions, the groundwater or moisture present in the finer in-situ soil tends to rise to the surface that is prone to freezing and will be subject to the subsequent heave. During freezing, the volume of the water expands against the slab,  thereafter, void spaces are created during heave with soil softening as a result. The gravel course provides an escape for the undesirable water and moisture, as it has larger voids to accommodate/minimize the expansion, cut down, if not cut off, the upward migration of water. Note that if the groundwater level is too close to the ground surface, you might need a thicker layer of coarse gravel, or to lower the groundwater table mechanically.

Note, as mentioned in 1 above, good compaction is absolutely essential to ensure a quality and durable slab/foundation. Don't skip it.
Comment: Why is 6 inches the magic number for compacted base? Will 5 inches work? What about 4? When is the compacted base too thin?
Comment: @Rider_X They may work if the base can pass the density test after compaction.
Answer: I think the purpose is to make money for a vendor. I have layed two patios, one in northern IL ( freezing) and one in east TX ( no freezing but average 50" annual rain). I layed them both on the native soil which were both very sandy. No problems, I admit the sandy soil may have been a help.
Comment: Yes, sandy soil is much dense than clayey soil, and the water is moving more freely in the sand soil than clay. However, if it is only a thin layer and underlay by thick clayey soil, you are taking a risk. Water table matters too.
Comment: How long have they been laid with "no problems" for?
Comment: 8 years for the first an 25 years for the second.


How does a apt repository work to find the available packages?

Question: For example i have this apt ubuntu (21.10) repository for postgres in my sources.list.d:
deb http://apt.postgresql.org/pub/repos/apt/ impish-pgdg main 13

Which results in apt-get update to fetch:
Hit:4 http://apt.postgresql.org/pub/repos/apt impish-pgdg InRelease
Get:5 http://apt.postgresql.org/pub/repos/apt impish-pgdg/main amd64 Packages [247 kB]

By default the shown packages for example via apt-cache policy postgresql-plpython3-13 only show the latest minor version of that package (= 13.5):
postgresql-plpython3-13:
  Installed: (none)
  Candidate: 13.5-1.pgdg100+1
  Version table:
     13.5-1.pgdg100+1 500
        500 http://apt.postgresql.org/pub/repos/apt impish-pgdg/main amd64 Packages

I took a deep look inside the repository structure and found various older minor versions for those packages located in:
http://apt.postgresql.org/pub/repos/apt/pool/main/p/postgresql-13/
A part of the directory structure is like:
dists/
  impish-pgdg/
  (...)
    13/
    main/
    InRelease
    Release
    (...)
pool/
  main/
    p/
    (...)
      postgresql-13/
      (...)
        postgresql-plpython3-13_13.5-1.pgdg100%2B1_amd64.deb
        (...)

Question: How is the algorithm where apt searches for packages? How can i tell apt or configure my source list entry to show/remember all minor versions of a package available on the repository?

For example the package above in version 13.1, not 13.5?
Answer: Really APT first scans dists folder. In your case it is http://apt.postgresql.org/pub/repos/apt/dists/impish-pgdg/ .
It fetches InRelease to determine available components:

Components: main 9.6 10 11 12 13 14

So you will get the packages defined in Packages file of the main, 9.6, 10, 11, 12, 13, 14 versions.
The Packages file for 13 exactly contain fields:

Version: 13.5-1.pgdg21.10+1

so this is why 13.5 is available from main 13 sources.list line.
Comment: So this means there is no way to get the other (older) versions from the subdirectory inside `pool` to be listed by apt when these versions are not part of the _Packages_ file(s)?
Comment: Yes, this is how it works. See details at https://wiki.debian.org/DebianRepository/Format .


iPad alpha on video tag

Question: Well I have a burning issue, with the iPad.. more specifically Safari on the iPad.
The  tag doesn't play .mov's at all and converting using Quicktime to .m4v loses my alpha layer.
Currently working with a PNG sequence but its horrible.. Is there any way I can keep my alpha channel and have the video tag work?
Many thanks!
Dave
Answer: html5-video is able to play mov-files! usually this happens, if the server isn t well configured with the MIME-type of the video. check my answer here Playing a movie/DVD on a website maybe this solves your mov problem and you don t have to use .m4v at all
Comment: its the alpha layer I'm interested in as its overlaying an image but on the iPad it won't play .mov's and won't play nice with m4v's I've tried putting a H264 in an MPEG4 container with an alpha layer but nothing and I've tried the canvas "buffer" trick but that didn't work either..
Comment: Also, I checked the MIME types and everything to deliver video content is set in place, we've opted for a PNG sequence now so its not an issue.
Comment: Be aware that playing .mov files on the web is not a good idea because of the very large filesize as compared to .h264 video. The alpha channel supporting video codecs supported by .mov generate very large files. A better structural approach is to use a mixed alpha + rgb set of videos and then compose them int a RGBA video before playing them. For example see this question: https://stackoverflow.com/a/21079559/763355
Answer: it turned out that the iPad doesn't support the alpha channel (or at least every method and format I tried wouldn't work) and it wouldn't play the video because Apple have disabled the autoplay attribute
But I did make a workaround, there appears to be a buffer at page load in which you can start the play() function on a video and stop it meaning its ready to play. But you can only get one video in...
Bummer..

iPad alpha on video tag


Where does the constructor invocation get stored? Stack or Heap?

Question: When an object is created and the constructor is called where does the constructor invocation get stored? is it on a stack or heap?
Comment: Useful read: https://stackoverflow.com/questions/2826222/jvm-heap-and-stack/7597480#7597480
Comment: Calling the constructor is just like calling a special method called `` It uses the stack like any other method.
Answer: The parameters and local variables for the constructor call are stored on the stack until the constructor returns.
The object that the constructor creates is stored in the heap1.

1 - ... unless you have "escape analysis" enabled, and the JIT compiler can determine that the object can be safely allocated on the stack.
Answer: Runtime data area in JVM for stack and heap is as below,
1) Heap : Storage area for Objects.(One per JVM instance)
2) Java stack: Storage are for local variables, results of intermediate operations.(One per thread)
Answer: Heap is only meant for storing objects . There is no way to have constructor invoked on heap.
It's invocation is done on stack.
Stack is used in method calling. It is used for creating method stacks. Although constructor is not a method. But you can always write any logic or assignment as is always done In any method. So it's implemented in a stack like any other method.


Is it possible to splice on to one of the hots of a base board heater for a plug?

Question: So I was on a maintenance call for a building. A string of 3 plugs were off and it's a huge building and I couldn't locate the breaker after 2 hours searching. I went with the building owner inspecting every single panel and gfci plug to test if that was the issue. We couldn't locate the breaker or power source for those plugs. So I gave up looking for the breaker and did the following instead. There was a baseboard heater on a 20 amp circuit nearby.  I tapped off one of the hots from that circuit with a 12/2 wire rated for 20 amps. There is no neutral so I left one wire  capped off in that box. The other end I replaced with a 20 amp receptacle. I took off the hot wire I identified as  the home run wire going to the panel and replaced it with the hot wire I spliced from one of the hots of the baseboard. I  kept the neutral wire from the home run cable as I needed that neutral to complete the circuit. So now all the plugs work.
Just wondering if there is any fire issues or nuisance tripping this will cause down the line? It's been 2 months and the client hasn't called to complain.
Comment: Just out of curiosity, what region are you in?
Answer: You cannot and must not take a phase from one cable/circuit and a neutral from another.
Amongst other issues, this:

Poses a threat to any maintenance worker who disconnects the neutral or earth of the original circuit, assuming that because they have isolated the hot, the neutral is not carrying current.
Can overload the neutral, which does not directly have overcurrent protection.
Can cause issues and heating in surrounding steel as the magnetic fields do not cancel.
Will cause immediate tripping if either circuit is converted to GFCI in future.
Violates the NEC/CEC/any other sensible rules.
Answer: What about that neutral you poached?  It is now returning current for two hots.  It can get what, 20A from its normal circuit, and an additional 20A from the circuit you cross-wired.  That's 40A on a neutral rated for 20A.  Neutrals don't have breakers.
Honestly this is such a bad practice that bootlegging ground would have been less bad.
However it's more troubling that this has been continued in service for any time.  It's one thing to rig a connection to get the bilge pumps running to keep the ship from sinking.  It's quite another to leave that in service for months.  You need to go back and fix that properly now that the time pressure is off.


Difference between navigation overlay and toggle navigation in Web Design

Question: I'm writing about responsive navigation for school.
I found on the internet that responsive navigation patterns could be divide as:

Toggle or multi-toggle pattern
Footer anchor pattern
Navigation overlay pattern
Slide-in/slide-out pattern
Vertical stacking pattern
<select>-drop-down pattern
"Transformer tabs" pattern
Off-canvas-navigation

Now, I can't find real difference between "Navigation overlay pattern" and "Toggle" pattern.
Can anyone help explain the difference?
Comment: This question appears to be off-topic because it is about UX rather than graphic design.
Comment: This question would definitely be better over on UX, but it's still mostly  just opinion based. The list of navigation patterns is fine, but also mostly arbitrary and somewhat subjective. There's no official dictionary of UI pattern terms, unfortunately. :)
Answer: Well, the definition of toggle is to switch from one effect, feature, or state to another. In the case of a navigation, it's a change between states.
On the other hand, an overlay is something laid as a covering over something else.
As you can see by the two definitions, they're completely different things.
However, navigation overlays often implement toggling between two states. This is because toggled navigation is usually hidden, then toggled to not be hidden. But, this isn't always the case.
Answer: I agree with Zach's answer. You can see a demo of these two navigation patterns in action here:

Toggle menu (AKA Accordion)
Overlay navigation


Xubuntu power settings file

Question: I'd like to create a toggle for suspending/doing nothing upon closing the lid for XFCE. For that, I need to find out where is the following setting stored:

Creating the toggle script and panel indicator won't be a problem afterwards.
Answer: The values you need are stored in xfce4-settings-editor. The function you require is lid-action-on-ac. So, to use xfconf-query to set it to do nothing, you would run
xfconf-query -c xfce4-power-manager -p /xfce4-power-manager/lid-action-on-ac -t int -s 0

Then to set it to suspend, substitute the 0 for a 1:
xfconf-query -c xfce4-power-manager -p /xfce4-power-manager/lid-action-on-ac -t int -s 1

The values usable with xfconf-query that correspond to the settings in the graphical application are:
lid-action-on-ac

0=nothing
1=suspend
2=hibernate
3=lock screen

This information was found by setting the values in the graphical settings dialog and then noting the value that appeared in xfce4-settings-editor under the appropriate function. You could do this for the other functions such as power-button-action, if you are interested in those as well.
However, you cannot use the toggle option (-T) here explicitly, as that only works with boolean values (true, false) and not integers. You could however just use the two xfconf-query commands above in a script and fashion a toggle within that script, as you said you wish to do.

Xubuntu power settings file


Found crack along where shower pan meets tile. Caulk it? Grout it?

Question: Was taking a shower and noticed pieces of grout had fallen into the shower pan. But I couldn't figure out where it had come from. Look along the bottom and found

I had redone the grout a couple weeks or so prior and it's strange that the grout lines quickly started getting orange at the base. Is this cause for concern? Should I just caulk along this crack?
Another thing is this morning when I was showering, I noticed the shower pan creaking really loudly when I stepped on it. It had never done that before. But a couple hours later and there is no creak at all.
Answer: The pan has a lip that goes up about an inch under the tile, so you are probably not going to have a leak because of the failing grout. This is a matter of opinion, but I think that grout looks better, but silicone-based caulk will probably be the solution in this case. You mention that the pan is creaking, which suggest some movement, and this is that is causing the cracking of the grout. Grout is not flexible, but silicone-based caulk will move with the pan and stay in place.
Comment: If the grout failed before, it probably will again, making caulk the preferred choice (unless one likes regrouting periodically).


Saving Plist data using Archiver vs creating a readable (xml) file

Question: I've finally managed to save my data using NSCoding and a plist file.
However, the solution (cobbled together from various tutorials) uses an Archiver so the resulting plist file is binary.
I'd like to save the data in a text/readable plist xml file (at least for testing purposes) since I can read it.
How can I change my code to do this?
My "encodeWithCoder" and "initWithCoder" methods are in my Class designation.
My AppDelegate uses this to save the data where "allMsgs" is an array of Class instances:
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:allMsgs];
    [encodedObject writeToFile:plistPath atomically:YES];
The AppDelegate uses this to read the data:
NSData *codedData = [[NSData alloc] initWithContentsOfFile:plistPath];
    if(codedData!=nil){
        allMsgs = [NSKeyedUnarchiver unarchiveObjectWithData:codedData];
    }
Comment: You'd want to save a dictionary (`NSDictionary`) to disk instead of saving `NSData`.
Comment: @sudorm-rf Not sure what you mean. Do you mean "allMsgs" must be of type Dictionary, or do you mean "encodedObject" must be of Type Dictionary?
Comment: what type of data has the allMsgs variable?
Comment: @Artanis allMsgs is an NSMutableArray
Comment: great then, you can use the example I provided below to add that Array into the dictionary and save it as plist...
Answer: Here is an example on how you can save your data in a plist:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *docFilePath = [documentsDirstringByAppendingPathComponent:@"UserSettings.plist"];

NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:0];

// add the data to dict here
[dict setObject:allMsgs forKey:@"allMsgsKey"];

// save the data as plist
[dict writeToFile:docFilePath atomically:YES];
[dict release];

Since a plist is actually represented by a NSDictionary your data must be able to be stored in a dictionary.
Comment: That didn't save anything. I think the problem is the data contained in allMsgs is Class Instance data containing int, BOOL, NSString, and UIColor. I'm pretty sure it has to be handled using NSCoding.
Comment: A plist can only store objective-c data types, not custom classes. So if you wish to save your data in a plist you can stick it in a NSData object but that won't help in your case (you want to read the plist data)
Comment: New weirdness - I went back to using the Archiver, and when I located the plist file in the Finder, and selected it, I got an XML preview in the Finder window! I can use 'QuickLook' from the finder to see the XML...
Comment: You can open the plist file in Xcode but it won't mimic the finder's view behavior.


pcap compile syntax error on Ubuntu 10.10

Question: When I try to run the command sudo tcpkill -i wlan0 -9 example.com it says
pcap_compile: syntax error
tcpkill: couldn't initialize sniffing

I am running Ettercap to initialize MITM
BTW I'm running this on a Dell Inspiron 14r N4010.
Answer: You don't specify a hostname but a pcap expression to tcpkill. The expression that's being used in this case is just example.com which is invalid. You'd have to use something like host example.com. Better yet, if you can use an IP address instead of example.com that'd be best.
With these expressions you can select traffic according to a wide variety of criteria, I suggest you have a look to see how things work. Incidentally, this is the same expression syntax used by tcpdump, so if you want to see which packets are being picked up by the filter/expression before using tcpkill on them, you can use tcpdump to test your expressions. Here's a reference on pcap expressions:
http://www.manpagez.com/man/7/pcap-filter/


Take a one-dimensional range as argument in today's VBA

Question: I have a user-defined function in VBA that used to work in older versions of Excel; =ArrayUnique(A5:A20) in a cell returned a one-dimensional array containing only unique elements:
Function ArrayUnique(ByRef aArrayIn() As Variant) As Variant
    Dim aArrayOut() As Variant, bFlag As Boolean, vIn As Variant, vOut As Variant
    Dim i As Long, j As Long, k As Long
    ReDim aArrayOut(LBound(aArrayIn) To UBound(aArrayIn))
    i = LBound(aArrayIn)
    j = i

    For Each vIn In aArrayIn
        For k = j To i - 1
            If vIn = aArrayOut(k) Then bFlag = True: Exit For
        Next
        If Not bFlag Then aArrayOut(i) = vIn: i = i + 1
        bFlag = False
    Next

    If i <> UBound(aArrayIn) Then ReDim Preserve aArrayOut(LBound(aArrayIn) To i - 1)
    ArrayUnique = aArrayOut
End Function

I try to run the same function in Excel Version 2012 (Build 13510.20004), it does not work anymore; it returns #VALUE!. Debugging it is not easy, because I realise that there is a caching; modify the code does not reflect immediately to the result, I need to change function name to refresh.
Does anyone know 1) how to disable this caching? 2) how to take a one-dimensional range as argument in the most recent version of VBA?
Comment: The oldest Excel version I have at hand is 2003. This code already returns `#VALUE!` in it. Excel has always returned a 2D array for a multicell range. There is no VBA caching either, the changes are reflected immediately. If you don't see your sheet formulas recalculate when you change your code, then yes, that happens, but not because there is code caching, rather, because Excel sees no need to recalculate a function because its arguments have not changed. To make it recalculate, re-enter the formula in just one cell.
Answer: In recent versions of Excel Range actually returns a two-dimensional array so you need to convert it to a one-dimensional array first. Something like this:
Function ArrayUnique(ByVal MyRange As Excel.Range) As Variant
    Dim aArrayOut() As Variant, bFlag As Boolean, vIn As Variant, vOut As Variant
    Dim i As Long, j As Long, k As Long, aArrayIn As Variant

    aArrayIn = Application.WorksheetFunction.Transpose(MyRange)

    ReDim aArrayOut(LBound(aArrayIn) To UBound(aArrayIn))
    i = LBound(aArrayIn)
    j = i

    For Each vIn In aArrayIn
        For k = j To i - 1
            If vIn = aArrayOut(k) Then bFlag = True: Exit For
        Next
        If Not bFlag Then aArrayOut(i) = vIn: i = i + 1
        bFlag = False
    Next

    If i <> UBound(aArrayIn) Then ReDim Preserve aArrayOut(LBound(aArrayIn) To i - 1)
    ArrayUnique = aArrayOut
End Function

Usage:
?Join(ArrayUnique(Range("A:A")), ",")

Comment: `In recent versions of Excel` - `Range` has always returned a 2D array for a multicell range and a single value for a single cell range.
Comment: @GSerg idk but SoftTimur claims that this function once worked.


Valid type casting of both covariant and contravariant class at runtime in Scala

Question: I wrote a class implementing the command design pattern:
class MyCommand[-T, +R](val name: String, val execute: T => R)

, prepared two command and stored it in a MutableList:
val commands = new mutable.MutableList[MyCommand[Nothing, Any]]
commands += new MyCommand[String, String]("lower", s => s.toLowerCase())
commands += new MyCommand[Date, Long]("time", d => d.getTime)

Then I have two data to be executed:
val data = Array("StRiNG", new Date())

The problem for me is that I don't know how to determine which datum is applicable to the command:
data.foreach {
  d => commands.foreach {
    c =>
    // println(c.execute(d)) if d is applicable to c.execute().
  }
}

what I tried is pattern matching with type specification, but it yields syntax error:
c.execute match {
  case m: (d.getClass => Any) => println(c.execute(d))
}

Help me :(
Comment: Please state your specific problem. What are you trying to do?
Comment: I proposed a solution which actually didn't work as I expected. Can you clarify where the data is coming from? I think that when you need to use Nothing there is something really strange going on :)
Answer: I am pretty sure that there are better ways of solving this problem, but this might work for you. I tested it with Scala 2.9.2.
MyCommand takes a Manifest as an additional implicit argument, which gives us access to the class that represents the from-type of the execute function at runtime:
class MyCommand[-T: Manifest, +R](val name: String, val execute: T => R) {
  val fromClass = manifest[T].erasure
}

The list of commands is basically as in your original post, as is the list of data:
val commands = List(
  new MyCommand[String, String]("lower", _.toLowerCase()),
  new MyCommand[Date, Long]("time", _.getTime)
)

val data = List("StRiNG", new Date())

Matching data to commands relies on the runtime representation of the involved types as classes, and a rather ugly cast. The cast is especially ugly because it does not give a precise return type, i.e., additional matches or casts are necessary if you need to know the precise return type of the command's return value.
data foreach { d =>
  commands foreach { c =>
    println("data: %s (%s), command takes: %s"
           .format(d, d.getClass.getSimpleName, c.fromClass.getSimpleName))

    if (d.getClass.isAssignableFrom(c.fromClass)) {
      println("    cmd(data) = " + c.execute.asInstanceOf[Any => Any](d))
    }
  }
}

The output is:
data: StRiNG (String), command takes: String
    cmd(data) = string
data: StRiNG (String), command takes: Date
data: Sun Aug 05 14:46:17 CEST 2012 (Date), command takes: String
data: Sun Aug 05 14:46:17 CEST 2012 (Date), command takes: Date
    cmd(data) = 1344170777681

Comment: Great! I didn't thought about using Manifest. It works perfect! Thank you.