Is it possible for this function on $R^2$ to be defined continuously at $0$?

Question: I wont post all the functions.I am practicing on continuity.So i wanna use definitions but i am not really sure how? Suppose i have the function
$$f(x)= \frac{x^4-y^4}{(x^2+y^2)^2}$$ When $(x,y)\neq (0,0)$ and
$f(x)=b $ when $(x,y)=(0,0)$
Proof:To be defined continouesly at $0$ the limit at zero must exist.So there must exist the $$\lim_{(x,y)\to(0,0)}\frac{x^4-y^4}{(x^2+y^2)^2} $$ Or if i do a variables change to polar coordinates  $x=rcosθ $  $y=rsinθ$
 then$$\lim_{(r,θ)\to(0,0)} cos^2θ-sin^2θ $$ but that function does not depend on $r$  and so will give the same limit for All $r's$ since it must be unique?. So i said the function cannot be defined continuously .Is it right?Does not seem that rigorous to me i think i need a better explanation as to why it might not be defined and why when it is not depended on both variables it doesnt work.
Also i would like a proof using other  definitions(open sets of the preimage or  the ε,δ,) because i do not know how to use the other definitions except that a function is continuous to a point iff when x-->xo then f(x)-->f(xo).
Answer: You have almost answered your own question...
When switching to polar coordinates, we do not need $\theta\rightarrow0$, in fact we must allow $\theta$ to do anything, as long as $r\rightarrow0$. This shows in fact that the function cannot be made continuous, since the limit will depend on $\theta$.
HINT an even easier approach is to consider the limit along the lines $y=mx$. Then the limit will depend on $m$...
Answer: Your computations appear correct with the exception that $(0,0)$ (the origin) is now just represented by $r=0$; you will also need to state that due to the limit being independent of $r$, you may approach from different angles and get different limits (e.g., approaching $r=0$ with $\theta=0$ gives a limit different than when $\theta=\pi/2$). This will prove that the function cannot be made continuous.
Answer: Already, $f$ is a continuous function from $\mathbb{R}^2 \setminus \{(0,0)\}$ to $\mathbb{R}$, and one might ask whether we can extend the domain of $f$ to all of $\mathbb{R}^2$ (that is, define $f(0,0)$) in such a way that $f$ is a continuous function from $\mathbb{R}^2$ to $\mathbb{R}$.
Suppose $f$ could be extended in some way.  Then (a general property of continuous functions from $\mathbb{R}^n \rightarrow \mathbb{R}^m$), if $C$ is any point of $\mathbb{R}^2$, then the limit as $(x,y)$ goes to $C$ of $f(x,y)$ should exist and be equal to $f(C)$.  In particular, the limit as $(x,y)$ goes to $(0,0)$ should be whatever you defined $f(0,0)$ to be.  But you can show that the limit $$\lim\limits_{(x,y) \to (0,0)} \frac{x^4 - y^4}{(x^2 + y^2)^2}$$ does not exist at all (you can use the polar form, or stick to rectangular coordinates, and give two specific examples of paths going to $(0,0)$ for which you get different limiting values).  So no matter how you define $f(0,0)$, the resulting function $f: \mathbb{R}^2 \rightarrow \mathbb{R}$ will not be continuous.
Answer: Hint: try and factorize $x^4-y^4$.
Answer: Consider $(x,y)=(t,0)$, then the function reduces to f(t)=1 so $\lim_{t\to 0}f(t)=1$; on the other hand, considering $(x,y)=(0,t)$, one gets $g(t)=-1$, $\lim_{t\to0}(t)=-1$. If the limit existed, it should have been unique and independent on how you approach the origin.


Hotmail wants me to modify my SPF record

Question: This is my current SPF record. It works well with gmail and yahoo but hotmail was ignoring. So i used their submit system and now they replied me with the text below.
This is my current spf
v=spf1 a mx ptr ~all

Now this is hotmail message
We have successfully added your domain to the Sender ID program. This may take up to 2 business days to be fully replicated in our systems. If you have any questions regarding this please let me know.
We reviewed your SPF record and note that it includes the "ptr" or reverse DNS lookup mechanism. The specification for SPF records (RFC 4408) discourages use of "ptr" for performance and reliability reasons. This is especially important for Windows Live Mail, Hotmail and other large ISPs as a result of the very high volume of mail we receive each day. We highly recommend you remove the "ptr" mechanism from your SPF record and, if necessary, replace it with other SPF mechanisms that do not require a reverse DNS lookup, such as "a", "mx", "ip4" and "include." This will help ensure that Sender ID validation is performed as accurately as possible, maximizing your email deliverability while protecting your domain from spoofing.
So my question is simple. What is the corrected way of it to make it as hotmail wants. Thank you.
Hotmail received email from my server headers
Authentication-Results: hotmail.com;
sender-id=temperror (sender IP is 220.127.116.11)
firstname.lastname@example.com;
dkim=pass
header.d=monstermmorpg.com;
x-hmca=pass
X-Message-Status: n:0:n
X-SID-PRA: MonsterMMORPG <email@example.com>

Comment: David and Sysadmin1138 are both correct, but it's worth noting that the "~" before all means "soft" fail all others. It's a cop-out for people who haven't put the time in to maintaining their SFP record and some servers will hold that against you (like all of the ones I control). The "correct" version should have "-all".
Comment: The exact answer will depend on why the `ptr` is in there. If it was added for no particular reason, it can just be removed. It was added for a particular reason, some other way to do whatever made it required will be needed.
Comment: You're asking what the correct method is and it seems to me they told you ..."We highly recommend you remove the "ptr" mechanism from your SPF record and, if necessary, replace it with other SPF mechanisms that do not require a reverse DNS lookup, such as "a", "mx", "ip4" and "include.""  So just remove ptr like they recommend.
Comment: Chris S so can you tell me the corrected one of it ?
Comment: @MonsterMMORPG Edited my previous comment. Thanks for pointing that out.
Comment: @Chris S Thanks a lot of reply. So the latest version is v=spf1 a mx -all
Answer: In your case, the same string you're using minus the ptr should do the trick.
v=spf1 a mx ~all

Comment: Thank you for answer. Actually i only need spf for verifying my noreply.monstermmorpg.com . Should i modify spf to better version instead of all ? though i am the only one who sends email via my domain. If i should modify how can i do it ?
Comment: added also hotmail received email from my server headers to the main post. So how should i modify spf record and make it best possible way like Chris S suggested ?
Answer: The first question you need to ask yourself is, "From how many domains am I sending email from?".
In this case, you are only sending email from one domain, namely monstermmorpg.com. The "@" in your screenshot refers to the ORIGIN, which is the domain that your zone file covers (presumably also monstermmorpg.com). The next question you ask is, "Do the A/MX/etc. records associated with the name that your TXT SPF record is pointing to point to the IP that sends mail?" For example, let's say your DNS zone looks like this...
$ORIGIN monstermmorpg.com.
 ...
monstermmorpg.com. A      126.96.36.199       ; this points directly to an IP, and will be the final destination in the DNS lookup chain
www                CNAME  monstermmorpg.com.  ; www.monstermmorpg.com will look up the A/CNAME record for monstermmorpg.com
mail               MX     monstermmorpg.com.  ; mail.monstermmorpg.com points to and will look up monstermmorpg.com
@                  MX     monstermmorpg.com.  ; email looking for monstermmorpg.com will look up the A/CNAME record for monstermmorpg.com
@                  TXT    "v=spf1 a mx ptr ~all"

In this case, if 18.104.22.168 is the public IP for the server that sends mail, you can change your SPF record to this...
"v=spf1 a -all"

This means that it takes the A record that corresponds with the TXT record and checks to see if it matches the IP in the emails supposedly sent from your domain. If it's a match, awesome! It goes through. If it doesn't match, it means some spammer is masquerading as your domain, and it will be dropped. You don't need to put redundant A and MX references in the SPF record if there's only one server sending mail, and both records ultimately point to the same IP. Another (more efficient, because it doesn't require a DNS lookup) option is as follows...
"v=spf1 ip4:126.96.36.199 -all"

If your mail server IP rarely changes, this may be a good solution. It's also much easier to understand from your (the admin's) perspective.
The hard -all is preferred over the soft ~all because some mail servers like to be 100% certain that the mail is really coming from you.
Comment: He's got multiple servers, at least one of which is on a hosted plan where the IP can change; it's a fair amount more complicated than this. But this is good advice in general.
Comment: Thanks a lot for detailed reply. This is my latest spf what do you think ? : v=spf1 a mx include:secureserver.net -all
Comment: Is the IP address of secureserver.net one of the places where mail  ending in @monstermmorpg.com originates from? If not, you can leave the include: part out. Also, if both the A and MX records point to the same IP, you can just use one or the other. There's no harm in having duplicates or extras if you're unsure though; as it stands, it's technically correct.
Answer: if you're not familiar with creating spf records i'd recommend a tool that does it for you based on a series of questions. for example, http://unlocktheinbox.com/spfwizard.aspx


What happens if you leave out an `access callback` specification?

