why don't set the placeholder attribute for contact field?

Question: this is my hook_form_alter function for set the placeholder attribute and other stuff:
 function mysubtheme_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'contact_site_form':
            $form['tel'] = array(
                '#title' => t('Tél'),
                '#type' => 'textfield',
                '#required' => TRUE,
            );
            if ($form_id == 'contact_site_form') {
                $form['name']['#title'] = t('name/family name');
                $form['name']['#attributes']['placeholder'] = t('Enter your name');
            }
                $order = array(
                '1' => 'name',
                '2' => 'mail',
                '3' => 'tel',
                '4' => 'subject',
                '5' => 'message',
                '6' => 'copy',
            );
            foreach ($order as $key => $field) {
               $form[$field]['#weight'] = $key;
            }
            break;
       }
  }

why don't set the placeholder attribute for contact field?
kpr() for this element shows:
Comment: What does `kpr($form['name'])` show you?
Comment: I edit the question.
Comment: What I asked you to do was to output the part of form you want to modify, so we could see what's actually there before you modify it. Here is a demo page about doing it: http://ratatosk.net/drupal/tutorials/debugging-drupal.html Sorry if I wasn't clear first time.
Comment: I received this result: (http://tb23.Trainbit.com/d/8065691884.png)
Answer: edit
$form['name']['#attributes']['placeholder'] = array(t('Enter your name'));

to
$form['name']['#attributes']['placeholder'] = t('Enter your name');

then execute "flush all caches"
Comment: Still doesn't work.
Comment: try to flush cache,My test is ok
Comment: I flush all caches but still doesn't work.
Comment: what file the mysubtheme_form_alter function is writted in?
Comment: In mysubtheme template.php file.
Comment: you should write it in module,for example,hello.module file in hello module
Comment: Not true, all `_alter` hooks can be implemented at the theme level
Comment: Further explain, please.
Comment: Clive's comment is right
Comment: Further explain Clive, please.
Answer: I added this line to code and the problem was solved:
 $form['name']['#default_value'] ='';

Edited code is:
if ($form_id == 'contact_site_form') {
    $form['name']['#title'] = t('name/family name');
    $form['name']['#default_value'] ='';
    $form['name']['#attributes']['placeholder'] = t('Enter your name');
}


How to add colorbox in views gallery

Question:
I follow these steps to achieve the gallery thumbnail in footer
  https://www.drupal.org/node/1497058
  and now my thumbnails shows like below

but only thing left is when i
  click thumbnail image its open the next page and show the big image
  but i want when i click the thumbnail the big page open on colorbox
  when i click on thumbnail its shown like below
Answer: Install and enable colorbox module. And add place colorbox library in sites/all/library and rename folder to colorbox

Goto to admin/structure/views
Click edit on your views, here my view name is "Colorbox"

Click on your image field, eg., content:Image

select Formatter as colorbox and click "apply"

Save the view and clear the cache.

Hope it works
Comment: where  you find the above screen when i click o n views under structure there is no such field
Comment: You need to install and configure the colorbox module.
Comment: Answer updated. Kindly check it.
Comment: @vamsi: i followed your step, now when i click the thumbnail the big image open there but not in colobox there is no cross button and all
Comment:
Comment: Above is the view source. Is anything missing in it?
Comment: i added the pic in questions
Comment: Go to admin/reports/status and check if you find any error like "colorbox library is missing"
Comment: no there is no such thing there
Comment: Then it should work. Clear your cache and try.
Comment: okay let me check
Comment: Is it working now.
Comment: yes perfectly working

How to add colorbox in views gallery


Understanding confidence intervals with coefficients

Question: maybe someone can put me in the right direction. I already read some of the "understand confidence intervals" posts, but none of them seem to give me the information I need. I am a student and I am dealing with a task, of which I do not understand the solution the professor has provided.
We are an ice cream shop and based on the history of data we have been thinking of adding two more types of ice cream to the shop. We have a total of 5 different shops, where each of them has a different amount of types of ice cream.
We have been given a full year of data, where each day records temperature, types of ice cream available, the revenue, and the location.
I created a linear model based on the data. The question where I am struggling to understand the solution is the following.
Question: Does it make sense to sell two more types of ice cream? The costs would increase by 2000$ per location. What is the confidence interval for the revenue generated?
What I basically did is the following:
df = read.csv(....)
modell1= lm(revenue ~ temp + location + types, data=df)

confidenceprediction = data.frame()
for( i in 1:1000){
  confidenceprediction = rbind(confidenceprediction, predict(modell1, newdata = data.frame( types = df$types[i]+2, temp = df$temp[i], location=df$location[i]), interval = "confidence"))
}
colMeans(confidenceprediction)

# > colMeans(confidenceprediction)
# fit      lwr      upr
# 697.0656 674.1053 720.0259

I wanted to use my model to predict a revenue each day with two more types of ice cream. I used the interval="confidence" parameter to get a confidence value.
Then I looked at the column Means for the entire prediction. This tells me that in a 95% confidence interval, my revenue should be at least 674$ and max 720$.
However, his solution just does something I cannot quite grasp.
confint(modell1)["types",]*2*365
#    2.5 %    97.5 %
# -1194.145  7851.394

He just multiplies the confidence interval, taken from the model by two, and of course by 365.
Please answer me this:
Why is he allowed to do something like this, and why does it differ from my solution so much?
For the sake of it here is a summary and a full confint. We did not transform any values or introduced interaction terms.
> summary(modell1)

Call:
lm(revenue ~ temp + location + types, data=df)

Residuals:
    Min      1Q  Median      3Q     Max
-428.21  -76.52    1.13   81.02  394.08

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 542.7094    39.8734  13.611  < 2e-16 ***
temp          6.7115     0.5877  11.421  < 2e-16 ***
locationB   105.9596    30.3248   3.494 0.000497 ***
locationC     2.4538    12.2817   0.200 0.841683
locationD   -11.5054    15.3460  -0.750 0.453595
locationE   -18.1600    12.3012  -1.476 0.140184
types        4.5598     3.1572   1.444 0.148988
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 120.4 on 993 degrees of freedom
Multiple R-squared:  0.4748,    Adjusted R-squared:  0.4716
F-statistic: 149.6 on 6 and 993 DF,  p-value: < 2.2e-16

> confint(modell1)
                 2.5 %     97.5 %
(Intercept) 464.463523 620.955204
temp          5.558346   7.864708
locationB    46.451474 165.467683
locationC   -21.647215  26.554820
locationD   -41.619779  18.609023
locationE   -42.299320   5.979235
types       -1.635815  10.755334

```

Comment: Concerning your lecturer's solution: is the multiplication not due to the fact that you work with daily data and add two new types of ice cream? Hence you need to multiply the uncertainty interval for the types variable by 2 (since you add two new flavours) and 365 days to get annual revenue.
Comment: @horseoftheyear hmm, that would make sense. But he cannot just ignore the fact that there are locations that sell 13 types, and others that sell 17 types? Additionally, doesn't this method introduce a lot of room for error?

On a mean(df$types) we get 13.64 types of ice cream per day. Is the confidence interval based on this 13.64 value? I do not know how this is calculated within the model itself, we never discussed this.

But multiplying it would mean we sell ~27 types of icecream now or?
Comment: So the types variable is a count for the number of different types of ice cream available at a location (from your description). Hence the estimated coefficient represents the effect of a one unit increase in types on the outcome variable, revenue. Ergo an additional type of ice cream is associated with an increase of 5 $\pm$ 3 whatever-currency in daily revenue.
Comment: Ah! everything makes sense now. Let's say I want to know how a +1.5 degree temperature increase reflects in the revenue I can just do a `confint(model1)["temperature",]*1.5*365` and I have my solution.

Could you maybe explain me, why my prediction solution does not come close to the interval we get with the `confint` method?
Comment: The prediction approach you used generates prediction intervals for single observations, which you then average. This is a different interval compared to the regression uncertainty interval based on a parameter estimate.
Answer: @horseoftheyear answered this one for me:
So the types variable is a count for the number of different types of ice cream available at a location (from your description). Hence the estimated coefficient represents the effect of a one unit increase in types on the outcome variable, revenue. Ergo an additional type of ice cream is associated with an increase of 5 ± 3 whatever-currency in daily revenue.


JasperReports JRBeanCollectionDataSource still confused

Question: So I do now have my  working and filling reports.  The users of my program can now pass objects from the program to a report object and fill it using the JRBeanCollectionDataSource and that does work.  However I can't get all the data in the report I want.  I am just very confused about this, how the fields that I declare with a name and a Class map to the properties of the beans in my collection.
I have a hibernate persistent object called Item
Item has a List properties
and property is a table that holds a name, type and value (all more persistent objects).
I need to show on my reports not just properties of the beans but properties of beans that are in List collections of other beans.  I am using iReport to build reports and I can do JavaBeanDataSource as well as HQL, but since when the report runs, it's going to have a collection of beans to be filled with, but I need to get only certain elements of the collection depending on criteria, needing to display fields on my report such as :
properties.value where properties.name = 'foo'
where properties is a collection property of the bean in my data source, basically having a query that queries the data in the Bean as my field, and even to be able to create a sub-report listing out the properties that are in the collection that is the property of the bean.
Any help and direction is much appreciated, thank you very much!
Joshua
Comment: If I had 100 rep points, I'd create a bounty for this!  I'm desperate!
Comment: Either it's a tough question or it's poorly asked, you can tell me.  :)
Comment: Well, I've even tried to outsource this problem on getafreelancer.com, have someone build three reports I can use to work off of, even accepted a bid of $200, and he told me:

The way to do this is with datases, subdatasets and crosstabs

which is great except that I'm completely out of time on this deadline, the big implementation is TOMORROW, and everything works except the reports aren't written, and if I don't get it by morning several (including me) look (rightfully) like fools.

Anyone?  Bounty?  Feeling desperate?  Please?
Answer: I have finally found at least a lead on the answer, though I don't have it working yet.
http://knol.google.com/k/nasir-qureshi/jasper-reports-working-with-beans-and/3az55pmbwf6s/3
This is basically exactly what I'm doing, except I want to embed the subreport in the report and I want to make reports that show some of the elements of the List based on criteria.
Comment: You should select your answer as the "chosen" answer.
Answer: This is not resolved I guess. Otherwise please update here with the solution.
I faced similar issue with iRerport 3.7.0
I logged a bug at

http://jasperforge.org/plugins/mantis/view.php?id=4480

I also followed Nasir Qureshi's blog

http://knol.google.com/k/jasper-reports-working-with-beans-and-sub-report#

I have asked this question on the blog as well. Till then if somebody knows the answer, please let me know.
Comment: The original question is still not clear to me, can you ask another question and be more specific with code or real life example
Comment: Could you please ask specific question about what are you unclear on. I can give objective inputs.

FYI:  I have solved the issue by manually editing jrxml.
Comment: The link that I mentioned have complete details about the problem
>> http://jasperforge.org/plugins/mantis/view.php?id=4480


Significance of the DEGREE of Differential equation

Question: Can anybody gives the idea why degree of a differential equation is important?. Every differential equation book writes the definition of "degree of a differential equation". But, why do we care about this definition? What we will get just by remembering definition of degree of a differential equation ?
Answer: Mathematicians love to classify things. The degree is one criterium to classify differential equations. Another one is for instance linear/non-linear.
Different methods of solution are appropriate for equations of different degree. And you have general results like: the general solution of an differential equation of degree $n$ depends on $n$ constants.
Comment: linear/non-linear some extant ok but it doesn't completely classify linear/non-linear things. Second statement you made that is related to only ORDER of a differential equation not for DEGREE.
Comment: Word "every" I used here as sentimental, but several book I have seen they are defined the degree of a differential equation and I couldn't find anything worthfull.
Comment: I misunderstood. I have checked several "classical" books on differential equations (but certainly not all.) The only ones I found that mention the degree are from 1888 and 1931. I have been teaching differential equation several years, and never mentioned it in my lectures.


Error in semantic exception return 0 rows in hive

Question: I got the below error in hive while I am executing the hql like this.
Select a.col,b.col from tab a left join tab b on a.id =b.id and a.code in
(Select c.code from tab c where c.id=123 and c.dec='123a');
Note: c.id is pk and c.dec is unique id
Error: semantic in exception 0 children returned.
Can any one help to resolve the above issue.
Answer: I think this is happening because you are using a MySQL reserved keyword "desc" as your column name. So you can change it and try again.
You can refer to this link for the list of all the reserved keywords for MySQL :https://dev.mysql.com/doc/refman/5.5/en/keywords.html


If there is an NHL lockout / partial lockout, what will happen to purchased tickets?

Question: I bought tickets for the Boston Bruins' opening night against the Montreal Canadians on October 18, 2012. What will happen to the tickets that people have bought if there is a lockout?
Also there is a possibility that there will be a partial lockout and the season will start in December rather than October (like the NBA 2011-2012 season). If this happens, and "opening night" gets moved from October 18th to December 1st, what will happen to all of those who bought tickets for games between those two dates?
Comment: This [article](http://ducks.ocregister.com/2012/08/31/ducks-prep-ticket-holders-for-lockout/112838/) talks about how the Anaheim Ducks will refund their season ticket holders...it would lead me to believe that individual teams have different policies and procedures, but that's just a vague hypothesis.
Comment: This is a general question about tickets.
Comment: I think these refund policies will be used league round. Thanks a lot!
Comment: Just found this article that goes over what every team in the league is doing... http://daysofyorr.com/2012-articles/september/cashing-in-on-the-lockout-what-teams-are-offering-season-ticket-holders.html
Answer: I know for season tickets they told me that I don't pay for games that aren't played.  So I think they refund anything that you may have purchased once the schedule is decided. As for individual tickets I would bet it is the same as a canceled event.
Comment: The Colorado Avalanche.
Comment: Just out of curiosity, who are you a season ticket holder for?


The least upper bound for $\frac{\sum_{i=0}^m{\binom{m}{i}x^i}}{\sum_{i=0}^{m}{x^i}}$

Question: I have proposed a classifier whose complexity can be written as
\begin{align*}
\mathcal{O}\left(f(m)\right)&=\mathcal{O}\left(\log\left(\max_{x\in(0,1)}\left\{g(x,m)\right\}\right)\right)\\
g(x,m)&=\frac{(1+x)^m(1-x)}{1-x^{m+1}}
\end{align*}
where $m\in\{0,1,2,3,...\},x\in(0,1)$.
There exist an evident upper bound for $g(x,m)$ but it is quite large:
\begin{align}
(1+x)^m=\sum_{i=0}^m{\binom{m}{i}x^i}&<\binom{m}{{\lceil}\frac{m}{2}{\rceil}}\sum_{i=0}^{m}{}x^i\\
&<\binom{m}{{\lceil}\frac{m}{2}{\rceil}}\frac{1-x^{m+1}}{1-x}
\end{align}
\begin{equation}
\longrightarrow \forall x: \frac{(1+x)^m(1-x)}{1-x^{m+1}}<\binom{m}{{\lceil}\frac{m}{2}{\rceil}}
\end{equation}
As you see $\binom{m}{{\lceil}\frac{m}{2}{\rceil}}$ is a generous upper bound.
Translating my question to Combinatorics language, I am seeking for a technique that provides the smallest or a small enough $U_m$ in the below formula.
\begin{equation}
\sum_{i=0}^m{\binom{m}{i}x^i}<U_m\sum_{i=0}^{m}{}x^i
\end{equation}
Can anyone provide any hint, please?
Answer: Hint. Note that the function
$$f(x)=\frac{(1+x)^m(1-x)}{1-x^{m+1}}$$
is increasing in $(0,1)$ and
$$\lim_{x\to 1^-} f(x)=\frac{2^m}{m+1}.$$
Comment: Thanks Robert!!


How do security updates and patching work for Windows Server 2016 containers?

Question: If I use the new "containers" feature (managed via docker) in windows server 2016 to create a containerised application, what happens when my underlying windows server operating system receives security patches?

Do I need to rebuild all my container images?
Do the containers all stop working?
Answer:
Do I need to rebuild all my container images?

Yes.

Do the containers all stop working?

No.
Comment: If they don't stop working it implies I'm not forced to rebuild my images, but if I don't are they simply left running, but without the security patches applied?


How do I do overtone singing?

Question: Is it just a head voice overlaying a steady chest voice? How does this work? Do you need to have 2 different airflows? Please explain! I have tried it multiple times but every time just end up in a head voice.
Comment: Are you talking about mixed voice? Somewhere in between chest voice and head voice?
Comment: Sing the word "long" on a loudish, lowish note, and hold the final 'ng' sound while mouthing with your lips the word "wow" repeatedly and extremely slowly. It helps if you make your mouth cavity as large as possible. If you listen you should hear high harmonics: a rising arpeggio on 'Wa' and a falling one on 'Ow'. Disappointingly I can only get the 3rd, 4th, 5th and 6th overtones but you might do better. Tuvan singing often dances around on the 6th, 7th and 8th. Stockhausen's Stimmung calls for at least the 7th. Once you've got it, opening your throat very slightly may make it louder.
Comment: That's what I am trying to figure out. How does he do it, and how can I recreate it?
Comment: Look up Avi Kaplan overtone singing. He keeps a steady chest note while hitting different notes in his head voice
Comment: No, btw, you don't need two airflows, just a big breath before you start.
Answer: Any note that you sing consists of overtones. However, humans will just think of it as one note, and interpret the overtones as "timbre".
The effect of overtone singing (or throat singing) is to emphasise one of those overtones. If you can do that strong enough (and especially if you can emphasise different overtones in a sequence), then eventually humans will start hearing it as two notes.
In practice, you take a deep breath and produce a low steady tone in your throat (just with your vocal tracts). Tighten your throat and make it 'ugly' so that the sound has a lot of overtones to begin with. Then make a relatively small "oh" opening with your lips and shape your mouth cavity to resonate with the frequency of one of those overtones (octave, octave+fifth, double-octave, double-octave+third, etc...). Sounds difficult, but if you can whistle a tune, then you are already capable of shaping your mouth to resonate with a desired frequency.
As a result, that overtone (which was already present in the original sound) will become stronger and more emphasised. And if you practice long enough... it will be convincing enough to be heard as 2 different tones.
Answer: You are Always Singing Overtones
Each note you sing produces many overtones, the relative volume of each changes depending on several things, including the shape of your lips and mouth, position of your tongue, etc. This actually plays a large part in why each mouth "position" sounds different from the rest. The human brain interprets all the notes as a single sound, but they are all still being heard.
Producing Overtones is Easy, Controlling Them...Not so Much
Adjusting the relative volumes of these overtones in order to make specific ones prominent enough to be clearly heard above the rest is actually very simple (you just need to have the correct mouth shape), but learning to actually sing melodies in overtones is exceptionally difficult, as the difference in mouth position between notes is nearly imperceptible.
How to Produce Distinct Overtones
To get started, choose a relatively low note that you can still sing at full volume. Next, sing "Wee" with an open pallet (try to resonate about half way back in your mouth). If you notice a slight whistling sound, what you are hearing is actually a series of ascending overtones. Now, sing "Wee" again, but transition from the starting "ooo" shape to the ending "eee" shape very slowly. If the resonance is in the right place in your mouth you will hear a high pitch tone that gets higher as you transition.
Go slowly enough and you might notice that the pitches are following the harmonic series, which makes sense, because that is exactly what they are! (If you happen to remember those plastic tube things that produce whistling noises when you twirl them, it sounds kind of like that (fun fact: those toys also follow the harmonic series as you twirl them faster)). If you do not hear the notes, that's ok. Just adjust the position of you tongue, and where in your mouth you are resonating, and you should find it.
How to Control Overtones (TLDR: I have no idea!)
Now that you are producing the pitches, try finding the exact shape between "ooo" and "eee" that produces a specific pitch. If you can't, don't worry (neither can I). This is the "exceptionally difficult" part I mentioned earlier. The differences in mouth shape are tiny and the harmonic series limits exactly which notes you actually have access too. Honestly, at this point, I can't help you. You can experiment with it, or possibly find a tutorial somewhere on how to hit specific pitches.
Good Luck!
But for now, hopefully this answer is enough to get you started and impress people at parties by singing two pitches at once!

How do I do overtone singing?


PHP print to receipt brother printer

Question: i'm trying to print to a Brother QL 720 NW lan receipt printer with a static ip address.
I'm trying in this way:
<code>$texttoprint = "RECIPT TEXT \n NEXT LINE \n MORE STUFF";
    $texttoprint = stripslashes ( $texttoprint );

    try {
        $fp = pfsockopen ( "10.66.112.35",9100);
        fputs ( $fp, $texttoprint);
        fclose ( $fp );
    } catch ( Exception $e ) {
        echo 'Caught exception: ', $e->getMessage (), "\n";
    }
    echo 'Successfully Printed';
</code>
I got always "Successfully printed" as result, but i'v never had printer working, could you help me?
Off course i've tried to ping from the server the printer and all was successfully...
Hope you'll help me.
Thank you very much
Comment: Are you sure the printer really interpretes random text coming over network as something to print?
Comment: you're maybe right, but this is the code i've found on the net, have you got any alternative idea?
Answer: I am also trying to implement the same functionality in my application. After searching for hours I am able to find a below library
https://github.com/RamyTalal/Label-Printer
It's seems to be tested with brother QL-720NW printer. You may give it a try.

PHP print to receipt brother printer


Computing shortest path including specific edge

Question: Consider the weighted undirected graph with $4$ vertices, where the weight of edge $\{i, j\}$ is given by the entry $W_{i, j}$ in the matrix $W$.
$$W =
\begin{bmatrix}
0&2&8&5\\
2&0&5&8\\
8&5&0&x\\
5&8&x&0\\
\end{bmatrix}
$$
The largest possible integer value of $x$, for which at least one shortest path between some pair of vertices will contain the edge with weight $x$ is ______?

My attempt:
Somewhere, answer is give $12$, and somewhere is $10$. According to me answer is $11$. Since, if we try to reach node_4 to node_3. There are three possible ways:

Node_4 → Node_2 → Node_3 $=$ cost $= 8+5=13$
Node_4 → Node_1 → Node_2 → Node_3 $=$ cost $= 5+2+5=12$
Node_4 → Node_3 $=$ cost $= x =$ maximum value should be less than $12 = 11$

Can you explain in formal way, please?
Comment: Please see question no-38 at page no.- 12 of section-technical http://www.gate.iisc.ernet.in/GATE2016questions/S5_CS.pdf
Comment: Official answer is given $12$, please see ans-38. http://www.gate.iisc.ernet.in/GATE2016answers/CS-1-AnsKey.pdf
Answer:
So between node 3 & 4, there are 5 paths,
$4->1->3 = 13$
$4->2->3 = 13$
$4->1->2->3 = 12$
$4->2->1->3 = 18$
$4->3 = x$
Clearly $X_{max} = 11.$
Answer: The answer is $12$.

Excluding the edge labeled $x$, the shortest paths are
$AB=2$, $AC=7$, $AD=5$, $BC=5$, $BD=7$, and $CD=12$.
The main theoretical ingredient of this problem is that
the lengths of the shortest paths can only decrease (or remain equal)
if we add a new edge.
The most promising is the longest shortest path $CD=12$.
Clearly, if we set $x=12$ on the edge connecting $C$ and $D$,
there will be two shortests paths, one simply $C-D$ and the other $C-B-A-D$, both of length $12$. So, if $x \le 12$ there will be at least one shortest path passing through $x$, as requested.
It is easy to see that a larger $x$ (say, $13$) can't be used, because all the existing shortest paths are already smaller of equal to $12$.
I think that the only confusion that can arise in this problem depends on misreading the question.
The question ask for "The largest possible integer value of $x$, for which at least one shortest path between some pair of vertices will contain the edge with weight $x$".
So, at least one shortest path, not every shortest path.  If it was every shortest path the answer would have been $11$, because we had to "beat" the shortest path $C-B-A-D=12$, but since the question asks for at least one among the shortest paths, then the answer is $12$, because having two shortest paths of length $12$ is fine, since one contains the edge $x$.
Comment: @MithleshUpadhayay The question, as I read it, does not say "such that THE shortest path between two vertices contains $x$", but "such that at least ONE shortest path between two vertices contains $x$", and for $x=12$ such shortest path exists. Nowhere in the question I read something about the fact we have to choose among shortest paths or something about our preferences.
Answer: We observe the graph corresponding to the transition matrix $W$ is undirected, i.e. $w_{i,j} = w_{j,i}$ with $1\leq i,j\leq 4$ and the graph is also complete, i.e. each node is reachable in one step from each other node.
We denote the nodes of the graph with $\mathcal{N}=\{1,2,3,4\}$ according to the indices of the matrix
\begin{align*}
W=\begin{bmatrix}
0&2&8&5\\
2&0&5&8\\
8&5&0&x\\
5&8&x&0\\
\end{bmatrix}=(w_{i,j})_{1\leq i,j\leq 4}
\end{align*}

We now consider systematically the weights of all relevant paths $P_{i,j}$ from node $i$ to $j$ with $1\leq i<j\leq 4$. According to the properties of $W$ these are all paths of length $\leq 3$.
Assuming $x\in \mathbb{N}\backslash\{0\}\\$,  we obtain
  \begin{align*}
P_{1,2}:&\min \{w_{1,2},w_{1,3}+w_{3,2},w_{1,4}+w_{4,2},w_{1,3}+w_{3,4}+w_{4,2},w_{1,4}+w_{4,3}+w_{3,2}\}\\
&=\min\{2,8+5,5+8,8+x+8,5+x+5\}\\
&=2\\
P_{1,3}:&\min \{w_{1,3},w_{1,2}+w_{2,3},w_{1,4}+w_{4,3},w_{1,2}+w_{2,4}+w_{4,3},w_{1,4}+w_{4,2}+w_{2,3}\}\\
&=\min\{8,2+5,5+x,2+8+x,5+8+5\}\\
&=\min\{7,5+x\}\\
P_{1,4}:&\min \{w_{1,4},w_{1,2}+w_{2,4},w_{1,3}+w_{3,4},w_{1,2}+w_{2,3}+w_{3,4},w_{1,3}+w_{3,2}+w_{2,4}\}\\
&=\min\{5,2+8,8+x,2+5+x,8+5+8\}\\
&=5\\
\mathcal{P}_{2,3}:&\min \{w_{2,3},w_{2,1}+w_{1,3},w_{2,4}+w_{4,3},w_{2,1}+w_{1,4}+w_{4,3},w_{2,4}+w_{4,1}+w_{1,3}\}\\
&=\min\{5,2+8,8+x,2+5+x,8+5+8\}\\
&=5\\
\mathcal{P}_{2,4}:&\min \{w_{2,4},w_{2,1}+w_{1,4},w_{2,3}+w_{3,4},w_{2,1}+w_{1,3}+w_{3,4},w_{2,3}+w_{3,1}+w_{1,4}\}\\
&=\min\{8,2+5,5+x,2+8+x,5+8+5\}\\
&=\min\{7,5+x\}\\
\mathcal{P}_{3,4}:&\min \{w_{3,4},w_{3,1}+w_{1,4},w_{3,2}+w_{2,4},w_{3,1}+w_{1,2}+w_{2,4},w_{3,2}+w_{2,1}+w_{1,4}\}\\
&=\min\{x,8+5,5+8,8+2+8,5+2+5\}\\
&=\min\{x,12\}\\
\end{align*}
We observe the minimum weighted path from node $3$ to $4$ has weight $\min\{x,12\}$ and admits the largest value $x=12$ with respect to all other relevant paths.


Is there any reason not to use TRS cables for typically TS applications?

Question: First, an assumption: given what I know about tip-sleeve and tip-ring-sleeve connections, using a TRS cable between two TS jacks just yields an unused contact/conductor in the cable.
Other than cost, all else being equal, is there any reason I should buy and use TS cables instead of TRS cables for various connections in my small studio?
Answer: No, for a small studio, other than the cost difference, you can use TRS in the place of TS cables.
When you start looking at cable runs over around six meters (20 feet) you can start seeing some issues with resistance, depending on what you are using the wire for. The dual wire TRS cable will sometimes have a smaller gauge wire than the coaxial cable that is often used for TS.
Usually there is no significant difference though.
EDIT: thinking about it, there may be some slight durability difference in the two types of cables as well, if you are using the TRS cables in applications where they get flexed often, such as for a guitar cable.  The tensile strength of the single wire is likely higher, resulting in a longer life before breakage in high flex use.
Comment: I'm pretty sure, at extreme distances, there's also an element of reinforced interference in the 'spare' core, but I don't have the math to defend that speculation.
Comment: Having just ordered a good few trs plugs ( at good price) I wonder if it's worth shorting the r and s, for better conductivity.
Comment: @Tim I have used two wire unified to tip in a TRS plug before, when I didn't have regular TS on hand.
Comment: @Tetsujin  Unless the spare core is somehow connected to your circuit, it should just be dead mass with no EM characteristics.  I could be wrong about that, but I'm pretty sure you have to have poor insulation or a large amount of metal for reinforced interference to happen.
Comment: For me, the tip is the tip. I'm more concerned about the point on the shaft which contacts the sleeve. If the ring is anywhere near, here may be problems.
Comment: @Tim  There are industry manufacturing standards set up for the distances for the TR (RRR) S connectors.  A correctly manufactured TS connector should have the sleeve connector lower than where the Ring connector goes.  A manufacturer not following industry standard would likely not be selling those products for very long. It it is unlikely that you would encounter a non-standard connector.
Answer: One "typically TS application" that would definitely present an issue is the connection between a guitar with active electronics and an effects unit (stompbox).
The output of the guitar and the input of the stompbox almost always have a TRS jack that is used to power the device on:
One battery terminal (usually negative) is connected to the Ring terminal of the jack so that when a TS cable is inserted, it shorts the Ring and Sleeve terminals to connect the battery to the ground in the electronics.
Putting a TRS cable between two such devices connects their batteries together through the "floating" Ring conductor, with unpredictable results (and possible damage).
Using a TRS from an active guitar to a "universal" input (like on some audio interfaces) designed for either unbalanced TS or unbalanced TRS may apply battery power to the interface unit.  It's probably blocked by a capacitor so as not to cause damage, but this is not guaranteed.  The guitar electronics are not likely to power on.
Using a TRS cable between an active guitar to an amplifier or between a passive guitar and a stompbox may work, but is not guaranteed.
Comment: This is absolutely true and I can confirm that a Boss RV-6 pedal won't work properly with a TRS cable!
Answer: I wouldn't use a TRS cable in a TS socket because it's a tossup whether or not R makes contact or not.  So you have a connection that will willy-nilly add a twisted core redundant core in parallel to the shield and not.  This is quite unlikely not to result in handling noise.
In addition, a TS cable is coaxial and usually intended for high-gain high-impedance connections.  A TRS cable (the twisted-pair variant for balanced connections, not a stereo cable) is not coaxial and intended for low-gain low-impedance connections.  Not being coaxial means that it has quite higher parasitic capacities and inductivities than a straight coaxial cable which has a fixed geometry and dielectric between shield and core.  This is important for high-impedance connections.
In contrast, a TS cable in a TRS socket is well-defined behavior and is often used for audio equipment that may accept balanced or unbalanced connections.
Comment: This is very interesting. Exactly the kind of electrical concerns I was wondering about. Is it then accurate to say that the S contact point position in a given jack could sometimes be contacting the R on the plug, or even bridging R and S?
Comment: Could you translate the middle paragraph into words that make sense to the man in the street, please. I'm lost.
Comment: I didn't get into it in my answer because there are too many variables in wire type used in the construction of the TRS cables.  From what I've seen in audio cables, the shielded twisted pair wire is less common than parallel cladded wire.   Seeing a detectable difference should only show up in long cable runs.
Comment: Also, if the manufacturer of the connection parts are following industry specification, then the sleeve connector should not be connecting to the ring location.   It would have to be a highly deviant input connector to do that.
Comment: @Tim A coaxial cable means that one conductor is nestled within the other; think of the wire shielding on a cable with a center conductor (like "coax" cable you use for cable television) wrapped in a plastic or synthetic material (the dielectric). What user48234 is saying is that the cable construction has certain characteristics which may be better for applications that just use TS jacks.
Comment: @AlphonsoBalvenie My sentiments exactly - I don't think my short (<5 meter) cable runs will be a problem. Also I agree that it would be highly unusual or rare to find a TS jack improperly connecting to or bridging the R. Though if problems arise, the meter will help rule that in or out!
Answer: No major reason if wired correctly, i.e. keep the shield as ground and optionally either connect the other two wires together as the hot, or use one for hot and tie the other to the shield.  You can cut one off, but might as well put it to use.
I have done both, my preference, mechanically, is if the wire has a good quality heavy shield I connect the other two to hot, if the shield is so-so I connect one wire to it and one to hot. Thin wire - both to hot.  Not any really noticeable sound difference in the two methods.
Answer: TRS cable may not work with active guitars, sometimes the additional pin causes short circuit.
Comment: It's a valid point, but could you explain more how the short circuit occurs and what is its role in guitar with active electronics?
Comment: Most guitars switches off the active circuit when no cable is plugged in to save battery. When you plug TRS jack into the plug, ring might cause a short circuit and prevent the activation of the circuit. I experienced this situation and here is a detailed explanation: https://www.talkbass.com/threads/active-bass-doesnt-work-through-focursite-scarlett.1474854/
Answer: Cutting all the nonsense - use TS for mono and TRS for balanced and appropriate cables - why? Because you don't know what the female socket on mono will touch - in ideal world, yes it should touch ground but in practice I had few cases that it was getting second leg of balanced signal (interface to amp as example). If you can't afford proper cables then I would say, try TRS and then TS - in 80%-90% cases it should be ok,  if there is difference in signal use proper one.
Comment: The stereo/mono distinction is different from the balanced/unbalanced though both can *under some circumstances* imply a change from 1 conductor + ground to 2 conductors + ground.


Ocultar caixa de clique (toque) em um site HTML5/CSS3?

Question: Estou fazendo um site para servir com um app para um trabalho na faculdade, o desing tá ok (por enquanto, e funcionou legal no smartphone.
Porém, no menu há um erro quando eu pressiono algum item do menu, uma caixa azul clara aparece, atrapalhando o desing do app, outra coisa é o hover dos
 que estão aparecendo apenas quando mantenho o dedo pressionado por bastante tempo no item. Segue a imagem do erro:

A misteriosa caixa azul atrapalha até o efeito do hover, a cor dele..
Se não for possível remove-lo, como mudo a cor da caixa? Outro erro é a demora para carregar a página (aparece uma tela branca entre esse processo), exemplo a referências, estranho, pois só as fontes estão online.
Aqui então os arquivos css e html (de um modelo) sem imagens, claro:

$(document).ready(main);

var contador = 1;

function main () {
 $('.menu_bar').click(function(){
  if (contador == 1) {
   $('nav').animate({
    left: '0'
   });
   contador = 0;
  } else {
   contador = 1;
   $('nav').animate({
    left: '-100%'
   });
  }
 });

 // Mostramos y ocultamos submenus
 $('.submenu').click(function(){
  $(this).children('.children').slideToggle();
 });
};
@import url(http://fonts.googleapis.com/css?family=Titillium+Web:200);

* {
 padding:0;
 margin:0;
 -webkit-box-sizing: border-box;
 -moz-box-sizing: border-box;
 box-sizing: border-box;
}

body {
    background-color: #F9FFF9   ;
    font-family: 'Titillium Web',sans-serif;
    text-align: justify;
}

.menu_bar {
 display:none;
    margin: 0;
}

header {
 width: 100%;
}

header#titulo h1{
    font-size: 19px;
    /*margin-bottom: 0;
    margin-top: 0;*/
    color: white;
    text-align: center;
    background: #d40000;
}

header#titulo h2{
    font-size: 13pt;
    color: white;
    background: #80c939;

    text-align: center;
}

header nav {
 background:#80c939;
 z-index:100%;
 max-width: 100%;
 width:100%;
 margin: 0;

}

header nav ul {
 list-style:none;
    margin: 0;
    text-align: center;
}

header nav ul li {
 display:inline-block;
 position: relative;
}

header nav ul li:hover {
 background:#d40000;
}

header nav ul li a {
 color: #444444;
 display:block;
 text-decoration:none;
 padding: 20px;
}

header nav ul li a:hover {
 color: white;;
}

header nav ul li a span {
 margin-right:10px;
}

nav img#logo{
    opacity: 0;
    position: relative;
    float: right;
    top: 0;
}
nav img#logo:hover{
    opacity: 1;
}

footer#final{
    clear: both;
    border-color: #80c939;
    border-style: solid;
}

footer#final p{
    font-family: 'Arial', sans-serif;
    font-size: 13px;
    text-align: center;
}

.topo{
    display: block;
    width: 30px;
    height: 30px;
    float: right;
    margin: 5px;
    position: fixed;
    bottom: 0;
    right: 0px;
}
.topo:hover{
    cursor:pointer;
}

@media screen and (max-width: 800px) {
 body {
  padding-top:60px;
 }

 .menu_bar {
  display:block;
        margin: 0;
  width:100%;
        height: 60px;
  position: fixed;
  top:0;
  background:#80c939;

 }

 .menu_bar .bt-menu {
  display: block;
  padding: 15px;
        margin: -1px;
  color: #444444;
  overflow: hidden;
  font-size: 25px;
  font-weight: bolder;
  text-decoration: none ;
 }

 .menu_bar span {
        margin-top: -13px;
        padding: -10px;
  float:right;
  font-size: 40px;

 }

    .menu_bar a{
        text-align: center;
    }

 header nav {
  width: 80%;
  height: calc(100% - 50px);
  position: fixed;
  right:100%;
  margin-top: -7px;
  overflow: scroll;

 }

    header nav::-webkit-scrollbar{
    display: none;
    }

 header nav ul li {
        height: 50px;
 display: block;
 /*border-bottom:1px solid rgba(0,0,0,.4);*/
        text-align: left;
        border: 0px;

 }

    header nav ul li span{
        border: 0px;
        margin-top: -8px;
        float: right;

    }
    header nav ul li span img{
        border-width: 0;
        border: 0px;

    }

 header nav ul li a {
        margin-top: 0px;
        font-weight: bold;
  display: block;
 }
    nav img#logo{
        opacity: 1;
        position: auto;
        float: right;

    }

}
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Menu</title>
 <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
 <link rel="stylesheet" href="../css/estilo.css">

 INICIAL

  ARTIGOS

  MULTIMÍDIA

  REFERÊNCIAS

  SOBRE

Página Inicial

Teste

© 2015 - IFTM

        Leonardo, Guilherme, Carlos V., Matheus, Victor A. e Jóse Humberto.

        Desing por Leonardo Vilarinho.

Answer: Sobre a demora no carregamento, não sei o que pode ser, sobre essa caixa, se a cor está definida no css, mude o background para transparent ou display: none; ou até mesmo opacity: 0;
Comment: Na verdade a tal 'caixa' misteriosa deveria  ser do próprio sistema do Windows Phone, e recentemente descobri que quando não manipulada pelo app ela segue a cor do tema do usuário, mas o target caiu muito bem
Comment: eu consegui diminuir isso com o :target
Comment: e conseguiu descobrir onde estava essa caixa?


Mysql queries help

Question: I have a mysql table as below..

The data in the table is as follows,

I want to get the total calorie by a user on a particular day (let's say Feb 20). I execute the below query to get the result.
SELECT sum( calorie ) AS sum
FROM test
WHERE extract(DAY FROM date ) = 20 AND extract(MONTH FROM date ) = 02
AND extract(year FROM date) = 2012
AND user_name = 'akshaynhegde';

The result I get is...1500 (as sum), which is exactly what I want. How do I execute this query in Drupal 7? I know how to execute it in Drupal 6, but I just upgraded to Drupal 7 and I am having many difficulty in executing queries.
//////////////////////MY ANSWER//////////////////////////////////
Here is a working Drupal & style code for the above query...
<?php
$query = db_select('test', 't')
->condition('t.user_name', 'akshaynhegde', '=');
$query->addExpression('SUM(calorie)', 'sum');
$query->where('EXTRACT(DAY FROM date) = :day', array('day' => '20');
$query->where('EXTRACT(MONTH FROM date) = :month', array('month' => '02');
$query->where('EXTRACT(year FROM date) = :year', array('year' => '2012');
$result = $query->execute()->fetchAll();
?>

Comment: Have you taken a look at this? http://api.drupal.org/api/drupal/includes!database!database.inc/function/db_query/7
Answer: You could use db_query() in your template file:
function theme_get_calories($user, $year, $month, $day) {
   $result = db_query("SELECT sum( calorie ) AS sum
                      FROM test
                      WHERE extract(DAY FROM date) = :day
                      AND extract(MONTH FROM date) = :month
                      AND extract(year FROM date) = :year
                      AND user_name = :user",
                      array(
                        ':day' => $day,
                        ':month' => $month,
                        ':year' => $year,
                        ':user' => $user
                      )
   )->fetch();
   return $result;
}

Comment: I have got the drupal 7 style code for the above query. Since I cant answer the question, am editing the question with my answer.
Comment: @akshaynhegde Dynamic queries are not more Drupal 7 style than static queries. Dynamic select queries should be used for queries you want to be altered from other modules. If you look at Drupal code, most of the queries are static, as the one reported in this answer.

Mysql queries help


How to provide storekit content?

Question: For my app i have it far enought that it will ask for a confirmation and account for an in-app purchase, but I don't know how to enable the item after the purchase is complete.
<code>SKPayment *payment = [SKPayment paymentWithProductIdentifier:@"com.silver.tapp.page2"];
</code>
[[SKPaymentQueue defaultQueue] addPayment:payment];
Thats what i have so far
<code>[[p2Controller tabBarItem] setEnabled:TRUE];
</code>
this is the code i would like to execute
Answer: First you should really go back and review the In App purchase documentation that Apple provides - they outline this in detail and it's useful to understand what is being done on their side.
What you are missing is the SKPaymentTransactionObserver - it's your responsibility to implement this observer which you add as an observer of the SKPaymentTransactionQueue.  Apple recommends that you add the observer at app launch to the default queue so that it will be able to observe all transactions that take place while your app is running.
Essentially you need to write your own class that implements the SKPaymentTransactionObserver protocol.  What this class does is observe catch the callbacks from the payment queue when the iTunes store processes the payment and let's you catch the success and failure events.
Here is the skeleton for the Payment Observer:
PaymentObserver.h
<code>#import <StoreKit/StoreKit.h>

@interface PaymentObserver : NSObject <SKPaymentTransactionObserver> {
}

- (void) completeTransaction: (SKPaymentTransaction *)transaction;
- (void) restoreTransaction: (SKPaymentTransaction *)transaction;
- (void) failedTransaction: (SKPaymentTransaction *)transaction;

@end
</code>
PaymentObserver.m
<code>#import "PaymentObserver.h"
@implementation PaymentObserver

- (void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray *)transactions
{
  // handle payment cancellation
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
  // handle the payment transaction actions for each state
  for (SKPaymentTransaction *transaction in transactions)
  {
    switch (transaction.transactionState)
    {
      case SKPaymentTransactionStatePurchased:
        [self completeTransaction:transaction];
        break;
      case SKPaymentTransactionStateFailed:
        [self failedTransaction:transaction];
        break;
      case SKPaymentTransactionStateRestored:
        [self restoreTransaction:transaction];
      default:
        break;
    }
  }
}

- (void) completeTransaction: (SKPaymentTransaction *)transaction;
{
  // Record the transaction
  //...

  // Do whatever you need to do to provide the service/subscription purchased
  //...

  // Remove the transaction from the payment queue.
  [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

}

- (void) restoreTransaction: (SKPaymentTransaction *)transaction
{
  // Record the transaction
  //...

  // Do whatever you need to do to provide the service/subscription purchased
  //...

  [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
  if (transaction.error.code != SKErrorPaymentCancelled)
  {
    // Optionally, display an error here.
  }
  [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

@end
</code>
Once you have implemented the PaymentObserver you need to add an instance off it to the default payment queue as a transaction observer.
<code>// Done at app launch...
PaymentObserver *paymentObserver = [[PaymentObserver alloc] init];
[[SKPaymentQueue defaultQueue] addTransactionObserver:paymentObserver];
</code>
Comment: hey, this answer saved my bacon today.  Sure it's in the apple docs, but I was trying to fix a bug in code written by another developer and looking at this, I was able to see what he had missed.  Thank you!

How to provide storekit content?


Mongoose doesn't save model

Question: I'm using mongoose to define my models and save it to my MONGODB cluster.
everything looks fine, but when I post request to my route to save the user model the post request loading process vill no complete :(
This is the Main file :
const express = require("express");
const app = express();

const bodyParser = require("body-parser");
app.use(bodyParser.json());

// DATABASE CONNECTION
const mongoose = require("mongoose");

mongoose.connect(
  connectionString,
  {
    useNewUrlParser: true
  },
  () => {
    console.log("database connected!");
  }
);

// ROUTES
const userRoute = require("./routes/user");
app.use("/", userRoute);

const port = 4040;
app.listen(port, err => {
  if (err) console.log(`Listening faild`);
  console.log(`Listening on PORT ${port}`);
});

This is my routes/user.js :
const router = require("express").Router();

const User = require("../models/user");

router.post("/reg", (req, res) => {
  const user = new User({
    phone: req.body.phone,
    pin: req.body.pin,
    fullName: req.body.FullName
  });

  user
    .save()
    .then(data => {
      res.json(data);
      console.log(data);
    })
    .catch(err => {
      res.json({
        message: err
      });
      console.log(err);
    });
});

module.exports = router;

and this the model of users object :
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = Schema({
  phone: Number,
  pin: Number,
  fullName: String
});

module.exports = mongoose.model("User", userSchema);

Comment: is the Mongo operation completed successfully? do you see the `data`?
Comment: @YoniMayer Database is connected, and i don't see any collection datas in mongodb atlas .
Comment: did you connect to the DB with `mongoose.connect()` ?
Comment: @YoniMayer yes i did.
Comment: Can you add `console.log(req.body) ` before save. And put the other console logs before res.json? Also can you add your main file to the question?
Comment: @SuleymanSah , i did bro, it responded me the JSON data.
Comment: So, post route responds but you see no document in your users collection?
Comment: yup, it's true.
Comment: Be sure that you are checking the correct database and collection, it must be the database which the application uses.
Comment: So the only problem is database connection?
Comment: @tafhim Did you try it in the mongo shell and see any collections?
Comment: @metalHeadDev I don't use mongo shell, I used MongoDB closter cloud, it was okay before, idk what is the problem now
Answer: You haven't defined connectionString.
It should look something like this - mongodb://username:password@host:port/database?options... or in localhost - mongodb://localhost:27017/database
Comment: I defined, I just didn't write it here
Comment: Honestly, I can't see any problem. Just check the path in user.js `const User = require("../models/user");`. Apart from that you gotta do yourself, sorry mate.

Mongoose doesn't save model


How to set end date relative to start date in date range field

Question: Is it possible to set the end date relative to the selected start date in a D8 date range field?
I have a date range field that I use to specify an accounting period. The end date should now be put to one year minus one day from the selected start date. For example, the start date 2016-07-01 will give the end date 2017-06-30.
How is this possible?
Answer: The current widgets in core for the Datetime Range module do not allow this.
You would need to create a custom widget for this.  Off the top of my head, I would create one that extends DateRangeWidgetBase() and mostly mirrors what DateRangeDefaultWidget() does, except to collect a relative period in a plain text field for the end date.  Then, add a massageFormValues() function to turn the relative date into an absolute one, and then call parent::massageFormValues().  You may also be able to do this with a #process callback on the end date element, but I forget which of the two runs first during form processing.
Comment: @leymannx The timestamp/datetime/daterange default widgets use HTML5 elements, which complicate matters.  You also need to convert to a proper date before the massageFormValues (which tweaks the values for date-only and sets the storage time zone) and validation (which is at both the element and widget level) runs.  This is messy in a node form alter.  Doing this as a new field Widget is the easiest option.
Comment: And as a side note, if you get this working, it would be a great addition to the https://www.drupal.org/project/datetime_extras module if you post it as a patch.
Comment: And just altering the node form and adding a custom submit to populate the end field? Couldn't that work as well?


How to disable cursor in textbox?

Question: Is there any way to disable cursor in textbox without setting property Enable to false?
I was trying to use ReadOnly property but despite the fact that I can't write in textbox, the cursor appears if I click the textbox. So is there any way to get rid of this cursor permamently?
Answer: In C#, you can use the following read-only textbox:
public class ReadOnlyTextBox : TextBox
{
    [DllImport("user32.dll")]
    static extern bool HideCaret(IntPtr hWnd);

    public ReadOnlyTextBox()
    {
        this.ReadOnly = true;
        this.BackColor = Color.White;
        this.GotFocus += TextBoxGotFocus;
        this.Cursor = Cursors.Arrow; // mouse cursor like in other controls
    }

    private void TextBoxGotFocus(object sender, EventArgs args)
    {
        HideCaret(this.Handle);
    }
}

Comment: Why set the `BackColor`? Windows already takes care of this to match the user's system theme.
Comment: This worked perfectly for a RichTextBox where I was having a similar issue.  The code in ReadOnlyTextBox() is superfluous.
Answer: In C# you can disable the cursor in a textbox by temporarily disabling and then re-enabling the text box whenever it receives the focus. Note there is no need to make the textbox read only if using this method. For example:
private void TextBox_Enter(object sender, EventArgs e)
{
  TextBox.Enabled = false;
  TextBox.Enabled = true;
}

Comment: This does the job, but then you can't select the text to copy it.
Answer: You could use a Label instead. When in the designer, you set BorderStyle = Fixed3D, BackColor = Window and AutoSize = False, it looks a lot like a TextBox.
However, the cursor in a TextBox is provided so that the user can scroll through the text when it is longer than the box. You'll lose that functionality with a Label, unless you are sure that it will always fit. Other than that, it is not possible to remove the cursor from a TextBox.
Comment: A ReadOnly textbox is also useful for displaying information that the user might want to copy and paste somewhere else. By using a Label (or otherwise disabling the cursor) that ability is lost or reduced. But if you truly want to display information without the ability to select it, then a Label is the right tool for the job.
Comment: @JeffreyLWhitledge I know this is an old question but just to weight in, what happens if the user requires scrollbars on a label?
Comment: @KyleT: If you have a sufficiently big amount of text that you require scroll bars, then I suggest you still use a `TextBox` instead, and set it's `ReadOnly` property to `true`. The cursor in there is actually nice to have, since it allows the user to select parts of the text without editing it.
Answer: Putting the hideCaret function inside the TextChanged event will solve the problem:
[DllImport("user32.dll")]
static extern bool HideCaret(IntPtr hWnd);

private void textBox1_TextChanged(object sender, EventArgs e)
{
    HideCaret(textBox1.Handle);
}

Answer: Easiest solution for me was to just override the on focus event and focus back to the parent. This prevents the cursor and any editing of the textbox by the user and basically disables the text box with out having to set the Enabled = false property.
private void Form1_load(object sender, EventArgs e) {
    textBox1.ReadOnly = true;
    textBox1.Cursor = Cursors.Arrow;
    textBox1.GotFocus += textBox1_GotFocus;
}

private void textBox1_GotFocus(object sender, EventArgs e) {
    ((TextBox)sender).Parent.Focus();
}

Answer: Like @Mikhail Semenov 's solution, you can also use lambda express to quickly disable the cursor if you do not have many textboxes should do that:
[DllImport("user32.dll")]
static extern bool HideCaret(IntPtr hWnd);

textBox1.ReadOnly = true;
textBox1.BackColor = Color.White;
textBox1.GotFocus += (s1, e1) => { HideCaret(textBox1.Handle); };
textBox1.Cursor = Cursors.Arrow;

Comment: :The GotFocus event helped me. Thanks!!
Answer: You can set it programatically.
textBox1.Cursor = Cursors.Arrow;

Answer: This is not strictly an answer to the question, but perhaps it can solve some similar problem(s). I use a textbox control which can look like a label for a control which displays a scale, but can be edited, when clicked. Start enabled = false and make an activation (enabled = true) in a mousehandler of the parent of the textbox control (which, when disabled, border None and backcolor = parent backcolor, looks like a label). E.g. when enter hit or other event, disable again in KeyDown handler.
(Of course the parent mouse click routine can check whether the mouseclick really occured in the label/textbox control).
If you need the textbox control to activate by tabbing, some more work is required (than I have done).
I use the form constructor to find the textbox parent at runtime and to apply the delegate mouse control. Perhaps you can do this as wel in compile time (Form header), but that seemed a little error-prone to me.
Answer: One way of doing it is using View + TabIndex, you can do indexing of some other controls on the dialog as first, let say for buttons if there any. Then as if the control tabIndex is not the first i.e 0, cursor won't get appear there.
Answer: To disable the edit and cursor in the TEXT BOX
this.textBox.ReadOnly = true;
this.textBox.Cursor = Cursors.No;//To show a red cross icon on hover
this.textBox.Cursor = Cursors.Arrow //To disable the cursor

Answer: I used the following that works as it was suggested by Troublesum.
And yes to set TabStop to false as prerequsite helps.
    this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.CustomTextbox_KeyPressed);
    ...
    private void CustomTextbox_KeyPressed(object sender, KeyPressEventArgs e) {
        if ( (Keys)e.KeyChar == Keys.Enter ) {
            ...
            e.Handled = true;
            ((TextBox)sender).Parent.Focus();
        } else {
            ...
        }
    }

Answer: you can use RightToLeft Property of Text Box, set it to true, you will not get rid of the Cursor, but it will get fixed at right corner and it will not appear automatically after every text you type in your text Box. I have used this to develop an application like Windows Calculator.
Comment: Only makes things worse. Also changes alignment, the cursor still appears where you click and selecting text is... strange.

How to disable cursor in textbox?


Drupal login error message display on page by make new module

Question: I created the module and added the field in the user login block form for displaying error. I want to display the error in warning field instead of using form_set_error(). I am able to see the warning field in the login block. When I submit with error it did not display the error. Code is as under. I am missing how to refresh the value of form once it gets error.
function usermoved_form_user_login_block_alter(&$form, &$form_state) {
$form['warning'] = array(
'#value' => t('oops'),
'#weight' => 11
);
$form['#submit'][] = 'usermoved_form_submit_code';
}

function usermoved_form_submit_code($form, &$form_state)
{
  global $user;
 if (!$user->uid) {
  $form['warning']['value']= "changed to something";

}

}

I have disabled the error in user.module as follows.
function user_login_final_validate($form, &$form_state) {
  global $user;
   if (!$user->uid) {
//form_set_error('name', t('Sorry, unrecognized username or password. Have you forgotten your password?', array('@password' =>
    //url('user/password'))));
}
}

Comment: it is not recommended to modify a core module directly as it can cause potential security risk or loss of functionality while upgrading, you could choose to remove `user_login_final_validate` from the `#validate` array of the form, please refer to modules such as [logintoboggan](http://drupal.org/project/logintoboggan/) to get better idea of how to implement custom validation without hacking the core module
Answer: I suggest you DO NOT CHANGE DRUPAL CORE , if you want your custom validation use something like this
function usermoved_form_user_login_block_alter(&$form, &$form_state) {
   $form['warning'] = array(
   '#value' => t('oops'),
   '#weight' => 11
   );
  $form['#submit'][] = 'usermoved_form_submit_code';
  $form['#validate'][] = 'yourcustomvalidationfunction';
     }

and in your custom validate fuction  put your error in warning field
 function   yourcustomvalidationfunction(&$form,&$form_state){
    if (your validation accure error) {
        $form['warning']['#value']= t('my error message that come in warning field') ;
       }
    }

or you can  create and initial warning  directly in validation function and not require create warning field in alter
Comment: Also see form_set_error()
Comment: @AyeshK,please read qustion again.:)
Comment: Oh, unlocked new badge: Stupidness.
Comment: :(.not say this. just say young Ayesh Karunaratne :)
Comment: @AyeshK , please sign this as accepted
Comment: I'm sorry I'm not the OP. However, in the second snippet, I think you will need to add the error message to #value. $form['warning'] expected to be an array (of form element's definitions) right ?
Comment: @AyeshK yes , I wrote it according to question, maybe I had better method ,but write it according you question. I edit it


