how to execute two query's alongside each other?

Question: i am trying to execute multiple query's at once / or one after the other but it's failing. why is this, here's how i've structured my code:
$query="
INSERT INTO ptb_users (user_id,
id,
first_name,
last_name,
email )
VALUES('NULL',
'NULL',
'".$firstname."',
'".$lastname."',
'".$email."'
)";
mysql_query($query) or die();
$result = mysql_query("UPDATE ptb_users SET user_id=id");

$query="INSERT INTO ptb_profiles (id,
user_id,
display_name )
VALUES('NULL',
'NULL',
'".$username."'
)";
mysql_query($query) or die();
$result = mysql_query("UPDATE ptb_profiles SET id=user_id");

Comment: what is error message you have got?
Comment: im not getting any error
Answer: You should really use PDO and prepared statements, mysql_* is no longer supported. It will make your life easier especially for repeating statements.
Otherwise, what is your error?
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Comment: Even if your answer really does not answer his question - it is sound advice not to use an obsolete interface.
Answer: Use different name for variable $query and $result
it should be
$query="INSERT INTO ptb_users (user_id,id,first_name,last_name,email )VALUES('NULL','NULL','".$firstname."','".$lastname."','".$email."')";
$result = mysql_query($query) or die();
$result1 = mysql_query("UPDATE ptb_users SET user_id=id");

$query2="INSERT INTO ptb_profiles (id,user_id,display_name )VALUES('NULL','NULL','".$username."')";
$result2 = mysql_query($query2) or die();
$result3 = mysql_query("UPDATE ptb_profiles SET id=user_id");

Comment: That should not affect if the queries succeed or not - only wether he retains any usable information about previous queries.
Answer: You are trying to insert 'NULL' in fields which I'm guessing are auto_increment columns.
You should omit them from the query:
$query = "INSERT INTO ptb_users (first_name, last_name, email )
            VALUES('".$firstname."', '".$lastname."', '".$email."')";

Even if the null should be there, according to your implementation/definition of the tables, they should not be enclosed in ' as that means the string NULL, not the value.


Format String is not a literal string (potentially insecure) warning

Question:
Possible Duplicate:
Warning: "format not a string literal and no format arguments"

I have the following line of code that is in my app that a Developer worked on. I am learning the basics of Objective C and as I was updating the App to be iPhone 5 compatible, I see the following warning (I did not change his code) Format String is not a literal string (potentially insecure). The code is as follows;
self.progressHud.labelText = [NSString stringWithFormat:message];