Question: In a custom module, if you have a menu hook item that has a custom access argument, but don't specify an access callback, what is drupal's default behavior? Does it use user_access? In other words, is an access callback necessary to specify?
Answer: Yes it uses user_access() by default, but only when you specify 'access arguments'. See http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_menu/7.
Answer: Drupal will use user_access() as default value for the access callback, if the menu item doesn't inherit the value for the access callback from the parent menu item, and you define the access arguments.
This is an example of menu item that inherits the access callback from the parent menu (the menu items are defined in node_menu()):
  $items['admin/content'] = array(
    'title' => 'Content',
    'description' => 'Find and manage content.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_admin_content'),
    'access arguments' => array('access content overview'),
    'weight' => -10,
    'file' => 'node.admin.inc',
  );
  $items['admin/content/node'] = array(
    'title' => 'Content',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

The second menu item doesn't define neither the access callback nor the access arguments, but they are inherited from the parent menu item.


What is the most general formalism for machine learning?

Question: Most of the literature I can find in the field of machine learning is extremely practical, listing many techniques you can use like neural networks, SVMs, random forests, and so on. There are lots of suggestions on implementations and what approaches are good for different problems. My question is, is there a single unifying formalism or theoretical framework in which one can think about problems of inferring patterns and conclusions from data?
In such a framework I'd be interested in exploring these kinds of questions:
What is the correct number of free parameters to use for a given data set? How do we know when we've over-fit? How do we express the trade-off between the accuracy of low-resolution fitting and the precision of high-resolution fitting?
Can we define a machine learning techniques in general terms (instead of specific ones like neurons or forests or deep learning or graphical models or...)? How can we objectively compare these techniques? Are any of them actually identical?
What kinds of signals are possible to extract from data? What kinds of noise could prevent successful learning?
Comment: Maybe you're looking for a [computational learning theory](http://en.wikipedia.org/wiki/Computational_learning_theory), such as [PAC learning](https://en.wikipedia.org/wiki/Probably_approximately_correct_learning) or [VC theory](https://en.wikipedia.org/wiki/Vapnik%E2%80%93Chervonenkis_theory).
Comment: I doubt there is a particularly good answer to your question: the experts in machine learning are much more focused on finding practical solutions to real problems than formulating an elegant theory.  However there do seem a few unifying themes: convex optimization in regression algorithms, entropy in classifiers, and the Johnson-Lindenstrauss lemma in sparse matrix theory and dimension reduction.
Answer: No idea why but the other answers ignore the rich and well-studied theory in ML that goes back decades - research that still continues today. As ML has blown up in terms of practical applications recently, there are many more people aware of the practical aspects (download library, preprocess data, and click go! (: ), but unfortunately ignorant of the theoretical aspects.
The one comment (from 4 years ago) has the right idea. Probably approximately correct (PAC) learning theory is the classical method of describing general learning theory. Another core pillar in learning theory is Empirical Risk minimization.
A standard basic reference is
Understanding Machine Learning: From Theory to Algorithms by Shalev-Shwartz and  Ben-David..
The comment also mentions Vapnik–Chervonenkis (VC) theory. The VC dimension is a method of quantifying the capacity of a model (i.e., how expressive or complicated it can become, if needed). There are other methods of measuring this, like covering numbers and Rademacher complexities.
Basically, if you want to bound the generalization error (i.e., guarantee you are not overfitting, given some assumptions on the data distribution [see the domain adaptation PAC theory]), then the complexity of your model plays a role in that. As you might expect, a more powerful model will tend to increase the difference between the training and testing error (i.e., have more overfitting) and in certain cases this amount can actually be quantified using measures like the VC dimension $\mathfrak{D}[H]$ of some hypothesis space $H$.
As an example, let $T$ be the set of IID training data points for binary classification, drawn from a distribution $P$, with $|T| >> \mathfrak{D}[H]$, and let $0 < \delta < 1$. Then $\forall\;h\in H$, we have that
$$
P\left(
R[h] \leq R_E[h]
+
2\sqrt{\frac{{2}}{|T|}\left[
\mathfrak{D}[H]\left[\ln\left(\frac{2|T|}{\mathfrak{D}[H]}\right) + 1\right]
-
\ln\left(\frac{\delta}{4}\right)
 \right]}\;
\right)
\geq 1 - \delta
$$
where the empirical risk (training error, or in-sample loss) is $\mathcal{L}_E[h] = (1/|T|) \sum_{x,y \in T} L(y, h(x)) $, the generalization error (out-of-sample loss, or test-time error) is $  \mathcal{L}[h] = \iint_{X,Y} P(x,y) L(y, h(x))\, dx\,dy $.
There are a few other assumptions;
there was nice summary here and wiki also mentions it.
Another popular example is the sample complexity of learning a binary function. Let $H$ be the space of binary functions. Then it is $(\epsilon,\delta)$-learnable with a sample of size $N$ on the order of $$ N = \mathcal{O}\left( \frac{\mathfrak{D}[H] - \ln\delta}{\epsilon} \right). $$
This tell us how many samples we require to learn a given function.
I will say though that PAC theory tends to be hard to apply in practice (e.g., to deep learning models and modern datasets). I do see some useful and interesting theory in some cases though, such as results concerning domain adaptation, which tell us how close two datasets need to be in order for e.g. transfer learning to work. Nevertheless, as a general, unified mathematical/theoretical framework to study classes of functions (hypotheses) and their ability to minimize an abstract concept of risk/error, this is the best I know of.

As to your questions (which incidentally should each be their own questions quite honestly):

My question is, is there a single unifying formalism or theoretical framework in which one can think about problems of inferring patterns and conclusions from data?

Sure, the standard one I mentioned above. Define a function space (hypothesis class) to search in and a error/risk function to minimize, and then use PAC theory to e.g. define notions of sample complexity (how much data is needed to get $\epsilon$ level accuracy with probability $1-\delta$?).

In such a framework I'd be interested in exploring these kinds of questions:
  What is the correct number of free parameters to use for a given data set? How do we know when we've over-fit?
  How do we express the trade-off between the accuracy of low-resolution fitting and the precision of high-resolution fitting?

Good question, but these are very applied/practical questions actually, and are hard to answer in general. These days we usually overfit on purpose with a "deep network", and then regularize it until it stops overfitting. We know when we overfit based on estimates of the generalization error.
Nevertheless, questions like overfitting are well studied in PAC theory (e.g., the bound I gave above expresses it rather concisely as the distance between train and test error, and bounds it for a particular case). Questions like "the correct number of free parameters" are also answerable: you can relate the number of free parameters to measures of complexity and capacity (like VC dimension), and deduce how complex the model should be. Of course, this is very tough in practice.
Separately, Bayesian learning approaches give us a very different way to detect overfitting via a natural Occam's razor.
See e.g. Occam's Razor by Rasmussen and Gharamani, 2001, for some simple but interesting examples.
Bayesian approaches allow for natural regularization in this way, and non-parametric Bayesian methods (e.g., Gaussian processes) are naturally intelligent in that they increase their capacity as a function of the amount of available data.
Nevertheless, the arbitrariness of the choice of prior does cause some difficulty (though this is well studied, see e.g. Radford Neal's thesis on Bayesian Learning for Neural Networks, which has a neat section on priors and their implications).
As an aside, the bias-variance tradeoff is a rather simplistic instantiation of another, much more general set of theoretical principles regarding tradeoffs. This includes the "No Free Lunch Theorem", which shows there can be no "universal learner" (for every learning algo/model, there is a task on which it fails), and the Bias-Complexity Tradeoff, which shows that minimizing risk (generalized error) has a balance: choosing a powerful hypothesis class helps reduce approximation error (caused by a weak model), but increases estimation error (caused by overfitting). This notion can be made very concrete and exact (see the book I linked for an intro).

Can we define a machine learning techniques in general terms (instead of specific ones like neurons or forests or deep learning or graphical models or...)? How can we objectively compare these techniques? Are any of them actually identical?

As mentioned before, you can view ML as searching through a function space to find a member (function/model) that minimizes some functional called the risk or loss. This is a very general formulation.
I do think it is interesting to consider the merging of probabilistic models with deep learning, via Bayesian methods.
For instance, infinitely large neural networks are known to be equivalent to non-parametric Bayesian Gaussian processes. (e.g. [a], [b]).

What kinds of signals are possible to extract from data?

Again, too many ways to tackle this question.
For instance, in generative modelling, we want to approximate the marginal distribution $p_\text{data}(x)$. Lots of theoretical work in GANs, VAEs, etc... discuss what different models are able to handle. (For instance, the choice of latent prior may determine which data topologies can be represented well).
The more classic answer is to ask what functions can be learned. This corresponds to the view of machine learning as the study of constructing function approximators.
Most people are familiar with universal approximation theorems, showing capabilities on e.g. continuous functions.
This kind of work is still common: e.g. more recent work on set-theoretic neural layers show that certain layers are universal approximators over permutation invariant functions; other recent work look at universal approximator theorems over signals defined on graphs (via graph convolutional networks)

What kinds of noise could prevent successful learning?

Depends where the noise is. Assuming you want to learn a mapping $f: X\rightarrow Y$, with a dataset $T=\{(x_i,y_i)\}_i$, if there is intrinsic noise in the data (i.e. in the $x$ and $y$ values), then an aleatoric uncertainty is created. In the simple case, this manifests as an additional error term in the bias-variance decomposition (with bias added if the noise has non-zero mean, and variance dependent on the spread of the noise).
See e.g. here.
There are other types of "noise", however, such as domain mismatch between train and test sets, which much domain adaptation research focuses on fighting.

Related:
[1],
[2],
[3],
[4],
[5]
Comment: Informative! And I always enjoy the use of words like "aleatoric" ;-)
Comment: Thank you! Where I can start with non-parametric neural network book?
Answer: I agree with the other respondent. The focus on machine learning is more geared towards ready-to-implement algorithms. However there are some Simple results like the Bias-Variance Tradeoff and other sort of discussions of "limiting" performance. From what I've seen, your question might be most practically addressed by the area of model selection (i.e. how to pick one of the algorithms you mentioned to solve a problem). In some cases, there is no single best algorithm, other than to use both (or several ) algorithms in an ensemble method, e.g. boosting, which takes advantage of when different learning algorithms are best at classifying different types of examples.
Answer: One of the general formalism for using ensemble methods for classification was developed by this author and his followers https://en.m.wikipedia.org/wiki/Yuri_Zhuravlev and called algebraic theory of algorithms, but i haven't seen any book or course in english, may be some papers, most information in russian.


Problema com Celery e Django/Python

Question: Estou tentando implementar um sistema de tasks com Celery no Django, mas está dando erro e eu não sei como resolver...
Erro que aparece no console:

tasks.py
from __future__ import absolute_import, unicode_literals
from celery import task

from datetime import date

@task(ignore_result=True)
def verify_post_date(string):
    print(string)

settings.py
from celery.schedules import crontab
from datetime import timedelta

CELERY_ALWAYS_EAGER = True
CELERY_BROKER_URL = 'redis://localhost:6379/0'
#CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
CELERY_TIMEZONE = 'America/Sao_Paulo'
CELERY_BEAT_SCHEDULE = {

    'verify_post_date': {
        'task': 'core.verify_post_date',
        'schedule': timedelta(seconds=10),

    },

}

Answer: Sua task recebe um parâmetro 'string'. Logo, para agendá-la, você deve passar este parâmetro através da chave 'args', conforme abaixo:
'verify_post_date': {
    'task': 'core.verify_post_date',
    'schedule': timedelta(seconds=10),
    'args': ('teste')
}

Espero ter ajudado.

Problema com Celery e Django/Python


Square-free factorization

Question: Let $p$ be a polynomial over $\mathbb C$, i.e. $p(x)=\prod_{k=1}^m(x-x_k)^{n_k}$ with $n_k\in\mathbb N$, $x_k\in\mathbb C$ and $x_k\neq x_j$ if $k\neq j$. In case that $n_k>1$ for some $k$, we can study the map
$$ \prod_{k=1}^m(x-x_k)^{n_k}\longmapsto \prod_{k=1}^m(x-x_k)$$
that deletes the multiple roots and produces a separable polynomial. I was wondering if there is a conceptual description of this map, be it algebraic or analytic. Many thanks for any hints!
Comment: by the way, you can express this map as $p(x)/(p(x),p'(x))$
Comment: the degree is not $m$
Comment: Thanks a lot, @Exodd !
Answer: As mentioned by Exodd above, a concrete expression for the this map would be $p\mapsto p/gcd(p,p')$, since the derivative of the polynomial $p$ over an algebraically closed field with repeated roots looks like $p'=(x-a_1)\cdots(x-a_k)Q$, where $Q$ has none of the $a_i$'s as its roots. A conceptual description could be the following: assuming you know what they are, you could think of this map as taking the characteristic polynomial of some class of similar matrices to its minimal one.

Square-free factorization


What are the downsides of a large realpath_cache_ttl setting?

Question: I've been researching and tweaking both realpath_cache_size and realpath_cache_ttl, but I'm not clear on what the consequences are if I set realpath_cache_ttl too high.
The documentation states the following:

Duration of time (in seconds) for which to cache realpath information for a given file or directory. For systems with rarely changing files, consider increasing the value.

Okay, great.  How much can I increase it?  What happens if I increase it too much?  Can I increase it too much?
Also, if it matters, I'm using PHP 7 FPM, but I would like to understand how large values of realpath_cache_ttl would affect non-FPM installs as well.
Answer: It's like any time-based cache expiry: if you set it too high, then you'll have all sorts of mysterious and hard-to-track-down problems when the reality (the realpath target) changes, with processes that have the out-of-date information cached using the wrong results, probably resulting in trying to read files that no longer exist, but possibly writing to directories that no longer exist, or all manner of other problems.
Comment: I'm looking for specifics.  What do you mean when you say, "too high"?  The default for this value is two minutes.  That seems high enough that it would already cause the kinds of things you're talking about, and yet it doesn't, which is why I want specific details.
Comment: To me the question seemed specific enough - and I would also like to hear the answer: what is too high? If I update the code on the server, will php be not aware of the changes in the next random period of 0 to 120s?
If 600s is too high because of possible mysterious issues, then why they don't  ever happen in 2 minutes time?
Comment: You're not going to get a specific answer to a non-specific question.


Error when accessing a resource: "param is missing or the value is empty: article"

Question: I want to pass in the whole object to my show action in order to update its viewed field, but for some reason I keep getting this error.

Why is that?
index.html.erb
<%= link_to 'Show', article_path(article) %>

controller
  def show
    @article = Article.find(params[:id])
    @article.viewed += 1
    @article.update(article_params)
  end

  private
    def article_params
      params.require(:article).permit!
    end

Answer: In the code you have the following line
params.require(:article).permit!

The require method invocation will raise the error you are experiencing if the params hash doesn't contain an article hash.
As you can see from the error page, your current parameters are
{"id"=>"1"}

There is no article hash. That's the issue.
Checking your code even further, the following line doesn't make sense at all
@article.update(article_params)

You pretend to update the @article from some parameters in the show action. However, you have at least two issues here:

The parameters are not passed in any way
That's a show action and it is not supposed to update a resource

It's likely to me you just want to increment the counter. If that's the case, your action should be
def show
  @article = Article.find(params[:id])
  @article.viewed += 1
  @article.save!
end

or even better you can use increment!
def show
  @article = Article.find(params[:id])
  @article.increment! :viewed
end

Comment: And is that record going to be saved without Active Record's save or update methods?
Comment: You can easily find the confirmation in the docs for [`increment!`](http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-increment-21)


Button in Fragment within Tabs in ANdroid

Question: i have sorted many solutions online but non seem to work. when ever I declare a button within on of the tab fragments, my app crashes before the holding activity starts please help me. Here's my code.
//this is the code for the containing activity with tabs
public class Dashboard extends FragmentActivity implements ActionBar.TabListener{
private Context ctx = this;
ActionBar AB;
ViewPager VP;
FragmentPageAdapter FP;
String note, timestamp;
EditText NOTE;
Button save;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);

    Intent intent = getIntent();
    String name = intent.getStringExtra("u_name");

    VP = (ViewPager) findViewById(R.id.pager);
    FP = new FragmentPageAdapter(getSupportFragmentManager());

    AB = getActionBar();
    VP.setAdapter(FP);
    AB.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    AB.addTab(AB.newTab().setText("Notes").setTabListener(this));
    AB.addTab(AB.newTab().setText("Contacts").setTabListener(this));
    AB.addTab(AB.newTab().setText("Schedular").setTabListener(this));

    Toast.makeText(getBaseContext(), "welcome " + name,  Toast.LENGTH_LONG).show();

    VP.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
            AB.setSelectedNavigationItem(arg0);

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.dashboard, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.item_change:
        change_password();
        return true;
    case R.id.item_burn:
        burn_diary();
        return true;
    case R.id.item_exit:
        exit();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}
public void burn_diary() {
    Button burn, cancel;
    final EditText DIALOG_USER;
    final EditText DIALOG_PASS;
    final Dialog custom = new Dialog(this);

    custom.setTitle("Burn Diary");
    custom.setContentView(R.layout.dialog_burn);

    DIALOG_USER = (EditText) custom.findViewById(R.id.burn_username);
    DIALOG_PASS = (EditText) custom.findViewById(R.id.burn_password);

    burn = (Button) custom.findViewById(R.id.burn);
    cancel = (Button) custom.findViewById(R.id.cancel);
    burn.setOnClickListener(new OnClickListener(){
        Intent intent = getIntent();
        String name = intent.getStringExtra("u_name");

        @Override
        public void onClick(View arg0) {
            String dialog_user = DIALOG_USER.getText().toString();
            String dialog_pass = DIALOG_PASS.getText().toString();

            DatabaseOperations DOP = new DatabaseOperations(ctx);
            Cursor CR = DOP.getInformation(DOP);
            CR.moveToFirst();
            boolean burnStatus = false;
            do
            {
                if (dialog_user.equals(CR.getString(0)) && dialog_pass.equals(CR.getString(1)) && !(dialog_user.equals("") || dialog_pass.equals("")) && name.equals(dialog_user))
                {
                    burnStatus = true;
                }
            }while(CR.moveToNext());
            if (burnStatus == true)
            {
                DOP.deleteUser(DOP, dialog_user, dialog_pass);
                Toast.makeText(getBaseContext(), "diary burnt successful",  Toast.LENGTH_SHORT).show();
                finish();
            }
            else
            {
                if((dialog_user.equals("") || dialog_pass.equals("")))
                {
                    Toast.makeText(getBaseContext(), "complete all fields", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(getBaseContext(), "burn diary fail", Toast.LENGTH_SHORT).show();
                    DIALOG_USER.setText("");
                    DIALOG_PASS.setText("");
                }

            }
        }
    });

    cancel.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {
            custom.dismiss();
        }
    });
    custom.show();
}
public void change_password() {
    Button change, cancel;
    final EditText DIALOG_CURRENTPASS, DIALOG_NEWPASS;
    final Dialog custom = new Dialog(this);

    custom.setTitle("Change Password");
    custom.setContentView(R.layout.dialog_change);

    DIALOG_CURRENTPASS = (EditText) custom.findViewById(R.id.change_currentPassword);
    DIALOG_NEWPASS = (EditText) custom.findViewById(R.id.change_newPassword);

    change = (Button) custom.findViewById(R.id.button_change);
    cancel = (Button) custom.findViewById(R.id.button_cancel);
    change.setOnClickListener(new OnClickListener(){
        Intent intent = getIntent();
        String name = intent.getStringExtra("u_name");

        @Override
        public void onClick(View arg0) {
            String current_pass = DIALOG_CURRENTPASS.getText().toString();
            String new_pass = DIALOG_NEWPASS.getText().toString();

            DatabaseOperations DOP = new DatabaseOperations(ctx);
            Cursor CR = DOP.getInformation(DOP);
            CR.moveToFirst();
            boolean changeStatus = false;
            do
            {
                if (current_pass.equals(CR.getString(1)) && !(current_pass.equals("") || new_pass.equals("")) && !(current_pass.equals(new_pass)) && name.equals(CR.getString(0)))
                {
                    changeStatus = true;
                }
            }while(CR.moveToNext());
            if (changeStatus == true)
            {
                DOP.updatePassword(DOP, name, current_pass, new_pass);
                Toast.makeText(getBaseContext(), "credentials change successful",  Toast.LENGTH_SHORT).show();
                custom.dismiss();
            }
            else
            {

            }
        }

    });
    cancel.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {
            custom.dismiss();
        }

    });
    custom.show();
}
private void exit()
{
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("EXIT", true);
    startActivity(intent);
}

