Find triangle with given orthocenter and an apex on a circle

Question: We are given $k(O; r)$, $A \in k$ and $H : OH>r$. Find points $B$ and $C$ ($B, C\in k$) such that $H$ will be the orthocenter of $\triangle ABC$.

I am trying to see what is the point $F$ ($AH \cap k = F$), but I can't figure it out. Also $AH\bot BC$ but I don't know how to continue. I will be very grateful if you help me.

Reversed:
Comment: The question (except the added diagram) says nothing about F.  It is just a distraction.
Comment: Yes, I see that but I am wondering how to find B, C.
Comment: Do it the other way round. Draw an obtuse  triangle ABC with $\angle ABC \gt 90^0$. Form the orthocenter, H. Draw the circle circium-scribing $\triangle ABC$.
Comment: It is just a suggestion. We need to know all the related facts from the actual figure. Hopefully we can find the required solution by reversing the thinking process.
Comment: @Mick, I think that $B$ and $C$ lie on perpendicular bisector of FH but I don't know how to show it. Isn't that so? [Reverse](https://i.imgur.com/nNPKK08.png)
Comment: I'm trying to show that $\triangle FEC \cong \triangle EHC$ because they share $EC$ and are right-angled. I should proof that $FC=HC$ or $\angle FCE = \angle HCE$ or $\angle EFC = \angle EHC$ but I can't figure it out.
Comment: 1) If H is the ortho-center of $\triangle ABC$ (with B being obtuse), then B is also the orthocenter of $\triangle AHC$. 2) If you also draw the other two altitudes (HX on AC and AY on HC, then $EXY$ forms the so-called orthic triangle in which CBE is the ***angle bisector*** of $\angle XEY$.
Comment: @Mick, I don't understand fully. Now we have $\angle XEC = \angle YEC$?
Comment: @Mick, what did I miss?
Comment: $\angle XEC = \angle YEC$ is correct because that is the properties of an orthic triangle. Also, You are correct that  CBE is also the ***perpendicular bisector of FH***. I cannot show my pictorial proof in the comment. I will add that in the solution section.
Comment: @Mick, Okay I'm looking forward to seeing it.
Answer: Added: Since $\angle AEC = \angle AYC = 90^0$, AEYC is cyclic. Hence, we have the added dotted circle. From that, $\angle 1= \angle 3$.

After that, E can be found. Hence, C is located. B......
Comment: I understood that $\angle FAB = \angle FCB$ but what happened next? Why do you have another circle?
Comment: @NikolDimitrova See added.
Comment: $\angle 1 = \angle 3 = \frac {\newcommand{arc}[1]{\stackrel{\Large\frown}{#1}}\arc{EY}}{2}$ and $\angle 1 = \angle 2 = \frac {\newcommand{arc}[1]{\stackrel{\Large\frown}{#1}}\arc{FB}}{2}$, thus $\angle 3 = \angle 2$. Right?
Comment: @NikolDimitrova ∠1 = ∠3 and ∠1 = ∠2, thus ∠3 = ∠2 directly.
Comment: Thank you! I think my way is also correct (inscribed angles). My last question is when we can state that a quadrilateral is cyclic? I haven't studied it yet, but I read some articles and still can't understand it. You've written $\angle AEC = \angle AYC = 90^\circ$...?
Comment: @NikolDimitrova Sorry to say that you way is NOT correct. We need $\angle 3 = \angle 2$ to prove the $\triangle CFE \cong \triangle CHE$. Once we have done that, we can then say FE = HE. That equality guarantees CE is the perpendicular bisector of  FH. To answer your question, the theorem that I quoted is called "the converse of angles in the same segment" which is one of the ways to prove a quadrilateral is cyclic.
Comment: I still don't understand why my way isn't correct. $\angle EAY = \angle ECY = \frac {\newcommand{arc}[1]{\stackrel{\Large\frown}{#1}}\arc{EY}}{2}$, $\angle FAB = \angle EAY = \angle FCB = \angle FCE = \frac {\newcommand{arc}[1]{\stackrel{\Large\frown}{#1}}\arc{FB}}{2}$, thus $\angle 3 = \angle 2$.
Comment: @NikolDimitrova The logic is incorrect. In the beginning, ARC FB is NOT equal to ARC BD yet. They will be equal only after we have proven $\angle 2 = \angle 3$. Out.
Comment: But you DO NOT need these arcs. Look at the angles. They're inscribed and are equal. We are looking at both circles and use the equal inscribed angles. Just see what I've written.


JUnit4 - AssertionFailedError: No tests found

Question: I'm using AndroidJUnitRunner with Espresso.
I wrote a simple test but always receive this exception. According to Stackoverflow answers, the problem is messing up the JUnit3 and JUnit4 but I have never used JUnit3 in my project.

junit.framework.AssertionFailedError: No tests found in com.walletsaver.app.test.espresso.SignUpPopupTest

package com.walletsaver.app.test.espresso;

import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.SmallTest;

import com.walletsaver.app.activity.LoginActivity;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.matcher.ViewMatchers.withText;

@RunWith(AndroidJUnit4.class)
@SmallTest
public class SignUpPopupTest {

    @Rule
    public ActivityTestRule<LoginActivity> mActivityRule =
            new ActivityTestRule<>(LoginActivity.class);

    @Test
    public void checkSignUpPopup() throws Exception {
        onView(withText("Sign Up")).perform(click());
    }
}

Run configuration:

Output:
Answer: I found the problem.
It was missed code in build.gradle in the main module.
If you have this problem I advise to start with adding this line:
android {
    ...

    defaultConfig {
        ...

        testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
    }
...
}

Comment: For AndroidX,
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
Comment: Thanks alot it solved the problem, can you tell why we have to add this?
Comment: Hi, I have Dynamic Feature Modules in my app. For tests in the Feature Module, I'm using a custom testInstrumentationRunner , which is located in the app module. I'm getting this error
 "Test running failed: Instrumentation run failed due to 'Process crashed.'"
Any idea how will it work across multiple modules? @Val
Comment: @OmerMalik I tried to mention `android.support.test.runner.AndroidJUnitRunner` in Run configuration but this didn't have an effect. Then I wrote it directly in `build.gradle` and it helped. It seems it should be set in `defaultConfig` to be visible.
Comment: I read the android documentation and it is mentioned their, I missed the step, thank alot
Comment: as a follow-up, one may see the message "Unable to find instrumentation info for".  To fix that, tell the Android Studio launch configuration to use the specific test runner from the _build.gradle_ file
Comment: For AndroidX, use `testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"` instead.
Answer: android {
    defaultConfig {
        testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
    }
}

dependencies {
    androidTestImplementation "androidx.test:runner:1.4.0"
    androidTestImplementation "androidx.test.ext:junit:1.1.3"
}

@RunWith(AndroidJUnit4::class)
class SomeInstrumentedTest {}


Target different database for a single query?

Question: Can I set the target database on a db_select()?
Example:
$result = db_select('table', 't')->fields('t')->db_target('db_name')->execute();

One can use db_set_active() to change to which database a query should be sent, but that requires one to manually "reset" the active db, which is a potential cause of bugs.
Comment: I've never come across any bugs with `db_set_active()`, could you elaborate a wee bit?
Comment: I haven't entirely figured out what happened, but it seemed like a query against db A triggered a hook, that made a module want to translate a string, which made locale try to lookup translations, which fails because locale_source is in db B. I had to hack a `db_set_actice('default')` into locale.module to work around it. Made me think it would be useful to set the target per query instead of per connection.
Comment: Wow that sounds like fun! I'm not sure but maybe the code in Kiamlaluno's answer to [this](http://drupal.stackexchange.com/questions/45199/how-to-write-db-query-or-db-select-from-multiple-databases-in-drupal-7/45542#45542) will help? The questions don't match but there's a technique in there for selecting from arbitrary databases that I hadn't seen before
Comment: Hmm, interesting, I will have to try it next time this problem bites me. Thanks @Clive.
Answer: From the comments above such as from @Clive, I do this alll the time:
$count_query = Database::getConnection('default', 'dew_remote_sources')
               ->select('survey', 's');
$count_query->addExpression('COUNT(DISTINCT(survey_number))', 'cnt');

For this to work you need to have various databases defined in your $databases value of settings.php (or you can add additional $databases[key] values to top of your module sometimes, or create such a connection on-the-fly using:
Database::addConnectionInfo('for_migration', 'default', array(
  'driver' => 'mysql',
  'database' => 'migration_database',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => '',
));

You see this pattern alot in the Migrate documentation pages, migrate examples and 3rd party modules that have implemented migrations. Because you are literally moving content from DatabaseX to DatabaseY alot and switching around with db_set_active can easily lead to confusion in such cases with the Object Oriented nature of the Migrate module.
Comment: This is probably one of the most useful things I have seen on this site.  Cheers!


Below code is not working as i expected it to work, Instead it is reversing the input

Question: This is a program, which should print a string in its descending length size. But this code is printing the given string in reverse. Any ideas about What I am missing in this code?
def listsorter(lst):
    lst=lst.split(" ")

    lstsize=list("a"*len(lst))
    lstindex=lstsize
    looper=len(lst)
    other=lst

    for i in range(looper):
        lstsize[i]=len(lst[i])
        lstindex[i]=lst.index(lst[i])

    while len(lstsize)>1:
        temp=max(lstsize)
        temp1=lstsize.index(temp)
        print(other[temp1])
        lstsize.pop(temp1)
    else:
        print(lst[0])

user_input=input("Enter anything\n")
listsorter(user_input)

Comment: Please provide sample input, desired output, and fix the indentation.
Comment: Oh man. You should learn to write clean Code. Try to name the variables readable and provide comments.
Comment: `lst` doesn't look like a list, but a string of "words"?
Answer: Do you want something like this:
def length_sorter(s):
    words = s.split(' ')
    for w in sorted(words, key=len, reverse=True):
        print(w)

lenth_sorter('hello world i am a computer')
# prints:
computer
hello
world
am
I
a

To do this without using the built-in sorted function, you can build your own sorting algorithm.  Bubble sort is the easiest to understand.
def bubble_sort(a):
    a = list(a) # make sure we are using mutable objects
    keep_sorting = True
    while keep_sorting:
        keep_sorting = False
        for i in range(len(a)-1):
            if len(a[i]) < len(a[i+1]):
                a[i+1], a[i] = a[i], a[i+1]
                keep_sorting = True
    return a

def word_sorter(s):
    words = s.split(' ')
    for w in bubble_sort(words):
        print(w)

word_sorter('hello world i am a computer')
# prints:
computer
hello
world
am
I
a

Comment: sir, i want to do that without using sorted or sorrt method. Is there a way?
Answer: edit: I guess what James wrote is what you want then?
Comment: sorry sir, i don't get you. Can you please give a little example. Will be big help :)
Comment: Sir i want,
If i input = hey hi what dones.    Output=dones what hey hi


How to load google map using jQuery on the anchor click

Question: I am trying to load google map on the anchor click. Below are the details.
I have index.aspx page where I have got one anchor tag and a div "divLoadMap"
Load Map

And I have map.aspx which have maps details. Below is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Simple Jquery CSS Tabs and V3 Google Maps</title>

   <form id="mapform" >

   </form>

Now I want load this map on the click of anchor tag which is present on index.aspx.
Please suggest!! would appreciate if can get code sample for above problem.
Comment: Your question is unclear - if you click the anchor, you will be taken to map.aspx, which will load in the map.  Can you be more specific?
Comment: On the anchor it will open the map.aspx in a overlay window i.e on the same page a lightbox.
Answer: I thought below approach.

Declare a div with id = 'GoogleMapContainer'
Make it by default display: none.
inside this div, declare iframe and assign src property of this iframe to index.aspx page.
Now onclick of anchor tag call a javascript function, which internally will call query modal dialog for above declared div.
this will result into a popup window which contain google map.

7.

Call javascript function on click of anchor tag. and in that javascript function write this code:
$jq ("#GoogleMapContainer").dialog({
        modal: true,
        width: 750,
        title: 'Google Map',
        resizable: false,
        open: function(type, data) {
            $jq(this).parent().appendTo("form");
        }
    });

Please suggest whether is it right approach or I need to do some modifications!!
Answer: Use this way....

      function initialize()
        {
            var latlng = new google.maps.LatLng(25.294371, 55.332642);
            var myOptions = {       zoom: 8,       center: latlng,       mapTypeId: google.maps.MapTypeId.ROADMAP     };
            var map = new google.maps.Map(document.getElementById("map_canvas"),

myOptions);
            var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                title: 'Dubai'
            });
            var contentString = 'Dubai';

            var infowindow = new google.maps.InfoWindow({
                content: contentString,
                maxWidth: 50
            });
            google.maps.event.addListener(marker, 'click', function() {
              infowindow.open(map,marker);
            });

        }

    });

    </script>

Now just call this initialize() function on a anchor click or a button click.....
Comment: But what about the pop up window in which, I need to show the map and also I need the parameter to be passed from the anchor click as I might have lots of countries to show in map.
Answer: You might want to try a lightbox plugin that handles iframes. Pirobox is one example.
this plugin uses the rel attribute to set the lightbox options.  In your case you would use iframe-width-height parameters.  Your code will look something like this:
//using 'full' for width and height will make the lightbox fullscreen
//or you can specify a width and height in pixels.
Load Map


Arc length does not change with a reparametrization

Question: Show that the arc length of a curve doesn't change with a reparametrization.
Let $\sigma: [a,b]\to\mathbb{R}^{3}, \;g: [c,d]\to[a,b]$ and $\alpha: [c,d]\to\mathbb{R}^{3}$. $\alpha(s)=(\sigma(g(s))$.
The length of the curve $\sigma$ is $L\sigma =\int_{a}^{b} \left\lVert \sigma'(t) \right\rVert dt$, if $t=g(s)$ then $dt=g'(s)ds$
So $L\sigma=\int_{c}^{d} \left\lVert\sigma'(g(s)) \right\rVert g'(s)ds$, if $g'(s)\gt 0$, then
$L\sigma=\int_{c}^{d} \left\lVert\sigma'(g(s)) g'(s)\right\rVert ds = \int_{c}^{d} \left\lVert\alpha' (s)\right\rVert ds= L\alpha$
But i don't know how to proceed if $g'(s)\lt 0$
Answer: You are not applying the change of variables properly. You get $L_{\sigma} =\int_c^{d} \|\sigma'(g(s))\||g'(s)|\, ds$. Also $\|\sigma'(g(s))g'(s)\|=\|\sigma'(g(s))\| |g'(s)|$.
Comment: So $\frac{dg(s)}{ds} = \left\lvert g'(s)\right\rvert $ ?
Comment: $\frac {dg(s)} {ds} =g'(s)$ but in the change of variable formula you have to multiply by $|\frac {dg(s)} {ds}|$, not $\frac {dg(s)} {ds}$.


Build a model of a universe of sets while the axiom of pairing fails.

Question: I'm new to set theory and came across this question in our notes. I don't know how to continue. The question is:

Build a model of a universe of sets where for each set $a$, the collection $\{a\}$ forms a set, while the axiom of pairing fails.

The axiom of pairing says:

The axiom of pairing states that for any two sets $a$ and $b$, there exists a set having $a$ and $b$ as its only elements. We write
  \begin{equation}
\{a,b\} = \{x | [x=a]\vee [x=b]\}
\end{equation}
  When $a=b$ we also write:
  \begin{equation}
\{a\} = \{a,a\}
\end{equation}

How can we show that there does not exist a set containing two other sets as its only elements? As soon as I try to place restrictions on either of these two sets, it gets invalidated by the $\vee$ because it's just a collection of all the elements of either sets. So even if we add a constraint on one set that, for example, says "this set cannot contain any elements from $b$", it doesn't matter because the $\vee$ basically ignores that. I don't know if that made sense...
Can anyone give me some tips on how to construct universes that break axioms in general?
Here's a list of all the axioms we know of (in class):

Axiom of equality of sets (Axiom of extensionality)
The empty set axiom
The axiom of restricted comprehension
The axiom of pairing
Comment: And should all other axioms of ZF(C) hold in that model?
Comment: I don't think so. We haven't done many of the axioms yet. I'll add a list of all the axioms we know of in the question.
Answer: I would guess by the wording of the problem that nothing needs to be satisfied other than what is written. One could start here by finding a simple, explicit universe where for any $a,$ $\{a\}$ always exists (so instead of trying to violate pairing, try to make the other condition succeed). Here is the simplest one that comes to mind: Start with an empty set $\varnothing$. Then add a set  $\{\varnothing\}$ that just contains the empty set, then the set $\{\{\varnothing\}\}$ that just contains that, and so on. (In other words, just take the closure of $\varnothing$ under the operation $a\mapsto \{a\}.$) If this universe violates pairing, you're done, and it should be pretty clear that it does.
A more abstract example would be a universe $\{a,b\}$ where $a\ne b$ and $a=\{a\}$ and $b=\{b\}.$ (Alternatively, you could take $a=\{b\}$ and $b=\{a\}$.) These kinds of sets violate our intuition since if you try to 'unpack their contents' you wind up in an infinite loop, but they're legal unless you assume the axiom of foundation.
Comment: @Imak:  a model can be anything you say it is.  It is just a collection of sets.  The hard part comes when it has to satisfy complicated axioms, like ZFC.  Here you only have one axiom to satisfy, then one to fail to satisfy.
Comment: Yes, exactly. Our universe does not contain any set matching the description $\{\varnothing,\{\varnothing\}\},$ so it violates pairing.
Comment: @Imak regarding 2, it contains exactly two sets, $a$ and $b.$ But $a=\{a\}$ and $b=\{b\},$ so it contains $\{a\}$ and $\{b\}.$
Comment: @Imak No problem, the second example is pretty abstract and more could be said about how it "works" (the key is that membership is an abstract relation: we just consider two distinct objects each related to itself and only itself by the membership relation). The first example $\{\varnothing, \{\varnothing\}, \{\{\varnothing\}\},\ldots\}$ is a better example of the more intuitive universes we typically work with.
Comment: Thank you for your answer. I am, however, still a bit confused. You say that your first example violates pairing. In what way? Maybe I am confused by what the axiom does... So, from what I see, you are defining a universe to contain only the empty set and the sets (of sets...) thereof. So because of that, when we try and pair, say, $\{ \emptyset \}$ with $\emptyset$, we expect to find the set $\{\{ \emptyset \}, \emptyset \}$, but from our definition, this set does not exist in our universe?
Comment: And for your second example, you say the universe is $\{a,b\}$. Does this mean the universe consists only out of set $a$ and set $b$ or would it also contain $\{a\}$ and $\{b\}$ as sets? And then, because $a$ and $b$ are the only sets in the universe, the pairing of $a$ and $b$ would form a set not in our universe?
Comment: Great stuff. Thank you. For some reason, I wasn't aware you could just define a universe like that xD


8 How to configure add-on products in Commerce 2.x

Question: What is the best way in Commerce 2.x to allow the shopper to check boxes to add optional accessories to a product before he adds the product to the cart. In addition, the product price should be updated.

Sounds like this module would do it in D7: Commerce Product Add-on.
This question asks the same question, but it's tagged with 7. Can a VBO form be integrated with the Commerce Add-to-Cart form to allow adding optional add-on products with checkboxes?
Answer: Commerce Product Add-on now has a beta release for D8.


What is the name of this perceptron-like classifier?

Question: I wanted to find a variant of the perceptron which works for non-separable data, so I tried using $f(x)=\mathrm{\tanh}(x)$ instead of the hard threshold function and finding a $w$ that minimises the function $$\frac{1}{2} \sum_i (y_i - f(w \cdot x_i))^2$$
where $y_i \in \{-1,1\}$ are the classes of the training examples and $x_i$ are the features. I minimised it by using "batch" gradient descent and it seems to work nicely and gives me what I want.
My question is: is this the same as Adaline? I found a few references to Adaline, but I can't tell whether Adaline refers to the classifer itself, or also the algorithm which is used to train it, or even the physical machine which originally implemented that algorithm (by the way, I am equally confused about the use of "perceptron"). Am I justified in saying that I am using Adaline?
Answer: The name ADALINE (ADaptive LInear NEuron) come from both the physical implementation of an early classifier, but it is also the name specific design.
See: http://en.wikipedia.org/wiki/ADALINE
Apparently McCulloch-Pitts perceptrons came first.  ADALINE was a variation on this that used a linear response function, as opposed to heaviside step.  ADALINE is fitted using gradient decent because its output is the dot product of the weights and the inputs, effectively with a linear transfer function.  The original McCulloch-Pitts neuron had a heaviside step transfer function, and so couldn't use gradient descent (I had this the wrong way round in my original answer).  More general artificial neurons apply any transfer function and so, if differentiable, can be fitted with gradient descent.
As to being "equally confused about the use of perceptron" then really a perceptron is just a linear classifier.  The main difference between a perceptron and other classifiers like logistic regression etc. is that they are "trained" using online algorithms - that is you can give them one datapoint at a time.  Each input/response pair that you give it updates the weights and should make it a better classifier.  In the early days the connection between perceptrons and logistic regression (and other classifiers) was not clear, but these days it is understood that they do the same thing, and you can "train" logistic regression one point at a time if you wish.  Typically perceptrons are now discussed as the elements of larger neural networks or multilayer perceptrons.  Some sources suggest that a perceptron must have a binary output, but then other sources on multilayer perceptrons don't enforce this.
For safety I would suggest you refered to your model as an artificial neuron.  It isn't ADALINE, and it's not an original McCulloch-Pitts; it might be a perceptron, but it is probably best to refer to it as an artificial neuron.
Incidentally, Information Theory, Inference and Learning Algorithms by D. MacKay has almost exactly your case as an example (chapter 39) and refers to it simply as a "Single Neuron".
Comment: @Flounderer, tried to address that in corrected answer, but probably not.  But McCulloch-Pitts was the first back in the 40s, and so all neurons inherit from those early works.  I doubt you will get extra gravitas by giving it a grand name though.  And if you get mixed up you look a bit of an idiot (like my first answer really...)
Comment: The learning rule given on the Wikipedia page for the ADALINE is gradient descent.
Comment: Does any classifier with a "threshold function" and a "learning rule" count as a "McCulloch-Pitts neuron"?
Comment: @alto yes you are quite right, my memory failed me.  My answer is clearly incorrect as it stands - I will edit to correct.  That will teach me to read a link before I post it!
Comment: Both answers were useful, but I have decided to accept this one. The classifier is *not* ADALINE; ADALINE uses the identity activation function.
Answer: What you describe is essentially just logistic regression with a scaled output using squared loss rather than the usual log loss. Notice that $\tanh(x) = 2\sigma(x) - 1$ where
$$
\sigma(x) = \frac{1}{1 + e^{-x}}
$$
is the logistic function. The decision boundary will still be linear.


Does std::wstring support UTF-16 and UTF-32 on Windows?

Question: I'm learning about Unicode and have a few questions that I'm hoping to get answered.
1) I've read that on Linux, a std::wstring is 4-bytes, while on Windows, it's 2-bytes.  Does this mean that Linux internal support is UTF-32 while Windows it is UTF-16?
2) Is the use of std::wstring very similar to the std::string interface?
3) Does VC++ offer support for using a 4-byte std::wstring?
4) Do you have to change compiler options if you use std::wstring?
As a sidenote, I came across a string library for working with UTF-8 which has a very similar interface to std::string which provides familiar functionality such as length, substr, find, upper/lower case conversion etc.  The library is Glib::ustring.
Please feel free to add any comments or additional advice, because I really need it.
Thank you!
Comment: The C++11 char32_t type should provide a solution, it is however dead last on the Microsoft to-do list.  Pretty doubtful that it will get any use in the next 10 years :)  Yes, you almost always need a library to do anything non-trivial.  ICU is a common choice.
Comment: @HansPassant, this was causing me quite a bit of VC++ confusion with undeclared identifiers and such.  ICU is so big...I think that I'm going to try Glib::ustring to see if it satisfies all of my needs.  BTW, a while back you warned me about codepages and you were so right.
Comment: Pretty much everything about it is written in utf8everywhere.org manifesto.
Answer:
1) I've read that on Linux, a std::wstring is 4-bytes, while on Windows, it's 2-bytes. Does this mean that Linux internal support is UTF-32 while Windows it is UTF-16?