How to get my function to increase variable "_time"

Question: // videogame.js
// don't forget to validate at jslint.com

/*jslint devel: true, browser: true */
/*global $*/

$(function () {
    "use strict";

    // global functions

    function boundaryCheck(element_selector) {
        var element = $(element_selector);
        var universe = $("#universe");
        var p = element.position();
        if (p.left < 0) {
            element.css("left", "0px");
        }
        if (p.top < 0) {
            element.css("top", "0px");
        }
        if (p.left + element.width() > universe.width()) {
            element.css("left", (universe.width() - element.width()) + "px");
        }
        if (p.top + element.height() > universe.height()) {
            element.css("top", (universe.height() - element.height()) + "px");
        }
    }

    function getRandomInt(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min)) + min;
    }

    // Constructor for Player Ship object
    function PlayerShip() {

        var my = {};

        $("#universe").append($("
").attr("id", "player"));

        my.navigate = function (keys) {
            var RIGHTARROW_KEYCODE = 39;
            var LEFTARROW_KEYCODE = 37;
            var UPARROW_KEYCODE = 38;
            var DOWNARROW_KEYCODE = 40;
            if (keys === RIGHTARROW_KEYCODE) {
                $("#player").css("left", "+=10px");
            }
            if (keys === LEFTARROW_KEYCODE) {
                $("#player").css("left", "-=10px");
            }
            if (keys === UPARROW_KEYCODE) {
                $("#player").css("top", "-=10px");
            }

            if (keys === DOWNARROW_KEYCODE) {
                $("#player").css("top", "+=10px");

            }
            boundaryCheck("#player");
        };

        return my;
    }

    // Constructor for Enemy Ship object
    function EnemyShip() {

        var my = {};

        $("#universe").append($("
").attr("id", "enemy"));

        my.move = function (paused) {
            if (!paused) {
                var left = Boolean(getRandomInt(0, 2));
                var top = Boolean(getRandomInt(0, 2));
                if (left) {
                    $("#enemy").css("left", "-=" + getRandomInt(1, 10) + "px");
                } else {
                    $("#enemy").css("left", "+=" + getRandomInt(1, 10) + "px");
                }
                if (top) {
                    $("#enemy").css("top", "-=" + getRandomInt(1, 10) + "px");
                } else {
                    $("#enemy").css("top", "+=" + getRandomInt(1, 10) + "px");
              }
                boundaryCheck("#enemy");
            }
        };

        return my;
    }

// this might make an asteroid happen, maybe. I don't know if it will work.
    function Asteroid() {

      var my = {};

      $("#universe").append($("
").attr("id", "asteroid"));

      my.move = function (paused) {
        if (!paused) {
          var left = Boolean(getRandomInt(0, 2));
          var top = Boolean(getRandomInt(0, 2));
          if (left) {
              $("#asteroid").css("left", "-=" + getRandomInt(1, 10) + "px");
          } else {
              $("#asteroid").css("left", "+=" + getRandomInt(1, 10) + "px");
          }
          if (top) {
              $("#asteroid").css("top", "-=" + getRandomInt(1, 10) + "px");
          } else {
              $("#asteroid").css("top", "+=" + getRandomInt(1, 10) + "px");
          }
          boundaryCheck("#asteroid");
        }
      };
        return my;
    }

    // Constructor for Game object
    function Game() {

        // total points
        var _health = 1000;

        var _time = 0;

        // is the game paused?
        var _game_paused = false;

        // speed of background animation in ms (larger = slower)
        var _background_speed = 100;

        // player ship
        var _player_ship = new PlayerShip();

        // enemy ship
        var _enemy_ship = new EnemyShip();

        var _asteroid = new Asteroid(); //make this an actual thing

        var my = {
            health: _health,
            time: _time,
            game_paused: _game_paused,
            background_speed: _background_speed,
            player_ship: _player_ship,
            enemy_ship: _enemy_ship,
            asteroid: _asteroid
        };

        $("#universe").append($("
").attr("id", "results"));
        $("#results").append($("
"));
        $("#universe").append($("
").attr("id", "results2"));
        $("#results2").append($("
"));

        my.health = function (value) {
            if (value === undefined) {
                return _health;
            }
            _health = value;

            return my;
        };

        my.time = function (value) {
          if (value === undefined) {
            return _time;
          }
          _time = value;

          return my;
        };

        my.game_paused = function (value) {
            if (value === undefined) {
                return _game_paused;
            }
            _game_paused = value;

            return my;
        };

        my.background_speed = function (value) {
            if (value === undefined) {
                return _background_speed;
            }
            _background_speed = value;

            return my;
        };

        my.player_ship = function (value) {
            if (value === undefined) {
                return _player_ship;
            }
            _player_ship = value;

            return my;
        };

        function runtimer() {
          _time++;
        };

        my.enemy_ship = function (value) {
            if (value === undefined) {
                return _enemy_ship;
            }
            _enemy_ship = value;

            return my;
        };

        my.asteroid = function (value) {
          if (value === undefined) {
            return _asteroid;
          }
          _asteroid = value;

          return my;
        };

        // METHODS

        // display total points
        my.displayHealth = function () {
            $("#results h1").html("Health: " + _health);
        };

        my.increaseTime = function () {
          setInterval(function(){ runTimer() }, 1000)
        }

        my.displayTimer = function () {
          $("#results2 h1").html("Time: "+ _time);
        };

        my.moveBackground = function () {
            if (!_game_paused) {
                var background_position = $("#universe")
                    .css("backgroundPosition")
                    .split(" ");
                var current_x = parseInt(background_position[0], 10);
                var current_y = parseInt(background_position[1], 10);
                var new_x = current_x - 1;
                var new_y = current_y;
                $("#universe").css({
                    "background-position": new_x + "px " + new_y + "px"
                });
            }
        };

        my.checkKeys = function () {
            var ESCAPE_KEYCODE = 27;
            $(document).keydown(function (key_event) {
                if (key_event.which === ESCAPE_KEYCODE) {
                    if (_game_paused) {
                        _game_paused = false;
                        $("#pause").remove();
                    } else {
                        _game_paused = true;
                        var pause = $("
", {id: "pause"});
                        $("body").prepend(pause);
                    }
                } else {
                    _player_ship.navigate(key_event.which);
                }
            });
        };

        my.checkCollisions = function (paused) {
            var p = $("#player");
            var e = $("#enemy");
            var ppos = p.position();
            var epos = e.position();
            if (!paused) {
                if (
                    (
                        (ppos.left + p.width() < epos.left) ||
                        (ppos.left > epos.left + e.width())
                    ) ||
                    (
                        (ppos.top + p.height() < epos.top) ||
                        (ppos.top > epos.top + e.height())
                    )
                ) {
                    return false;

                } else {
                    return true;
                }

            }
        };

        my.checkAsteroid = function (paused) {
            var p = $("#player");
            var a = $("#asteroid");
            var ppos = p.position();
            var apos = a.position();
            if (!paused) {
                if (
                    (
                        (ppos.left + p.width() < apos.left) ||
                        (ppos.left > apos.left + a.width())
                    ) ||
                    (
                        (ppos.top + p.height() < apos.top) ||
                        (ppos.top > apos.top + a.height())
                    )
                ) {
                    return false;

                } else {
                    return true;
                }

            }
        };

        my.play = function () {
            _enemy_ship.move(_game_paused);
            _asteroid.move(_game_paused);
            if (my.checkCollisions(_game_paused)) {
              _health --;
              my.displayHealth();
            }  else if (
            my.checkAsteroid(_game_paused)) {
                _health --;
                my.displayHealth();
            }
        };
        return my;
    }

    var game = new Game();

    game.checkKeys();
    game.displayHealth();
    game.displayTimer();
    game.increaseTime();
    setInterval(game.moveBackground, game.background_speed);
    setInterval(game.play, game.background_speed);
});

I'm relatively new to programming. I took a class in high school, which was very mediocre. I'm now taking some starter courses in college, and my assignment is to improve a generic space game (which I have already started doing). I have a div for the timer, but for some reason, I can't get any functions to increase the _time variable. It's almost as though they're not allowed to access it. I have a function called "runTimer", which is supposed to increase "_time" by one every time it is run. I have another function called "increaseTime", which is supposed to run "runTimer" every 1000 milliseconds. The variable never seems to increase though. This hasn't been my first spaghetti code implementation of a timer, since I've tried various things over the past few hours. I just can't understand why the variable won't increase.
Comment: Please see [*How do I ask a good question?*](https://stackoverflow.com/help/how-to-ask) and [*How to create a minimal, complete and verifiable example*](https://stackoverflow.com/help/mcve). As written, this is likely to be closed as being too broad. Isolate your issue to the smallest amount of code that demonstrates the problem and post that.
Answer: This is a big hunk of code. As RobG pointed out, try to work on paring back your question to the minimal, complete, and verifiable example you can.
That said, at a glance, it would appear that your timer probably is updating. At least _time is.
The problem is likely you are never re-drawing your div, so it isn't showing the updated value. You need to call game.displayTimer() every time _time updates.
Probably the easiest place to add it would be in your setInterval() in increaseTime():
my.increaseTime = function () {
  setInterval(function(){
    runTimer();
    my.displayTime();
  }, 1000)
}


Preciso pegar uma coluna com varias informações redundantes e pegar apenas uma delas

Question: Possuo uma combo-box onde necessito que ele percorra a coluna "A" e pegue apenas uma informação de cada (pois possue redundância dela), um exemplo seria departamente no caso há redundancia e não usa-se uma chave primária
O código que alimenta a combo-box:
Public Function carregaCombobox()
    cmbDepartment.Clear
    Worksheets("Full Control").range("A3").Select
    Dim itemLista As String
    Do While ActiveCell.Value <> ""
        If verificaItem(ActiveCell.Value) = False Then
            itemLista = ActiveCell.Value
            If cmbDepartment.ListCount >= 2 Then
                 cmbDepartment.AddItem itemLista
            Else
                cmbDepartment.AddItem itemLista
            End If

        End If
         ActiveCell.Offset(1, 0).Select
    Loop

End Function

Porém quando executo ele retorna um erro: '381': Could not get the
  List Property. Invalid property array index.

Ele possui uma função para verificar se existe ou não a informação que ele pega da célula selecionada pelo Do While que é esse:
Public Function verificaItem(itemPlanilha As String) As Boolean
    Dim i As Long
    Dim itemLista As String
    verificaItem = False
    If cmbDepartment.ListCount > 0 Then
        For i = 0 To cmbDepartment.ListCount
            itemLista = cmbDepartment.List(i, 0)
            If itemLista = itemPlanilha Then
                verificaItem = True
                Exit Function
            End If
        Next i
    End If
End Function

Exemplificando:
Tenho essas informações em uma coluna

  A
Parede
Parede
Teto
Teto
Parede
Chão

E quero apenas as informações sem repeti-las em uma combo-box
  aparecendo então assim

Parede
Teto
Chão

Comment: Não sei se entendi direito. Você deseja inserir valores não duplicados na ComboBox?
Comment: Não, eu tenho valores duplicados na tabela, porém eu só quero um deles, por exemplo tenho assim (valor1, valor1, valor1, valor2, valor2, valor1)-> gostaria de pegar apenas assim (valor1,valor2) entendeu?
Answer: Se o ComboBox estiver num formulário, o código deve ser inserido na Subrotina Private Sub UserForm_Initialize() para carregar os dados da ComboBox ao inicializar o formulário.
Código
Dim x As Long, ncell as Long
Dim Rng As Range, c As Range
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("nome_planilha")

With ws

    ncell = .Cells(.Rows.Count, "A").End(xlUp).Row
    Me.ComboBox1.Clear

    For y = 1 To ncell
        Set c = .Cells(y, 1)
        Set Rng = .Range(.Cells(2, 1), .Cells(y, 1))
        x = Application.WorksheetFunction.CountIf(Rng, c)
        If x = 1 Then Me.ComboBox1.AddItem c
    Next y
End With

Variáveis
Este código realiza um loop e verifica a quantidade de valores em que a string da célula atual aparece, com a função CountIf. Adiciona ao ComboBox somente na primeira vez em que a string aparece na coluna.

ws: é a variável com a planilha em que os dados se encontram
ncell: é a última linha preenchida da coluna "A"
c: é a célula atual em que o loop é realizado
x: é a quantidade de elementos daquela string presentes no intervalo
Rng: é o intervalo, que é incrementado a cada loop

Obs.: Este código realiza um loop em cada linha por ser mais fácil. Se a quantidade de dados for muito grande, é necessário preencher um array com os dados da coluna e obter os dados únicos no vetor, um exemplo de função que pode ser utilizada:

Public Function unicoArr(ByRef Arr As Variant, x As Long) As Object
    Set unicoArr = New Collection
    Dim a
    Dim i As Long

    On Error Resume Next
    For i = LBound(Arr) To UBound(Arr)
        a = Arr(i)(x)
        unicoArr.Add a, a
    Next

End Function

Comment: Muito obrigado, consegui com esse código, me ajudou muito


Amazon EC2: how would I configure EC2 for a global public web app?

Question: I have a web app that's accessed by a global audience:  33% Asia, 33% Europe, 33% North & South America.  The Ubuntu web tier (5 physical servers loaded balanced using F5) and data tier (clustered MySQL) are currently hosted in the US.  We expect to grow from 200K to 1 million users over the next year.  I'm unclear on how to select Region and map my physical configuration to AWS.  What would be a high level AWS solution for this configuration?
Answer: have been thinking about this, but have not implimented it, so these are just ideas...

I would use Amazons RDS Service for storing my Data. Let them manage it. use the replication feature to replicate it around the world to different data centers. for redundancy, you might want to have 2 read replicas in each data center you want to run in. you could have your master sitting in the US, and slaves in Dublin and Tokyo... not sure how much of a Lag there would be replicating, but it should work...
each front end server should talk to the local DB for reads. if you are doing lots of writes, these should be sent back to the master asynchronously. Ideally, when a write should occur, it should be stored in a local cache of some sort (memcache). there will be a lag, but depending on how many writes you get, it might be acceptable...
infront of the front end servers, stick something like Varnish. each varnish server should have a dedicated IP address. using GeoIP (Zerigo now offer it quite cheap... about $20 a month) you can load balance world wide.

again, these have not been put into practice... these are just ideas i have had if i where going global...
Comment: Thanks.  The one point I'm unclear about is how to load balance across regions.  For example, I have web servers in the US, Europe and Asia.  So how I do route/load balance requests from each region to the local web server?  I'll ask a new question on this.
Comment: so, you have load balancers or web servers in each region, each with a public IP (preferably static). using the Zerigo DNS service, you tell them all your publicly available IPs and they do the GeoIP stuff... if you have multiple servers in each country, Amazon will manage the load between them if you use their load balancer, but Zerigo will manage externally facing servers. not sure if they check load though...


What techniques do you use to read sheet music faster

Question: As I'm learning piano without any teacher due to lack of resources, I wanted to know what techniques other people employ to read sheet music without much effort. For example, right now, I use the landmarking system
to read as fast I can, but I still feel like it's not that "natural" and spontaneous. Also, I want to know how to read music which requires both hands. Looking at two staves is very very tough for me.
What kind of sheets should I go for? I am a bit comfortable with treble clef and bass clef but still, it's only been 2 months since I started playing the piano it'd be great if you can share any resource or suggest any resource to practice. Thanks!
Comment: It's not about selecting the right product such as a system ... it's about training. :) It takes time and effort. You spend a lot of time practicing, and then you get better at it.
Comment: Practice, practice, practice.  Read something new every day.
Comment: What I did was playing some games online about identifying randomly generated notes. Although it initially took me 3 seconds to identify the notes, I can now identify most of them for more or less a second. Just make sure you don't push it: practice for a few minutes then try again tomorrow for example. Your brain will have taken the time to assimilate what you learnt.
Answer: Take heart!  What you're trying to learn is difficult, and takes a lot of time and practice.
One particular difficulty is in finding your place in the score again after you've looked down at your hands.  (Note that every pianist looks down at their hands at some stage in learning a piece - the effortlessness you see in the concert hall hides the hundreds of hours of practice which created it).  Pay a lot of attention to bar-lines; be aware of which bar you "are" in, in which system on the page.  (A "system" is a number of staves linked together because they're played simultaneously.  For an orchestral score it might be up to 50 staves - for piano music it's almost always 2.  Piano sheet music tends to have about 4-6 "systems" per page).
So think to yourself "second system, third bar", for example.  When this becomes easier, become aware of where you "are" within the bar.  First beat, second beat?  Halfway through?
If this sounds like thinking about too many things at once (over and above playing!), that's because that's exactly what it is.  It's hard.
The ultimate way to sightread is to aggregate.  If this is your native language, you won't be reading every letter or even every word in this sentence.  You might take in one of these short paragraphs "in one go".
Music is exactly the same.  At the moment I'm learning Polish, which puts me in a similar position to you.  At first what I read is just a mass of random letters (with far too many consonants!).  Now I'm beginning to see not letters but sounds, syllables and words.  If I get (much) better at it, I'll start to see phrases; sentences; ideas and arguments spanning many sentences.
In language and in music, the link between symbol, sound and meaning (what does "na" do in this Polish sentence?  What does the note G do in this context?) is crucial.  By learning how to sight-read more quickly, that is effectively what you're trying to learn. Just as I have to mouth Polish words (under my breath if necessary), you have to play what's on the page to learn how to read it.  Which is tough, because you're learning how to play at the same time.  When you get very good at it you can sightread music, and even start learning a piece, without a piano or even without moving your fingers.  But before then, the link between reading, playing, hearing what you play and knowing that you've got it right (because it sounds right) is vitally important.
However good anyone's sight-reading is, it can be pushed back to close to zero when you encounter a different "language".  Just like me with Polish.  My teacher once gave me a Bartók piece to learn: I had to read it note by note.  But, oddly, after a few weeks I could to some extent "speak Bartók", and tell when I'd made a mistake.
To make progress, here are some tips:

Choose your music carefully.  It has to be music you can rely on to clearly tell you when you get something wrong - by sounding clearly wrong.  Beginner classical music is very good for this.  Pop/theme-tune arrangements can be very difficult.  They can sound awful, because they're badly transcribed for piano, or because, for them to sound good,  the pianist has to "vamp" or improvise rather than playing exactly what's written (which is a whole other can of worms!).  Also, this kind of music, though familiar to the ear, can be very complex musically.
Little and often.  Practice sight-reading on small pieces well below your playing ability.  It's much better to sight-read 4 simple bars every day, than to struggle with 20 complex bars once a week.

In the UK exams are set by the Associated Board (ABRSM).  Their sight-reading tests, at each level, are way below the difficulty level of the exam pieces themselves.  That's a clue to how difficult sight-reading is.  ABRSM publish books of specimen sight-reading tests, at various levels.  They are great for practising: they can be just 4 simple bars, but there are a lot of them in each book.
Good luck!
Answer: There are no shortcuts. With enough practice and time, reading sheet music will come more naturally.
If you want more focused practice on note reading, Teoria has an online exercise you can use to practice. It has a bunch of options you can change to your liking (types of notes, clef, etc.).
Comment: It's the same method as getting to play in Carnegie Hall or winning the Van Cliburn competition: practice, practice, practice. I got a bunch of graded pieces and started going through them in increasing difficult order. It took some time; it worked.
Answer: The main techniques are to look ahead and to identify patterns rather than individual notes.  As the other answer says, there are no magic shortcuts to developing these skills.  However, focusing on certain aspects of the skill can help you acquire it more efficiently.
The second skill is analogous to reading an alphabetic script.  In the early days of learning to read, you learn the sounds of the individual letters, and when you see, for example, cat, you put the three sounds together and hope that you recognize a word.  But fluent readers don't read like that anymore.  They recognize the shape of entire words all at once.  Similarly, a pianist who reads fluently will look at a measure or more and translate a series of notes into a hand position and fingering.
Of course the ability to process more beats or measures at once enables the reader to read ahead, so these two elements of sight reading technique are closely related.
As with reading alphabetic scripts, the mind learns to do this on its own, with practice.  But a conscious effort to look at larger groups and to look farther ahead can certainly help.  This should also help with your problem of reading multiple staves simultaneously.  Even if you're reading each staff separately, the ability to read ahead will allow you to keep up, as it were.  Eventually, as your focus widens, you'll be able to see patterns across staves and therefore to read both at once.
I am unfamiliar with particular methods of teaching sight reading, but I would definitely look for methods that pay attention to these considerations.
Comment: 2 months is very little time to actually becoming great at this. Take your time and play slowly and practice practice practice.
Comment: @hakiki_makato A lot of people run down Czerny, but I think his easy works, like the _Recreations_ make nice sight reading material.
Comment: what kind of sheets should I go for? I am a bit comfortable with treble clef but still, it's only been 2 months since I started playing it'd be great if you can share any resource or suggest any resource! Thanks!
Comment: Reading music is probably about as hard as reading English. You didn't learn that in 2 months. Be patient, it will come! (Not that I'm an expert, just slowly getting a bit better over the years...)
Answer: When I was starting out with piano (I actually used a beginner's book, which might be helpful for you too!), I didn't memorize the notes right away. Rather, I learned how the notes are found on the staff for each clef (bass and treble) and literally counted the lines and spaces to find the right note. Even with just playing simple songs I was able to remember them pretty quickly, and associate the line/space with the key on the keyboard as well.
Here's a really quick explanation of what I learned at the beginning:
you know the order of the notes is ABCDEFG repeat (which is alphabetical order, and I mention that because apparently my brother didn't even notice this after 2 years of learning piano). In treble clef (image below) the second line that the clef sort of curls onto is the G above middle C, so you can use that to find the other notes (i.e. the space above G is A, the line above A is B, the space above that is C). This is a failsafe strategy, and it may seem time consuming, but if you practice then you'll start to remember the notes. Bass clef is the same, except the dot in center of the curve lies on the F below middle C.
Answer: This is an interactive sight reading training software, which doesn't do both hands (it's for all instruments, not specifically piano) but which allows gradual increase in difficulty, notes range, rhythmic elements, etc. You should probably give it a good look and see if it can help you develop better reading skills on both hands individually. Once reading for both hands individually has become almost effortless, it will be much easier to read both at the same time.
For full disclosure, I participated in writing the software used in the course. You can see it here:
http://www.micrologus.com/courses/sight_reading_method
Answer: There are three components to becoming a better reader:

Have a solid technique.  Your hands must know where to go without thought.
Have a good ear.  Believe it or not, your brain's ear knows what is coming next and can prepare your hands for it.
Know music theory.  It is the alphabet of music. You should be able to glance at the score and just know what the chords, scales and arpeggios are. Again, without thought.  Like this:

"It deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht the frist and lsat ltteer be at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit porbelm. Tihs is bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the wrod as a wlohe.
Of course, practice.  When you get a new score, study it away from the piano before you play a note.  See the intervals, chords, scales, patterns, progressions, counterpoint, rhythms and harmonies.  Sing them.  Hear them in your head.
It is not so much a single skill but the amalgamation of various skills.
Answer: As concluded by others, daily practice is essential. I have good experience with sight reading trainers on the smartphone.
I won't mention any particular apps. Just take a look in your app store and try out a few.
Try incorporating short but regular training sessions in your day. E.g. 10 minutes during a commute.
Give it some time and your brain will do its thing.
Answer: Just to add to the other good answers, maybe also think about breaking the habit of looking at your hands and developing a more tactile sense of the keyboard and building a "mental map" of the keyboard. Try playing short drill material - like scale & arpeggio patterns, sequencing short patterns, or cadences - with your eyes closed, in multiple keys. It sort of like keeping your eyes closed, but imaging your watching a movie of your hands moving around the eye board. You try to "see" you hands in your mind rather than in actuality with your eyes.
Learn good fingering for changing positions.
As far as reading material goes, two things I like are brief pieces like Czerny's Recreations and hymnals like the Geneva psalter or The Chorale Book for England where the voices move mostly in block chord style. That kind of music uses a lot of simple movements so you can focus on reading the relative motion changes without looking at your hands.
Answer: I think first of all you should get your technique to around grade 3 level so that you are comfortable with most of the stuff you will see on sheet music.
Ensure in particular that you are rhythmically fluent and that you don't stumble and hesitate, it's always better to play the wrong note at the right time than vice-versa.
You will not likely be a terrific sight-reader by the time you get to this point but you will have been able to learn a variety of music at grade 3 and then perform it reasonably confidently, particularly triplets, three against two rhythms and dotted notes. Stay with the classical idiom, as someone else has said, modern music is much trickier due to syncopation and other techniques that make transcriptions more challenging to read.
Once you feel fairly comfortable playing music to this level, find a cheap source of grade 1 classical exam books - the Royal School of Music and Trinity College both produced copious numbers of these for many years.
Now work your way through these, deliberately not practising the pieces until you know them, but sight-reading through each book, then put that book aside and don't re-use it for a while - this is so you don't actually learn how to play the pieces from muscle memory.
With a library of dozens or ideally more of these pieces, you will find that your sight-reading confidence grows considerably. You can then advance to more complex material.
Few players can fluently sight-read material much beyond grade 5 or 6. At this point the technical difficulties are sufficient that these pieces have to be learned by practice and working on difficult sections bit by bit. So don't expect to be able to pick up a late Beethoven sonata for the first time and sight-read it, even if, technically, you could master it. Only the exceptionally gifted musician can do this.
Comment: And hymn books are also a great resource. They are rhythmically and harmonically simple, and so also make great sight reading trainers.
Answer: Apart from "systems"... I think that the main idea is to be soooo familiar with scales (in all keys), chords/arpeggios, and typical chord progressions, so that the bulk of classical music would be just a pastiche of these elements.
It is true, as others have mentioned, that many pop-music transcriptions are really not good, so, even if you can read them flawlessly, it won't sound at all like the original, and may sound pretty dumb. Similarly with many too-easy jazz-standard transcriptions. Much "discretion" is necessary, with regard to tweaking rhythm, choice of voicings, etc. This is an issue beyond sight-reading... but can be conflated with it, and be discouraging. As others have said, for practice sight-reading, look at easy classical music (where "as written" is apt), or maybe hymnals, where, again, everything is intended as written, and does not need interpretation to sound as intended.
Answer: You may also consider looking at other notation systems that require less mental overhead, like how tabs reduce mental computation for guitar players.
Systems for piano include:

Klavarskribo
Dodeca
Hummingbird
Chromatic Staff

and more!
Comment: I don't know why this answer is downvoted. There are other ways to start learning sheet music. Personally, I think Hummingbird is doing a great job teaching beginners what each note is named, and they are placed on exactly the same places on the staff. I tend to forget what each note on the Bass-cleff is named (when I play a different instrument than bass), because I remember fret and string position faster than the name of the note, so I use the Hummingbird notation to quickly read which note we are talking about when I play piano, or something else for that matter.


Continuous Function From Compact Space to Hausdorff Space is an Identification

Question: Mendelson's Introduction to Topology: Third Edition, Chapter 5, Section 1, Question 6:
Let $f: X \rightarrow Y$ be a continuous mapping of a compact space $X$ onto a Hausdorff space $Y$.  Prove that $f$ is an identification.
Comment: It's **onto** $Y$. Every word matters. So $f$ is assumed to be surjective.
Comment: That makes sense.  I suppose I was treating the word onto as you would to, because in English they are generally interchangeable.  If it were included in the $f:X \rightarrow Y$ notation, then I would not have ignored it, because I tend to assume mathematical notation has a mathematical meaning.  I clearly do not always do this with words in a mathematical context.
Comment: Sometimes $f:X \twoheadrightarrow Y$ is used to denote ontoness. The clue can be in words or symbols.
Answer: Let both $X$ and $Y$ be the real interval $[0,1]$ and let $f(x) = 0$ for all $x$ in $X$. Then $X$ and $Y$ are both compact and both Hausdorff.  A constant function is continuous, but $f$ is not surjective so it is not an identification.
From this, we realise that we are supposed to assume that $f$ is surjective, so then it only remains to show that any subset of $Y$ with open preimage is open. (This part is fine)
But this seems to come up a lot... sometimes the notation $f:X \rightarrow Y$ means that $f$ is mapping into (possibly only a subset of) $Y$, while at other times it seems to be implicitly "understood" that $f$ is surjective.  Frustrating...
Comment: 'Onto' is synonym for 'surjective'.
Answer: It suffices to show that if $f^{-1}[C]$ is closed in $X$ for some $C \subseteq Y$ then $C$ is closed in $Y$.

$f^{-1}[C]$ is compact (as $X$ is compact).
$C=f[f^{-1}[C]]$ because $f$ is onto (i.e. surjective).
As $f$ is assumed to be continuous, $C$ is compact.
As $Y$ is Hausdorff, $C$ is closed in $Y$.

QED.
See how all assumptions are used..