@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
    VP.setCurrentItem(arg0.getPosition());

}

@Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

}
//this the code for the fragment adapter
public class FragmentPageAdapter extends FragmentPagerAdapter {

public FragmentPageAdapter(FragmentManager fm) {
    super(fm);
    // TODO Auto-generated constructor stub
}

@Override
public Fragment getItem(int arg0) {
    switch (arg0)
    {
    case 0:
        return new NoteFragment();
    case 1:
        return new ContactFragment();
    case 2:
        return new SchedulerFragment();
    default:
        break;
    }
    return null;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return 3;
}

}
//this is the code for the first tab fragment
public class NoteFragment extends Fragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View v;
    v = inflater.inflate(R.layout.notelayout, container, false);
    Button save = (Button) v.findViewById(R.id.saveButton);
    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            //Implement the code to run on button click here
        }
    });
    return v;
}

}
//this is the code for the second tab fragment
public class ContactFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    return inflater.inflate(R.layout.contactlayout, container, false);
}

}
//this this the code for the third tab fragment
public class SchedulerFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    return inflater.inflate(R.layout.schedulerlayout, container, false);
}

}
//this is the code for the first tab fragment xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
    android:id="@+id/note"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignTop="@+id/saveButton"
    android:layout_toLeftOf="@+id/saveButton"
    android:ems="10"
    android:hint="type a note"
    android:paddingBottom="1dp" />

<ImageButton
    android:id="@+id/saveButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:src="@drawable/ic_action_name" />

<ListView
    android:id="@+id/noteView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/note"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" >
 </ListView>
 </RelativeLayout>

Here is the LogCat
09-29 20:58:51.403: D/Databsse operations(797): Database created
09-29 20:58:53.202: D/Databsse operations(797): One row inserted
09-29 20:58:54.271: D/gralloc_goldfish(797): Emulator without GPU emulation detected.
09-29 21:00:07.152: D/dalvikvm(797): GC_CONCURRENT freed 67K, 7% free 2719K/2908K, paused 82ms+22ms, total 561ms
09-29 21:00:07.492: I/Choreographer(797): Skipped 53 frames!  The application may be doing too much work on its main thread.
09-29 21:00:26.392: D/Databsse operations(797): Database created
09-29 21:00:26.501: D/Databsse operations(797): Table combed
09-29 21:00:26.722: I/Choreographer(797): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-29 21:00:27.552: D/dalvikvm(797): GC_FOR_ALLOC freed 187K, 10% free 2894K/3204K, paused 111ms, total 122ms
09-29 21:00:27.602: I/dalvikvm-heap(797): Grow heap (frag case) to 3.547MB for 635812-byte allocation
09-29 21:00:27.893: D/dalvikvm(797): GC_FOR_ALLOC freed 2K, 9% free 3512K/3828K, paused 294ms, total 295ms
09-29 21:00:28.192: D/dalvikvm(797): GC_CONCURRENT freed 34K, 9% free 3512K/3828K, paused 9ms+65ms, total 300ms
09-29 21:00:29.062: D/AndroidRuntime(797): Shutting down VM
09-29 21:00:29.082: W/dalvikvm(797): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
09-29 21:00:29.272: E/AndroidRuntime(797): FATAL EXCEPTION: main
09-29 21:00:29.272: E/AndroidRuntime(797): java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
09-29 21:00:29.272: E/AndroidRuntime(797):  at com.example.databank.NoteFragment.onCreateView(NoteFragment.java:17)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.support.v4.view.ViewPager.populate(ViewPager.java:1011)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.support.v4.view.ViewPager.populate(ViewPager.java:880)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1374)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.View.measure(View.java:15518)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.View.measure(View.java:15518)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.View.measure(View.java:15518)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-29 21:00:29.272: E/AndroidRuntime(797):  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.View.measure(View.java:15518)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.Choreographer.doCallbacks(Choreographer.java:562)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.Choreographer.doFrame(Choreographer.java:532)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.os.Handler.handleCallback(Handler.java:725)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.os.Handler.dispatchMessage(Handler.java:92)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.os.Looper.loop(Looper.java:137)
09-29 21:00:29.272: E/AndroidRuntime(797):  at android.app.ActivityThread.main(ActivityThread.java:5041)
09-29 21:00:29.272: E/AndroidRuntime(797):  at java.lang.reflect.Method.invokeNative(Native Method)
09-29 21:00:29.272: E/AndroidRuntime(797):  at java.lang.reflect.Method.invoke(Method.java:511)
09-29 21:00:29.272: E/AndroidRuntime(797):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-29 21:00:29.272: E/AndroidRuntime(797):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-29 21:00:29.272: E/AndroidRuntime(797):  at dalvik.system.NativeStart.main(Native Method)