It is actually wchar_t, not std::wstring, that is 4 bytes on Linux and 2 bytes on Windows.  std::wstring is a typedef for std::basic_string<wchar_t>, so std::wstring supports UTF-32 on Linux and UTF-16 on Windows, yes.

2) Is the use of std::wstring very similar to the std::string interface?

Both std::wstring and std::string are typedefs of std:basic_string, so they have the same interface, just different value_type types (wchar_t vs char, respectively).

3) Does VC++ offer support for using a 4-byte std::wstring?

Not for std::wstring itself, no.  But you can create your own std::basic_string typedef, eg:
typedef std::basic_string<int32_t> u32string;

In fact, this is exactly how the new C++11 std::u16string and std::u32string types are defined:
typedef std::basic_string<char16_t> u16string;
typedef std::basic_string<char32_t> u32string;

It is also not unheard of to make a typedef of std::basic_string for TCHAR:
typedef std::basic_string<TCHAR> tstring;

As a sidenote, I came across a string library for working with UTF-8 which has a very similar interface to std::string which provides familiar functionality such as length, substr, find, upper/lower case conversion etc. The library is Glib::ustring.

Technically speaking, you can (and many people do) use a standard std::string for UTF-8.  Glib::ustring just takes it further by using gunichar (a typedef for guint32) instead of char, and exposes its interfaces to operate in terms of raw Unicode codepoints instead of encoded codeunits.
Answer: 1) wstring is a basic_string<wchar_t> and the size of wchar_t is implementation dependent and encoding agnostic (the standard just says that "its values can represent distinct codes for all members of the largest extended character set specified among the supported locales".  But yes, an implementation that has sizeof(wchar_t)=4 bytes supports UTF-32, and sizeof(wchar_t)=2 bytes supports UTF-16.
2) wstring is a basic_string<wchar_t> whereas string is a basic_string<char>, so yes, it is a very similar interface. You will have to use wcout, wcin and wfstream though, and have some other constraints like this.
3) No, MSVC defines wchar_t as unsigned short, which defines and limits wstring as you said.  MSVC gives possibility of handling wchar_t as a typedef instead of an internal type.  You could imagine then to redefine the typedef, but I suspect this is extreamly risky and evil.
4) No, it's up to you to choose to the string type you want.
5) UTF-32 and the standard :  Interestingly, in the very encoding agnostic C++ standard, UTF-32 is mentionned explicitely only for codecvt:  "the specialization codecvt <char32_t, char, mbstate_t> converts between the UTF-32 and UTF-8 encoding forms. codecvt converts between the native character sets for narrow and wide characters."  This suggests that char32_t would be the portable approach to UTF-32.  Unfortunately MSVC doesn't support this type yet.
Comment: At Christophe and @RemyLebeau, thank you for the excellent answers.
Comment: "MSVC defines wchar_t as unsigned short" By default, `wchar_t` is a builtin type. The page you linked to explains that.
Comment: @DDrmmr, yes, my wording is misleading.  Of course, with the default options of the compiler, MSVC handles wchar_t as a native type.  What I meant was that the MSVC impelmentation --whatever the option-- gives this  type the same caracteristics/limits as an unsigned short.