I don't know exactly what this means and don't want to upload anything that can either be a security issue or get rejected by Apple. Any and all help is appreciated from you all.
Comment: http://en.wikipedia.org/wiki/Uncontrolled_format_string, please search for "format string vulnerabilities" and you'll find lots of potential security holes with this type of thing.
Comment: possible duplicate of [Warning: "format not a string literal and no format arguments"](http://stackoverflow.com/questions/1677824/warning-format-not-a-string-literal-and-no-format-arguments) http://stackoverflow.com/questions/6337187/warning-format-not-a-string-literal-and-no-format-arguments
Comment: This is not a duplicate of the suggested question. The referenced question concerns the warning "format not a string literal and no format arguments" whereas this question refers to the warning "Format String is not a literal string (potentially insecure) warning". Careful inspection will show that the warnings are not at all the same so this question is not a duplicate. It is a possible duplicate of this question: http://stackoverflow.com/questions/9961363/why-is-my-string-potentially-unsecure-in-my-ios-application
Answer: Use the following Lines:
self.progressHud.labelText = [NSString stringWithFormat:@"%@", message];

In objective C, this line get the values from any format such as int,float etc to display the Label. because UILabel and IBOutlet Elements only display the NSString values.
However, if you don't need to create a string with multiple variables, it would be more efficient to simply use:
self.progressHud.labelText = message;

Comment: The code is right, but can you add some explanation as to why?


polymorphic code always has same result

Question: Lets consider I have Class B and C which is inherited from class B:
namespace ConsoleApp1
{
 class B
 {
    public void foo(B obj)
    {
        Console.WriteLine("B1 ");
    }

    public void foo(C obj)
    {
        Console.WriteLine("B1 ");
    }
 }

 class C : B
 {
    public void foo(B obj)
    {
        Console.WriteLine("C1 ");
    }

    public void foo(C obj)
    {
        Console.WriteLine("C1 ");
    }
 }
 public class Program
 {

    static void Main(string[] args)
    {
        B c = new C();
        B b = new B();

        b.foo(c);
        c.foo(b);
        c.foo(c);

        Console.ReadLine();
    }
 }
}

I am getting these results:
B1

B1

B1

I don't understand what happened exactly specially for the part:
c.foo(b); // prints B1

c.foo(c); // prints B1

Note: this question is just a mirror of the java version which prints:
B1

C1

C1

It will be great if someone can explain why C# print different values than Java for exactly same OOP code!
Answer: Your compiler warnings should tell you enough. It tells you your C.foo hides the method B.foo since you are not using inheritance. Instead of you are just overwriting a previous method declaration.
You should use virtual and override in C# to declare method inheritance.
class B
{
    public virtual void foo(B obj)
    {
        Console.WriteLine("B1 ");
    }

    public virtual void foo(C obj)
    {
        Console.WriteLine("B1 ");
    }
}

class C : B
{
    public override void foo(B obj)
    {
        Console.WriteLine("C1 ");
    }

    public override void foo(C obj)
    {
        Console.WriteLine("C1 ");
    }
}

Answer: Look at your debug console, you will see:
warning CS0108: 'C.foo(B)' hides inherited member 'B.foo(B)'. Use the new keyword if hiding was intended.
warning CS0108: 'C.foo(C)' hides inherited member 'B.foo(C)'. Use the new keyword if hiding was intended.

If you want to know more, read Inheritance and Derived Classes (C# vs Java)

polymorphic code always has same result


Any recommended keyboard accessibility solution for user to navigation to the menu efficiently?

Question:
We have this top bar on the page and the menu is on the left. Every page has lots of content within it (could have 100+ tabbable elements).
For screen users, they have shortcuts to invoke the navigation.
But for motor disability users or people who want to use keyboard only, it's very inefficient to navigate between pages, as when they are done with a page they might be at the bottom of the page and have to use shift + tab to go all the way to the top to go to another page.
Anyone has seen any webpage has a quick way to open the navigation menu by keyboard no matter where you are on the page?  I know pressing 'Home + End' to the top or bottom of the page, however, the focus remains at where you were previously, so when you tab again it jumps back to the next item you were on. I'm reluctant to introduce custom keys as that might conflict with screen reader/browser or system shortcuts.
This is not a programming question, not related to coding. I'm looking for a good practice suggestion.
Comment: Hello and welcome to this site. If I understand correctly, your question is about how keyboard focus can be implemented programmatically and is thus not for this community. In fact, a similar one has already been [answered](https://stackoverflow.com/a/17500784/1827854) on StackOverflow. I've also proposed that your question is moved there by admins. Please, do clarify in comments if I misunderstood anything.
Comment: Not really, I want to see if there is a common accessibility practice to handle this.
Comment: Could you please give a sample scenario of the behaviour. To me it seems that you are unnecessarily bringing together keyboard focus and window scrolling. It is browser default behaviour that focus is at the first element when you load the page. When you select something, it is also default behaviour that the focus stays there. As far as I can tell, this is invariant of your scrolling, given that you don't do a deliberate action to change the focus. Please clarify.
Comment: Maybe somewhere here - didn't find this particular key function immediately: https://www.w3.org/TR/wai-aria-practices/#kbd_common_conventions
Answer: I think that kind of question needs more technical answers, but I read about this a lot of times where researching about UX in forms in a previous design, so here is my thoughts.
More than a convention or a solution, there are some attributes in HTML5 like tab-index and autofocus which can serve the purpose you're looking for. You have to think the best way to exploit this because you can change your web into some kind of unusable experience very quickly.
Good practices in a11y advice in having an easy flux with the tabs because some people with motor skills use only the keyboard (for an example). Another case could be blind people with screen readers.
You can read about how to technically use this here.
I hope it helps!


Projection of $\log(x)$ on $(x,x^2)$

Question: For a positive random variable $X$, is it true that $\mathrm{cov}(X,\log(X))>0$ and $\mathrm{cov}(X^2,\log(X))<0$, where $\mathrm{cov}(X,Y)$ denotes the covariance between any $X$ and $Y$?
The reason I ask: I am considering a linear regression of $\log(X)$ on $X$ and $X^2$ and I would expect that the coefficients have the above signs based on the concavity of the function $\log(x)$ for $x>0$. In fact, I would not expect the signs of the above covariances to depend on the distribution of $X$.
My attempt: I have tried writing $$\log(X)=\log(x_0)+\frac{1}{x_0}(X-x_0)-\frac{1}{2x_1^2}(X-x_0)^2$$ for all $x_0$ and some $x_1$ in $\mathbb R^+$. I end up with expressions for $\mathrm{cov}(X,\log(X))$ and $\mathrm{cov}(X^2,\log(X))$ that depend on the distributional properties $\mathbb VX$, $\mathbb VX^2$ and $\mathrm{cov}(X^2,X)$, where $\mathbb VY$ denotes the variance of a random variable $Y$. I'm not sure if this approach is correct, but it seems to show that the signs of $\mathrm{cov}(X,\log(X))$ and $\mathrm{cov}(X^2,\log(X))$ can be positive or negative depending on the distribution of $X$.
Comment: Can you give any examples where $\mathrm{cov}(X^2,\log(X)) \lt 0$ (for a positive random variable $X$)?  Or where (if $X$ takes at least three values) where the regression coefficient of $X^2$ is positive?
Answer: Since for positive $x,y$ you have $x \lt y \iff x^2 \lt y^2 \iff \log(x) \lt \log(y)$, you will find  $\mathrm{cov}(X^2,\log(X)) \gt 0$ for positive $X$ (if there is a covariance and $X$ is not almost always constant).  The actual value will depend on the distribution of $X$.
So when you do the calculations for a linear regression of $\log(X)$ on $X^2$, the coefficient of $X^2$ will be positive.
But when you do the calculations for a linear regression of $\log(X)$ on $X$ and $X^2$, you should not be surprised if you find the coefficient of $X^2$ is negative, considering your convexity point.
Comment: The distinction between the signs of $\mathrm{cov}(X,\log(X))$ and $\mathrm{cov}(X^2,\log(X))$ and the signs of the coefficients in a linear regression on **both** $X$ and $X^2$ allowed me to show the result. I guess I still don't completely understand why the covariance between two increasing functions of $X$ is necessarily positive when it exists, but this is something I could look up.

Projection of $\log(x)$ on $(x,x^2)$


Applying a Patch (created through Patch Design View) over previous Quick patches already installed

Question: For one of our product, we deployed two quick patches to update few files. Recently, to overcome an issue in the product we needed to include a new custom action in the patch. As adding a custom action is not possible in case of quick patch we had to create a full patch instead (through Patch Design View in Install Sheild).
Now the problem we are facing is, though it shows installation of new patch is successful, updates of the new patch do not get reflected in the target system. My question, is it possible to apply a full patch over a system that has quick patches already installed.
Vinit
Answer: In theory, yes, you can create such a patch. In practice, since it requires exactly recreating the changes applied in the quick patches in your new upgraded image, very few people try to do this. My recommendation is to just create a major upgrade. But if you truly require a minor upgrade patch, you should be able to finagle it.


Proof that $\frac{f(x+h)-2 \cdot f(x)+f(x-h)}{h^2}\to f''(x)$

Question: I want to proof that if $f \in C^2(\mathbb{R})$ then, for every $x \in \mathbb{R}$, $$\lim\limits_{h \to 0} \frac{f(x+h)-2 \cdot f(x)+f(x-h)}{h^2}=f''(x).$$
My attempt:
$$\begin{aligned}
f''(x)&= \lim\limits_{h \to 0} \frac{f'(x)-f'(x-h)}{h}\\\\
&= \lim\limits_{h \to 0} \Bigg(\frac{\frac{f(x+h)-f(x)}{h}-\frac{f(x)-f(x-h)}{h}}{h}\Bigg)\\\\
&= \lim\limits_{h \to 0} \frac{\frac{f(x+h)-2 \cdot f(x)+f(x-h)}{h}}{h}\\\\
&= \lim\limits_{h \to 0} \frac{f(x+h)-2 \cdot f(x)+f(x-h)}{h^2}
\end{aligned}$$
Now I have a few questions regarding my solution:

Is my attempt correct for $f \in C^2(\mathbb{R})$ ?
I don't see that I have used that $f \in C^2(\mathbb{R})$, only the part of it that tells me that $f$ is differentiable twice in $x \in \mathbb{R}$. Am I right, or did I use the fact that $f$ is continuously differentiable twice without realizing ?
If I have not used the fact that $f$ is continuously differentiable twice, wouldn't that mean that the proof is also valid if $f$ is not necessarily $C^2(\mathbb{R})$ but twice differentiable in $x \in \mathbb{R}$ ? If not, how can I prove it for $f$ twice differentiable but not necessarily $C^2(\mathbb{R})$ ?
Comment: Related: https://math.stackexchange.com/questions/4589237/interpreting-lim-z-to-x-dfrac-dfracfz-fxz-x-fxz-x/4589272#4589272
Answer: By L'Hopital's rule (differentiating $h \mapsto f(x+h)$ and $h \mapsto f(x-h)$ in the first step)
$$\lim_{h \to 0}\frac{f(x+h)-2 \cdot f(x)+f(x-h)}{h^2}= \lim_{h \to 0}\frac{f'(x+h) - f'(x-h)}{2h} \\= \frac{1}{2} \left[\lim_{h \to 0}\frac{f'(x+h) - f'(x)}{h}+ \lim_{h \to 0}\frac{f'(x) - f'(x-h)}{h}\right]= f''(x)$$
Answer: Your approach is problematic: when you replace $f'(x)$ and $f'(x-h)$ with difference quotients, the corresponding limits must be independent of $h$. In particular, you don't even get the following:
$$
\lim_{h\to0}\frac{f'(x) - f'(x-h)}{h} = \lim_{h\to0} \frac{f'(x) - \frac{f(x)-f(x-h)}{h}}{h}
$$
without some additional work.
The most concise proof I know of the statement involves Taylor series, namely the Lagrange Remainder Theorem. Let $f \in C^2(\Bbb{R})$ be given, and choose any $x \in \Bbb{R}$. Then, by LRT, for any $h > 0$ there exist $\xi_h \in (x,x+h)$ and $\eta_h \in (x-h,x)$ such that
$$
f(x+h) = f(x) + hf'(x) + \frac{h^2}{2}f''(\xi_h) \text{ and } f(x-h) = f(x) - hf'(x) + \frac{h^2}{2}f''(\eta_h).
$$
Add these two equations and subtract $2f(x)$ to reveal
$$
f(x+h) - 2f(x) + f(x-h) = \frac{h^2}{2}\left(f''(\xi_h) + f''(\eta_h)\right).
$$
Dividing by $h^2$ gives you your difference quotient on the LHS. Hence to complete the proof, we only have to show that $\lim_{h\to0} \frac{1}{2}\left(f''(\xi_h) + f''(\eta_h)\right) = f''(x)$.
See if you can complete the argument from there. Hint: Show $\lim_{h\to0} \xi_h = \lim_{h\to0} \eta_h = x$ and use continuity of $f''$ at $x$.
Answer: Your approach is right to me, even quite rough.
If you can use Taylor expansion, I'd suggest to follow that way, i.e. expanding $f(x+h)$ and $f(x-h)$, and then performing $\frac{(f(x+h) - 2f(x) +f(x-h))}{h^2}$.
You use the double differentiability when you compute the derivative of the first derivative with the limit $h\rightarrow 0$.
In the first line of your question you forgot either a $\lim_{h\rightarrow 0}$ or a $o(h)$


How to save the current goal / subgoal as an `assert` lemma

Question: During a proof, I come to a situation where the current goal/subgoal turned out to be useful in a later stage of the same theorem.
Is there a tactic to "save" the current goal as a lemma as if the current goal is asserted?
Of course, I can copy&paste to  assert the goal explicitly, or write a separate Lemma before the current theorem. But I am just curious if shortcuts exist.
Thanks.
Answer: To my knowledge, there is no such feature in Coq, and neither CoqIDE nor ProofGeneral seems to provide one.
Answer: Leaving this answer for future reference.
I don't know since when it exists, but maybe the abstract tactic could help.
It allows you to name a part of the proof and re-use it later, even if you are in a different sub-goal.
Answer: If you are using Proof General, you can install a company-coq extension which provides this functionality. It is bound the C-c C-a C-x key sequence.


What should I do about a stubborn screw on the middle of a dryer cord connection?

Question: I am attaching a 3 prong dryer cord to a dryer. The middle connection is being stubborn. The screw gets to a certain point and is stuck. It will not tighten and the connection is very loose. Can I safely use a metal washer to tighten the connection?
Comment: Picture would help, or a link to the exact plug replacement you have.
Comment: Sure it's the right screw and it's properly mounted?
Comment: It could be an incompletely threaded hole for the set screw and this is preventing the set screw from coming down completely. Do you have a set of taps to chase the threads all the way through?
Comment: Trade the screws to determine if you have a bad screw, a badly tapped hole, or maybe a damaged hole.
Comment: tight is tight. if *all* parts are tight, suggests good electrical contact.
Answer: The important thing about the electric cord is that all connections be tight, so if the screw will hold then using a washer to pack the gap so that the connector is pressed against the conductor would create a safe connection.
Comment: Its better to twist then fold the electrical wire into the fitting. or create an l-shaped shim which goes in first. basically trying to minimise the risk of a washer slipping out and causing shorts inside the plug
Answer: If the connection you are referring to is at the dryer end the connection is typically a piece of terminal strip, just replace it. You can buy lengths of terminal strip at a wholesaler for peanuts. I definitely don't recommend jamming anything in there that isn't meant to be there you could short it out or expose yourself to live electrical parts.
Answer: Using a washer probably isn't a good idea.
The screws on those terminals are critical and must work exactly right.  The tightness of those screws makes the electrical connection secure and keeps it secure over months and years subject to heat, humidity, and vibration.  If that connection is loose, it is not safe.
You might be able to figure out what's stopping the screw.  It's possible there's some debris inside the hole, and if you can remove it without damaging the threads, the screw will work as it should.
If the threads in the hole were malformed or damaged, either by cross threading the screw when you tried to drive it or otherwise, that will stop the screw.  If you force it in, it might hold the terminal down securely, but it might not hold up.  I would not force it and hope for the best.
It's possible the screw that you're installing bonds the terminal to the metal frame of the dryer - the screw goes through the terminal block into a tapped hole in the sheet metal below.  This bond is particularly important for safe function of the dryer. If the terminal block isn't aligned correctly with the tapped hole in the underlying sheet metal, you won't be able to land the screw all the way, and if you just force it, you may damage the terminal block.  If this is the case, you may be able to move the terminal block around a little and get the block aligned with the hole.
If you have to buy a replacement terminal strip, do not assume that a generic terminal strip is a suitable replacement, buy one from the dryer manufacturer.  Even if you buy a generic terminal strip rated for the voltage and current, if one of the terminal screws is a bonding screw as described above, a generic terminal block won't provide that bond, which would be a hazard.
Answer: You may have cross-threaded the screw in the hole. Back it out and try again and make sure it goes in straight.
It'll be more difficult now because it will want to keep going in crooked because the screw will have created a new set of grooves criss-crossing over the real threads.
Hopefully you haven't damaged the holes threads too much and can get it going right.


Slick Slider - CSS animation flashes

Question: I'm using a Slick Slider with CSS animations to make a smooth visual effect, everything works fine but the current slide flashes for a sec at the end of the animation. See the undesired effect in the Snippet.
What is causing this? there's a probably solution for this kind of customized animations?

$(document).ready(function(){
  $('.index-slider').slick({
  slidesToShow: 1,
  slidesToScroll: 1,
  infinite: true,
  arrows: false,
  fade: true,
  autoplay: true,
  autoplaySpeed: 8000
  });
});
.index-header {
 font-family: Arial, sans-serif;
 font-size: 72px;
 line-height: 100%;
 color: #BC9E6C;
 opacity: 0;
}

.index-label {
 font-family: Arial, sans-serif;
 font-size: 24px;
 padding: 2rem 0;
 opacity: 0;
}

.index-link {
 font-family: Arial, sans-serif;
 color: #BC9E6C;
 opacity: 0;
}

.slick-active .index-header {
    animation: anim-header 8s 0s ease;
 opacity: 1;
}

.slick-active .index-label {
    animation: anim-label 8s 0s ease;
 opacity: 1;
}

.slick-active .index-link {
    animation: anim-link 8s 0s ease;
 opacity: 1;
}

@keyframes anim-header{
    0% {opacity: 0; margin-top: -25px;}
 10% {opacity: 1; margin-top: 0px;}
 90% {opacity: 1;}
 100% {opacity: 0;}
}

@keyframes anim-label{
    5% {opacity: 0; padding: 0 0;}
 20% {opacity: 1; padding: 2rem 0;}
 90% {opacity: 1;}
 100% {opacity: 0;}
}

@keyframes anim-link{
    5% {opacity: 0;}
 20% {opacity: 1;}
 90% {opacity: 1;}
 100% {opacity: 0;}
}

<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.5.9/slick.css" />

Slide Nº1

Lorem ipsum dolor sit amet, dilige et quod vis fac, cogito ergo sum, vi veri veniversum vivus vici.

    Lorem ipsum

Slide Nº2

Lorem ipsum dolor sit amet, dilige et quod vis fac, cogito ergo sum, vi veri veniversum vivus vici.

    Lorem ipsum

Your help is really appreciated!
Answer: You need animation-fill-mode: forwards;

$(document).ready(function(){
  $('.index-slider').slick({
  slidesToShow: 1,
  slidesToScroll: 1,
  infinite: true,
  arrows: false,
  fade: true,
  autoplay: true,
  autoplaySpeed: 8000
  });
});
.index-header {
 font-family: Arial, sans-serif;
 font-size: 72px;
 line-height: 100%;
 color: #BC9E6C;
 opacity: 0;
}

.index-label {
 font-family: Arial, sans-serif;
 font-size: 24px;
 padding: 2rem 0;
 opacity: 0;
}

.index-link {
 font-family: Arial, sans-serif;
 color: #BC9E6C;
 opacity: 0;
}

.slick-active .index-header {
    animation: anim-header 8s 0s ease;
    animation-fill-mode: forwards;
 opacity: 1;
}

.slick-active .index-label {
    animation: anim-label 8s 0s ease;
   animation-fill-mode: forwards;
 opacity: 1;
}

.slick-active .index-link {
    animation: anim-link 8s 0s ease;
    animation-fill-mode: forwards;
 opacity: 1;
}

@keyframes anim-header{
    0% {opacity: 0; margin-top: -25px;}
 10% {opacity: 1; margin-top: 0px;}
 90% {opacity: 1;}
 100% {opacity: 0;}
}

@keyframes anim-label{
    5% {opacity: 0; padding: 0 0;}
 20% {opacity: 1; padding: 2rem 0;}
 90% {opacity: 1;}
 100% {opacity: 0;}
}

@keyframes anim-link{
    5% {opacity: 0;}
 20% {opacity: 1;}
 90% {opacity: 1;}
 100% {opacity: 0;}
}

<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.5.9/slick.css" />

Slide Nº1

Lorem ipsum dolor sit amet, dilige et quod vis fac, cogito ergo sum, vi veri veniversum vivus vici.

    Lorem ipsum

Slide Nº2

Lorem ipsum dolor sit amet, dilige et quod vis fac, cogito ergo sum, vi veri veniversum vivus vici.

    Lorem ipsum

Slick Slider - CSS animation flashes


File extension validation with python

Question: I want to check if a given file's extension is correct or not. For example, someone give me a file with an extension .zip but actually it may be an executable.
Using mimetypes I could not determine a file's real type. As far as I see, mimetypes needs an extension.
I can map the output of unix file command with some extensions. Even if you change the extension, you cannot deceive file command. However, this solution needs a subprocess.
I thought, there may be a more pythonic solution of this problem. Does anyone know?
Comment: @JesseJ It is no problem to me. It may be handled as text file. I want to seperate archive, executable, library etc.
Answer: Searching the name of the C library (libmagic) used for the file command, nets 3 interesting python packages on PyPI:

libmagic (bitbucket repo)
python-magic (you can find some documentation in the github repo)
filemagic (github repo)
Answer: Ultimately, there is no absolute way of knowing.  For several reasons:

Some file format use simple identifiers, but others don't.
For those that don't, the only way is analyzing the behavior of a program able to able the format.  If the program can successfully open the file, then it belongs to it.
But if not, the file could belong to hundreds of formats you don't have a program to open with.

I'm afraid you will need to be content with a partial answer like the ones you already have.

File extension validation with python


c++ Multiple inheritance from 2 functions, while one of them is pure virtual

Question: Let's say we have a class which inherits from 2 other classes which have both a virtual function with the same signature.
Because the signature is the same, there will be an error because the main class doesn't know who to inherit the virtual function from.
adding to that, if a function is pure virtual, it needs to be initialized in the main class.
So my question is, if the main class inherits from 2 classes with same virtual function but one of them is a pure virtual, will it just use the second one?
Or something else needs to be done?
Btw, if possible, I'd like to see the code you wrote to answer this.
Thanks :)
Comment: Sounds suspiciously like homework help.  Why don't you write that up and test it out?
Comment: What have you tried so far?
Comment: Re: "main class doesn't know who to inherit the virtual function from" -- that's rather muddled. There in no problem having a single function in a derived class overriding two functions with the same signature from two different base classes. When you **call** the base-class function the call is ambiguous, but that's true regardless of whether any of the functions are virtual.
Comment: Re: "if a function is pure virtual, it needs to be initialized in the main class" -- no, it needs to be **overridden** if you want to create objects of the derived type.
Answer:
if the main class inherits from 2 classes with same virtual function but one of them is a pure virtual, will it just use the second one?

No.  C++ will not assume that you want that behavior.

Or something else needs to be done?

You must implement the function if you don't want the derived class to be abstract.
<code>void Derived::func()
{
    SomeBase::func();
}
</code>


Sorting big list in Python

Question: I have a text file of 2 million lines whereby each line displays the coordinates and a value for potential at these coordinates e.g. <x> <y> <z> value. How should I go about reordering this file with a python script so that the data is sorted first by the x coordinate, then by the y coordinate and then by the  z coordinate.
Format:
1 2 1 value
1 8 6 value
4 3 2 value

etc ...
Desired Format:
1 1 1 value
2 1 1 value
3 1 1 value

etc..
Many Thanks in advance!
Comment: I like Python too, but the standard `sort` Linux/Unix command line utility is the perfect tool for this task.
Comment: @WillC `sort  -n -k1,1 -k2,2 -k3,3 < infile >outfile` i.e. numeric sort with 3 keys: 1st, 2nd and 3rd field
Comment: Perhaps consider the `pandas` package. But first try just loading and sorting it like normal as Mr_U4913 suggests. It'll probably take less time to run than developing a more efficient solution.
Comment: you are asking about reordering this file, 2 mil lines is not a Big list, you basically can do it in memory and the write the list back to file. Please show us what you have tried.
Comment: Welcome to StackOverflow.  Please read and follow the posting guidelines in the help documentation.  [on topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here.
StackOverflow is not a design, coding, research, or tutorial service.  Do your searches before you ask.  "Python sort tutorial" should have kept you from having to type in your problem.
Comment: @VPfB valid point, but the OP may have no access to a Linux machine. You know, some people use Python on MS Windows.
Comment: @Błotosmętek Yes, it may be the case. I should have added something like _"Please let us know if this is an acceptable apporach for you"_ to my comment.
Comment: I am on a linux machine, how would I go about doing this with Linux sort?
Answer: You can read the file into a list and sort it, but it will take time because of the size. For example:
with open(file, 'r') as f:
    data = sorted(f.readlines(), key=lambda x: int(''.join(x.split()[:3])))

If you want to remove the new line characters, use f.read().splitlines() instead.
Comment: You seem to have made an assumption that x, y, z are always 1-digit integers. This may not be the case.
Answer: Use a key function:
the_list.sort(key=lambda line: tuple(map(int, line.split()[:3])))

(if your x, y, z coords are not integer, replace int with float)

Sorting big list in Python


Replace an image with a youtube video

Question: I have an image, and I would like to make the image link to an embedded YouTube video, such that if the user clicks on the image, it starts playing in the place where the picture used to be. Any thoughts on how I can accomplish this?
Thank you,
David
Answer: Place the embedded video in a div that is invisible:

 embedded video code here

Then give the img an id too:

Then, put a link round the image pointing to some JavaScript which hides the image and shows the embedded video:

So, the full code would be:

 embedded video code here

Answer:

<object style="height: 390px; width: 640px">
<param name="movie" value="http://www.youtube.com/v/V4jZ_BV4MQ4?version=3&autoplay=1">
<param name="allowFullScreen" value="true">
<param name="allowScriptAccess" value="always">
<embed src="http://www.youtube.com/v/V4jZ_BV4MQ4?version=3&autoplay=1" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="390"></object>

something like this :)

Replace an image with a youtube video


Removing the "broken shield" icon

Question: I got hit by a mega-rocket and have a broken shield icon over my head. I haven't noticed this on my previously revived units—when does it appear and what does it do? Can I repair my defenses, or am I permanently impaired?
Answer: The Annihilator gives every unit (and crystal) it directly hits a temporary armour penalty of -50%, which is indicated by the broken shield icon.  Note that the units that suffer the area of effect damage from the Annihilator do not get the armour penalty.
The penalty is temporary, as it only remains until the unit takes physical damage and suffers the penalty.  After that, the unit's armour rating returns to normal and the icon goes away.
The Team Fortress 2 Jarate item uses the same icon, though it also adds a haze effect around the unit.  In the case of Jarate, the icon indicates that the unit has a temporary armour penalty of -175% AND a temporary magical defense penalty of -175%.  The penalty goes away after any attack.

Removing the "broken shield" icon


Add C wire to very old gas furnace

Question: There is a very old gas furnace in our attic. It has a two-wire transformer and no obvious terminals to expand.

I need to run a C wire to my nest thermostat, which I'm planning to do via their nest power connector so I don't have to refish any thermostat wire.
Given the wiring diagram and available transformer terminals, where do I tie in? Just figure out where the hot 24v wire is and add the connector to that?
Comment: check out this Q&A https://diy.stackexchange.com/questions/10482/how-can-i-add-a-c-wire-to-my-thermostat
Comment: Additionally, instead of adding one wire for the C, it'd be better future-proofing to add an 18/5 cable. Use the old 2 wire cable to pull the new 18/5 through.
Comment: Thanks @pmont, I couldn't quite grok how to apply the thorough discussion in that link to my scenario. Given that I only have two terminals coming out of the transformer, are you suggesting I run new wire w/ several wires attached to one of the transformer terminals?
Comment: Yes new 18/5 cable to replace the existing 18/2 cable. 2 of the 5 wires in the cable will connect to where your existing thermostat wires go. Red for the heater, White for the switched side to complete the circuit. It may not matter which is R or W since they both go to the 2-pole gas valve (if I'm reading that diagram right). Use blue or black for the common wire and connect it directly to the low side of the transformer (basically bypass the gas valve). Which leg on the transformer may need experimentation. It shouldn't hurt if you put it on the wrong one. The thermostat just won't power up.
Comment: Use a multimeter to be sure you're connecting to the 24 VAC side, not the 120 VAC from the breaker. As long as you're connecting to the 24 VAC side, your thermostat will be fine.
Answer: With your current gas valve, it's the terminal not labeled "THERM"
Generally speaking, 3-wire gas valves, like your current ones, have their terminals designated as such:

TH -- "thermostat", for the W wire controlling the gas valve
TR -- "transformer", for the return wire to the transformer
TR/TH -- "transformer/thermostat", a spare terminal for the power supply from the transformer to be passed thru to the 'stat

Your gas valve is labeled somewhat differently, but it's clear where the thermostat hooks up -- the two terminals labeled THERM.  As a result, those can be treated as R and W, leaving the other terminal as a suitable C connection by process of elimination.
Comment: That makes sense. I'm assuming the wire currently connected there is from the transformer? I saw some info about 3-wire valves having a "dummy" terminal, is that the same thing as the TR/TH?
Comment: @justinbelcher -- yeah, the wire currently connected there should come from the transformer, and yeah, TR/TH is that "dummy" terminal

Add C wire to very old gas furnace


Keeping towns alive

Question: With respect to towns of abandoned players: these will vanish after 90 days unless sieges are put around them, and the practice of putting siege encampment around towns to stop them vanishing is called placeholder sieges.
Do placeholder sieges keep them alive from when the encampment is formed or from then the siege army is sent?
Answer: From GC, 22nd Feb 2017:

[08:17]Hobblez: it should be once the incoming is sent, you can also just send diplo missions to keep an account active
[08:18]Hobblez:  As long as they have another player actively trying to take something from the account it won't delete
[08:18]Mistery:  as per my answer from earlier - [08:14]Mistery:  abandoned towns will stay in place as long as there are hostile
    actions taken against it
[08:19]Alti:  Do scounts count as hostile?
[08:19]Kodabear:  yes
[08:19]Kodabear:  no
[08:19]Kodabear:  no
[08:20]Kodabear:  the game doesnt count them as hostile
[08:20]Kodabear:  players on the other hand due
[08:20]Alti:  So they won't keep a town around?
[08:20]Kodabear:  yes?
[08:20]Kodabear:  ish
[08:21]Hobblez:  from what I've heard any diplo or military action against a player will keep the account "active" aka not delete it
[08:21]Kodabear:  when it comes to terms of runes they arent counted as hostile

Keeping towns alive


In zenity forms, how can I set default values (initialize) entries?

Question: I've got a zenity form working, but I can't find any information on initializing the entries.  The Zenity help manual webpage doesn't address the issue.
For example, the example from that webpage is
<code>#!/bin/sh

zenity --forms --title="Add Friend" \
--text="Enter information about your friend." \
--separator="," \
    --add-entry="First Name" \
    --add-entry="Family Name" \
    --add-entry="Email" \
    --add-calendar="Birthday" >> addr.csv

case $? in
    0)
        echo "Friend added.";;
    1)
        echo "No friend added."
    ;;
    -1)
        echo "An unexpected error has occurred."
    ;;
esac
</code>
How would I initialize First Name, Last Name, etc. before displaying the window?
Answer: Use yad. It's a fork of zenity that I ended up using to overcome this missing functionality in zenity. The key is to use the --form option and include the initial values on the command line after the defined options and parameters. This "extra data" is assumed to be initial values for the fields.
<code>initial_name_data='Jane Doe'; firstname.lastname@example.com'
yad --form --title='Contact Info' --text='Edit Data' --field=Name --field=Email "$initial_name_data" "$initial_email_data"
</code>
Comment: This doesn't seem to work if the field type is "CB" (combo box) - it assumes the first entry is the default, which isn't always what is desired.
Answer: yad --form --title='Contact Info' --text='Edit Data' --field=Name:CB --field=Email 'Joe Cool!^Jane Doe!Write Another Name' "email@example.com"
Joe email@example.com|
You should start the default option with ^ and separate each one with ! (notice that I enclose all of them with ' ... '
Comment: Welcome to SO, please refer to this for better presenting your question/answer: https://meta.stackoverflow.com/a/251362/3519504


Ceiling strapping over plaster

Question: I have old plaster walls that are not in the best shape. I want to strap them with 1x3 or 1x4 and will screw right into the joists. Would that be enough for me to run conduit in between the strapping? Also has anyone ran copper plumbing in between the strapping?
Comment: Your title mentions ceilings and your post refers to walls. Please revise to be more accurate and to make your title a specific question. See [ask] and take the [tour].
Comment: 1x wood (~ 3/4") is going to be pretty tight for conduit and/or plumbing. 2x wood might work better.
Answer: No.  If you are planning to run new electrical and plumbing behind a new ceiling you should remove the old ceiling.  Running electrical and plumbing in a 3/4 inch space behind a false ceiling will create a LOT of problems, and you'll be creating dangerous, hacky laborious solutions.   If it was minimal, you just need to run one cable or provision for one ceiling pendant, you could work around it.  But if you're installing lots of new utilities you'll regret it.
Comment: Thanks for the input
Answer: The 1x strapping allows for electric cable and 1/2" copper,CPVC, or PEX. Conduit may be tight, but you could scrape away some of the old plaster, ( it's being covered anyway) and imbed the conduit so it doesn't bulge the new drywall.
This is done in homes built in Fla. often where the 1x is installed over solid polyisocyanurate insulation on the inside of exterior block walls.
There are Stand off straps to hold the cable away from the 1x or furring strips.
For the ceiling, just run utilities in the attic, or open the space needed for cable and plumbing.  More detail from you would get a more specific answer.
Comment: Thanks. For the help. It's maybe best for me to just punch holes in the old plaster and just strapping to over the plaster so i don't have to patch anything?
Comment: You would be best served to add the details to your original post, with some pics. That way we know more precisely what you are dealing with and trying to accomplish.

Ceiling strapping over plaster


Fredholm Integral Equations

Question: I'm having problems obtaining the solution of
the homogeneous Fredholm Integral Equation of the
2nd kind, with separable kernel. I always get a zero
if I use the normal method I was taught for the non
homogeneous type. I have an example: $$y(x) =
\lambda \int_{-1}^1(x+z)y(z)dz$$.
Can you help me please?
Comment: I edited your question a tad to fix up the $\LaTeX$.  Hope this is OK with you (please do let me know), and that I got your math right.  Cheers!
Comment: You are most welcome!  Math on!
Comment: yea thanx, @Roberts
Answer: If $y$ is such a solution, then
$$
          y = \left(\lambda \int_{-1}^{1}y(z)dz\right) x + \left(\lambda\int_{-1}^{1}zy(z)dz\right)
$$
forces $y=Ax+B$ for some constants $A$ and $B$. Substituting into the above
$$
     Ax+B=\left(\lambda\int_{-1}^{1}(Az+B)dz\right)x+\left(\lambda\int_{-1}^{1}(Az^{2}+Bz)dz\right) \\
   =2\lambda Bx+\frac{2}{3}\lambda A.
$$
So it is necessary that
$$
              A=2\lambda B,\;\;\;B=\frac{2}{3}\lambda A \\
                A=\frac{4}{3}\lambda^{2}A,\;\;\; B=\frac{4}{3}\lambda^{2}B.
$$
So, either $A=B=0$, or $\lambda = \pm\frac{\sqrt{3}}{2}$. All that remains is to try the possibilities. Refer to the second equation above.

Fredholm Integral Equations


infragistics webdatagrid get selected cell from keydown event in client side

Question: I have build an infragistics webdatagrid in c# :
        var columnOne = new BoundDataField();
        columnOne.DataFieldName = "ColumnOne";
        columnOne.Key = "columnOne";
        columnOne.Header.Text = "columnOne";

        var columnTwo = new BoundDataField();
        columnTwo.DataFieldName = "ColumnTwo";
        columnTwo.Key = "columnTwo";
        columnTwo.Header.Text = "columnTwo";

        WebDataGridObject.DataKeyFields = "ColumnOne";
        WebDataGridObject.Columns.Add(columnOne);
        WebDataGridObject.Columns.Add(columnTwo);

I would like from javascript to update the cell from the column two when something is typed in the cell from the column one.
For example, my user starts typing a value in cell at line 3 and column one, the cell at line and column two must be automatically updated with a constant value, like "updated".
To do that, I am a bit struggling, I have attach a lot of client events from my c#, and I think that the one usefull is the keydown :
WebDataGridObject.ClientEvents.MouseDown = "WebDataGridView_MouseDown";
WebDataGridObject.ClientEvents.KeyDown = "WebDataGridView_KeyDown";
WebDataGridObject.Behaviors.EditingCore.Behaviors.CellEditing.CellEditingClientEvents.EnteredEditMode = "enteredEditMode";
WebDataGridObject.Behaviors.EditingCore.Behaviors.CellEditing.CellEditingClientEvents.ExitedEditMode = "exitedEditMode";

I would like my js keydown event handler, getting the column key of the cell currently edited, and if it's equals to "columnOne", update the value of the cell at the same line and on column two. This is my js :
function WebDataGridView_KeyDown(webDataGrid, evntArgs) {

}

function WebDataGridView_MouseDown(webDataGrid, evntArgs) {
// this is where I am trying to get the column key of the currently edited cell
    webDataGrid.get_behaviors().get_selection().get_selectedRowsResolved()    [0].get_cell(3).get_text()
 }

var gridRef;
var cellRef;

function enteredEditMode(grid, args) {
    gridRef = grid;
    cellRef = args.getCell();
    if (cellRef._column._key === "headerName") {
        alert('toto');
    }
}

function exitedEditMode(grid, args) {
    gridRef = null;
    cellRef = null;
}

Answer: To get the column key, you should try this:
    webDataGrid.get_behaviors().get_selection().get_selectedRowsResolved()[0].get_cell(3).get_column().get_key();

or this:
   webDataGrid.get_behaviors().get_selection().get_selectedRowsResolved()[0].get_cell(3).get_column()._dataFieldName

Answer: In order to get the column key of the cell that is going to be put in edit mode, it is recommended to use the eventArgs parameter.
Below you will find the two client events from where you can access this information (Column Key)
function WebDataGrid1_CellEditing_EnteringEditMode(sender, eventArgs)
{
    // Get the key of the currently edited cell
    var columnKey = eventArgs.getCell().get_column().get_key();
}

function ClientEvents_MouseDown(sender, eventArgs) {
    // Get the key of the currently edited cell
    var columnKey = eventArgs.get_item().get_column().get_key();
}

As you will see the difference is the getCell and getItem methods from eventArgs


Add a class to the HTML  tag with React?

Question: I'm making a modal in my React project that requires a class to be added to the body when the modal is open and removed when it is closed.
I could do this the old jQuery way by running some vanilla JavaScript which adds / removes a class, however this doesn't feel like the normal React philosophy.
Should I instead setState on my top level component to say whether the modal is open or closed? Even if I did this, as it's rendered into the div on the page it's still a side-effect to edit the body element, so is there any benefit for this extra wiring?
Comment: I prefer `some vanilla javascript`, you can add class in `componentDidMount` and remove in `componentWillUnmount`, `mousewheel` is global and not `React philosophy`, still you use it
Comment: It might help to have a top-level container instead of directly manipulating the body tag.
Comment: Possible duplicate of [How to add or remove a className on event in ReactJS](https://stackoverflow.com/questions/28732253/how-to-add-or-remove-a-classname-on-event-in-reactjs)
Answer: TL;DR use document.body.classList.add and document.body.classList.remove
I would have two functions that toggle a piece of state to show/hide the modal within your outer component.
Inside these functions I would use the document.body.classList.add and document.body.classList.remove methods to manipulate the body class dependant on the modal's state like below:
openModal = (event) => {
  document.body.classList.add('modal-open');
  this.setState({ showModal: true });
}
hideModal = (event) => {
  document.body.classList.remove('modal-open');
  this.setState({ showModal: false });
}

Comment: I wonder if modifying the `` element is a so-called `side effect` in React Framework. If it is, should I put the logic in `useEffect` hook?
Answer: With the new React (16.8) this can be solved with hooks:
import {useEffect} from 'react';

const addBodyClass = className => document.body.classList.add(className);
const removeBodyClass = className => document.body.classList.remove(className);

export default function useBodyClass(className) {
    useEffect(
        () => {
            // Set up
            className instanceof Array ? className.map(addBodyClass) : addBodyClass(className);

            // Clean up
            return () => {
                className instanceof Array
                    ? className.map(removeBodyClass)
                    : removeBodyClass(className);
            };
        },
        [className]
    );
}

then, in the component
export const Sidebar = ({position = 'left', children}) => {
    useBodyClass(`page--sidebar-${position}`);
    return (

            {children}

    );
};

Comment: 16.8, not 16.9 :)
Comment: This doesn't remove the previous body class on navigation for me. Every page component that mounts just adds the class to the body
Comment: @user3869231 not sure where the problem might be but for me it seems to be working fine, see https://codesandbox.io/s/usebodyclass-v59mkt?file=/src/App.js
Answer: Actually you don't need 2 functions for opening and closing, you could use document.body.classList.toggle
const [isOpen, setIsOpen] = useState(false)
useEffect(() => {
  document.body.classList.toggle('modal-open', isOpen);
},[isOpen])

<button onCLick={()=> setIsOpen(!isOpen)}>Toggle Modal</button>

Comment: I would also add a cleanup function `return () => document.body.classList.remove('modal-open')` within the useEffect hook.
Comment: Replace isMobileOpen with isOpen: `document.body.classList.toggle('modal-open', isOpen);`
Answer: Like what @brian mentioned, try having a top-level container component that wraps around your other components. (assuming you're not using redux in your app)
In this top-level component:

Add a boolean state (eg. modalOpen) to toggle the CSS class
Add methods (eg. handleOpenModal & handleCloseModal) to modify the boolean state.
Pass the methods created above as props into your <Modal /> component
Answer: ReactJS has an official React Modal component, I would just use that: https://github.com/reactjs/react-modal

Add a class to the HTML  tag with React?


Need help writing a better if statement with JS/jQuery

Question: Is there a better way of writing this?  Seems like the if statements could be combined somehow.
Here is the HTML

I wrote this code to change the class name of this header tag.  It works just fine, but I feel like it could be shorter.  Any help would be great as I am still learning JS/jQuery.  Thanks!
$("nav#main_nav li a").on('click', function(){
    var link = $("nav#main_nav li a").index(this);
    var banner = $("header#main_header");

    if (link === 0) {
        banner.attr('class', "gray_bg");
    }

    if (link === 1) {
        banner.attr('class', "orange_bg");
    }

    if (link === 2) {
        banner.attr('class', "green_bg");
    }

    if (link === 3) {
        banner.attr('class', "purple_bg");
    }
});

Comment: These kinds of "multiple if statement for a single variable" work best as a [`switch statement`](http://www.w3schools.com/js/js_switch.asp). However, the answers provided (using the number to index into an array) are great when all of your code branches are essentially parallel. Use one of the answers below, but be aware of the existence of `switch`.
Answer: $("nav#main_nav li a").on('click', function(){
    var link = $("nav#main_nav li a").index(this);
    var colors = ["gray_bg", "orange_bg", "green_bg", "purple_bg"];

    $("header#main_header").attr('class', colors[link]);
});

Answer: just put your classes in array and just read from it with the index you got
var classes = ["gray_bg" ,"orange_bg","green_bg" ,"purple_bg"];
$("nav#main_nav li a").on('click', function(){
    var link = $("nav#main_nav li a").index(this);
    var banner = $("header#main_header");

    banner.attr('class', classes[link]);

});


How to have real full screen with Civilization in DOSBox?

Question: My screen have a resolution of 1366x768. When I play Civilization (version 1), I got the image in a resolution of 640x400 in the middle of the screen, the rest being black. Instead, when I play Orion, the image occupies all screen.
Which DOSBox option should I change to have the same with Civilization?
Comment: try Sid Meier's Civilization 1.2 for Windows, released for Windows 3.11 in 1991; it still runs natively on Windows 7, supporting windows up to 1600 x 900 px in size
Answer: You probably will need to change the scaler parameter - this controls how the "classic" DOS resolution is upscaled to fill the higher resolution of today's monitors.  The various types represent the algorithm used to upscale the image, and the "2x" or "3x" control how much upscaling should be applied.
You may also have to change fullresolution, which does additional scaling to match your monitor's resolution.
Comment: scaler=normal3x does the trick (however, it slow thing down).
Answer: Try using
<code>fullresolution=1366x768
output=overlay
scaler=normal2x
</code>
Now try to play it fullscreen.
Answer: You can also try to press the fullscreen key combination, usually Alt+Enter. If it still doesn't work, check first that you have the dosbox window grabbed (Ctrl+F10).


Returning a whole array in C

Question: Hi I am pretty new to C and was wondering how to return an entire array. For example I have this function here.
char* foo(int x)
{
    char *num = (char*)malloc(x*sizeof(int));

    num[0] = '1';
    num[1] = '2';
    num[2] = '3';
    num[3] = '4';

    return num;

}

I realized that when I return num it only returns the first index of num. But is there any way to return the whole array, 1234? Any help will be greatly appreciated!
Comment: It returns a pointer to the first element of the array which you can use to access the rest, assuming you know how many elements were allocated. Perhaps you can describe in greater detail the issue you're having and expand your code example to demonstrate it.
Comment: The general-purpose answer to "how do I return an array in C?" is well addressed at: https://stackoverflow.com/q/11656532/ . But for the `foo()` you have tried to implement here, three points: 1) this should work fine, try accessing indexes [0], [1] etc. of the return value; 2) you're malloc'ing `x*sizeof(int)`, why isn't this `x*sizeof(char)`?; 3) if you're malloc'ing in a function, make sure it's really clear in your documentation/comments and that any callers of `foo()` then `free()` the memory to avoid memory leaks. This is kind of risky for introducing memory leaks.
Answer: Since the foo() function returns a pointer, you can see that all values are printed when you use the %s format specifier. The display() function prints the data in the memory area pointed to by the pointer as characters.
#include <stdio.h>
#include <stdlib.h>

char* foo(int x)
{
    char* num = (char*) malloc((x + 1) * sizeof(char));

    for(size_t i = 0 ; i < x ; ++i)
        num[i] = i + 1 + '0';
    num[x] = '\0';

    return num;
}

void display(char *array, size_t size)
{
    for(size_t i = 0 ; i < size && array[i] != '\0' ; ++i)
        printf("array[%ld]: %c\n", i, array[i]);
}

int main()
{
    const size_t size = 4;
    char *result = foo(size);

    printf("%s\n", result);
    display(result, size);

    return 0;
}

Output:
1234
array[0]: 1
array[1]: 2
array[2]: 3
array[3]: 4

Comment: This prints the array contents as a string without ensuring it is terminated with a null character.
Comment: Hi thank you very much, your code was exactly what I was looking for. But just one quick question, can you explain why you  + '0' in the foo for loop? I realize it doesn't work without it but I'm not exactly sure what it does. Thanks in advance!
Comment: @OctoRise When you initialize an array manually, the compiler guarantees that the last element will be `'\0'`. However, when allocating memory with `malloc()`, assigning `'\0'` to the data in the last index helps avoid errors.
Comment: @OctoRise For example, in the above program, instead of assigning `num[x] = '\0'` in `foo()`, instead of assigning `num[2] = '\0'`, 3 elements (two data members and `'\0'`) are odd while printing the data to `stdout`.
Comment: @Sercan Okay so I tried adding `+ '0'` similar to how you did this `num[i] = i + 1 + '0';`, but I think the `+ '0'` interfered with my results. For example I malloced an array called num and did this: `num[0] = 1+2;` which sets num[0] to 3 which is perfect, but when I do `num[1] = 1+2 + '0'`, num[1] is equal to 51. Sorry if my question is convoluted but essentially, how do i make `num[1] = 1+2+ '0'` equal to 3? Thanks.
Comment: @OctoRise I think I got it wrong. The statement you refer to is used to convert the data in int type to the data of the char type. For example, the statement of '0' + 1 is equal to the character of '1'. ie used to achieve the desired character in the ASCII table.
Comment: @OctoRise The '3' character of the ASCII table is 51. Since the num sequence is defined, you will see the output of 51 if the %d format specifier is used instead of %c format specifier in the printf() method. In addition, the statement of "1 + 2 + '0'" is not equal to the integer of 3; this statement is equal to '3' characters.
Comment: @Sercan Oh okay thank you for clarifying. So upon playing with my code even more, I somehow made it so that `num[0] = 2 + 1 + '0';` equals 3 but I notice that when the numbers are greater than 9 for example `num[1] = 5 + 5 + '0';` it equals to ASCII representation, `:`. But what I want is for num[1] to equal 10. Is that possible?
Comment: @OctoRise You can do this more easily if you define the "num" pointer of type char* as an int*. I didn't want to change this since in your question the "num" pointer is defined as a char* type.
Answer: See if you are new to C, then learn it first do some googling and research. If you don't find anything then read some theory of a similar topic for examples (How to return an array in C?). After that some error is happening in your code then you can ask it on stackoverflow.
By the way your should be like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *foo(int x); // fix prototype errors
char *foo(int x)
{
    char *num = (char *)calloc(x + 1, sizeof(char)); // we added +1 to append the null terminating character in `num`
    for (size_t i = 0; i < x; i++)
        num[i] = (char)(i + 48);
    return num;
}

/* @returns no. of character written on stdout */
int print_foo(const char *num); // fix prototype errors
int print_foo(const char *num)
{
    if (num)
    {
        size_t z = 0;
        for (size_t i = 0; i < num[i] != '\0'; i++)
           z +=  fprintf(stdout, "num[%lu] = %c\n", i, num[i]);
        return z;
    }
    return -1;
}

int main(void)
{
    char *num = foo(10);
    print_foo((const char *)num);
    free(num); // free any heap allocated resources before exiting the application
    return 0;
}

Returning a whole array in C


Is an IDENTITY column auto-incremented before or after an order by clause is applied to it?

Question: I have a temporary table that has an identity column. There are multiple inserts into this table from several other tables. In one of the inserts, however, I need to insert rows into it in a specific order for which I am using an ORDER BY clause. Will the auto-increment be applied before or after the rows in the temporary table are sorted?
Thanks!
<code>CREATE TABLE #tempTable
 (
    SeqNo INT IDENTITY(1, 1),
    Column1 INT,
    Column2 INT,
    Column3 INT
)

INSERT #tempTable
 (
    Column1,
    Column2,
    Column3
)
SELECT  W,
        X,
        Y
FROM    dummyTable
ORDER BY Z
</code>
I guess my question is whether SeqNo will be auto-incremented in a way such that the row with the smallest Z value gets 1, second smallest gets 2 and so on.
Apologies if the code example is a bit scruffy..
Comment: Try posting some code / sql that shows what you are doing and we might be able to answer the question.  :)
Answer: The SQL Server Engine Team have made this blog post:

INSERT queries that use SELECT with ORDER BY to populate rows guarantees how identity values are computed but not the order in which the rows are inserted

They clarify what "the order in which the rows are inserted" means in the comments:

Yes, the identity values will be generated in the sequence established by the ORDER BY. If a clustered index exists on the identity column, then the values will be in the logical order of the index keys. This still doesn't guarantee physical order of insertion. Index maintenance is a different step and that could also be done in parallel for example. So you could end up generating the identity values based on ORDER BY clause and then feeding those rows to the clustered index insert operator which will perform the maintenance task.


Deploy on AWS ElasticBeanstalk - run custom npm script before starting server?

Question: I have been trying to deploy my nuxt universal app onto AWS elastic beanstalk. I've tried using custom npm script in my package.json:
"scripts": {
 "dev": "nuxt",
 "build": "nuxt build",
 "start": "nuxt start",
 "generate": "nuxt generate",
 "precommit": "npm run lint",
 "deploy": "nuxt build && nuxt start"
},

Then under AWS EB config, i added Node command: npm run deploy
However, it is not working.
Basically, i need to tell EB to run "npm run build" before "npm run start"
Anybody can help?
Answer: What you've described lies in the npm realm, and can be solved by using a prestart script, like so:
"prestart": "nuxt build"

More details here: https://docs.npmjs.com/misc/scripts
Comment: This doesn't seem like the right way to solve this.... Anytime the server restarts, it will have to rebuild first.  There should be some way to run it only after EB deploy and before start
Answer: So far this has helped me, it seems to work for default nuxt project (nuxt create) in universal mode.
I am using Elastic Beanstalk, CodePipeline and Bitbucket.
CodePipeline takes code from Bitbucket once it is pushed and builds in on Elastic Beanstalk.
What helped me is adding to package.json:
"deploy": "npm run build && npm run start"

or
 "deploy": "npm run install && npm run build && npm run start"

and creating Procfile in root directory of project, content/command of Pocfile triggers the deploy script in package.json file
web: npm run deploy

Answer: Before, there were "hooks" but now they're almost deprecated https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/custom-platform-hooks.html
Now you can use Buildfile and Procfile as described here https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-linux-extend.html
Comment: Have you found that Buildfile is supported on the AWS Linux 2 Node.js platform? We've been struggling with the same issue as the OP and found that Procfile is supported, but, and it's not super clear in the docs, Buildfile does not appear to be supported. From the docs: "Each individual platform topic specifically mentions Buildfile and/or Procfile if the platform supports them." The Node.js platform only specifically mentions Procfile.

We've found hooks to be unsatisfactory as they aren't called again on environment updates, even though the app seems to get undeployed.
Comment: It seems like "Custom platform hooks" are deprecated, but "Platform hooks" are not. https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-linux-extend.html and the Node.js environment doesn't seem to support Buildfile.
Answer: Try Adding to your .ebextensions a "source_compile.config" file as follows:
# source_compile.config
container_commands:
  compile:
    command: "./node_modules/.bin/nuxt build"
    env:
      PATH: /opt/elasticbeanstalk/node-install/node-v12.16.3-linux-x64/bin/

Got the idea from the same need to pre compile a typescript nodejs server before deploying to Elastic Beanstalk :)
Here a ref:
https://medium.com/@lhviet88/deploy-a-typescript-expressjs-into-elasticbeanstalk-nodejs-server-8381e00e7e52


Editing a question's title to help prevent future dups

Question: Someone just asked
https://drupal.stackexchange.com/questions/41428/disabled-modules-performance-impact
This is clearly a dup.  Oddly enough, this question
Do non-enabled modules affect performance?
came up as #8 in the list when I copied/pasted the title/body into a new question.
I am thinking an edit may be in order to push this higher (this is not the first time there has been a dup), especially considering the good answers and comments on it.
Before I went ahead and did it, I was wondering what other thought about it.  I suspect "Do disabled modules affect performance?" would be best.
?
Comment: As side note: Congratulations for being close to be a 10K user! The effort you put in the site, even through the meta site is admirable.
Answer: Changing the title of the question that appears as 8th suggestion doesn't help, as its position in the list of suggested questions depends also from the title entered when asking a new question; change the title, and the same suggested question can change position, or not be shown at all.
I would not edit a question, or one of its answers, just to push it up in the front page, hoping that it would be noticed from who is going to ask a questions that is its duplicate. If there is effectively something that needs to be changed, then an edit is fine.
Consider that 63 questions have been asked between today (and there are still 6 hours before the day is over), and yesterday. Even if you would push the question up the front page, it would not stay long in the front page.
Furthermore, a post is automatically changed in a Community Wiki, when it is edited from 5 different users, or 8 times from its author; the purpose is exactly avoiding useless edits done just to bring the question to the front page.
As you said, the user who asked the question already had a list of possible questions containing the answer s/he is looking for. It is true that the user is not blocked from asking the question, but it would be possible that the OP is asking a different question, despite the title being very similar to the title used from another question.
Stack Exchange shows also a list of possible related questions, when users are writing a question's body, but in this case it doesn't happen, probably because the text of the question is too short. I tried asking a question using the same title as the duplicate question, and using the text of both the questions you are referring, and this is the result.

The questions you are referring are the first two, and there are other questions that could probably give more information about something that is related.
If users don't look to possible duplicates before asking a question, or they don't look at the questions Stack Exchange suggests, there isn't much we can do, if not closing the question that is a duplicate. If then you see a user who keeps asking duplicate questions, then you could also down-vote the question, as it doesn't show any search effort, which IMO it means also the user didn't search in the site for a similar question, before asking it. Once a question score is at least −3, it gets pushed out the front page.
Also, from the SEO point-of-view, duplicates are not bad: They help users finding the original, possibly answered question. If the previous question has not been answered, the duplicate points to it; users who find the original question through the duplicate could answer it.
That is the reason why duplicates are generally not deleted, from Stack Exchange sites. There are a few cases where the duplicate is deleted: When the two questions are using too similar wording, or too similar titles. (Imagine a "Disabled modules performance impact" question that is duplicate of "Disabled modules performance impact".)
Comment: I actually wasn't talking about editing http://drupal.stackexchange.com/questions/41428/disabled-modules-performance-impact to push it to the fton page.  I meant editing the title of http://drupal.stackexchange.com/questions/22/do-non-enabled-drupal-modules-affect-performance; it is #8 in the "Questions that may already have your answer" list.  I am wondering if a better title on that would would help people find it easier, ie push it up the "Questions that may already have your answer" list.
Comment: I have updated my answer.


I can't replace my JLabel which is in a JPanel

Question: So I want to "move" my JLabel which is included to a panel. When I change the first number at setBounds for my label (bcopy) its location doesn't change. What did I do wrong?
bcopy = new JLabel("CST made by ColdStormy");
    bcopy.setBounds(50, 0, 100, 25);
    add(bcopy);

bottom = new JPanel();
        bottom.setBackground(Color.GRAY);
        bottom.setBounds(0, 450, 750, 50);
        bottom.add(bcopy);
        add(bottom);

If it's important here's the code for the frame in the main-class:
Frame frame = new Frame();

    frame.setSize(750, 500);
    frame.setLayout(null);
    frame.setLocationRelativeTo(null);
    frame.setTitle("ChampionSelectTool - Help yourself selecting champions!");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setVisible(true);

Comment: Use a `LayoutManager`, `JFrame` instead of `Frame`, `Frame` does not have a `setDefaultCloseOperation` method
Comment: Plus you add `bcopy` to two different containers. Doesn't make sense.
Comment: *"..want to "move" my `JLabel`.."* Why?
Answer: When you dynamically add/remove components the basic code is:
panel.add(...);
panel.revalidate();
panel.repaint(); // sometimes needed


removeNodeAfter method explanation

Question: this is a method to remove a current selected node in the linked list. What i don't get is link.link part. Isn't ".link" a method? There is no link method written in the class yet it still works. Can someone explain why?
public void removeNodeAfter( )
{
  link = link.link;
}

Full class can be found at https://www.cs.colorado.edu/~main/edu/colorado/nodes/IntNode.java
Answer: Look at the top of the class, where you can find the definition of link as private IntNode link;. It's an attribute or instance variable.

removeNodeAfter method explanation


Use Layout as OverlayItem on MapView?

Question: Is it possible to use a layout defined in XML as an OverlayItem to be added to a MapView instead of just a single drawable?  I have several Overlays being drawn on the map but they are just single images, I would now like to place Overlays that are more complex objects instead of just a simple drawable.
I am planning on drawing a marker with a dynamic image inside it (just a friend locator type thing), where each marker has a different picture inside.
Is adding these as OverlayItems the way to go about it or do I need to add each one to the MapView as a child view (this seems like it would be inefficient)?
Answer: I was trying to do something similar - draw Google Maps style balloons with custom views inside them onto the map. I tried overriding the draw() of an OverlayItem, and drawing the layout I'd defined in XML that way. The problem was in coverting the View to a Drawable to draw onto the MapView canvas meant I lost all event handling capabilities of the Layout so things like buttons etc. did not work properly. If you don't have any events on the images to worry about then this could work, you'll just need to inflate your view using the current Activity's LayoutInflater (activity.getLayoutInflater()), measure and lay it out as described under the 'How Android Draws Views' page on the android developers site (couldn't post a link due to new user restrictions, sorry!), and finally call buildDrawingCache() and getDrawingCache() on your View to get it as a Bitmap. This can then be drawn onto the Canvas passed the draw() method of a subclass of Overlay that you've built.
I actually went for the second approach you suggested (adding each one as a child view to MapView, using MapView.LayoutParams to hover the layout over the OverlayItem in question) in the end. I only had one child view to worry about though so I wasn't too worried about the efficiency here, it might be more of a problem to you if that is actually something to be concerned about (it might be worth testing first though). There's a small writeup of what I did here with a bit more detail.
Finally you might want to look at android-mapviewballoons's approach to this, which is well worth a look.
Answer: I was able to add a layout as a Marker on a map by converting the layout to a drawable. Here's a bitmapFromView function taken from this tutorial:
public static Bitmap bitmapFromView(View layout, int width, int height, Context context) {
    // Create a new bitmap and a new canvas using that bitmap
    Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bmp);
    layout.setDrawingCacheEnabled(true);
    // Supply measurements
    layout.measure(View.MeasureSpec.makeMeasureSpec(canvas.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(canvas.getHeight(), View.MeasureSpec.EXACTLY));
    // Apply the measures so the layout would resize before drawing.
    layout.layout(0, 0, layout.getMeasuredWidth(), layout.getMeasuredHeight());
    // and now the bmp object will actually contain the requested layout
    canvas.drawBitmap(layout.getDrawingCache(), 0, 0, new Paint());
    return bmp;
}

I use the method to add the bitmap as a Marker like this:
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.MY_LAYOUT, null);
Bitmap markerBitmap = bitmapFromView(layout, MY_WIDTH, MY_HEIGHT, context);

MarkerOptions markerOptions = new MarkerOptions()
            .title(MY_TITLE)
            .position(MY_POSITION)
            .icon(BitmapDescriptorFactory.fromBitmap(markerBitmap));
map.addMarker(markerOptions);

Use Layout as OverlayItem on MapView?


Passing variables to django template from view

Question: In my base.html, i have the following code
{% if user_anon == "true" %}
    {% block login_with_fb %}{% endblock %}
{% else %}
    SOMETHING ELSE

And in views.py , i have
t = get_template('login.html')
try:
    c = Context({ 'user_anon':"false" , 'STATIC_URL':'/stic'})
except ObjectDoesNotExist:
    c = Context({ 'user_anon':"true" , 'STATIC_URL':'/stic'})
r = t.render(c)
return HttpResponse(r)

but the base.html always responds with user_anon = "true" code... irrespective of the value of c being passed :/
Answer: Why not check the request directly in the template?
Example:
{% if user.is_authenticated %}

Secondly, why are you casting it to a string? It would be easier to just use true/false in Python I would think.
Lastly, why are you injecting your static url? You should be setting this in your configuration, then you can just use it directly via template tag. See the official docs about this here.
Example:
 {% load staticfiles %}

Comment: That was the first thing i tried, `{% if user.is_authenticated %}` and it didn't work... since i am using an external library for login, i really have no clue where the variable "user.is_authenticated" is set to be true and how to modify it, so went with the custom variables.
Comment: If that value is not accessible, it probably means you are not passing your request context to your template properly.

Also you can try to do  as I suggested, don't pass string to your template, use a Python True/False which is cleaner IMO. Also, why are you not using render_to_response shortcut? It would simplify your code a bit here.
Comment: turns out that instead of `user.is_authenticated` ... i needed to use `user.is_anonymous` to make it work. Probably the library is old school :P Thanks for the help.


Sheaf Cohomology of Injective Sheaves respects Products

Question: Let $(\rho_{\lambda})_{\lambda}$ a family of injective sheaves on the space $X$ (therefore injective objects on the category of abelian sheaves). Using universal property of product it's easy to see that $\prod_{\lambda} \rho_{\lambda} $ is also an injective sheaf.
My question is why then for the sheaf cohomology holds the isomorphism
$$ H^r(X, \prod_{\lambda} \rho_{\lambda}) \cong \prod_{\lambda} H^r (X,\rho_{\lambda})$$
Ideas:
I know that the sheaf cohomogies induced by injective and acyclical resolutions are identical, but I don't see why this fact may inply the isomorphism above.
Comment: Both sides are obviously zero by the construction of a right derived functor.
Answer: Since injective sheaves are acyclic for global sections, the statement is trivial for $r > 0.$ So all you're claiming is that global sections of the product is the product of global sections. There are various ways to see this -- for example, you could check that the presheaf (sectionwise) product is actually a sheaf, or you could observe that global sections is representable.
Comment: Or the global section functor is right adjoint to the "locally constant sheaf"-functor, hence it commutes with all limits, in particular products.


How to search register in Pentaho with million registers

Question: What is the best alternative to find a record among millions of records using Pentaho Spoon?
I'm using a 'stream lookup' with a 'table input', but my query on the 'tbResponse' step returns a lot of data, causing a lot of slowness. Has anyone ever experienced this?
Answer: If you expect to use most of the records from the lookup table, the stream lookup is not the best option. Use a (merge) join operation instead, with both input streams sorted on the join keys.
If you only expect to use a low percentage of the records a database lookup is much better as it doesn't retrieve all of the records from the table, at the cost of many single select operations.
Answer: If youren't processing a lot of records in your main data stream, you should use Database Lookup instead. That way it will only return the one record you need from the db, by using a specific field as key to find the correct record. However, it has the disadvantage of performing one query for each record you want to retrieve, so it might not be as good idea if you also have millions of records in your main stream. Anyway, that can be partially solved by caching some of the results in memory ("Enable cache?" checkbox and set number of records to store in cache).


Will users know to click the top item in navigation menu?

Question: I've got a navigation menu on my website which has several levels of submenu.
In the example pictured below I'd like users to be able to click "Services" in the top level menu and go to a "services" page. But I'm worried they won't think it is clickable, and will assume only the bottom level actually will take you to a page.
Can anyone advise? Has there been any research done on this?
Comment: I'd expect clicking `Services` to open the menu... if clicking changes page I'd be puzzled.
Comment: Certain navigation bar designs (e.g. [this one](http://www.epson.com/cgi-bin/Store/jsp/index.do) which I came across today) don't look like menus, so I click the top item. Then the menu opens, so I try to click another item. But then the first page already starts to load. Two [POLA](https://en.wikipedia.org/wiki/Principle_of_least_astonishment) violations in one design is what I'd call a bit of a failure.
Comment: Back then I would assume I've gotta clicked to open dropdown. But nowadays I often found navbar that implement it like that. So nowadays, I expect I only need to hover to open dropdown, because it started to be set in my thought that clicking will lead me to a new page. But yeah that's for input using mouse. Insight about what happen with touchscreen as being mentioned below is very good.
Comment: Interesting that [Wordpress](https://wordpress.com/) sites by default assume that all menu items are pages, including the top items.
Comment: Drupal does the same thing and I hate it.
Answer: Good question. I can only offer my opinion, no research.
In my opinion, it seems as though doing this is mixing 2 separate actions on one element (I've done it myself in the past).
I've come to the conclusion that the navigation click action on the "Services" item should be removed. You will face further problems when people use touch screens. E.g. when they tap the "Services" item will you open the sub menu or navigate to the Services page? This could be a big problem if those sub pages are only accessible from that drop down.
Some examples of solutions to the problem:

Have an option on the sub menu called "All Services".
Split the button in 2: a larger part that is the link to the Services page, and a smaller part with an obvious arrow and border that opens the submenu (from Nate Kerkhofs in the comments below)

Additional solution (from my comments) to cater for problems caused by hiding sub options on hover:
You should at a bare minimum offer that sub menu list of links (the ones hidden until hover) on the actual "Services" page. This is a backup for when the sub menu can't be opened (e.g. on touch) and so at least a user can navigate to the services page, and then navigate to a sub page from the links provided on there.
Here is an example from BBC Food. See the recipes menu option and its sub menu. Tap recipes to see that the sub menu is permanently visible on there.
Comment: If you don't want to add another option, you could split the button in 2: a larger part that is the link to the Services page, and a smaller part with an obvious arrow and border that opens the submenu.
Comment: I hadn't thought about touch-screen. Good point.
Comment: Does this mean there is any problem with menus that have _no_ sub-menu opening pages? (e.g. "Home" on the example)
Comment: correct. If there isn't a sub menu then navigate to the page e.g. "Home" on click/tap. IF there is a sub-menu e.g. "Services" then only open/close that sub menu on click/tap. If you want to provide navigation to the "Services" page either add a link in the sub menu or do what @NateKerkhofs suggested by splitting the button into 2 sections.
Comment: @Urbycoz this may sound contradictory to my answer but its an option - if you want to retain the navigation tap event on the "Services" and hover too, then you could make that sub menu visible when you are on that page. e.g. take a look here: http://www.bbc.co.uk/food/chefs the recipes sub menu appears on hover, but you can also click recipes in the main nav to go to that page, but when you are there the sub menu is visible. this caters for the problem I mentioned in my answer
Answer: Pro users will, but novice users won't. Index pages are hidden behind the hover. This is one reason among many why hover menus are a bad choice for navigation.
Why Hover Menus Do Users More Harm Than Good
To summarize:

Index pages are often hidden in the category name that users first
  hover their mouse over. Most users don't know that the category name
  leads to the index page because it looks like it's already selected.
  The highlighting on hover makes it unclear that the category name is a
  link. This hurts new users who often need index pages to give them an
  overview of content to know where to navigate.
Answer: The big problem of your screenshot is that the "arrow" icon is looking like a horizontal arrow, which usually means that you click it and then come to another site.
The whole confusion here can be easily solved by an arrow that shows people that this menu item is expandable. Very much like this ▲ or ▼. The menu item becomes a dropdown menu item in this case.
Also for easier discoverability you should make it show on hover not only on click.
An example can be seen on amazon.com
Comment: on amazon.com their hoverable items which reveal the sub-menus aren't clickable themselves.
Comment: I agree with this. When I saw the horizontal arrow I thought it was a link to an external site. You don't see it much these days, but it was almost convention a few years back.
Answer: I don't think having the services part clickable is a good idea if it leads to a page that has nothing to do with the entities that are part of the drop down. Though i have seen sites that have the first item as clickable but the page that it redirects to is not a separate page but a page that has info on all the entities of the drop down. ( Kind of a home page ) . But this type of navigation would certainly cause problems on a touch device .
Answer: I think this IA is a bit complex for what seems to be a simple site. I would recommend bringing the content of services to the top level. So you top level nav is
home | web design |Identity | logo design | wordpress| portfolio (put testimonials here) | contact
Avoiding drop down menus like that in a simple site is really good idea - not only does putting your services in top level immediately disambiguates what you actually do, but it is painless for navigation and great for SEO.


Can I install current version of ubuntu on a Dell Inspiron mini 10 (CPU=Atom Z530)?

Question: Hopefully this is an easy question for the collected knowledge here.  I have an old Dell Inspiron mini 10 with a Atom Z530 CPU.  I am interested in installing ubuntu on it to run Kodi.
Due to it being 6 years old, would it be able to run the current version of ubuntu?  If it can, I'm looking at upping the RAM from 1Gb to 2Gb and installing a solid-state harddrive if it can handle that.
Answer: I've run it on worse.  It should run the latest versions of Ubuntu fine, but it may be a little slow.  I would go with Lubuntu, since it's lighter-weight.
In short, yes, but it will be a tad slow.  Go with Lubuntu for better results.
Comment: Awesome, thanks for the post edit (muru) and the post reply (Daniel).  I think I'll try Ubuntu 14.04 Server Installation Minimal and, if it's too slow, go with the Lubuntu per your suggestion, Daniel.
Comment: If this answer worked for you, you can mark it accepted (or perhaps not, now that it's a duplicate?).


Synchronous RPC Calls in GWT

Question: (That title alone should cause people to come out of the woodwork to bash me with clubs, but hear me out).
I have a use case where I need to return a value from a asynchronous call. (I'm using GWT-Platform, but the concepts are the same.) I declared a final JavaScriptObject array, then assigned the value within the AsyncCallback. However, I need to return the value, and the method returns before the AsyncCallback completes. Therefore, I need to block somehow until the AsyncCallback completes. I need the returned value in another method, or I'd just do what I need to in onSuccess().
I've tried loops, Timers, and a few other methods with no luck. Can anyone help?
@Override
public JavaScriptObject doGetWhereAmIMarker(final double lng, final double lat) {

    final JavaScriptObject[] markerArray = new JavaScriptObject[1];  // ugly hack, I know
    dispatch.execute(new GetLocationDescriptionsAction(lng, lat), new AsyncCallback<GetLocationDescriptionsResult>() {
        @Override
        public void onFailure(Throwable caught) {
            caught.printStackTrace();
        }

        @Override
        public void onSuccess(GetLocationDescriptionsResult result) {
            Map<String, Location> resultMap = result.getResult();
            StringBuffer message = new StringBuffer();
            for (String key : resultMap.keySet()) {
                message.append(key).append(": ").append(resultMap.get(key)).append("\n");
            }

            Map tempMap = new HashMap();
            tempMap.put("TITLE","Location Information");
            tempMap.put("LAT", lat);
            tempMap.put("LNG", lng);
            tempMap.put("CONTENTS", message.toString());

            JavaScriptObject marker = GoogleMapUtil.createMarker(tempMap);
            markerArray[0] = marker;
            if (markerArray[0] != null) {
                GWT.log("Marker Array Updated");
            }

        }
    });

    return markerArray[0];
}

UPDATE: As requested, here is the code that calls doGetWhereIAmMarker(). I've tried having a separate native method with the Google Map object (as a JavaScriptObject) as a parameter, but it appears that passing that object between native methods kills the ability to update said object.
public native void initMap(JavaScriptObject mapOptions, JavaScriptObject bounds, JavaScriptObject border, JsArray markerArray, Element e) /*-{

    // create the map and fit it within the given bounds
    map = new $wnd.google.maps.Map(e, mapOptions);
    if (bounds != null) {
        map.fitBounds(bounds);
    }

    // set the polygon for the borders
    if (border != null) {
        border.setMap(map);
    }

    // set up the info windows
    if (markerArray != null && markerArray.length > 0) {
        var infoWindow = new $wnd.google.maps.InfoWindow({
            content:"InfoWindow Content Goes Here"
        });

        for (var i = 0; i < markerArray.length; i++) {
            var marker = markerArray[i];
            marker.setMap(map);
            $wnd.google.maps.event.addListener(marker, 'click', function() {
                infoWindow.setContent(marker.content);
                infoWindow.open(map, this);
            });
        }
    }

    // need to reference the calling class inside the function(), so set a reference to "this"
    var that = this;

   $wnd.whereAmI=function(lng, lat) {
        that.@org.jason.mapmaker.client.view.MapmakerMapViewImpl::whereAmI(DD)(lng,lat);
   }

    $wnd.google.maps.event.addListener(map, 'click', function(event) {
        var lat = event.latLng.lat();
        var lng = event.latLng.lng();
        $wnd.whereAmI(lng, lat);
    });

}-*/;

Comment: Can you show some more code?  I am interested in the parts that call this code, and also the parts that consume the JavaScriptObject that is returned from `doGetWhereAmIMarker(...)`.
Comment: Added the calling native method. GoogleMapUtil is at https://github.com/dartmanx/mapmaker/blob/master/src/main/java/org/jason/mapmaker/client/util/GoogleMapUtil.java, but isn't commited with the createMarker() method. It's similar to the createMarkerArray() method, however.
Comment: Why does it not work then if you just put a while(asyncIsDone){sleep}. that seems like the most simple thing to do... or make it a for(){sleep} that will continue after a certain time has passed?
Answer: At some point I had to do something similar but eventually I eliminated that code in favor of asynchronous stuff. Therefore, I can't give exact code that you need to use but only few pointers on how to approach it.

Firstly, this blog describes how to do synchronous AJAX using javascript.
Second, you must provide support for sync calls. The problem is that GWT does not support the parameter that provides synchronous AJAX calls. Most likely is that they don't want to encourage its use. Therefore you would need to use JSNI to add appropriate method to XMLHttpRequest (which you probably would extend) and then to RequestBuilder (also should extend it).
Finally, amend your service using extended RequestBuilder. Something like

((ServiceDefTarget)service).setRpcRequestBuilder(requestBuilder);

And in conclusion - from the same blog post (slightly out of context):

Because of the danger of a request getting lost and hanging the browser,
      synchronous javascript isn't recommended for anything outside of
      (onbefore)unload event handlers.
Comment: You should be able to use any Javascript code with GWT using JSNI. `RequestBuilder` is used internally when you deal with RPC. Once you have your service, you can assign your custom `RequestBuilder` using snippet that I provided.
Comment: I've done manual synchronous AJAX before, but since this is GWT I'm stuck with GWT's limitations. I'm using GWT-Platform's DispatchAsync for getting data, and I'm not seeing anything in there using RequestBuilder.
Comment: I'm going to accept your answer as it's interesting and might be something I need to try someday. However, I found the answer to my original problem that was preventing me from using the async request.
Answer: I Think its all fate....
We cannot do in Gwt to catch the Response and Send it, because immediately after the request is send the next method starts executing, neither bothering the response
Still however they satisfy us to use the Timers, is what i think...
 Timer t = new Timer() {
      @Override
      public void run() {
        Window.alert("Nifty, eh?");
      }
    };
    t.schedule(5000);

Synchronous RPC Calls in GWT


How to change the text of a textlabel in a game scene

Question: I am trying to change the text of a basic text label which I added within a game scene.
But I do not know how to do this by code.
For now I assigned a name to the label in scene editor but I do not know how to continue from here and a sign an new text value to the label.
Currently I use
    let scoreLabel = childNodeWithName("scoreLabel") as! SKLabelNode

But I receive an error message "Use of instance member 'childNodeWithName' on type 'SKNode'; did you mean to use a value of type 'SKNode' instead?
But since I want to make use of functionalities of a text labe, the SKNode Class is not sufficient for me.
Anyone who got some help?
Comment: If you want more info about that error, please provide more context about where this code is placed (eg. is it a property of a scene / some other class, which would be wrong, or it is defined locally in some method etc).
Comment: @Whirlwind Basically I just place the line within the GameScene Class, where I also put my other variables and definitions. But I am searching for an opportunity to do something like: scoreLabel.text = "3"
Comment: I put the setup of the timer in a separate function and called it on "didMove", Solved the problem :) Thanks anyway!
Answer: This is an example of how to set a SKLabelNode either as a property and locally, and access those variables later in your code:
import SpriteKit

class GameScene: SKScene {

    let label = SKLabelNode(fontNamed: "ArialMT")

    override func didMoveToView(view: SKView) {

        label.text = "This is a label defined as a property of scene";
        label.fontSize = 35;
        label.fontColor = .blackColor()
        label.position = CGPoint(x:frame.midX, y:frame.midY)

        addChild(label)

        let anotherLabel = SKLabelNode(fontNamed: "ArialMT")
        anotherLabel.text = "This is a label defined localy and added to a node tree"
        anotherLabel.name = "anotherLabel"
        anotherLabel.fontSize = 35;
        anotherLabel.fontColor = .whiteColor()
        anotherLabel.position = CGPoint(x:frame.midX, y:frame.midY - 100.0)

        addChild(anotherLabel)

    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        self.label.text = "Your text"

        if let anotherLabel = childNodeWithName("anotherLabel") as? SKLabelNode {

            anotherLabel.text = "Your text"
        }
    }
}

In the case of a property, accessing is simple as self.label.text = "...". In the case of a local variable, added to a node tree, you use its name property to find it later using childNodeWithName method.
Answer: Not sure if this will work for the original poster, but as of 2020, the correct syntax to add a node created in the scene builder to the program is something like that
var mySkNode = childNode(withName:"//nameOfNode") as? SKNode;

If it is a SKLabelNode, you should replace SKNode with SKLabelNode, and same for every specific SpriteKit class.


Putting a ViewController on top of a TabBarController

Question: Basically I want to make a login screen in my iPhone app before I show my TabBarController. I tried the following approach, adding first to the window subview my TabBarController and on top my LoginViewController. What am I doing wrong or should I do it completely different?
<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [self.window makeKeyAndVisible];

    NSMutableArray *tabItems = [[NSMutableArray alloc] initWithCapacity:2];

    DefaultViewController *dvc = [[DefaultViewController alloc] init];
    UINavigationController *dvc_nc = [[UINavigationController alloc] initWithRootViewController:dvc];
    dvc_nc.tabBarItem.title = @"Home";
    //dvc_nc.tabBarItem.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Default" ofType:@"png"]];
    [tabItems addObject:dvc_nc];
    [dvc release];
    [dvc_nc release];

    OptionsViewController *ovc = [[OptionsViewController alloc] initWithStyle:UITableViewStyleGrouped];
    UINavigationController *ovc_nc = [[UINavigationController alloc] initWithRootViewController:ovc];
    ovc_nc.tabBarItem.title = @"Option";
    //ovc_nc.tabBarItem.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Option" ofType:@"png"]];

    [tabItems addObject:ovc_nc];
    [ovc release];
    [ovc_nc release];

    UITabBarController *tbc = [[UITabBarController alloc] init];
    tbc.viewControllers = tabItems;
    self.tabController = tbc;
    [tabItems release];
    [tbc release];

    [self.window addSubview:self.tabController.view];

    LoginViewController *lvc = [[OptionsViewController alloc] init];
    UINavigationController *lvc_nc = [[UINavigationController alloc] initWithRootViewController:lvc];
    [self.window addSubview:lvc_nc.view];
    [lvc release];
    [lvc_nc release];

    return YES;
}
</code>
Answer: <code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [self.window makeKeyAndVisible];

    NSMutableArray *tabItems = [[NSMutableArray alloc] initWithCapacity:2];

    DefaultViewController *dvc = [[DefaultViewController alloc] init];
    UINavigationController *dvc_nc = [[UINavigationController alloc] initWithRootViewController:dvc];
    dvc_nc.tabBarItem.title = @"Home";
    //dvc_nc.tabBarItem.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Default" ofType:@"png"]];
    [tabItems addObject:dvc_nc];
    [dvc release];
    [dvc_nc release];

    OptionsViewController *ovc = [[OptionsViewController alloc] initWithStyle:UITableViewStyleGrouped];
    UINavigationController *ovc_nc = [[UINavigationController alloc] initWithRootViewController:ovc];
    ovc_nc.tabBarItem.title = @"Option";
    //ovc_nc.tabBarItem.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Option" ofType:@"png"]];

    [tabItems addObject:ovc_nc];
    [ovc release];
    [ovc_nc release];

    UITabBarController *tbc = [[UITabBarController alloc] init];
    tbc.viewControllers = tabItems;
    self.tabController = tbc;
    [tabItems release];
    [tbc release];

    [self.window addSubview:self.tabController.view];

    LoginViewController *lvc = [[OptionsViewController alloc] init];
    UINavigationController *lvc_nc = [[UINavigationController alloc] initWithRootViewController:lvc];
[self.tabController presentModalViewController:lvc_nc animated:no];
    [lvc release];
    [lvc_nc release];

    return YES;
}
</code>
Comment: I had the same problem yesterday and the `presentModalViewController` as @rckoenes wrote is the correct and working solution
Comment: Aha, seems too work! Is this the proper way to remove the LoginView after i'm done with it?  [self.parentViewController dismissModalViewControllerAnimated:YES];
Comment: `[self dismissModalViewControllerAnimated:YES];` will do just fine.
Answer: I would use two different views. One will handle the login proccess and one is your "Logged in view" that provides the features of your app. When your app starts up, you add the login view, check username/password and when the login went fine you switch to your second view.
Comment: Do you have a code sample that works with my tabbarcontroller?
Comment: No sorry, am at work and can not provide code samples :/ From the logic: Just create 2 different UIViewControllers one that has your login form in it and get's presented/added in yout applicationDidFinishLaunching method. Put a method in there that validates the entered user credetials and presents your second view (which holds your UITabBar) if the username/password is correct.