Comment: Paste in the crash details too please :-)
Comment: I have added the LogCats
Answer: In NoteFragment, you're trying to cast an ImageButton to a Button.
Despite the name, ImageButton isn't a subclass of Button, it actually extends ImageView.
Change your line to this:
ImageButton save = (ImageButton) v.findViewById(R.id.saveButton);

Or, even just this if you don't intend to change the icon or anything:
View save = v.findViewById(R.id.saveButton);

Comment: the first solution works fine. App doesn't crush anymore. Thanks alot
Answer: In your NoteFragment#onCreateView method has such a line:
Button save = (Button) v.findViewById(R.id.saveButton);
and In notelayout.xml the R.id.saveButton refers to a ImageButton,
from the name maybe you think Button is superclass of ImageButton,
but actually not,as the Android ImageButton doc says,
the ImagButton's superclass is ImageView,so ClassCastException is throwed.
Then Change save's type from Button to ImageButton, your code will work.


Yet another "OpenGL Not Drawing" Issue

Question: Ok, I think I'm going crazy.
I've been developing a 3D game in OpenGL for a while now - all working well.
Then I decided to redesign it from scratch since it was turning to custard. So I set up a basic framework for rendering with OpenGL, and I can't for the life of me get the thing to render a triangle.
I have gone over every line of code about 60 times, gone through every checklist I can find on the internet, checked it against my old project which worked, and still can't see anything wrong with it.
So here is where it all starts (the main method):
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, char* cmdLine, int cmdShow)
{
    try
    {
        GLContext gl(WINDOW_TITLE, 800, 600);
        TestRenderable test;

        while(true)
        {
            glClearColor(0.0f, 0.15f, 0.3f, 1.0f);
            glClear(GL_COLOR_BUFFER_BIT);
            test.draw();
            gl.swapBuffers();
        }

    }
    catch(const std::string& err)
    {
        std::string msg = "Error: ";
        msg += err;

        MessageBox(NULL, msg.c_str(), WINDOW_TITLE, MB_OK | MB_ICONERROR);
    }
    catch(...)
    {
        MessageBox(NULL, "Unknown Error", WINDOW_TITLE, MB_OK | MB_ICONERROR);
    }

}

And all class methods are below:
GLContext::GLContext(const std::string& title, int width, int height)
{
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    m_pWindow = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL);
    m_glContext = SDL_GL_CreateContext(m_pWindow);

    if(glewInit() != GLEW_OK)
        throw(std::string("Failed to initialize GLEW"));
}

GLContext::~GLContext()
{
    SDL_GL_DeleteContext(m_glContext);
    SDL_DestroyWindow(m_pWindow);
}

void GLContext::swapBuffers()
{
    SDL_GL_SwapWindow(m_pWindow);
}

TestRenderable::TestRenderable() : m_pShader(nullptr), m_pMesh(nullptr)
{
    std::vector<std::string> attributes;
    attributes.push_back("position");
    attributes.push_back("color");

    m_pShader = new Shader("shaders\\shader", attributes);
    m_pShader->addUniform("transform");

    glm::vec3 positions[] =
    {
        { 10.0f, 10.0f, 0.0f },
        { 200.0f, 10.0f, 0.0f },
        { 10.0f, 100.0f, 0.0f }
    };

    glm::vec4 colors[] =
    {
        { 0.0f, 1.0f, 0.0f, 1.0f },
        { 1.0f, 0.0f, 0.0f, 1.0f },
        { 0.0f, 0.0f, 1.0f, 1.0f }
    };

    m_pMesh = new Mesh_PC(positions, colors, 3);

    m_projection = glm::ortho<float>(0.0f, 800.0f, 600.0f, 0.0f, 0.0f, 1.0f);
}

TestRenderable::~TestRenderable()
{
    if(m_pShader != nullptr)
        delete m_pShader;

    if(m_pMesh != nullptr)
        delete m_pMesh;
}

void TestRenderable::draw()
{
    m_pShader->bind();
    m_pShader->setUniformMatrix("transform", m_projection);

    m_pMesh->draw();
}

Mesh_PC::Mesh_PC(glm::vec3 positions[], glm::vec4 colors[], unsigned numVertices) : m_vertexCount(numVertices)
{
    glGenVertexArrays(1, m_vertexArray);

    glBindVertexArray(m_vertexArray[0]);

    glGenBuffers(NUM_BUFFERS, m_buffers);

    glBindBuffer(GL_ARRAY_BUFFER, m_buffers[POSITIONS_BUFFER]);
    glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(positions[0]), positions, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, m_buffers[COLORS_BUFFER]);
    glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(colors[0]), colors, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0);

    glBindVertexArray(0);
}

Mesh_PC::~Mesh_PC()
{
    glDeleteBuffers(NUM_BUFFERS, m_buffers);
    glDeleteVertexArrays(1, m_vertexArray);
}

void Mesh_PC::draw()
{
    glBindVertexArray(m_vertexArray[0]);
    glDrawArrays(GL_TRIANGLES, 0, m_vertexCount);
    glBindVertexArray(0);
}

Shader::Shader(const std::string& filename, const std::vector<std::string>& attributes)
{
    m_program = glCreateProgram();
    m_shaders[0] = createShader(loadShader(filename + ".vs"), GL_VERTEX_SHADER);
    m_shaders[1] = createShader(loadShader(filename + ".fs"), GL_FRAGMENT_SHADER);

    for(unsigned int i = 0; i < NUM_SHADERS; ++i)
        glAttachShader(m_program, m_shaders[i]);

    for(unsigned int i = 0; i < attributes.size(); ++i)
        glBindAttribLocation(m_program, i, attributes[i].c_str());

    glLinkProgram(m_program);
    checkShaderError(m_program, GL_LINK_STATUS, true, "Program linking failed");

    glValidateProgram(m_program);
    checkShaderError(m_program, GL_VALIDATE_STATUS, true, "Program is invalid");
}

Shader::~Shader()
{
    for(unsigned int i = 0; i < NUM_SHADERS; ++i)
    {
        glDetachShader(m_program, m_shaders[i]);
        glDeleteShader(m_shaders[i]);
    }

    glDeleteProgram(m_program);
}

void Shader::addUniform(const std::string& name)
{
    m_uniforms.insert(std::make_pair(name, glGetUniformLocation(m_program, name.c_str())));
}

void Shader::bind()
{
    glUseProgram(m_program);
}

void Shader::setUniformMatrix(const std::string& name, const glm::mat4& value)
{
    bind();

    auto it = m_uniforms.find(name);

    if(it != m_uniforms.end())
    {
        glUniformMatrix4fv(it->second, 1, GL_FALSE, &value[0][0]);
    }
}

void Shader::setUniformVec4(const std::string& name, const glm::vec4& value)
{
    bind();

    auto it = m_uniforms.find(name);

    if(it != m_uniforms.end())
    {
        glUniform4fv(it->second, 1, &value[0]);
    }
}

std::string Shader::loadShader(const std::string& filename)
{
    std::ifstream file;
    file.open(filename.c_str());

    std::string output;
    std::string line;

    if(file.is_open())
    {
        while(file.good())
        {
            getline(file, line);
            output.append(line + "\n");
        }

        file.close();
    }
    else
    {
        std::string err("Unable to load shader: ");
        err.append(filename);
        throw(err);
    }

    return output;
}

void Shader::checkShaderError(GLuint shader, GLuint flag, bool isProgram, const char* errorMessage)
{
    GLint success = 0;
    GLchar error[1024] = { 0 };

    if(isProgram)
        glGetProgramiv(shader, flag, &success);
    else
        glGetShaderiv(shader, flag, &success);

    if(success == GL_FALSE)
    {
        if(isProgram)
            glGetProgramInfoLog(shader, sizeof(error), NULL, error);
        else
            glGetShaderInfoLog(shader, sizeof(error), NULL, error);

        std::string err(errorMessage);
        err.append(": '");
        err.append(error);
        err.append("'");
        throw(err);
    }
}

GLuint Shader::createShader(const std::string& text, GLenum shaderType)
{
    GLuint shader = glCreateShader(shaderType);

    if(shader == 0)
        throw("Shader creation failed");

    const GLchar *shaderSourceStrings[1];
    GLint shaderSourceStringLengths[1];

    shaderSourceStrings[0] = text.c_str();
    shaderSourceStringLengths[0] = static_cast<GLint>(text.length());

    glShaderSource(shader, 1, shaderSourceStrings, shaderSourceStringLengths);
    glCompileShader(shader);

    checkShaderError(shader, GL_COMPILE_STATUS, false, "Shader compilation failed");

    return shader;
}

And by the way I am initalizing SDL - I have an object of the below type in the GLContext class:
class SDL
{
public:
    SDL() { SDL_Init(SDL_INIT_VIDEO); }
    ~SDL() { SDL_Quit(); }
};

And my shaders:
Vertex Shader:
#version 120

attribute vec3 position;
attribute vec4 color;

varying vec4 color0;

uniform mat4 transform;

void main(void)
{
    gl_Position = transform * vec4(position, 1.0);
    color0 = color;
}

Fragment Shader:
#version 120

varying vec4 color0;