Como empregar multithreading com arduino

Question: Estou fazendo uma campainha com arduino.
Esta campainha será composta de:

01 Arduino UNO,
01 Buzzer,
01 Transmissor 433 Mhz,
01 Receptor 433 Mhz.

A minha dúvida gira em torno de como posso tratar o listener que ficará escutando
os comandos dos controle 433 Mhz e ao mesmo tempo fazer o tratamento para
que o buzzer oscile utilizando delays.
Meu código é basicamente este. Estou usando a biblioteca RFremote que encontrei neste link https://github.com/renatoaloi/RFremote
#include <RFremote.h>
SignalPatternParams params;
RFrecv rfrecv;

int status_prog = 0;

const int buzzer = 11;
const char *BOTAO1 = "0100100100110110110100100110110100100110110110110110100100110100100110100100110100110";
const char *BOTAO3 = "0100100100110110110100100110110100100110110110110110100100110100100100110100110100110";

void setup()
{
  Serial.begin(9600);
  delay(500);

  Serial.println("INICIADO!");

  // COMPATEC remote
  params.spaceMin = 10000;
  params.spaceMax = 15000;
  params.dotMin = 450;
  params.dotMax = 600;
  params.traceMin = 950;
  params.traceMax = 1150;
  params.skipFirst = 0;
  params.skipLast = 0;

  rfrecv = RFrecv(&params);
  rfrecv.begin();

  pinMode(buzzer,OUTPUT);

}

void loop()
{

  if (rfrecv.available()) // LISTENER DO CONTROLE - RECEBE ID DO CONTROLE/TECLA VIA FREQUENCIA 433 Mhz
  {
    if (strncmp((char*)rfrecv.cmd, BOTAO1, CMD_SIZE) == 0) {
      status_prog = 1; // LIGA O BUZZER
    }
    if (strncmp((char*)rfrecv.cmd, BOTAO3, CMD_SIZE) == 0) {
      status_prog = 3; // DESLIGA O BUZZER
    }
  }

  if(status_prog == 1) {  // SE O BOTÃO PRESSIONADO FOR EQUIVALENTE A 1 LIGA
      tone(buzzer, 650); // ACIONA BUZZER COM A TONALIDADE 650
      delay(400);        // PAUSA POR 400 MS
      noTone(buzzer);    // DESLIGA BUZZER
      delay(400);        // PAUSA POR 400 MS
  }

  if(status_prog == 3){
    noTone(buzzer);      // SE O BOTÃO PRESSIONADO FOR EQUIVALENTE A 3 DESLIGA
  }

}

Se eu retirar o delay nesta parte
if(status_prog == 1) {  // SE O BOTÃO PRESSIONADO FOR EQUIVALENTE A 1 LIGA
   tone(buzzer, 650); // ACIONA BUZZER COM A TONALIDADE 650
   //delay(400);        // PAUSA POR 400 MS
   //noTone(buzzer);    // DESLIGA BUZZER
   //delay(400);        // PAUSA POR 400 MS
}

o programa funciona corretamente.
Penso que o delay(400) acaba tomando o tempo que o programa como um todo tem para escutar o controle. Qual seria a abordagem a tomar neste caso? Uma Thread seria bem vinda...
Answer: O Arduino não suporta multithreading, mas já ouvi falar de bibliotecas que simulam isso. Porém, o mais simples é não usar delays (que realmente deixam o programa "surdo e mudo"), e calcular se está na hora de ligar ou desligar o buzzer com base no tempo decorrido desde que o programa começou a rodar (usando a função millis()). Algo assim (não testado):
bool oscilando = false;
bool tocando = false
long comeco = 0;
long intervalo = 400;

void loop()
{
  unsigned long agora = millis();

  if (rfrecv.available()) // LISTENER DO CONTROLE - RECEBE ID DO CONTROLE/TECLA VIA FREQUENCIA 433 Mhz
  {
    if (strncmp((char*)rfrecv.cmd, BOTAO1, CMD_SIZE) == 0) {
      oscilando = true;
      tocando = false;
      comeco = agora;
    }
    if (strncmp((char*)rfrecv.cmd, BOTAO3, CMD_SIZE) == 0) {
      oscilando = false;
      tocando = false;
      noTone(buzzer);
    }
  }

  if(oscilando && agora - comeco > intervalo) {
      tocando = !tocando;
      comeco = agora;
      if(tocando) {
          tone(buzzer, 650);
      } else {
          noTone(buzzer);
      }
  }
}