void main(void)
{
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

I know there is unused stuff in the shaders etc but this is just for testing purposes.
Can anyone help me here?
Comment: Try to pass in some screen coordinates ((0,0,0), (1,0,0), (1,1,0)) and comment out the transform in the shader. That way you can exclude the case that the triangle lies outside of the view frustum and is simply not visible due to the camera not looking at it.
Comment: Those things are remembered by the vertex array object. I think the way it is set up here is OK (apart from the mistake mentioned in my answer).
Comment: @leemes Yeah I've tried that - no luck.
Comment: I'm never 100% sure which state is contained in which objects. Try to setup the vertex attributes in each draw call. For that, move the four lines with `glEnableVertexAttribArray` and `glVertexAttribPointer` from your c'tor in `draw()` before the drawing call, after binding. Also add `glDisableVertexAttribArray` calls after drawing, before unbinding.
Answer: You need to call glBindBuffer before calling glVertexAttribPointer. At the moment, both attributes will be using the last buffer bound (the one with the color values).
Comment: You're welcome. It helped that your code's easy to read and I could see you already had error checking for the shader compilation. After that, the geometry set-up was the obvious place to look. Glad to help you get past a looking-at-a-blank-window moment. Been there many times!
Comment: By the way - the color array (interpreted as 3 float-triples), would specify a degenerate triangle, explaining why you would not see anything even when you do no transformation.
Comment: Or simply move the `glVertexAttribPointer` calls up a few lines, each one just after the corresponding `glBufferData` call.
Comment: You, sir, are a genius! Thank you! It's good when there's someone whos prepared to read through screeds of code to help someone!

Yet another "OpenGL Not Drawing" Issue


Spectral Clustering of Gaussian Mixture Model

Question: I am working on Exercise 4.7.6(e) in R. Vershynin's High-Dimensional Probability. For convenience, I will put the background below:

Let $m, n$ be a positive integers and, for $i = 1,..., m$, let $X_i = \theta_i \mu + g$, where $\theta$ is a symmetric Bernoulli random variable, $\mu\in\mathbb{R}^n$, and $g\sim \mathcal{N}(0, I_n)$. Let $\Sigma$ be the covariance matrix of $X$ and $\Sigma_m = (1/m)\sum_{i=1}^m X_iX_i^T$ be the empirical covariance matrix of $X$. Let $v$ be the eigenvector corresponding to the largest eigenvalue of $\Sigma_m$. Notice that $\mu$ is the eigenvector of $\Sigma$ corresponding to its largest eigenvalue (which equals $1 + \Vert \mu \Vert_2^2$).

The grouping of $X_i$ is based on the sign of $\langle v, X_i \rangle$, i.e., all $X_i$ with the same sign of $\langle v, X_i \rangle$ are classified to the same group. Now I want to show the following (Theorem 4.7.5 in Dr. Vershynin's notes):

Suppose $\Vert\mu \Vert_2^2 \geqslant C\sqrt{\log (1/\epsilon)}$. Then, if $$
m \geqslant \left(\frac{n}{\Vert\mu \Vert_2} \right)^c,
$$
where $c$ is an absolute constant, then, with probability no smaller than $1 - 4\exp(-n)$, the clustering strategy above will identify the communities correctly up to $\epsilon m$ misclassified points. (Apart from this, I also want to find some bound on $c$, since it is an absolute constant)

Here is what I have done so far:

Now I have chosen some $0 < \delta \ll 1$ such that
$$
m = O(\delta^{-2} n) \implies \Vert \Sigma - \Sigma_m \Vert \leqslant \delta\Vert\Sigma \Vert
$$
Further, by Davis-Kahan I have shown that
$$
\sin\angle(v, \mu) \leqslant \frac{2\delta\Vert\Sigma \Vert}{\Vert\mu \Vert_2^2}
$$
Also, I have shown that grouping based on the sign of $\langle \mu, X_i \rangle$ will give a good prediction, and one needs to contrast this with prediction based on the sign of $\langle v, X_i \rangle$. Suppose WLOG that $\langle v, \mu \rangle > 0$. Then the groupings of $X_i$ based on these strategies will differ whenever $X_i$ lies in the small wedge $W$ enclosed by $v^{\perp}$ and $\mu^{\perp}$. Suppose $X_i \sim \mathcal{N}(\mu, I)$. Then one has that
$$
Y_i = \left\langle\frac{v}{\Vert v \Vert_2}, X_i\right\rangle\sim \mathcal{N}\left(\frac{\mu^T v}{\Vert v \Vert_2}, 1\right),\quad
\quad Z_i = \left\langle
\frac{\mu}{\Vert \mu \Vert_2}, X_i\right\rangle \sim \mathcal{N}\left(
\Vert\mu \Vert_2, 1
\right).
$$
And the probability that the groupings of $X_i$ are different equals
$$
p = 2\mathbb{P}(\mu^T X_i < 0, v^T X_i > 0) = 2\mathbb{P}\left(
Y_i < 0, Z_i > 0
\right).
$$
But I am not sure how to proceed. It looks like $Y_i$ and $Z_i$ are not independent. Could anyone please give me a hint on how to bound this probability from above? Any help will be appreciated!
Answer: Here are some hints for the problem:

As stated in the theorem, we should be choosing $m \geq \left( \frac{n}{\Vert \mu \Vert} \right)^c$ for some $c > 0$. If $c = 2$ (say), then using the theorem on covariance estimation (or more precisely, the high probability version for the tail bound Exercise 4.7.3), we should deduce that $\Vert \Sigma - \Sigma_m \Vert \lesssim \frac{\Vert \mu \Vert^3}{\sqrt{n}}$. (We can assume that $\Vert \mu \Vert \geq 1$, and also $n \geq \Vert \mu \Vert$ (why?).)

Let $v$ denote the unit eigenvector of $\Sigma_m$ corresponding to the largest eigenvalue. The Davis-Kahan theorem therefore implies that the distance between the unit eigenvectors, up to sign, satisfy $\Vert v - \eta \frac{\mu}{\Vert \mu \Vert} \Vert \lesssim \frac{\Vert \Sigma_m - \Sigma \Vert}{\delta}$, where $\eta \in \{\pm 1\}$, and $\delta = \Vert \mu \Vert^2$ is the spectral gap (why?). Assuming without loss of generality that $\eta = 1$, this means $\Vert \Vert \mu \Vert v - u \Vert \lesssim \frac{\Vert \mu \Vert}{\sqrt{n}}$ with high probability.

Now we should understand why the signs of $\langle \mu, X_i \rangle$ predict the communities of $X_i$ well. For each $i$, note that $\langle \mu, X_i \rangle = \theta_i \Vert \mu \Vert^2 + \langle \mu, g_i \rangle$. Thus, as long as $\langle \mu, g_i \rangle \lesssim \Vert \mu \Vert^2$, the sign will be correct. But since $\langle \mu, g_i \rangle \sim N(0, \Vert \mu \Vert^2)$, we can secure this fact with high probability. Using the assumption that $\Vert \mu \Vert \gtrsim \sqrt{\log(1/\epsilon)}$, this implies that the sign of $\langle \mu, X_i \rangle$ is correct with probability $O(\epsilon)$. By a Chernoff bound on this event for all $m$ points, this indeed holds for all except $O(\epsilon m)$ points with high probability.

To finish the argument, you want to argue that the signs of $\langle v, X_i \rangle$, which are equal to the signs of $\langle \Vert \mu \Vert v, X_i \rangle$, are also correct with high probability. This can be deduced by chaining the previous parts: with high probability, $\langle \mu, X_i \rangle$ is correct and is well separated from zero by a distance $O(\Vert \mu \Vert^2)$. But with high probability, $\langle \Vert \mu \Vert v, X_i \rangle \approx \langle \mu, X_i \rangle$, and they are separated by a distance $O(\Vert \mu \Vert^2)$. Choosing all the constants carefully means that for all $i$, the sign of $\langle \Vert \mu \Vert v, X_i \rangle$ is correct with probability at least $1 - \frac{\epsilon}{2}$. Applying the Chernoff bound argument to this implies that with high probability all but at most $\epsilon m$ of the points will have the wrong sign.
Answer: Let us adopt the following notations
$\mu=r_1u_1, v=r_2u_2$ with $u_1$ and $u_2$ of norm $1,$ $\rho=\langle u_1,u_2\rangle,$ $Z_i=\langle u_i,g_i\rangle$ for $i=1,2$ where $g_i\sim N(0,I_n)$.
It is standard to see that
$(Z_1,Z_2)$ is Gaussian such that $Z_1,Z_2\sim N(0,1)$ and $E(Z_1Z_2)=\rho.$
The explicit calculation of your $p$ does not seem possible since it depends entirely from the distribution function $$F_{\rho}(z_1,z_2)=\Pr(Z_1<z_1,Z_2<z_2).$$
Your $X_i$ is $\theta_i r_1u_1+ g_i$ and you are interested in
$$\Pr(\langle X_i,u_1\rangle<0<\langle X_i,u_2\rangle)=\Pr(Z_1<-\theta_ir_1,\,  Z_2>-\theta_ir_1\rho)$$ which is easily expressed in terms of the number $F_{\rho}(-\theta_ir_1,-\theta_ir_1\rho).$ Even while using $Z_2=\rho Z_1+\sqrt{1-\rho^2}Z_3$ with $Z_1,Z_3$ independent and $N(0,1)$,  you land on $\Pr((Z_1,Z_3)\in C)$ where $C$ is a cone whose submit is not $(0,0)$, something not computable.
Comment: Thanks for your answer! Yet is there any way to derive a nontrivial upper bound of this probability?
Answer: $\DeclareMathOperator*{\PP}{\mathbb P}\DeclareMathOperator*{\E}{\mathbb E}\DeclareMathOperator*{\T}{\mathsf{T}}\DeclareMathOperator*{\sign}{\mathrm{sign}}$I think the other answers do not deal with the harder part of the problem. When $\lVert x \rVert_2 > \sqrt n$, the theorem about covariance estimation does not give any guarentee in fact, so in this case a different analysis should be used. I will post my answer in my homework below:

Note that $\E X = \E (\theta \mu) = \E g = 0$. $\Sigma = \E X X^{\T} = \E (\theta \mu + g) (\theta \mu + g)^{\T} = \E \theta^2 \mu \mu^{\T} + \E g g^{\T} = \mu \mu^{\T} + I_n$. The spectrum of $\Sigma$ is one eigenvalue $1 + \lVert \mu \rVert_2^2$ and $n-1$ eigenvalues $1$.

To use Theorem 4.7.1 (in fact, Exercise 4.7.3), we need to verify the condition. For any $x \in \mathbb R^n$, $\langle X, x \rangle = (\theta \mu^{\T} x + g^{\T} x)$. By the triangle inequality, $\lVert \langle X, x \rangle \rVert_{\psi_2} \preceq |\langle \mu, x \rangle| + \lVert x \rVert_2$. On the other hand, $\lVert \langle X, x \rangle \rVert_{L^2} = \sqrt{\E \langle X, x \rangle^2}=\sqrt{\langle \Sigma x, x \rangle} = \sqrt{\langle \mu, x\rangle^2 + \lVert x \rVert_2^2}\le \langle \mu, x\rangle + \lVert x \rVert_2$. Hence, we yield the bound with $K=O(1)$ as
\begin{equation}
    \lVert \Sigma_m - \Sigma \rVert \le C\left(\sqrt{\frac{n}m} + \frac n m\right) \lVert \Sigma \rVert = C\left(\sqrt{\frac{n}m} + \frac n m\right) (1 + \lVert \mu \rVert_2^2)
  \end{equation}
w.p. $1 - 2e^{-n}$ ($u = n$ is substituted.).

Plug $S = \Sigma$, $T = \Sigma_m$, $i=1$, and $\delta = \lVert \mu \rVert_2^2$ in the bound. Then,
\begin{equation}
    \exists \theta \in \{-1,1\}: \lVert v_1(\Sigma) - \theta v_1(\Sigma_m) \rVert \le \frac{3\lVert \Sigma_m - \Sigma \rVert}{\lVert \mu \rVert_2^2}
  \end{equation}
for the unit eigenvector $v_1$.

Calculate $\PP \{ \sign(\langle \mu, \theta \mu + g \rangle) = \theta\} = \PP \{ \langle \mu, \mu + g \rangle > 0\} = \PP \{ \langle \mu, g \rangle > \lVert \mu \rVert_2^2\} = \PP \{ N(0, \lVert \mu \rVert_2^2) > \lVert \mu \rVert_2^2\} \le 2\exp(-c \lVert \mu \rVert_2^2) \ll \varepsilon$.

Let $v' = v \lVert \mu \rVert_2$. We know by part (c) (WLOG set $\theta = 1$) that $\lVert v' - \mu \rVert_2 \le \frac{3\lVert \Sigma_m - \Sigma \rVert}{\lVert \mu \rVert_2}$.  We want to bound $\PP \{ \sign(\langle v, \mu + g \rangle) =  \sign(\langle v, \mu\rangle)\}$.
If $m \succeq n / \varepsilon$, by part (b), $\lVert \Sigma_m - \Sigma \rVert \ll \lVert \mu \rVert_2^2$ w.p. $1 - 2e^{-n}$. Then, $\lVert v' - \mu \rVert_2 \le \lVert \mu \rVert_2 / 2$. In this case, $\lVert v, \mu \rVert \ge \lVert \mu \rVert_2^2 / 2$ and $\PP \{ \sign(\langle v, \mu + g \rangle) =  \sign(\langle v, \mu\rangle)\} \le \PP \{\langle v, g \rangle > \frac 1 2 \langle v, \mu \rangle\} \le \PP \{N(0, \lVert \mu \rVert_2^2) > \lVert \mu \rVert_2^2/4\} \ll \varepsilon$. By Chernoff's bound, the number of misclassified communities is bounded by $\varepsilon m$ w.p. $1 - e^{-\varepsilon m} \le 1 - e^{-n}$. By union bound, this finishes the proof.
However, the bound wrote in the statements is $m \succeq (n / \lVert \mu \rVert_2)^c$, which can be smaller than $n$ when $\lVert \mu \rVert_2 \ge n^{1-1/c}$. We fix $c = 2$. In this case $\lVert \mu \rVert_2 \succeq \sqrt n$, we cannot expect Theorem 4.7.1 to give any guarentee. Hence, we use a new strategy. Observe that $X_i X_i^{\T} = \mu \mu^{\T} + \theta_i (\mu g_i^{\T} + g_i \mu^{\T}) + g_i g_i^{\T}$. When $\lVert \mu \rVert \gg \sqrt n$, the term $\mu \mu^{\T}$ dominates. Now formalize this.
Write
\begin{equation}
    \frac{1}{m}\sum_{i=1}^m X_i X_i^{\T} = \mu \mu^{\T} + \mu \left(\frac 1 m \sum_{i=1}^m g_i\right)^{\T} + \left(\frac 1 m \sum_{i=1}^m g_i\right) \mu^{\T} + \frac{1}{m} \sum_{i=1}^m g_i g_i^{\T}.
\end{equation}
Because $\frac 1 m \sum g_i \sim N(0, I_n / m)$, by concentration of norm, we have $\lVert \frac 1 m \sum g_i \rVert \preceq \sqrt{n/m}$ w.p. $1 - 2e^{-2n}$. Hence, the norm of two terms on the middle is bounded by $C \lVert \mu \rVert_2 \cdot \sqrt{n/m} $.
We simply bound $\lVert \frac{1}{m} \sum_{i=1}^m g_i g_i^{\T}\rVert $ by Theorem 4.6.1 which gives $C(\sqrt n + \sqrt m)\preceq \sqrt n$ w.p. $1 - 2e^{-2n}$.
Combining two bounds, we have $\lVert \frac{1}{m}\sum_{i=1}^m X_i X_i^{\T} - \mu \mu^{\T} \rVert \preceq \sqrt n + \sqrt{n / m} \cdot \lVert \mu \rVert_2 \le \lVert \mu \rVert_2^2 / 2$. By Davis-Kahan, this implies $\lVert v - \mu \rVert_2 \preceq \lVert \mu \rVert_2^2 / 2$ and $|\langle v, u \rangle| \ge \frac 1 2 \lVert \mu \rVert_2$. Now $\PP \{ \sign(\langle v, \mu + g \rangle) = \sign(\langle v, \mu \rangle)\} \le 2\exp(-c\lVert \mu \rVert_2^2) \le 2\exp(-2n)$. By union bound of everything, there is no misprediction (i.e. $\varepsilon = 0$) w.p. $1 - 4\exp(-n)$.

In summary, if $\lVert \mu \rVert_2 \preceq \sqrt n$, we use the first analysis based on covarience estimation and otherwise we use the second analysis based on estimation of overlap with $\mu$. This proof gives a sharper bound: the algorithm works with $m \succeq \min(n / \varepsilon, (n / \lVert \mu \rVert_2)^2)$.


React Native - How to call c# .NET Web Api from React NAtive

Question: What i have done so far:
I have added my website .net framework 4.7.1 into IIS, i browsed the website and works on http://localhost which i added all the web files to the wwwroot.
I have a values controller that extends Api controller:
<code>        using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;

    namespace NewsFeedWebApi.Controllers
    {
        public class ValuesController : ApiController
        {
            // GET api/values
            [HttpGet]
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }

            // GET api/values/5
            public string Get(int id)
            {
                return "value";
            }

            // POST api/values
            public void Post([FromBody] string value)
            {
            }

            // PUT api/values/5
            public void Put(int id, [FromBody] string value)
            {
            }

            // DELETE api/values/5
            public void Delete(int id)
            {
            }
        }
    }
</code>
And this is my React NAtive Code:
<code>        /**
     * Sample React Native App
     * https://github.com/facebook/react-native
     *
     * @format
     * @flow strict-local
     */

    import React, { useState, useEffect } from 'react';
    import { Button, View, Text, StyleSheet, TouchableOpacity, } from 'react-native';

    function App() {

      useEffect(() => {
        // Update the document title using the browser API

        function GetInit(){

          fetch('https://192.168.1.32:80/api/values')
          .then((response) => response)
          .then((json) => {
            console.log(json);

          })
          .catch((error) => {
            //alert(error);
            console.log(error);
          });
        }

        GetInit();
      });

      return (
        <View><Text>wwww</Text></View>
      );
    }

    export default App;
</code>
In the webconfig i added thisto enable cors:
<code>  <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
       <add name="Access-Control-Allow-Credentials" value="true" />
      </customHeaders>
    </httpProtocol>
</code>
Can someone tellme where im making a mistake or something im missing?
Comment: "i browsed the website", do you  mean you used MVC and you accessed a special page or do you mean you got simple  a simple response with each request? If it's the latter then you need to ensure you have to have the minimal set of headers being sent from react native. To test that I would test it on Postman or something similar.
Comment: You'd want to check what headers your react native app is sending. Many ways of doing including debug (might require injecting some parameters in ASP web api for whatever you are testing) or Fiddler.
Comment: Ah using https instead of http.
Answer: Because my web app .net framework was working under iis in http rather than https, i just changed the fetch call to this:
<code>fetch('http://192.168.1.32/api/values',{
    method: 'GET', // *GET, POST, PUT, DELETE, etc.
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    }
  })
  .then((response) => response.json())
  .then((json) => {
    console.log(json);

  })
  .catch((error) => {
    //alert(error);
    console.log(error);
  });
</code>
and i got the data to return:
<code>["value1", "value2"]
</code>


Setup AD FS 3.0 Proxy when Primary AD FS Server is behind firewall

Question: I am trying to setup an AD FS Proxy server. In my case, my AD FS Server is behind a network firewall and is accessible only within the intranet. I have spawned a DMZ machine and have set it up as a Web Application Proxy(WAP). I want to use AD FS as the IdP using this proxy server. The AD FS Proxy can access the internal AD FS Server and am able to pull up the configuration from the internal AD FS Server. The appropriate Firewall rules are in place which allow for communication to the ADFS Server from the Proxy server.
I have added a Pass-through application in the Remote Access Management console in the Proxy server and added the backend and front end server url's as those of the internal AD FS server. When I try to access the following:
https://adfs.proxyserver.com/adfs/ls/IdpInitiatedSignOn.aspx

I get a 'Webpage Not Available'. Is there any configuration I am missing?
Answer: You should be using the ADFS Service Name - which should match your SSL certificate: i.e. https://sts.contoso.com/adfs/ls/IdpInitiatedSignOn.aspx
Are you accessing the ADFS externally or internally when you get this error?


How can I inform license details to RavenDB throw Docker-Compose?

Question: I'm trying to create 3 RavenDB containers using docker.
This is working as expected, but, I need do inform license details to RavenDB and I could not get this working.
this is my first try docker-compose file:
version: '3'
services:
  raven1:
    container_name: raven1
    image: ravendb/ravendb
    ports:
      - 8080:8080
      - 38888:38888
    environment:
      - RAVEN_LICENSE='{"Id":"xxx","Name":"abc","Keys":["111","222","333","444","555","666","777","888","999"]}'
      - RAVEN_Security_UnsecuredAccessAllowed=PublicNetwork
      - RAVEN_Setup_Mode=None
      - RAVEN_License_Eula_Accepted=true
      - "RAVEN_ServerUrl=http://0.0.0.0:8080"
      - "RAVEN_PublicServerUrl=http://localhost:8080"
      - "RAVEN_ServerUrl_Tcp=tcp://0.0.0.0:38888"
      - "RAVEN_PublicServerUrl_Tcp=tcp://localhost:38888"

  raven2:
    container_name: raven2
    image: ravendb/ravendb
    ports:
      - 8081:8080
      - 38889:38888
    environment:
      - RAVEN_LICENSE='{"Id":"xxx","Name":"abc","Keys":["111","222","333","444","555","666","777","888","999"]}'
      - RAVEN_Security_UnsecuredAccessAllowed=PublicNetwork
      - RAVEN_Setup_Mode=None
      - RAVEN_License_Eula_Accepted=true
      - "RAVEN_ServerUrl=http://0.0.0.0:8080"
      - "RAVEN_PublicServerUrl=http://localhost:8081"
      - "RAVEN_ServerUrl_Tcp=tcp://0.0.0.0:38888"
      - "RAVEN_PublicServerUrl_Tcp=tcp://localhost:38889"

  raven3:
    container_name: raven3
    image: ravendb/ravendb
    ports:
      - 8082:8080
      - 38890:38888
    environment:
      - RAVEN_LICENSE='{"Id":"xxx","Name":"abc","Keys":["111","222","333","444","555","666","777","888","999"]}'
      - RAVEN_Security_UnsecuredAccessAllowed=PublicNetwork
      - RAVEN_Setup_Mode=None
      - RAVEN_License_Eula_Accepted=true
      - "RAVEN_ServerUrl=http://0.0.0.0:8080"
      - "RAVEN_PublicServerUrl=http://localhost:8082"
      - "RAVEN_ServerUrl_Tcp=tcp://0.0.0.0:38888"
      - "RAVEN_PublicServerUrl_Tcp=tcp://localhost:38890"

I get containers working, but a "no licensed server" message.
My second try was:
version: '3'
services:
  raven1:
    container_name: raven1
    image: ravendb/ravendb
    ports:
      - 8080:8080
      - 38888:38888
    environment:
      - RAVEN_Security_UnsecuredAccessAllowed=PublicNetwork
      - RAVEN_Setup_Mode=None
      - RAVEN_License_Eula_Accepted=true
      - "RAVEN_ServerUrl=http://0.0.0.0:8080"
      - "RAVEN_PublicServerUrl=http://localhost:8080"
      - "RAVEN_ServerUrl_Tcp=tcp://0.0.0.0:38888"
      - "RAVEN_PublicServerUrl_Tcp=tcp://localhost:38888"
    env_file: ./license.env

  raven2:
    container_name: raven2
    image: ravendb/ravendb
    ports:
      - 8081:8080
      - 38889:38888
    environment:
      - RAVEN_Security_UnsecuredAccessAllowed=PublicNetwork
      - RAVEN_Setup_Mode=None
      - RAVEN_License_Eula_Accepted=true
      - "RAVEN_ServerUrl=http://0.0.0.0:8080"
      - "RAVEN_PublicServerUrl=http://localhost:8081"
      - "RAVEN_ServerUrl_Tcp=tcp://0.0.0.0:38888"
      - "RAVEN_PublicServerUrl_Tcp=tcp://localhost:38889"
    env_file: ./license.env

  raven3:
    container_name: raven3
    image: ravendb/ravendb
    ports:
      - 8082:8080
      - 38890:38888
    environment:
      - RAVEN_Security_UnsecuredAccessAllowed=PublicNetwork
      - RAVEN_Setup_Mode=None
      - RAVEN_License_Eula_Accepted=true
      - "RAVEN_ServerUrl=http://0.0.0.0:8080"
      - "RAVEN_PublicServerUrl=http://localhost:8082"
      - "RAVEN_ServerUrl_Tcp=tcp://0.0.0.0:38888"
      - "RAVEN_PublicServerUrl_Tcp=tcp://localhost:38890"
    env_file: ./license.env