Answer: Para complementar um pouco a resposta do @bfavaretto sobre Mult-task no Arduino
O Arduino pode vir a suportar multtasking (Multitarefa) com base em time-sharing, mesmo nos controladores AVR que são 8 bits, porém isso somente é aplicável em códigos muito simples e se a atividade demandar cálculos e controles e tempo real, mas sem dúvida o ideal é usar um Arduino DUE caso realmente preciso de Multtask, eu comecei alguns estudos com o FreeRTOS e cheguei ao DuinOS, fiz inclusive um fork e algumas atualizações mas por falta de tempo parei.
O uso d RTOS mesmo em arquitetura 8bits ajuda muito em tarefas que demandam um bom sincronismo para acionar portas e ler portas desde que sejam tarefas e cálculos simples. É possível rodar inclusive no Arduino UNO até 3 tarefas básicas, vamos supor leitura alguns medidores de nível, acionar bombas de forma que tudo funcione em três blocos de controle independentes ou sincronizados.
A vantagem muitas vezes é se ter um melhor sincronismo e como diz, RTOS, nos traz resultados em tempo real, o que elimina o uso de funções como delay() e reduz a simplicidade do código na camada relativa a lógica de seprocesso, eliminando diversas variáveis de controle de tempo, como usado quando se quer eliminar o uso dodelay()`;


Alpine.js When I re-render with x-for, the checked of checkbox is removed

Question:

        <input x-model="text" type="text" id="tag" list="taglist" placeholder="Enter a tag" style="width:15em;">
        <button id="addTag" @click="addTag()">addTag</button>

        <datalist id="taglist">
            <option value="html"></option>
            <option value="PHP"></option>
            <option value="JavaScript"></option>
            <option value="CSS"></option>
        </datalist>
        <template x-for="(tag,index) in tags" :key="index">

                <input type="checkbox" name="tags[]" :id="tag.id" :value="tag.text" :checked="tag.isChecke"
                    @change="removeTag($event,index)">

        </template>

https://codepen.io/y0sh1m0t0/pen/eYeyJod

added tag
Removed first tag. For some reason, the second checkbox is unchecked.
The checkbox in the code are checked, but they do not work.
If you remove the checkmark from behind, no problem will occur.

It would be helpful if you could see the images for more details.
The cause of this is unknown.
I can't find a solution.
Answer: I modified the code as follows, and it worked.
//correction
<input type="checkbox" name="tags[]" :id="tag.id" :value="tag.text" checked
     @change="removeTag($event,tag)">

//correction
removeTag($event,tag) {
   // console.log($event.target.id,tag.id);
   this.tags = this.tags.filter(t => t.id !== tag.id);
},


Lowering power circuit at data-center, please help clarify what PDU I need

Question: I have the following question:
We have a rack at a datacenter with a 208V/60 amp circuit coming into a 208V/60 AMP PDU and I was wondering if we lower the circuit to let say 208V/30 amp or 120/30 amp do I need to change the PDU to a 208V/30 or 120/30 as to match the amperage on the circuit?
I guess my question is if the PDU has to always match the amperage and volts of the circuit?
Thanks in advance
Answer: Voltage has to match, amperage has to be less than or equal (but with some margin to spare).
Answer: It doesn't need to match no, all you're doing is potentially moving which part will trip out first.


Process Array contents

Question: I've done a database query which returns the results in the following array:
Array ( [0] => stdClass Object ( [field_latitude_value] => 25.2000000000 ) [1] => stdClass Object ( [field_latitude_value] => 51.9456801568 ) [2] => stdClass Object ( [field_latitude_value] => 51.9471747475 ) [3] => stdClass Object ( [field_latitude_value] => 51.9471218425 ) )

How do I process this information so I get just the values instead of the added keys? I.e a list of said values.
I'm currently using the following code, which gives me a recoverable fatal error:
<?php

$query = db_query('SELECT field_latitude_value FROM {field_data_field_latitude}')->fetchAll();

print_r($query);
foreach($query as $value){
    echo $value;
};?>

Answer: Instead of fetchAll(), try fetchCol(), like this:

$latitude_values = db_query("SELECT field_latitude_value FROM {field_data_field_latitude}")->fetchCol();

Process Array contents


MySQL query comparing values to previous rows' values

Question: I've been searching but have been unable to find a solution to this--I know it's do-able but I just don't have the ninja SQL skills I need (yet)....
I'm looking for a solution to this issue: I have a 2 tables related to stock market data.  The first is a simple list of stock symbols with an ID and stock ticker symbol (ID,SYMBOL).  The second table contains historical price data for each of the stocks.  (ID, DATE, OPEN, HIGH, LOW, CLOSE, VOLUME).
I'm trying to figure out how to query for stocks that have the most recent CLOSE price that is greater than their CLOSE price 5 trading-days ago.  I can't just do date math because the stocks don't trade every day (no trading on weekends & holidays, as well as some stocks may not trade on a normal trading day).  Thus, I just need to compare the CLOSE price from most recent row and the 5th row proceeding it for each symbol.
I have sample tables and data here:
http://sqlfiddle.com/#!2/5fe76/2
CREATE TABLE `STOCKS` (
  `ID` int,
  `SYMBOL` varchar(10)
);

INSERT INTO `STOCKS` (`ID`,`SYMBOL`)
VALUES
  (1, 'AA'),
  (2, 'ADT'),
  (3, 'AEO'),
  (4, 'AFA');

CREATE TABLE `PRICES` (
    `ID` int,
    `DATE` date,
    `OPEN` decimal(6,2),
    `HIGH` decimal(6,2),
    `LOW` decimal(6,2),
    `CLOSE` decimal(6,2),
    `VOLUME` bigint
  );

INSERT INTO `PRICES` (`ID`,`DATE`,`OPEN`,`HIGH`,`LOW`,`CLOSE`,`VOLUME`) VALUES
(1, '2014-11-06',   16.37,  16.42,  16.15,  16.37,  14200400),
(1, '2014-11-05',   16.68,  16.69,  16.17,  16.26,  18198200),
(1, '2014-11-04',   16.85,  16.87,  16.43,  16.56,  13182800),
(1, '2014-11-03',   16.78,  17.03,  16.65,  16.93,  15938500),
(1, '2014-10-31',   16.43,  16.76,  16.24,  16.76,  18618300),
(1, '2014-10-30',   16.17,  16.36,  15.83,  16.22,  17854400),
(1, '2014-10-29',   16.58,  16.70,  16.05,  16.27,  31173000),
(1, '2014-10-28',   16.5,   16.65,  16.41,  16.60,  12305900),
(1, '2014-10-27',   16.56,  16.57,  16.31,  16.38,  15452900),
(1, '2014-10-24',   16.33,  16.57,  16.22,  16.55,  12840200),

(2, '2014-11-06',   35.9,   36.12,  35.75,  36.07,  1018100),
(2, '2014-11-05',   35.68,  35.99,  35.37,  35.96,  1101500),
(2, '2014-11-04',   35.13,  35.69,  35.02,  35.49,  819100),
(2, '2014-11-03',   35.81,  35.99,  35.27,  35.32,  1304500),
(2, '2014-10-31',   35.79,  35.86,  35.46,  35.84,  1319400),
(2, '2014-10-30',   34.7,   35.34,  34.66,  35.19,  1201800),
(2, '2014-10-29',   35.06,  35.56,  34.5,   34.92,  1359000),
(2, '2014-10-28',   34.32,  35.17,  34.15,  35.07,  1301800),
(2, '2014-10-27',   34.2,   34.2,   33.66,  34.1,   662600),
(2, '2014-10-24',   34.02,  34.54,  33.95,  34.5,   750600),

(3, '2014-11-06',   13.27,  13.92,  13.25,  13.82,  6518000),
(3, '2014-11-05',   12.95,  13.27,  12.74,  13.22,  8716700),
(3, '2014-11-04',   12.85,  12.94,  12.65,  12.89,  4541200),
(3, '2014-11-03',   12.91,  13.12,  12.73,  12.89,  4299100),
(3, '2014-10-31',   13.2,   13.23,  12.83,  12.87,  7274700),
(3, '2014-10-30',   12.83,  12.91,  12.68,  12.86,  4444300),
(3, '2014-10-29',   13.02,  13.20,  12.79,  12.91,  2974900),
(3, '2014-10-28',   12.87,  13.10,  12.52,  13.04,  7365600),
(3, '2014-10-27',   12.84,  13.00,  12.67,  12.92,  6647900),
(3, '2014-10-24',   13.26,  13.29,  12.60,  12.92,  12803300),

(4, '2014-11-06',   24.59,  24.59,  24.49,  24.55,  20400),
(4, '2014-11-05',   24.81,  24.9,   24.81,  24.88,  11800),
(4, '2014-11-04',   24.87,  24.88,  24.76,  24.88,  10600),
(4, '2014-11-03',   24.85,  24.88,  24.76,  24.81,  18100),
(4, '2014-10-31',   24.82,  24.85,  24.77,  24.78,  8100),
(4, '2014-10-30',   24.83,  24.87,  24.74,  24.79,  13900),
(4, '2014-10-29',   24.86,  24.86,  24.78,  24.81,  5500),
(4, '2014-10-28',   24.85,  24.85,  24.80,  24.84,  10600),
(4, '2014-10-27',   24.68,  24.85,  24.68,  24.85,  7700),
(4, '2014-10-24',   24.67,  24.82,  24.59,  24.82,  9300);

Pseudo code for the query would be something like this:
"Find symbols whos most recent closing prices is greater than the closing price 5 trading-days earlier"
The query I'd like to create should result in the following:
Date        Symbol   Close   Close(-5)
2014-11-06  AA       16.37   16.22
2014-11-06  ADT      36.07   35.19
2014-11-06  AEO      13.82   12.86

(the symbol 'AFA' would not match as it's recent close is 24.55 and 5 rows prior it was 24.75)
Comment: So you want to find a) the most recent price for each stock but b) only hang onto those whose price is higher than 5 days ago? BUt if what if there wasn't a price 5 days agao !?!
Comment: And seeing as symbols are unique and (presumably) unchanging, why would you store the id instead of the symbol!?!
Comment: I guess I understand why ADT and AEO are in the result, but not AA
Comment: To your first question... I probably wasn't clear enough in my original description. I want to hang on to those who's price is higher than 5 trading days ago, not 5 calendar days ago. Trading days are simply defined as the 5 previous rows from the PRICE table.
Comment: Symbol names do occasionally change, thus storing an id.
Answer: You can get the price 5 days ago using a correlated subquery.  In fact, you can get the most recent price the same way.  So, this  might be the right path:
  select s.*,
         (select p.close
          from prices p
          where p.id = s.id
          order by date desc
          limit 1
         ) as Close,
         (select p.close
          from prices p
          where p.id = s.id and p.date <= date(now()) - interval 5 day
          order by date desc
          limit 1
         ) as Close_5
  from stocks s
  having Close > Close_5;

Comment: Gordon - thank you for this answer. Unfortunately date-based offset won't work in every case as some days such as weekends and holidays are not trading days. The sub query needs to select the 5th-most-recent closing price--that's the part that has me stumped :)
Comment: @paul I think you should amend your question accordingly
Comment: @Paul . . . I think you should ask another question and be clearer about the issues you are facing with dates.
Comment: @GordonLinoff In the orig. question it says that "date math" wont work as the dates have gaps.  So I'd say this isn't a "date issue". As I'm unable to figure this out perhaps I'm not asking the correct question; any suggestion on how to make this more clear? Trying to boil-it-down... I need to select stock symbols where the most recent closing price is greater than the closing price 5-ROWS prior (the rows are sorted by date but the dates in each row are not consecutive days--there are "gaps" in the dates).  Any guidance on how to make the question more clear is greatly appreciated, thanks! :)


Ferramenta para Firebird - Quais

Question: Qual seria o software mais utilizado para o gerenciamento de banco de dados firebird, se possível, me mostre opções free e pagas.
Comment: Possível duplicata de [Como abrir um arquivo .fdb?](http://pt.stackoverflow.com/questions/112883/como-abrir-um-arquivo-fdb)
Comment: Concordo com a resposta do @Guilherme Sanches IBExpert e um dos melhores , você pode também pode dar uma olhada no FlameRobin https://sourceforge.net/projects/flamerobin/
Answer: Bom dia, eu usei por muito tempo o IBExpert, na minha opinião é o melhor nesta área!
Ele executa praticamente tudo que você precisa em relação ao Firebird: Comparação de BD's com geração de script de diferença entre os dados, busca dinâmica de tabelas, triggers, procedures, backup, restore, etc
segue abaixo lista de quase todos gerenciador de BD Firebird disponíveis:
Firebase Brasil
Segundo o próprio site, sobre o IBExpert:
"Mais um administrador de BD Interbase. Interface muito similar ao QuickDesk, mas contém alguns recursos à mais, como um "preenchedor de tabelas" para inserir dados de teste nas tabelas, um GRANT manager, etc... Suporta o IB 4,5 e 6 e Firebird 1.0. Possui uma versão FREE para substituir o IBConsole, uma versão educacional completa que funciona com bancos de até 50MB e a versão shareware com todos os recursos."
Existe a versão paga também com muito mais recursos...
Abraços :)
Answer: Tem algumas dentre elas são:

EMS SQL Manager for InterBase/Firebird       Com versão Free e Paga.
IBExpert                                     Com versão Free e Paga.
Advanced Data Generator e Database Workbench Com versão Free e Paga.

Acho o EMS SQL Manager for InterBase/Firebird mais fácil de entender. Veja o que melhor se encaixa com sua preferencia.

Ferramenta para Firebird - Quais


python + Semicolon written to file is written on the next line

Question: I have this simple python expression:
fscript.write (("update %s va set %s = %s where %s = %s;") % (argv[1],argv[2],vl[0],argv[3],vl[1]))

And I would expect to receive output like this
update some_table va set active_id = 1 where id = 5;
update some_table va set active_id = 1 where id = 3;
...more lines...

However, i'm getting this
update some_table va set active_id = 1 where id = 5
;update some_table va set active_id = 1 where id = 3
...more lines....

Anything i'm missing ?
Thanks in advance
Answer: I would try adding a strip() to your latest parameter that could end with \n.
fscript.write (("update %s va set %s = %s where %s = %s;") % (argv[1],argv[2],vl[0],argv[3],vl[1].strip()))

Comment: Nice, didn't think about that.
Answer: Some value of vl[1] is a string with a newline in it, not an integer.


Calculating Principal curves

Question: I have been given a surface patch, $X(u,v)$, and I have calculated its unit normal, coefficiants of its first and second fundamental form and found its principal curvatures. Now it's asking me to find the principal "curves" and she they equal what they have given me. How do I find these curves? Is it just the eigenvectors of the matrix used to find the principal curvature multipled by $X_u$ and $X_v$?
Answer: As soon as you know the eigenvectors of that matrix (shape operator), you have two vector fields on the surface. These are called principal directions (not well defined at umbilic points!). For each eigenvalue you have an ODE to solve, that gives you two families of curves on the surface which are called "principal curves".
See Wikipedia, Line of Curvature. Be careful, though. as I explain in this answer.

Calculating Principal curves


Not properly converting epoch time to normal time in PHP

Question: Here is my code which I have used to convert the EPOCH time to normal time in PHP. I haven't set timezone as its not required. In the following code $timeD is the input time which is getting properly converted in http://www.epochconverter.com/
 $timeD = 1449034934000;
 echo gmdate('r', $timeD);

Expected output is this 12/2/2015, 11:12:14 AM GMT+5:30. But what is getting is

Wed, 08 Feb 47888 14:56:40 +0000
Answer: The time you're using has millisecond precision (probably from Javascript) so you simply need to chop the last three digits off the timestamp. 1449034934 vs 1449034934000
$timeD = 1449034934000; //$timeD = 1449034934; is what we want.
$timeD = substr($timeD,0,10); // Chop off those pesky unnecessary milliseconds!
echo gmdate('r', $timeD);

Comment: thank you loads dude.. you solved my problem. thank you again. i would appreciate you more if you can guide me on next as. how can i add +5.30 Hr in output of your program.
Comment: @yudihukkeri This might work for you: **`echo date('m/d/Y h:i:sA P',$timeD);`** for me I get `12/01/2015 09:42:14PM -08:00` .. I'm in different timezone so let me know if it needs adjusting
Comment: Thank you for comments @nextlocal


Google Apps Script: Copy cell value to another sheet with condition to copy and position the value

Question: I have a spreadsheet with 4 sheets: "List", "Map N1", "Map N2" and "Map N3". It is supposed to work as a control for a deposit of Metallic Units.
"List" has these columns:
-MU (Metallic Unit)
-Weight
-Position (Level)
-Position (Letter)
-Position (Number)
-Arrival date and time
-Departure date and time
-Destination
-Status
-Observations
When a MU arrive, the data is entered and the column "Status" receive "Awaiting positioning" as value. When the MU is positioned within the deposit, the "Status" change to "Positioned". What I need to do is:
-When the "Status" change to "Positioned", copy the value of the respective MU column to one of the Maps, depending on the "Position (Level)". If the "Position (Level)" is "N1", it goes to "Map N1", "N2" to "Map N2" and so it goes.
-The Map sheets look like this:

-The MU value should position in the sheet according to the "Position (Letter)" and "Position (Number)" values. That way, the MU below should go to the sheet just like this image:

I've searched and managed to find this code:
function onEdit(event) {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var s = event.source.getActiveSheet();
    var r = event.source.getActiveRange();
    if(s.getName() == "List" && r.getColumn() == 9 && r.getValue() == "Posicionada") {
      var targetSheet = ss.getSheetByName("Map N1");
      var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
      s.getRange(1, 1, 1, 1).copyTo(target);
    }
  }

The idea was to use this code to figure out how to copy the value automatically, and then adapt it to the positioning thing. But This isn't even copying the values to the other sheet.
Comment: It isn't copying because you are using the "moveTo" function
Comment: Thanks for the comment. I changed it to "copyTo". No results.
Answer: You can use setValue() instead of moveTo/copyTo.
 targetSheet.getRange(row,column).setValue(s.getRange(r.getRow(), 1, 1, 1).getValue());

Here is the rest of your code if you will need it.
It basically uses the reference in cell to get the correct sheet, column and row. As your columns are not original, I added a loop to cycle through the first row on the Map sheet and find the correct column.
function onEdit(event) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = event.source.getActiveSheet();
var r = event.range;
if(s.getName() === "Lista" && r.getColumn() === 9 && r.getValue() === "Posicionada") {
  var sheetname = s.getRange(r.getRow(),3).getValue();
  var columnRef = s.getRange(r.getRow(),4).getValue();
  var rowref = s.getRange(r.getRow(),5).getValue();
  var targetSheet = ss.getSheetByName("Mapa " + sheetname);
  var headers = targetSheet.getRange(1, 1, 1, targetSheet.getLastColumn()).getValues().toString().split(",");
  var rows = targetSheet.getRange(1, 1, targetSheet.getLastRow(), 1).getValues().toString().split(",");

  //Getting The correct Column
  for (var i = 1; i < headers.length; i++) {
    if (headers[i] === columnRef) {
      break;
    }
  }

  var column = i + 1;

  //Getting the correct row
  for (var i = 1; i < rows.length; i++) {
    if (Number(rows[i]) === rowref) {
      break;
    }
  }

  var row = i + 1;

  targetSheet.getRange(row,column).setValue(s.getRange(r.getRow(), 1, 1, 1).getValue());
}
}

Comment: Thanks for the reply. However, the columnRef will not receive "A, B, C..." values, actually there is "A1, A2, B1, B2..." so when this code receive the columnRef and read, for example "B1", it doesn't understand the number and ends up putting the value in the first column, but in the right row. The code is really good, but, to make it work like it needs to, I can only think of testing individually with many conditions the column, and I fear this will make the sheet really slow.
Comment: I adapted your code using:

    `var column;  if (columnRef === "A1") {  column = 2;  }`

And it works for A1, but I'd need to test A1 all the way to N2. You know a better way to test this?
Comment: I don't know if it's wrong to write many comments. But thanks to you everything is working. The code is kinda big, but it ended up like this: http://freetexthost.com/4mgqlkicuq (in lines 101 to 107, I subtracted those numbers because the grid of N2 and N3 is different, so this corrects the position).
Comment: That;s why I wrote a loop to scroll through the headers and find the relevant column: if (headers[i] === columnRef)
Comment: Well, I'm confused now. Before adding those conditions, no matter what was in the cells, it would always put the MU value in the column A, substituting the white numbers in blue background. But it's working now, I'll experiment on it later to optimize the code.
Comment: Could you give the output of this: Logger.log(headers)
Comment: I couldn't see the log, since I only know how to look in the debugger, and the onEdit() needs to be triggered in the spreadsheet. But I did this:
`SpreadsheetApp.getUi().alert(headers);`
And it returned the string "Range". I don't know if it has the same result, using this alert, if it needs to be done with the Logger, could you help me in seeing the logs?
Comment: if you type in Posicionada like norma, it will trigger the script and you can see the output of the logger.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/87034/discussion-between-bruno-vaz-and-akshin-jalilov).
Answer: function onEdit(event) {
  var range = event.range;
  var fromRow = range.getRow();
  var fromCol = range.getColumn()
  ...
  s.getRange(fromRow, fromCol, 1, 1).copyTo(target);

Comment: Thank you for posting an answer to this question! Code-only answers are discouraged on Stack Overflow, because a code dump with no context doesn't explain how or why the solution will work, making it difficult for the original poster (or any future readers) to understand the logic behind it. Please, edit your question and include an explanation of your code so that others can benefit from your answer. Thanks!


Tap button in tableview - wrong cell

Question: Hi I am trying to pass a variable in the cell which is the label when i click on a button in the cell. but the problem is every when I put the code in cellForRowAtIndexPath, it gets the label from the wrong cell every time. why and how to fix this?
var variableToPass: String!

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell

    variableToPass = label1.text

    cell.label1.userInteractionEnabled = true
    let tapButton = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapLabel(_:)))
    cell.label1.addGestureRecognizer(tapButton)

    return cell as MainCell
}

func tapButton(sender:UITapGestureRecognizer) {
    performSegueWithIdentifier("SegueIdentifierName", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "SegueIdentifierName" {
        let viewController = segue.destinationViewController as! ViewController
        viewController.getVariablePassed = variableToPass
    }
}

Comment: You should separate out your code and subclass the UITableViewCell and then in that sub class create the tap gesture recognizer. Also, you need to set the delegate of the gesture recognizer to the CELL.
Comment: You can use `didSelectRowAtIndexPath` delegate method for that.
Comment: @DharmeshKheni you can, I do this all the time, but never like this, always in a subclass of UITableViewCell, never in the in controller
Comment: yes that way you can do it. @Loxx
Comment: if you go this route, attach a block to the Cell with a property exposed, the block then can be set to the "tapButton" function by setting the block to weakified self and weakified cell, this is complicated, so I won't confuse you if this is too much, point being, it's possible, but don't do it the way you're trying to do it
Answer: The way your code is set up, variableToPass is always the text in the last cell acquired from dequeueReusableCellWithIdentifier. Instead, set variableToPass in your tapButton method, because then you know what cell was selected and you can correctly set variableToPass:
func tapButton(sender:UITapGestureRecognizer) {
    let label = sender.view as! UILabel
    self.variableToPass = label.text
    performSegueWithIdentifier("SegueIdentifierName", sender: self)
}

Answer: My way to do this is using a cell delegate and registering my viewController as delegate for the cell, later when the user taps on the UIButton I will call a method like
- (void)buttonWasPressedWithIndexPath:(NSIndexpath*)indexPath
and in cellForRowAtIndexPath I pass the indexPath as a cell property

Tap button in tableview - wrong cell


Drupal View Filter Criteria "Contains Taxonomy"

Question: I need to filter based on taxonomy term in my view, I have set up this filter however I would like to return nodes that 'contain', not "Is one of". See screenshot below:

Is there a module or a way I can achieve this? If I put 'vod' instead of 'vodafone' it does not return anthing:

The end goal is to filter nodes from the URL e.g. localhost/numbers?field_company=vod will return nodes for vodafone and vodafoneblahblah.
Answer:
Add a Relationship of type "Terms in node"
Add a filter "Taxonomy term: Name"

Now you can set "Contains" has an option for your filter


Android: Resuming a paused Thread after an orientation change

Question: I have a question involving threads and recovering from an orientation change.  I have seen a lot of great answers that cover threads or orientation changes, but precious few that cover both.  Here is a general scenario that covers my question:

App starts, contains one activity: one TextView populated with the variable "count", initially 0, a START and a STOP button.
Start button starts thread (using Thread), which loops incrementing
the number and updating the TextView.
Stop button sets boolean flag so thread exits.
All variables global and volatile, Object variable signal used to control thread.

Now, what is the best way to handle an orientation change.  I am assuming that I:

in onPause(), I call signal.wait() to pause the thread
Save the variable "counter" on onSaveInstanceState()
in onResume() I get "counter" back from onRestoreInstanceState()

Since onCreate()will create a new Object for "signal", how do I reestablish a link to the thread that is currenting wait()ing so that I can call notify() and resume it?
I explained this the best I could, I'll try to provide any additional information requested.
Comment: Why not just start a new thread and feed it the counter variable as an argument so it knows where to start? You correctly save the state of your Activity so that when everything restarts, you pick up where you left off. So just restart the Thread as well, and tell it where the counter left off (which you have in your savedInstanceState).
Comment: Thanks @drschultz, that will work.  I was wondering though what was the best practice.  I know that wait() and notify() work great for managing threads when the app goes in the background, I was just wondering if I could use them for an orientation change as well.
Comment: Added an answer below. Please accept it if you feel it solves your issue. Thanks!
Answer: The lifecycle of an Activity is designed so it can be destroyed and recreated based on system needs or user interaction, so generally speaking, any in-app operations should also be destroyed and re-created when these lifecycle changes happen. The exception would be long-running processes that run in the background apart from the Activity (like a Service).
So to answer your question, instead of trying to pause and resume the Thread, it would be better to simply restart the Thread when the Activity restarts, and feed the Thread your counter variable as an indicator of where the count left off. You are already saving this variable in your savedInstanceState, so it would simply be a matter of grabbing it at the start of your Activity, then passing it into your (new) Thread to continue counting.
Comment: Correct.  Retained fragments are just for preserving things across config changes; they may still be destroyed in the background or backstack.  To distinguish config changes from going into the background, you'd use  [`isChangingConfigurations()`](http://developer.android.com/reference/android/app/Activity.html#isChangingConfigurations%28%29) and cancel the background processing if it's false.
Comment: Thanks again @drschultz - that's the information I was looking for.
Comment: An exception is that retained fragments can persist across a config change.  If the `Thread` (or, preferably, `AsyncTask`) lives in the fragment, it too can survive the config change.  If it finishes around the same time as the config change, it's guaranteed that any main thread callback cannot slip in between the destruction of the old activity and the creation of the new one.
Comment: @KevinKrumwiede If you are retaining a Fragment and keeping track of its current Activity through (I assume) onAttach(), would that mean your thread continues to run even when your app is minimized for long periods in addition to config changes? I'm just wondering because in the case of the "counter" thread specific to this question, it seems using this method would cause your UI to "jump" to the current count since your counter has been running in the background this whole time (but not updating the paused UI thread). So in that case, a retained Fragment wouldn't work so well, correct?


Unable to log in due to session cookies not being passed in

Question: I have an html5 app which logs the user into drupal via services 3.11 but I am unable to connect.
Using the Chrome Postman plugin I can connect as expected.
The difference between Postman and my code is that the cookie session is not being passed from my app.
From what I have read the withCredential: true is supposed to pass the session cookie but it's not working for me?

api/user/login.json - Logs the user in as expected
api/user/token.json - returns the token as expected
api/system/connect.json - Always returns the data for Anonymous user 0

The system/connect code sent after login and token is:
<code>                jQuery.ajax({
                    type: "POST",
                    url: connectUrl,
                    xhrFields: {
                        withCredentials: true
                    },
                    success: function (result) {
                        dosomething();
                    },
                    error: function (result) {
                        dosomething();
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('X-CSRF-Token', Session.user_token);
                    },
                });
</code>
Comment: I'm voting to close this question as off-topic because it is  about code you wrote, for which you want to write better code, or you want to understand why it doesn't work, but you didn't show the code you are using, or the part of the code that is relevant for the question.
Comment: Not sure I follow - The code shown is the code that is failing and yes, I would like to understand why it doesn't work. Just to clarify, I've been using the same snippet (taken from the jQuery examples) to do ajax posts with no problem. It was only after trying it with cross-origin that it started to fail. After researching extensively I'd learned that 'withCredentials: true' is supposed to pass the session cookie, but for some reason it's not doing it.
Answer: For anyone else who stumbles across this problem I did finally manage to solve it with the following which ensures the credentials are pass for each call consistently. I'm assuming where CORS adds in the additional OPTIONS request, the credentials we're going through.
<code>jQuery.support.cors = true;
    jQuery.ajaxSetup({
        xhrFields: {
            withCredentials: true   // Pass session cookie with requests
        }
    });
</code>


$\pi_1(S^1, 1)$ via the fundamental groupoid

Question: I'm currently reading Ronnie Brown's Topology and Groupoids and am stuck on a small detail of his computation of the fundamental group of the circle (in particular his computation of the group's generator). Recall that there is a functor $\pi:\mathbf{Top}\rightarrow \mathbf{Grpd}$ from the category of the topological spaces to the category of groupoids taking a space $X$ to its "fundamental groupoid" $\pi X$, the category with objects the elements of $X$ and morphisms the homotopy classes of paths in $X$. For any set $A$, we define $\pi XA$ to be the full subcategory of $\pi X$ with objects $X\cap A$. Chapter 6 gives a proof of a kind of baby van-Kampen theorem for fundamental groupoids: if $X$ is a topological space with subspaces $X_0, X_1, X_2$ such that $X_0=X_1\cap X_2$ and $X=\mathrm{Int}(X_1)\cup\mathrm{Int}{X_2}$, and $A$ is a set (for convenience assume contained in $X$) such that $A$ meets every path component of $X_0$, $X_1$, and $X_2$, then the following commutative square induced by inclusion maps is a pushout in $\mathbf{Grpd}$:
$\require{AMScd}$
\begin{CD}
\pi X_0A @>i_1>> \pi X_1A\\
@Vi_2VV @VVu_1V\\
\pi X_2A @>u_2>> \pi XA
\end{CD}
A further theorem is that, if $A'$ is a subset of $A\cap X_1$ that meets every path component of $X_1$, then letting $A_1=A'\cup (A\setminus X_1)$ we can extend this square to another groupoid pushout
$\require{AMScd}$
\begin{CD}
\pi X_0A @>i_1>> \pi X_1A @>r>> \pi X_1A_1\\
@Vi_2VV @VVV @VVu_1V\\
\pi X_2A @>u_2>> \pi XA @>r'>> \pi XA_1
\end{CD}
where $r$ and $r'$ are deformation retractions – i.e. their composition with the natural inclusion functors on the left are homotopic as functors to the respective identity on $\pi X_1 A$ and $\pi X A$ ($\mathrm{rel}(\pi X_1 A_1)$ and $\mathrm{rel}(\pi X A_1)$ respectively). (The use of $u_1$ here as the induced inclusion map is a slight abuse of notation.)
I've read and understood the proofs of both of these results. Now, the final result of the chapter is to apply the latter theorem to a computation of the fundamental group of the circle (which is isomorphic to the "object group" $\pi(S^1, 1):=\pi S^1(1, 1)$). Here is the proof (Brown uses $+$ to denote composition of paths and $\mathbf{I}$ to denote the unique tree groupoid on two objects $0$ and $1$):

Everything is clear to me except the very last argument that $\varphi$ is a generator, and in particular the claim that the retraction $r'$ satisfies the identity $r'=-\varphi_1+\varphi_2$. As best as I can see, an argument for this might run by taking $F:\pi S^1 A \times \mathbf{I}\rightarrow\pi S^1 A_1$ to be a functor homotopy $ir'\simeq \mathrm{id}_{\pi S^1 A} \space\mathrm{rel}(\pi S^1 A_1)$ where $i:\pi S^1 A_1 \rightarrow \pi S^1 A$ is the map induced by inclusion. Then, if $\iota$ is the unique element of $\pi I(0, 1)$, we have by definition of functor homotopy a commutative square in $\pi S^1 A$
$\require{AMScd}$
\begin{CD}
F(1, 0)=ir'(1)=1 @>ir'\varphi_2=r'\varphi_2>> F(-1, 0)=ir'(-1)=1\\
@VF(\mathrm{id}_{1}, \iota)=\mathrm{id}_{1}VV @VVF(\mathrm{id}_{-1}, \iota)V\\
F(1, 1)=\mathrm{id}_{\pi S^1 A}(1)=1 @>\mathrm{id}_{\pi S^1 A}(\varphi_2)=\varphi_2>> F(-1, 1)=\mathrm{id}_{\pi S^1 A}(-1)=-1
\end{CD}
(where the arrow on the left side of the square is the identity by the $\mathrm{rel} (\pi S^1 A_1)$ condition). Clearly if we had $F(\mathrm{id}_{-1}, \iota)=\varphi_1$ then we would be done, but I don't see anywhere in the construction of $r'$ why this has to be the case. Does anyone have any insight? Sorry for the overly long post; if notation is unclear check out Chapter 6 of the attached pdf above. Thank you so much in advance.
Answer: Aha, I've figured it out! The construction of $r'$ and $r$ in the composed commutative square in the question statement also gives that
$\require{AMScd}$
\begin{CD}
\pi X_1A @>r>> \pi X_1A_1\\
@Vu_1VV @VVu_1V\\
\pi XA @>r'>> \pi XA_1
\end{CD}
commutes (and is in fact a pushout as well, though we do not need this); again we abuse notation with respect to $u_1$. In the context of $S^1$ and $X, X_1, A, A_1$ as given, this is a square
$\require{AMScd}$
\begin{CD}
\pi X_1\{-1, 1\}\cong\mathbf{I} @>r>> \pi X_1\{1\}\cong\mathbf{0}\\
@Vu_1VV @VVu_1V\\
\pi S^1\{-1, 1\} @>r'>> \pi S^1\{1\}\cong\pi_1(S^1, 1)
\end{CD}
where $\mathbf{0}$ is the tree groupoid on the singleton $\{1\}$ and $\mathbf{I}$ is as above. In particular, $\varphi_1$ is the unique element of $\pi X_1(1, -1)$, so the commutativity of the square gives $r'(\varphi_1)=r(\varphi_1)=id_1$. Using the same functor homotopy square as in the question text but substituting $\varphi_1$ for $\varphi_2$ in the horizontal morphisms gives also that $\varphi_1 id_1=F(id_{-1}, \iota)r'(\varphi_1)=F(id_{-1}, \iota)id_1 $, whence $F(id_{-1}, \iota)=\varphi_1$ as desired.
Question: is this the best way of seeing this? The fact that Brown didn't include this argument in the proof makes me feel like there must be a more "immediate" way to see it.


Determining whether a website is active using daily visits

Question: Context:
I have a group of websites where I record the number of visits on a daily basis:
W0 = { 30, 34, 28, 30, 16, 13, 8, 4, 0, 5, 2, 2, 1, 2, .. }
W1 = { 1, 3, 21, 12, 10, 20, 15, 43, 22, 25, .. }
W2 = { 0, 0, 4, 2, 2, 5, 3, 30, 50, 30, 30, 25, 40, .. }
...
Wn

General Question:

How do I determine which sites are the most active?

By this I mean receiving more visits or having a sudden increase in visits during the last few days. For illustration purposes, in the small example above W0 would be initially popular but is starting to show abandoning, W1 is showing a steady popularity (with some isolated peak), and W3 an important raise after a quiet start).
Initial thoughts:
I found this thread on SO where a simple formula is described:

// pageviews for most recent day
y2 = pageviews[-1]
// pageviews for previous day
y1 = pageviews[-2]
// Simple baseline trend algorithm
slope = y2 - y1
trend = slope  * log(1.0 +int(total_pageviews))
error = 1.0/sqrt(int(total_pageviews))
return trend, error

This looks good and easy enough, but I'm having a problem with it.
The calculation is based on slopes. This is fine and is one of the features I'm interested in, but IMHO it has problems for non-monotonic series. Imagine that during some days we have a constant number of visits (so the slope = 0), then the above trend would be zero.
Questions:

How do I handle both cases (monotonic increase/decrease) and large number of hits?
Should I use separate formulas?
Comment: I'm surprised you have not received any answers yet (although it is an obviously popular question). Since each of your four bullets are worth a question in and of themselves, how about limiting this question to one of them and post the others in separate questions. They are all really excellent questions that take distinct approaches, and all four are worthwhile on their own.
Comment: I'm still failing to understand why having one estimate with a small error makes an approach 'unusable'.
Comment: Hi Andy, thanks a lot for your answer. I'll try to rephrase it and focus on a single issue at a time. My initial thought was making it as broad as possible (and avoid repeating the same question afterwards) but given the lack of answers, it seems it is too general for someone to answer.
Comment: I edited the question to expose the two main issues I'm mostly interested in. I chose to put them in the same question given their tight relationship.
Comment: Thanks for the comment. I'm not saying the aproach (trend calculation) was unusable, but its error calculation could have a potential problem. Given that I got no answer so far, I'll remove that item from the question hoping it gets easier to answer.
Answer: It sounds like you are looking for an "online changepoint detection method."  (That's a useful phrase for Googling.)  Some useful recent (and accessible) papers are Adams & MacKay (a Bayesian approach) and Keogh et al.  You might be able to press the surveillance package for R into service.  Isolated large numbers of hits can be found using statistical process control methods.
Answer: There are definitely more and less complex ways to address this kind of problem. From the sound of things, you started out with a fairly simple solution (the formula you found on SO). With that kind of simplicity in mind, I thought I would revisit a few key points you make in (the current version of) your post.
So far, you've said you want your measurement of "site activity" to capture:

Slope changes in visits/day over "the past few
days"
Magnitude changes in visits/day over "the past few days"

As @jan-galkowski points out, you also seem to be (at least tacitly) interested in the rank of the sites relative to each other along these dimensions.
If that description is accurate, I would propose exploring the simplest possible solution that incorporates those three measures (change, magnitude, rank) as separate components. For example, you could grab:

The results of your SO solution to capture slope variation (although I would incorporate 3 or 4 days of data)
Magnitude of each site's most recent visits/day value (y2) divided by the mean visits/day for that site (Y):

y2 / mean(Y)
For W0, W1, and W2 respectively, that yields 0.16, 1.45, and 2.35. (For the sake of interpretation, consider that a site whose most recent visits-per-day value was equal to it's mean visits-per-day would generate a result of 1). Note that you could also adjust this measure to capture the most recent 2 (or more) days:
y2 + y1 / 2 * mean(Y)
That yields: 0.12, 1.33, 1.91 for your three sample sites.
If you do, in fact, use the mean of each site's visit/day distribution for this kind of measure, I would also look at the distribution's standard deviation to get a sense of its relative volatility. The standard deviation for each site's visit/day distribution is: 12.69, 12.12, and 17.62. Thinking about the y2/mean(Y) measure relative to the standard deviation is helpful because it allows you to keep the recent magnitude of activity on site W2 in perspective (bigger standard deviation = less stable/consistent overall).
Finally, if you're interested in ranks, you can extend these approaches in that direction too. For example, I would think that knowing a site's rank in terms of the most recent visits per day values as well as the rank of each site's mean visits per day (the rank of mean (Y) for each W in Wn) could be useful. Again, you can tailor to suit your needs.
You could present the results of all these calculations as a table, or create a regularly-updated visualization to track them on a daily basis.
Answer: Caution that arrival rates of users at Web sites are nasty series, tend to be overdispersed (from a Poisson standpoint), so consider negative binominal distributions to look at arrivals, and their fitting. Also, you may want to examine the order statistics of the sites on each day rather than their numbers.


Best Practices in Handling Modules Prerequisites

Question: Recently I started working on a personal project in my notebook that, all going OK, it will be placed in a server elsewhere. The problem is that I make use of modules. Some were installed from apt-get, others from easy_install and one or two of those were placed directly under a subdirectory since I changed them a bit. My question is: is there a way to move all those things together? Moreover, I don't want any of those modules being updated since it may break something. How to handle that?
Finally, I'm pretty sure that I've done things the wrong way since the beginning. How do you guys work to avoid those problems?
Answer: Have a look at virtualenv. Virtualenv is a tool to create isolated Python environments.


Plotting confidence interval bars from summary statistics

Question: A bit like a box plot. I mean not necessarily the standard upper confidence interval, lower confidence interval, mean, and data range-showing box plots, but I mean like a box plot with just the three pieces of data: the 95% confidence interval and mean.
This is a screenshot of a journal article which had exactly what I want:
I would also like to know how I would use the software the answerer mentions to create such a plot.
Comment: What you call "the standard upper confidence interval, lower confidence interval, mean, and data range-showing box plots" are not standard box plots at all. The standard box plot shows median, quartiles, minimum and maximum and often other details.
Comment: This kind of plot is standard (it's not a box plot, though) and can be produced by all major statistical packages: Stata, SAS, [R](http://cran.r-project.org/), MATLAB. I guess you could do it with Excel as well.
Comment: I'd call these confidence interval plots, but not every plot really needs a distinct name. Every plot deserves a text caption, however....
Comment: @Nick Right: but what *are* such graphics actually called?  (I'm not sure.)
Comment: @COOLSerdash great! Could you write up an answer for MATLAB since I already have MATLAB?
Comment: I don't know MATLAB. But something like [this](http://www.mathworks.ch/ch/help/matlab/ref/errorbar.html) or [this](http://www.cs.utsa.edu/~cs1173/lessons/Lesson6ErrorBarsQuestions/Lesson6ErrorBarsQuestions.html)?
Comment: OK, sure I'm willing to concede I don't know enough about statistics to make that statement with confidence, so thanks for correcting me on that.
Answer: Look if this helps you. R solution:
par(mfrow=c(2,1)) # to stack the charts on column

#Dataset 1

upperlimit = c(10,12,8,14)
lowerlimit = c(5,9,4,7)
mean = c(8,10,6,12)

df = data.frame(cbind(upperlimit,lowerlimit,mean))

plot(df$mean, ylim = c(0,30), xlim = c(1,4))

install.packages("plotrix")
require(plotrix)
plotCI(df$mean,y=NULL, uiw=df$upperlimit-df$mean, liw=df$mean-df$lowerlimit, err="y",      pch=20, slty=3, scol = "black", add=TRUE)

#Dataset 2

upperlimit_2 = upperlimit*1.5
lowerlimit_2 = lowerlimit*0.8
mean_2 = upperlimit_2-lowerlimit_2

df_2 = data.frame(cbind(upperlimit_2,lowerlimit_2,mean_2))

plot(df$mean_2, ylim = c(0,30), xlim = c(1,4))

plotCI(df_2$mean_2,y=NULL, uiw=df_2$upperlimit_2-df_2$mean_2, liw=df_2$mean_2-   df_2$lowerlimit_2, err="y", pch=20, slty=3, scol = "black", add=TRUE)

rm(upperlimit,lowerlimit,mean,df,upperlimit_2,lowerlimit_2,mean_2,df_2) #remove the objects stored from workspace

par(mfrow=c(1,1)) # go back to default (one graph at a time)

Comment: I can help you to give a shot, but firstly you need to follow two steps: i) install R Studio on your pc, ii) provide a reproducible example: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
Comment: and how do I run such a code? I am totally new to R so you'll have to walk me through it because I am clueless.
Comment: @AndreSilva, I think you went the extra mile there. Great support and mentoring!
Comment: This is what I got for running your code http://i.stack.imgur.com/yrZaJ.png
Comment: @BrentonHome. Strange. I just tested and it worked. The "error" bars are nor appearing. Did you instal the `plotrix` package? I added a program command line in the code that installs the plotrix package. Please, try again and let know.
Answer: In MATLAB, you might want to try the errorbar function: http://www.mathworks.de/de/help/matlab/ref/errorbar.html
Alternatively, you can do it the dumb and manual way. For example, given a matrix of data points "a", you can calculate your means using the function m = mean(a), calculate your CIs (depending on what CI you need), and plot the results by hand.
Demonstration if you already know the mean and CI, assuming CIs are in a matrix CI (first and second column) and means are in a matrix a:
plot(1:length(CI),a,'o','markersize', 10)           % plot the mean
hold on;
plot(1:length(CI),CI(1,:),'v','markersize', 6)              % plot lower CI boundary
hold on;
plot(1:length(CI),CI(2,:),'^','markersize', 6)              % plot upper CI boundary
hold on;

for I = 1:length(CI)                                        % connect upper and lower bound with a line
line([I I],[CI(1,I) CI(2,I)])
hold on;
end;

axis([0 length(CI)+1 min(CI(1,:))*0.75 max(CI(2,:))*1.25])  % scale axis

Demonstration in the case where you know individual measurements, for a repeated-measures experiment, 3+ conditions, one condition per column, one subject per line in matrix a, no missing samples, 95% CI as by MATLAB's ttest():
[H,P,CI] = ttest(a);                                        % calculate 95% CIs for every column in matrix a
                                                            % CIs are now in the matrix CI!

plot(1:length(CI),[mean(a)],'o','markersize', 10)           % plot the mean
hold on;
plot(1:length(CI),CI(1,:),'v','markersize', 6)              % plot lower CI boundary
hold on;
plot(1:length(CI),CI(2,:),'^','markersize', 6)              % plot upper CI boundary
hold on;

for I = 1:length(CI)                                        % connect upper and lower bound with a line
line([I I],[CI(1,I) CI(2,I)])
hold on;
end;

axis([0 length(CI)+1 min(CI(1,:))*0.75 max(CI(2,:))*1.25])  % scale axis

Comment: Read my latest edit, I'm sorry but some people who are annoying the hell out of me, edited out the fact I only know the 95% CI and mean no additional data.
Comment: @BrentonHorne did the link to the errorbar function not help?  It looks to be exactly what you want.
Comment: As Peter said, use *errorbar()* then.
Or use the script I wrote, but ignore the first line with the ttest and just feed it mean and CI directly. I'll edit it in I guess.
Comment: @BrentonHorne To be fair, you never discussed the point extensively or even mention it at all in the body of the question. It was implied by the title but this title also mistakenly mentioned box plots, which is the issue the edit tried to fix. It's unfortunate that the word "only" disappeared in the process but nobody purposefully edited it out a big part of your question. Besides, the answer did contain a solution and the rest of the text might be interesting to other readers.
Comment: I ran the code it went well, the problem is that I would like it if there was some means by which I could join the upper CI and lower CI with a line like in the screenshot in my question.
Comment: http://i.stack.imgur.com/SMjpk.png is a pic of what the figure your code creates for the data I have
Comment: @Brenton Home, did you run this part of the code:

`for I = 1:length(CI); plot(I,[CI(1,I):CI(2,I)]); hold on; end;`

That should draw the lines. I'll make a screenshot in a second.
Comment: I did run that part of the code
Comment: @BrentonHorne, this is what it looks like for me:
[Imgur](http://i.imgur.com/ZoVIkwa.png)

Your CI is a 2x4 matrix, right (`whos CI`)?
The `plot(I,[CI(1,I):CI(2,I)]` line should simply draw a line that goes from one CI boundary to the next.
Comment: https://docs.google.com/file/d/0B1_sXH68hMWBYVVacDFUUVdnV0k/edit?usp=sharing is my code.
Comment: I think I understand the problem; your data scale is different from mine and the interval is too fine-grained. Use this:
`for I = 1:length(CI);line([I I],[CI(1,I) CI(2,I)]);hold on;end;`
I will edit the original proposal accordingly.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9762/discussion-between-jona-and-brenton-horne)
Answer: This type of plot in R using ggplot2, though you might have to do some fiddling with the axis font size:
library(ggplot2)
data.estimates = data.frame(
  var   = c('1', '2', '3', '4', '5', '6', '7', '8', '9'),
  par = c(1.12210,0.18489,1.22011,1.027446235,0.43521,0.53464,1.93316,-0.43806,-0.12029),
  se = c(0.42569,0.32162,0.58351,0.771608551,0.24803,0.65372,0.92717,0.45939,0.51558))
data.estimates$idr <- exp(data.estimates$par)
data.estimates$upper <- exp(data.estimates$par + (1.96*data.estimates$se))
data.estimates$lower <- exp(data.estimates$par - (1.96*data.estimates$se))

p2 <- ggplot(data.estimates, aes(var,idr, size=10)) + theme_bw(base_size=10)
p2 + geom_point() +geom_errorbar(aes(x = var, ymin = lower, ymax = upper, size=2), width = 0.2) + scale_y_log10(limits=c(0.1, 50), breaks=c(0.1, 0.5, 1, 5, 10, 25, 50)) + xlab("Site") + ylab("RR")

Answer: This could be done in R with points() (or plot(..., type="p")) and segments().  There might also be R functions designed to create the CI's for you, but those might require the original data. The multiple panels in the same figure created with par(mfrow=c(4,1)).  If you don't know any R, this would be hard to do easily (as in, you would have to learn a bit more R or get someone to help with your specific data set).
Answer: In Stata use serrbar or ciplot (SSC) or eclplot (Stata Journal, SSC).
Answer: Assuming you have access to the original data you can do this in R with the lineplot.CI function in the sciplot library
Example with mtcars dataset:
lineplot.CI(x.factor=gear, response=mpg, group=vs, data=mtcars)

Note that lineplot.CI by default plots SE bars (it can be changed defining a new function with the argument ci.fun to plot 95% CI intervals)
lineplot.CI(x.factor=gear, response=mpg, group=vs, data=mtcars, ci.fun=function(x) c(mean(x)-1.96*se(x), mean(x)+1.96*se(x)))

Answer: GraphPad Prism can easily make this kind of graph, plotting error bars from error values you enter. Create a grouped table formatted for entery of mean, - error and + error.
Comment: @BrentonHorne: No. It is not free software.
Comment: Is it possible to get a free copy of it that isn't just a 30 day trial version?


Cron job executed multiple times daylight saving time

Question: We run a CentOS release 6.2 (Final)  2.6.32-220.13.1.el6.x86_64 with a stock cronie.x86_64 1.4.4-7.el6.
On Mar 31 we moved to summer time: 03:00 become 04:00.
In crontab we have:
0 4 * * * /usr/bin/php /some_script.php

In log we discovered that this script was executed 12 times:
Mar 31 02:56:01 web CROND[1910]: (root) CMD (/etc/webmin/virtual-server/collectinfo.pl)
Mar 31 04:00:01 web CROND[2492]: (root) CMD (/usr/lib64/sa/sa1 1 1)
Mar 31 04:00:01 web CROND[2496]: (mailman) CMD (/usr/lib/mailman/cron/gate_news)
Mar 31 04:00:01 web CROND[2491]: (root) CMD (/usr/lib64/sa/sa1 600 6 &)
Mar 31 04:00:01 web CROND[2497]: (root) CMD (/etc/webmin/status/monitor.pl)
Mar 31 04:00:01 web CROND[2500]: (some_user) CMD (/usr/bin/php /some_script.php )
Mar 31 04:00:01 web CROND[2509]: (some_user) CMD (/usr/bin/php /some_script.php )
Mar 31 04:00:01 web CROND[2512]: (some_user) CMD (/usr/bin/php /some_script.php )
Mar 31 04:00:01 web CROND[2514]: (some_user) CMD (/usr/bin/php /some_script.php )
Mar 31 04:00:01 web CROND[2534]: (some_user) CMD (/usr/bin/php /some_script.php )
Mar 31 04:00:02 web CROND[2553]: (some_user) CMD (/usr/bin/php /some_script.php )
Mar 31 04:00:12 web CROND[2560]: (some_user) CMD (/usr/bin/php /some_script.php )
Mar 31 04:00:22 web CROND[2670]: (some_user) CMD (/usr/bin/php /some_script.php )
Mar 31 04:00:32 web CROND[2673]: (some_user) CMD (/usr/bin/php /some_script.php )
Mar 31 04:00:42 web CROND[2675]: (some_user) CMD (/usr/bin/php /some_script.php )
Mar 31 04:00:52 web CROND[2678]: (some_user) CMD (/usr/bin/php /some_script.php )
Mar 31 04:01:02 web CROND[2680]: (some_user) CMD (/usr/bin/php /some_script.php )
Mar 31 04:01:02 web CROND[2683]: (root) CMD (run-parts /etc/cron.hourly)
Mar 31 04:01:02 web CROND[2684]: (root) CMD (/etc/webmin/virtual-server/collectinfo.pl)
Mar 31 04:01:02 web run-parts(/etc/cron.hourly)[2683]: starting 0anacron
Mar 31 04:01:02 web anacron[2693]: Anacron started on 2013-03-31
Mar 31 04:01:02 web run-parts(/etc/cron.hourly)[2695]: finished 0anacron
Mar 31 04:01:02 web run-parts(/etc/cron.hourly)[2683]: starting awstats

Any sugestions are higlhy apreciated.
Comment: And now you know why all the default crontabs start at 4:02 am.
Answer: It is a known bug:

http://bugs.centos.org/view.php?id=5590
https://bugzilla.redhat.com/show_bug.cgi?id=436694

I've seen it happen on CentOS 6.2 with cronie-1.4.4-7.el6.x86_64 on the 31st of march (CET -> CEST)
Answer: As I use my servers principally to host web-based services that could be accessed by any timezone in the world, I have my servers operating on UTC (which does not experience DST). Any public facing interface converts to the user's local time (as configured by their preferences).
It should be noted that some services do not gracefully handle being thrown into the future (or the past).
Comment: That is a very good ideea. Still, according to man page CRON  should handle DST corectly and avoid executing same job more than once, not to mention 12 times. :-)
Comment: What timezone are you set for? does `date -u` show the correct UTC time?
Comment: Date show correct time, both local and UTC: `[root@web ~]# date -u
Wed Apr  3 07:31:42 UTC 2013
[root@web ~]# date
Wed Apr  3 10:31:45 EEST 2013`


Solution method linear differential equation

Question: I'm solving for the equilibrium strategy in a first-price auction with common value. During the process of maximization of the utility function of a generic bidder I've encountered the following differential equation, but I'm not able even to guess a possible solution because I've never studied ODE.
Start from here:
$$ \pi= \int_{0}^{\omega}v + y- b(\omega)-b(\omega)+ydy$$
then
$$\frac{d \pi}{d \omega} = v + 2 \omega -2[b(\omega)+ \omega b'(\omega)]$$
My problem is to solve the following:
$$3v - 2b(v) - 2 vb'(v) = 0  $$
where $ b(\cdot)$ is a strictly increasing function and $b(0)$ need not to be equal to $0$. Does somebody can help me?
Comment: $\frac {d}{dv}bv = b + b'v.$  Isolate this expression, and then integrate both sides.
Answer: Hint
$$3v - 2b(v) - 2 vb'(v) = 0$$
$$3v - 2(b +  vb') = 0$$
$$3v - 2(bv)' = 0$$
$$ (bv)'= \frac 3 2 v $$
Simply integrate :
$$ bv=\frac 3 2 \int vdv $$
For $v \neq 0 $
$$\boxed { b(v)=\frac 3 4 v+ \frac Kv}$$
Note that for $(v=0)$ we have $3v - 2b(v) - 2 vb'(v) =-2b(0) =0$ And $b(0)=0$


Problemas com phpMyAdmin UolHost

Question: possuo um site na uol host e um banco de dados também, o site se comunica perfeitamente com o mySql, porém possuo um software desktop que preciso que se comunique com o mySql também, existe alguma configuração que preciso ajustar para que o mySql permita este software desktop se conectar com ele? pois não estou conseguindo fazer esta comunicação. Se alguém puder ajudar agradeço.
Comment: Na hostinger você tem que habilitar a conexão fora do localhost, veja se no seu provedor também tem essa configuração.
Comment: Como é feito isto no hostinger? no próprio phpMyAdmin?
Answer: Acredito que a UOL Host deve liberar o acesso remoto (se eles permite isso) para você no seu usuário, se você tem acesso com privilégios necessários, você pode definir o acesso remoto executando o seguinte SQL:
GRANT ALL ON . TO meuuser@'SEUIP' IDENTIFIED By 'senha';
Liberando para qualquer ip acessar o banco com senha usando % (não recomendado)
GRANT ALL ON . TO meuuser@'%' IDENTIFIED By 'senha';
No arquivo de config do mysql deve permitir acesso ao ip "público" algo como:
/etc/mysql/my.cnf
bind-address = 0.0.0.0
Acredito que sua hospedagem for compartilhada deve a UOL Host liberar o acesso remoto (se for permitido), caso seja você o administrador do banco, deve efetuar as configurações acima.
Comment: Consegui, obrigado.

Problemas com phpMyAdmin UolHost


Simplenews - how pass values from own input

Question: How I can pass value from added input to database(?) in Simplenews? I want to use this value later in newsletter, e.g. print it in block template.
Below is how I created field
function news_hook_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'simplenews_block_form_2730'){
        $form['field_name'] = array(
        '#type' => 'textfield',
        '#title' => t('First name'),
        '#required' => TRUE,
        '#size' => 20,
);
}}

Answer: function my_module_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'YOUR_FORM_ID') {
    $form['field_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
    $form['field_name_submit'] = array(
      '#type' => 'submit',
      '#value' => t('SAVE'),
      '#submit' => array('my_module_name_submit'),
    );
  return $form;
  }
}

function my_module_name_submit($form,&$form_state) {
  if ($form_state['values']['field_name']) {
    variable_set('Name', $form_state['values']['field_name']);
  }
}

variable_set stores textfield value in variable table. You can access/get this value using variable_get as mentioned below

variable_get('Name')
Comment: hmm but now I have two submit buttons - one from Simplenews module, and second created by alter_form. There's no option which can link or something my values to module's submit button? Moreover - I can hide Simplenew's submit button, but this created button will not pass other values (e.g. from e-mail field originally rendered by module) and mailing won't work :C
Comment: You can get the values using **variable_get**,  which can be used anywhere