this version points to a license.env file with
RAVEN_LICENSE='{"Id":"xxx","Name":"abc","Keys":["111","222","333","444","555","666","777","888","999"]}'

inside of it
both versions didnt work.
what am I doing wrong? Whats the correct way to inform the license detais to RavenDB using Docker?
Answer: Try using "RAVEN_LICENSE" all caps, it worked for me.
Answer:
remove the single quote and all whitespace from "license.env"


clustering with equal elements

Question: Assume that we have a set of observations: $\mathbf{X} = \{x_{1}, \dots, x_{n}\}\subseteq \mathbb{R}^{d}$, containing $n$ observations for a fixed dimensionality $d$. Assume, we have some fixed integer $k$. The k-means clustering (with l2 distance) is the problem of finding centroids the clusters $S_{1}, \dots, S_{k}$ that minimize
$$
cost(S_{1}, \dots, S_{1}) = \sum_{j=1}^{k}\sum_{x\in S_{j}}||x - q_{j}||^{2},
$$
where $q_{1}, \dots, q_{k} \in \mathbb{R}^{d}$ are the centroids, i.e. $q_{j} = \frac{1}{|S_{j}|}\sum_{x\in S_{j}}x$.
Assume, there in $\mathbf{X} = \{x_{1}, \dots, x_{n}\}$ there are equal elements $\{x\} \subset \mathbf{X}$.
Is it possible that in a global (theoretical) solution these equal to each other elements $\{x\}$ belong to different clusters?
Answer: First we need to distinguish between the globally optimal k-means solution and the result you get from a k-means algorithm. There are quite a number of these around, and unless the dataset is very small, they will deliver a local optimum that isn't necessarily the global one. (You say "global" in your question so I assume you mean the globally optimal solution; just to make sure.)
The answer to your question starts with "not normally"; their $\|x-q_j\|$-values are obviously equal for all $q_j$, so once the algorithm is converged (or the globally optimal $q_j$ are known), they will all be assigned to their closest $q_j$, which is the same for them all.
An exceptional situation that is not covered by the above argument occurs if not only several $x$ are equal, but they are also in equal distance to two or more $q_j$. I actually don't know of any algorithm that in this case can assign them to different clusters, but I cannot exclude that such implementations exist.
In fact I haven't tried to prove it but I suspect that the global optimum will never separate equal observations, because chances are that if equal observations are separated, one can achieve a better solution putting all of them into the cluster that has the majority of them (or just any cluster if they are evenly distributed). It doesn't seem to make sense to have these obsrvations influence more than one cluster mean (making it potentially worse for the majority of other observations in that cluster). One could probably prove this spending an afternoon doing maths, but no guarantee here, just a guess.
What I have looked at is a number of 1-d examples with equal points sitting between two halves of the data such as 1,2,3,3,4,5. Indeed you get a better solution ($k=2$) in terms of cost if you put the two 3 both either in a cluster with 1,2, or with 4,5, rather than one to the left and one to the right (you can check this by explicitly computing the cost functions).
Comment: Dear @Lewian, I have updated the question. I was curious about the global, i.e. minimum, the theoretical solution.

clustering with equal elements


Limit of function aproximated by some other functions

Question: Problem
1.$\lim_{x\to\infty}\frac{\log(x^4+1)}{\log(x^6+1)}$
2.$\lim_{n\to\infty} \sqrt[n]{n+\sin n}$

Its easy with l'Hopital's rule but i was wandering is this correct to say.
since $\lim_{x\to\infty}\log(x^4+1)=\lim_{x\to\infty}\log(x^4)$ and $\lim_{x\to\infty}\log(x^6+1)=\lim_{x\to\infty}\log(x^6)$ it follows that $\lim_{x\to\infty}\frac{\log(x^4+1)}{log(x^6+1)}$=
$\lim_{n\to\infty}\frac{\log(x^4)}{\log(x^6)}=\frac{4}{6}$.

i thought same for second problem:$  \sqrt[n]{n-1}<\sqrt[n]{n+\sin n}<\sqrt[n]{n+1}$. Since i know that  $\lim_{n\to\infty}\sqrt[n]{n}=1$ can i just say like above $ \lim_{n\to\infty}\sqrt[n]{n+1}=\lim_{n\to\infty}\sqrt[n]{n}=1$ and $ \lim_{n\to\infty}\sqrt[n]{n-1}=1$ so by squezze theorem result is $1$.
Comment: Your answers are correct but the arguements are not correct.
Comment: Well you need to edit by example $sinn$
Answer: For the first one indeed we don't need l'Hopital, the correct argument should be
$$\frac{\log(x^4+1)}{\log(x^6+1)}=\frac{\log x^4+\log(1+1/x^4)}{\log x^6+\log(1+1/x^6)}=\frac{4\log x+\log(1+1/x^4)}{6\log x+\log(1+1/x^6)}=$$
$$=\frac{4+\frac{\log(1+1/x^4)}{\log x}}{6+\frac{\log(1+1/x^6)}{\log x}} \to \frac{4+0}{6+0}= \frac23$$
To prove that $\lim_{n\to\infty}\sqrt[n]{n+1}=1$ let consider
$$\sqrt[n]{n+1}=e^{\frac{\log (n+1)}{n}} \to e^0=1$$
indeed
$$\frac{\log (n+1)}{n}=\frac{\log (n+1)}{n+1} \frac{n+1}{n}\to 0\cdot 1=0$$
Comment: Thank you can u tell me how did u conclude this $\frac{\log(1+1/x^6)}{\log x} \to 0$.
Comment: We have $1/x^6 \to 0$ then $\log(1+1/x^6) \to \log 1=0$ and of course $\frac{\log(1+1/x^6)}{\log x} \to 0$.
Comment: ye i understand now. can u tell me what is wrong with this approach difference between $\sqrt[n]{n+1}$ and $\sqrt[n]{n}$ when n goes to infinity goes to 0 so their limits must be same.
Comment: @zorzpapadubi The point is that given $\lim_{n\to\infty}\sqrt[n]{n}=1$, in principle, we need to prove that $\lim_{n\to\infty}\sqrt[n]{n+1}=1$ holds.
Comment: ye i understand that.  u solution is 100% formally corect but my question is this: If i prove formally that limit of difference of $ \lim_{n\to\infty}(\sqrt[n]{n+1}- \sqrt[n]{n})\to 0 $, then their limits be same. is that correct
Comment: @zorzpapadubi Yes in that case since we know that $\lim_{n\to\infty}\sqrt[n]{n}=1$ therefore $$\lim_{n\to\infty}(\sqrt[n]{n+1}- \sqrt[n]{n})\to 0 \implies \lim_{n\to\infty}\sqrt[n]{n+1}=1$$


Why is there a m3 in diminished triads and diminished sevenths?

Question: In a diminished triad, the diminished interval is 1>5. In a full diminished seventh chord, the 1>7 is also diminished. In a half-diminished chord, the 1>5 is diminished.(But one third of it still has a  minor third!).
The third is always m3, and that sounds good. But what is the technicality behind 'it must be m3'. Theoretically, one may expect dim.3, but that's not good. I realise it sounds better with m3, but that's m3.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/119673/discussion-on-question-by-tim-why-is-there-a-m3-in-diminished-triads-and-diminis).
Comment: Yes, it's a dupe, which either I missed, or it didn't show up. My apologies.
Answer: It seems there are two ways of thinking about this.

chords are arbitrary intervals above a root
chords are the diatonic intervals above a root

It isn't purely one or the other, but I think the primary foundation is diatonic with some chromatic modification.
Rather than a diminished triad being arbitrarily a minor third and diminished fifth above a root, it's the diatonic triad rooted on the leading tone.
I think this accounts for most common practice harmony. Even a chromatic chord like a French sixth chord is just an inversion of diatonic iiø7 with the chord's third raised. In other words, it's just a diatonic chord iiø7, with one tone altered.
Diminished triads has a minor third, because the diatonic viio has a minor third. That diatonic chord is the basis for identifying a functional diminished chord.
Comment: I like the logic behind this. Not that I expect theory to be logical - although isn't that what any theory *ought* to be based on? So, purely diatonic? That accounts for the triad.
Comment: Accepted your answer. Forgot about the dupe, which ironically, i commented on profusely. Don't get old - it's not a lot of fun.
Comment: Youth is wasted on the young! Ha ha!


RegEx for " but not \"

Question: I have the following input:
download "http://google.com/index.html" "C:\Users\%username%\AppData\Roaming\test.zip"
keyboard "\"test\""

I need a regex that gives me the content between the quotes like
http://google.com/index.html
C:\Users\%username%\AppData\Raming\test.zip
\"test\"

Its important it ignores the \" character.
Comment: Which regex engine? And you mean quotes, not brackets, right?
Comment: i'm currently working with AutoIT.
Answer: AutoIT's regex engines has some limitations, so you'll need to match the string including the quotes around it, and then remove those. This can most easily be done using a capturing group, which means that you need to work with group 1 of the match result instead of the entire match result:
"((?:[^\\"]|\\.)*)"

will match an entire string.
Explanation:
"         # Match "
(         # Match and capture into group 1:
 (?:      # Start of non-capturing group: Either...
  [^\\"]  # match one character that's neither a quote nor a backslash
 |        # or...
  \\.     # match an escaped character.
 )*       # Repeat as needed
)         # End of capturing group
"         # Match "

Comment: Uh oh, I just spotted a problem: `"((?:[^\\"]+|\\.)*)"` experinces catastrophic backtracking when applied to non-matching strings such as `"12345678901234567890`. (The `+` on the `[^\\"]+` needs to either be made atomic (prolly not supported by AutoIT), or removed entirely.)
Comment: Uh, what limitations?
Comment: @Jerry: Lookbehinds need to be fixed-length. That means I can't make sure I start my regex match at an unescaped quote. But you're right, my current regex doesn't make sure of that, either...
Comment: Yes, +1, but `/"[^\\"]*(?:\\.[^\\"]*)*"/` is much more efficient. See: [PHP: Regex to ignore escaped quotes within quotes](http://stackoverflow.com/a/5696141/433790) Haven't you read  [MRE3](http://www.amazon.com/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124 "Mastering Regular Expressions (3rd Edition)") yet? (I'f not you are really missing out - especially considering your ginormous regex-fu! - Just sayin')
Comment: I see that the contents of the string are to be captured. In this case my recommended regex would be: `/"([^\\"]*(?:\\.[^\\"]*)*)"/`
Comment: @ridgerunner: Sorry for not replying sooner, was AFK for a while. You're right that the "unrolled loop" technique is more efficient (of course I've read Friedl), but I find this simpler version easier to understand. But certainly the `+` needs to go.

RegEx for " but not \"


Core Data predicate to fetch based on two of relationship's properties

Question: I have two simple Entities:
Part {
    @NSManaged var states: Set<PartState>
}

PartState {
    @NSManaged var date: Date
    @NSManaged var state: Int
}

I want to fetch those entities from Part, that newest PartState has state == 1.
I've tried to create NSPredicate:

NSPredicate(format: "SUBQUERY(states, $s, $s.date == max($s.date) AND $s.state == 1).@count > 0")
It looks like max($.date) checks all existing PartState entities, not just those belonging to a given Part and always returns 1 or 0 results.
NSPredicate(format: "ANY (states.state == 1 AND states.date == states.@max.date)")
Fails with: Unable to parse the format string...
NSPredicate(format: "ANY states.state == 1 AND ANY states.date == states.@max.date")
Returns all entities that have ever had state == 1 (which is what I would expect).

The only other solution that comes to my mind, is to have newestState property in Part but I still looking for some NSPredicate-based way.
Answer: You can fetch latest entry based on date using sort Descriptor
and apply predicate to fetch which has state == 1
let fetchRequest = NSFetchRequest<Part>.init(entityName: "Part")
fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "states.date", ascending: false)]

 let predicate = NSPredicate.init(format: "states.state = %@","1")

Comment: I think this will return me those parts that have ever had the state == 1. States property is Set and contains history of state changes. I want fetch all parts with current (newest) state == 1.


What database my applications will use if I have a locally installed database beside it's pod running on local Kubernetes?

Question: I have installed mysql on my Ubuntu machine. I also have a locally running Kubernetes and deployed a mysql deployment on Kubernetes and can reach to that using kubectl exec -it mysql-b4769786-5hf4m sh command, then mysql -p.
I am a little confused now. I don't know do I have two separated databases, one running locally on my OS and the other one also runs locally but upon my Kubernetes cluster? If so, how can I reach to each of them? How should I know the shell I am working with is connected to Kubernetes mysql or my OS mysql?
Or when I write a NodeJS app, will that connect to the mysql installed on Ubuntu or mysql pod is running on local Kubernetes?
Answer: You indeed have two different databases. The container could even have an entirely different operating system (base image).
You can double check by running a simple test:

create a "container" database inside the MySQL container

run SHOW DATABASES; on the other MySQL instance. You shouldn't find anything.
Answer: You have two mysql database: one on you Ubuntu machine and another one in kubernetes BUT
If you want to use mysql on kubernetes from your Ubuntu machine you need to create a Nodeport.
If you do not expose mysql service your local application on your Ubuntu machine is unable to connect to kubernetes mysql pod.
If you expose mysql pod use another port to avoid mysql problems.


Download generated PDF use FileSaver on client side and Snappy on server side

Question: I try to use FileSaver to download generated PDF from server. However, it's not work.
In Laravel framework, I use Snappy to create PDF file from HTML.
$pdf = \PDF::loadView('pub.view', $data);
//$pdf->save('myfile.pdf');    //It's saved successfully.
return $pdf->download('printing.pdf');

From client, I apply $resource service of AngularJS for getting PDF file.
printPDF: {
            method: 'GET',
            headers: {
                accept: 'application/pdf'
            },
            responseType: 'arraybuffer',
            cache: true,
            transformResponse: function (data) {
                var pdf;
                if (data) {
                    pdf = new Blob([data], {
                        type: 'application/pdf'
                    });
                }
                return {
                    response: pdf
                };
            },
            url:'/u/:id/exportTopdf',
            params:{id:'@id'}
        }

After server response, FileSaver will save this file.
myService.printPDF({id: myId},
function successCallback(response){

   saveAs(response, 'filename.pdf');  //FileSaver function

}, function errorCallback(response){

});

When running, the issue is happen in browser console:
`TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided`.

I think FileSaver makes the problem but I don't know how to fix it.
Comment: I fixed it. My issues is response is not blob file. Response is object. I have to extract blob data in response and put in saveAs function. I download it by browser's downloader. However, FDM (free download manager) catch it after browser download. How can I make FDM catch it before browser?
Comment: FDM (free download manager) can not download blob file.
Answer: param = {
  action: "downloadReport",
};
$http({
  method: 'POST',
  url: 'http://localhost:8080/ivftcwcm2/services/fundTransferServices/downloadFile',
  //url:'http://localhost:8080/FundTransferUI/resources/locales/Disclosure.pdf',
  data: param,
  responseType: 'arraybuffer'
}).then(function(response) {
  var file = new Blob([response.data], {
    type: 'application/pdf'
  });
  var fileURL = URL.createObjectURL(file);
  var a = document.createElement('a');
  a.href = fileURL;
  a.target = '_blank';
  a.download = 'pdfFile.pdf';
  document.body.appendChild(a);
  a.click();
}, function(response) {
  alert('call failed');
});


Como pegar informações de clima e tempo?

Question: Me deparei com um problema que gostaria de ver se pode ser solucionado de maneira similar ao dos correios. Quando se tem um cep pode-se resgatar de um web service outros dados, como o endereço e a cidade desse cep informado.
Em relação ao clima, existe alguma forma de com informações do lugar pegar a temperatura da previsão do tempo, o horário e a temperatura atual daquele lugar(a intenção depois era estilizar o css dessa parte da página para deixar um visual agradável)?
Comment: mas eu não queria algo pronto Diego, como deixei claro na pergunta, queria pegar as informações via json por exemplo, algo similar como se faz nos correios, para depois eu manipular e criar meu próprio widget, mas vou dar uma olhada nesses sites também para ver como é.
Comment: "ver se pode ser solucionado de maneira similar ao dos correios" - justamente, fazer um crawler próprio pode ser o caminho. Precisa ver se a licença do site permite. "Não posso nem negar nem confirmar" que eu faço isso atualmente com uma fonte de qualidade, mas de qq forma eu cito a fonte no resultado final, imagino que não tenha problemas com a "licença" dessa forma kkk.
Comment: Existem vários widgets no site do Climatempo e do Tempo Agora. Dá uma pesquisada.
Answer: Você consegue essas informações através de APIs dos serviços de meteorologia, como a do Yahoo!
Criei e testei um exemplo de utilização, como mostrado abaixo:

Onde:

format: é o tipo de dado que será retornado, podendo ser JSON ou XML;
callback: é a função que irá tratar a resposta da sua requisição.

Você também pode adicionar
and u = 'c'

na cláusula WHERE para alterar para o sistema métrico e a escala para Celsius.
Caso seja somente uma cidade, você pode pesquisar o WOEID antes para melhorar o tempo de resposta.
Por exemplo, para São Paulo capital,
http://woeid.rosselliot.co.nz/lookup/sao%20paulo
Iria retornar 455827, onde a consulta final seria:
select * from weather.forecast where woeid = 455827&format=json&callback=callbackFunction

Existe este site, próprio do Yahoo!, onde você pode testar a sua YQL (Yahoo Query Language).
Vale dizer que de acordo com a API do Yahoo, o limite de consultas diárias é de 2 mil requisições, e fique atento aos termos de uso, onde só pode ser utilizada por indivíduos, empresas sem fins lucrativos e uso não comercial.

Lembre-se que a API do Yahoo! é só uma das soluções, caso ela não atenda à suas necessidades, pode pesquisar por 'weather api' ou 'previsão tempo api'.
Comment: vou testar essa solução silvalexandre e depois falo se consegui usar
Comment: Demorei para ver rs, mas tá funcionando direitinho!
Answer: Achei esta 'API' que retorna os seguintes dados:
{
 "cidade":"Sao Paulo - SP",
 "agora":{
  "data_hora":"08\/11\/2013 - 19:59",
  "descricao":"Muito Nublado (noite)",
  "temperatura":"19",
  "humidade":"73%",
  "visibilidade":"9,99 km",
  "vento_velocidade":"20,92 km\/h",
  "vento_direcao":"SE",
  "pressao":"1.015,92 mBar",
  "pressao_status":"subindo",
  "nascer_do_sol":"6:16 am",
  "por_do_sol":"7:25 pm",
  "imagem":"http:\/\/developers.agenciaideias.com.br\/images\/tempo\/27.png"
 },
 "previsoes":[
  {
   "data":"Sexta - 08\/11\/2013",
   "descricao":"Parcialmente Nublado (noite)",
   "temperatura_max":"23",
   "temperatura_min":"16",
   "imagem":"http:\/\/developers.agenciaideias.com.br\/images\/tempo\/29.png"
  },
  {
   "data":"S\u00e1bado - 09\/11\/2013",
   "descricao":"Tempo Bom (dia)",
   "temperatura_max":"27",
   "temperatura_min":"18",
   "imagem":"http:\/\/developers.agenciaideias.com.br\/images\/tempo\/34.png"
  },
  {
   "data":"Domingo - 10\/11\/2013",
   "descricao":"Ensolarado",
   "temperatura_max":"29",
   "temperatura_min":"21",
   "imagem":"http:\/\/developers.agenciaideias.com.br\/images\/tempo\/32.png"
  },
  {
   "data":"Segunda - 11\/11\/2013",
   "descricao":"Parcialmente Nublado (dia)",
   "temperatura_max":"32",
   "temperatura_min":"23",
   "imagem":"http:\/\/developers.agenciaideias.com.br\/images\/tempo\/30.png"
  },
  {
   "data":"Ter\u00e7a - 12\/11\/2013",
   "descricao":"Parcialmente Nublado (dia)",
   "temperatura_max":"30",
   "temperatura_min":"19",
   "imagem":"http:\/\/developers.agenciaideias.com.br\/images\/tempo\/30.png"
  }
 ]
}

Segue a url:
http://developers.agenciaideias.com.br/tempo
Testei a requisição descrita na documentação, com Angularjs, e retornou tudo certinho.  =)
Comment: Essa tal agência tem "api" pra um monte de coisa e não diz as fontes de dados. Não posso afirmar isso, mas me dá impressão de ser uma mera coleção de dados de terceiros obtidos por _crawlers_. E _crawlers_ costumam quebrar quando a fonte original muda de estrutura, além de não necessariamente respeitar as regras de uso da origem. Provavelmente eu nunca usaria uma solução dessas (agora, se eu estiver enganado, basta me apontarem onde está essa informação, que eu mudo de idéia, e ainda faço um elogio pela diversidade de informações).
Comment: @JorgeMatheus também chamados de scrapers, depende do contexto. São aplicações que acessam os dados como se fossem usuários normais navegando no site ou aplicação, e retiram os dados das páginas via operações de strings. Como não é um processo "oficial", e as páginas sempre mudam, dependem de constante atualização de quem fez o crawler, e muitas vezes violam a permissão de uso do site original.
Comment: Sem contar que não está funcionando mais rs... pelo menos não hoje
Comment: @Bacco o que seria `crawlers`?
Answer: A Climatempo (empresa brasileira de meteorologia) lançou uma API em 2017, você consegue pregar a previsão de forma grátis..
O site é https://advisor.climatempo.com.br
Lá tem toda a documentação. É só entrar com seu "Facebook", "Google" ou "Github", gerar um token e fazer a requisição via GET.
Comment: Excelente colaboração Vitor! Muito bom mesmo :)
Answer: Se for via programação com c# recomendo utilizar o Html Agility Pack, com ele voce pode dizer a origem da informação (Site) e informar ao codigo em qual div esta a informação que você quer podendo utilizar para diversos fins, eu por exemplo utilizei para pegar os resultados da mega sena.
http://html-agility-pack.net/?z=codeplex
Answer: Uma alternativa JSON é: http://webservice.seriesanalysis.com/moment/linhares_es
só trocar o nome da cidade seguido do estado. Tirar acentos, exemplo:
linhares_es,
saopaulo_sp,
vitoria_es,
riodejaneiro_rj

Comment: Não consigo consumir dados dessa url
Answer: Baseado na resposta do silvalexandre
Usa o link antes para descobrir o woeid do seu local
    select woeid from geo.places(1) where text='são paulo, sp'

Javascript
Chama a lib jquery e

PHP
$cont = file_get_contents("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(455822)&format=json");

$cont = json_decode($cont,1);

$umi = $cont['query']['results']['channel']['atmosphere']['humidity'];
$temp = $cont['query']['results']['channel']['item']['condition']['temp'];

$temp = intval( ($temp - 32) /1.8 ); //F to C

echo $umi." ".$temp;