The special status of the implication connective in natural deduction

Question: In natural deduction, it seems that implication is not 'yet another connective', at least because it is the only one whose introduction rule requires the apparatus of 'assume', then 'discharge':
As a reference http://www.cs.cornell.edu/courses/cs3110/2013sp/lectures/lec15-logic-contd/lec15.html says:

In natural deduction, to prove an implication of the form P ⇒ Q, we assume P, then reason under that assumption to try to derive Q. If we are successful, then we can conclude that P ⇒ Q.

My question is a soft one. Why this design? Could one have designed a system with no apparatus for 'assume then discharge'? Making the process of creating inferences more 'canonical'? Is the reason for taking this path in natural deduction simply the fact that reasoning by 'assume and discharge' is more 'natural', closer to the way informal inference works? Are there other reasons?
Comment: Negation ($\neg$)/falsity ($\bot$) and disjunction ($\lor$) also use hypothetical judgements in typical presentations of natural deductions, e.g. [the one on Wikipedia](https://en.wikipedia.org/wiki/Natural_deduction#Hypothetical_derivations), so it is not limited to implication.
Answer: It is indeed a rather 'natural' thing to conclude $P \rightarrow Q$ when the assumption of $P$ leads to $Q$. However, many formal proof systems use the 'assume and discharge' for fairly natural proof techniques other than this kind of conditional proof.
The proof by contradiction is a very common one in fact: Assume $P$, and if that leads to a contradiction, then infer $\neg P$. This is often formalized in formal proof systems as $\neg$ introduction.
Proof by cases is another common one: when  you have a disjunction $P \lor Q$, and if the assumption $P$ leads to $R$, and the assumption of $Q$ (in a second, parallel, subproof) leads to $R$ as well, then we can infer $R$. This rule is often formalized as $\lor$ Elimination.
Also, some formal proof systems have no 'assume and discharge' mechanism at all. Axiom systems are like that. The Hilbert system is a well known axiom system.
Still, the conditional does seem to have some kind of 'special' or 'central' status in all of this. As Henning points in the Comments, even when we use 'assume and discharge' for connectives other than the $\rightarrow$, we can still make a close link to the $\rightarrow$. Proof by cases, for example, is sometimes formalized as $P \lor Q, P \rightarrow R, Q \rightarrow R \vdash R$, and to get the two conditionals, one often ends up doing a conditional proof. And, as Luca points out, even the proof by contradiction can be seen as a kind of conditional proof: some systems define $\neg P$ as $P \rightarrow \bot$, and some systems define the rule as $P \rightarrow Q, P \rightarrow \neg Q \vdash \neg P$, and so yet again to get the relevant conditionals one effectively ends up doing a conditional proofs yet again.
And finally, even in axiomatic systems, where there are no 'assume and discharge' rules at all, it is often the case that they have a single inference rule, Modus Ponens, which is, yet again, a conditional rule.
So this is rather interesting: as dozens of questions to this site can attest, the conditional (material implication)  is rather controversial as a truth-functional connective (see: Paraodxes of Material Implication), and yet it in many ways does seem to have this central status in logic ... though this can probably be explained by its close connection to the logical implication, which clearly is central in logic.
Comment: On the other hand, the introduction rule for $\to$ is in some sense the "most general" possible assume-and-discharge rule in that it does not require any particular relation between $P$ and $Q$ but just packs them up in a conclusion. Therefore one may choose to express all _other_ assume-and-discharge rules on top of implication, and for example have a $\lor$elim rule that concludes $R$ from $P\lor Q$ and $P\to R$ and $Q\to R$. This gives a certain economy of concepts that can look attractive from some angles.
Comment: @HenningMakholm True!  And, it should be said, axiom systems often involve one inference rule, Modus Ponens, which is a conditional rule. So, yes, the conditional *is* rather special ... as controversial it is as a truth-functonal connective at all :)
Comment: Just a small remark: if one defines $\neg P$ as $P \to \bot$ (as is customary in intuitionistic logic), then what you call "proof by contradiction" is in fact a proof of an implication.
Comment: @LucaBressan Oh, that's a good point too!  I'll add some of these comments to my Post.
Comment: I found this related, succinct and useful:
`To every argument there corresponds a conditional statement whose antecedent is the conjunction of the argument's premisses and whose consequent is the argument's conclusion. is the argument's conclusion. As has been remarked, an argument is valid if
and only if its corresponding conditional is a tautology.`
*(Symbolic Logic, Copi)*


Learning how to prove that a function can't proved total?

Question: In proof-theory one can prove that in, say, Peano Arithmetic one can't prove a function $f$ total. Often this seems to mean $f$ is growing too fast to be provably total.
I have some background in logic and know the very basics about formal proofs in FO, but overall I'm more familiar with finite model theory than proof-theory. Now I want to learn how to prove a function total in PA and how to prove that a function can't be proved total in PA.
Are there any books that would cover the topic with my background? Also, if there are any lecture notes near the area, I would be very happy receive pointers to them (books do cost a lot and I think I can only afford one).
Answer: The proof theoretic terminology for this concept is "Provable Total Functions"/"Provably Recursive Functions" of a theory.
You will find quite a number of articles on the topic if you search for these terms.
The third chapter of Samuel Buss, "Handbook of Proof Theory", 1998, is devoted to the topic:

Matt Fairtlough and Stanley S. Wainer, "Hierarchies of Provably Recursive Functions".

Part 5 of the chapter is "Independence results for PA".
The totalness of (a $\Sigma^0_1$ representation of) a function corresponds to a $\Sigma^0_1$ formula, or equivalently $\Pi^0_2$ sentence.  Therefore proving that a function is not total in a theory corresponds to an independence result for a $\Pi^0_2$ sentence, and there are not that many core techniques to do this. One technique as you mentioned is to show that the function is growing too fast, so fast that its totality would imply the consistency of the theory at hand. (There are some tricky issues here about the representation chosen for the function.)
Comment: @rank, it is generally a very good book. For a professional review, see [this](http://projecteuclid.org/DPubS?service=UI&version=1.0&verb=Display&handle=euclid.bsl/1182353732) or [this](http://www.math.ucla.edu/~asl/bsl/0604/0604-003.ps). (Arai says it is an excellent exposition of the topic and recommends it for beginners.) But I would suggest using a library copy in place of buying it. It is a handbook after all.


Symfony3 Factory as Service

Question: I have been trying to get my head around this
http://symfony.com/doc/current/service_container/factories.html
But there seems to be a piece missing that tires it all together OR I am completely missing the point.
The example has a factory Class
class NewsletterManagerFactory
{
    public static function createNewsletterManager()
    {
        $newsletterManager = new NewsletterManager();

        // ...

        return $newsletterManager;
    }
}

And then that factory is configured via a service to be the factory class and method for NewsletterManager service.
services:
    app.newsletter_manager_factory:
        class: AppBundle\Email\NewsletterManagerFactory

    app.newsletter_manager:
        class:   AppBundle\Email\NewsletterManager
        factory: 'app.newsletter_manager_factory:createNewsletterManager'

So now we have a NewsletterManager Class that is aware of the NewsletterManagerFactory Class via the factory: param in services.yml
Question
How do you make use of this configuration? What is now exposed inside of NewsletterManager that allows me to call createNewsletterManager in the factory Class?
The two services are still completely separate as far as I can tell?
Answer: I used this pattern once. Here is the use case for it.
Imagine that you have multiple widget classes i.e. Acme\Widget1, Acme\Widget2, Acme\WidgetN.
Each widget has an advanced instantiation process so you decide to use a factory. It also has a complex dependency chain that is needed for each widget to be instantiated. I.e. Acme\Dependency1, Acme\Dependency2, Acme\Dependency3.
So what you'd do is to create Acme\WidgetFactory service with dependencies once. Then you need to specify that Acme\WidgetFactory as factory for each widget. In case something changes in the way of widget instantiation you only need to change one class and one service definition. All 1 to N widget services stay the same.
Here is the example...
Typical way of implementation:
acme.widget1:
    class: Acme\Widget1
    factory: ['Acme\Widget1', 'create']
    arguments: ['@acme.dependency1', '@acme.dependency2', '@acme.dependencyN']

acme.widget2:
    class: Acme\Widget2
    factory: ['Acme\Widget2', 'create']
    arguments: ['@acme.dependency1', '@acme.dependency2', '@acme.dependencyN']

acme.widgetN:
    class: Acme\WidgetN
    factory: ['Acme\WidgetN', 'create']
    arguments: ['@acme.dependency1', '@acme.dependency2', '@acme.dependencyN']

Here you have a strong smell of code duplication. If you want to change something you need to do it N times.
Instead here is what you can do.
acme.widget_factory:
    class: Acme\WidgetFactory
    arguments: ['@acme.dependency1', '@acme.dependency2', '@acme.dependencyN']

acme.widget1:
    class: Acme\Widget1
    factory: ['@acme.widget_factory', createWidget]

acme.widget2:
    class: Acme\Widget2
    factory: ['@acme.widget_factory', createWidget]

acme.widgetN:
    class: Acme\WidgetN
    factory: ['@acme.widget_factory', createWidget]

Code duplication is gone.
Appeared small inconvenience... Factory does not know what concrete class to instantiate. I used the following technique for it.
I tagged each widget and then during compiler pass added extra parameter to factory.
acme.widget_factory:
    class: Acme\WidgetFactory
    arguments: ['@acme.dependency1', '@acme.dependency2', '@acme.dependencyN']

acme.widget1:
    class: Acme\Widget1
    factory: ['@acme.widget_factory', createWidget]
    tags:
        - { name: acme.widget }

acme.widget2:
    class: Acme\Widget2
    factory: ['@acme.widget_factory', createWidget]
    tags:
        - { name: acme.widget }

acme.widgetN:
    class: Acme\WidgetN
    factory: ['@acme.widget_factory', createWidget]
    tags:
        - { name: acme.widget }

Then in DepencencyInjection\AcmeDemoExtension.php
class AcmeDemoExtension implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $widgets = $container->findTaggedServiceIds('acme.widget');
        foreach ($widgets as $id => $tags) {
            $definition = $container->getDefinition($id);
            $definition->setArguments([$definition->getClass()]);
        }
    }
}

and finally in the factory...
class AcmeWidgetFactory
{
    //.....
    public static function createWidget($class)
    {
        //.....
        return new $class(/*  dependencies */);
        //.....
    }
    //.....
}

So at the end when you do $this->get('acme.widget1') the factory method with class name as a parameter is called. Factory already has all dependencies and knows the logic of class instantiation. So it does all the work and return required widget instance.
Comment: Thanks this is useful and I can see why this is handy. But I am still not clear on why you add the `factory` param to the service. For instance the `acme.widget2` service now has a factory param of `['@acme.widget_factory', createWidget]` but how is that used inside of the class `Acme\Widget2`. Can you show me what the `Acme\Widget2` class might look like?
Comment: Nothing special in there. Just a class with a constructor. All instantiation logic is moved to a factory. When Symfony wants to instantiate `acme.widget2` it takes instance of `acme.widget_factory` and calls its method `createWidget()` with widget class name as parameter. All complex logic of instantiating and setting up happens there. At the end `createWidget()` returns ready to be used instance of `Acme\Widget2`.
Comment: Hi! So useful example, but I can't guess how to pass and get dependency arguments from the controller (doing that ->get('service.id')) to the factory. Thank you in advance. Cheers!
Comment: Hi, could you please elaborate on how the WidgetFactory's "createWidget()" method gets the dependencies?
Answer: This is simple. If you gonna call
$nm = $container->get('app.newsletter_manager')

then the newsletter manager will be created by factory automatically.
Comment: @JakeN, no, the return value of the factory method is the service. The factory class itself is just an intermediary that is not directly adressable. You can however write a separate service definition for the factory too, if desireable.
Comment: Ok so the point is that the service returns a new object. Rather than the service itself?
Comment: Exactly. The service (the factory) returns an new service or entity or what ever your factory creates.

Symfony3 Factory as Service


Reference only answers

Question: This answer just consists of a couple of paper references. My initial feeling is that we should treat these like link only answers and ask the author to add more details inline etc so that the answer is valid even if the paper isn't available. Ultimately if this doesn't happen the answers might end up being deleted or converted into comments.
On the other hand academic papers should be more durable/findable in the long-term than random Internet links, so I thought I'd ask a general question here first.
EDIT: the poster has now added the abstracts to the answer, which makes the references a lot more helpful, so for me this question is now just about future cases.
Comment: I think there are some questions best answered with a reference (not only reference requests), e.g. "Is there someone using method X on the labor market?  - Yes, for example paper Y uses this method." It might not be the best answer but imho still a valid answer. (The question you mentioned is imho not answered by the "answer" and not answerable by a reference only, but I wouldn't condemn reference only answers per se.)
Comment: Some paraphrasing of the source material would also be useful if the source is behind a paywall.
Comment: I think at least a sentence or two about why a reference is relevant should be in order. Papers may be durable, but finding and reading them takes time and there are potentially large efficiency savings if I can determine beforehand how relevant the referenced work is likely to be.
Comment: Unless the question is asking for references, references don't answer questions. Flag as not an answer.
Comment: @TheAlmightyBob: I agree with you, but I still think a few words explaining what is in the references are in order. Remember that the answer is not only for the original asker, but also for anyone in future who comes here with a similar question. That may include people who legitimately can't access the references. It might also include people with slightly different, but related questions who may therefore have a hard time judging whether the references are relevant or not. such people would surely be helped by a brief synopsis.
Answer: Just a few thoughts. Something is always better than nothing and people are giving up their own time to post anything at all. Not that anybody is suggesting it, but I just want to suggest that no one should be punished for posting a link/citation only answer. Hopefully, if the question is a good question, other people will post more complete answers (and get compensated with upvotes or whatever) and the asker doesn't need to accept the answer until he/she is satisfied. So, my recommendation is that

citation only answer should NOT be automatically removed
don't downvote unless the question was actually harmful (the citation was irrelevant to the question or something)
it's ok to ask for more details---always ok. But, we should just remember that people are giving up their own time to provide answers---even if it's just a citation (citations alone can be super useful after all)
Comment: This is not how other SE sites work and I see no reason why it should be how this site works.
Answer: Having read the other answers and thought about this a bit more, I don't think reference-only answers should be deleted/converted into comments.
Looking again at Shog9's post about link-only answers, he points out that a link where the link text describes the content - e.g. "You probably want a FileOutputStream" - are valid answers, even if not very good ones.
References also include that kind of information, so we should keep them. They are certainly better - i.e. more worthy of upvotes - if they include a synopsis and explanation of why they are relevant, though.
Answer: I'm the OP in that question and I would actually be satisfied with references only if the papers were relevant, which they were not.
I'm asking whether anyone has dealt with argument XYZ, so if I get some references that deal with it, I'm happy. If I want to be sure that its the right paper, I can still look into the abstract.
The link-only policy on Stackexchange was also established because of the dependency on the external website - if the link breaks, the answer becomes useless.
However, with scientific references (especially published ones), there is no way the "link breaks" - so this point is somewhat invalid.
Ah, and regarding paywalls: Most authors have the final working paper version of the publication online, so there's always a "free" version available. I have not encountered else, at least.
Update
Actually, the (lengthy) descriptions that it contains now are copies of the abstracts. I feel uncomfortable with that, not only due to potential copyright/plagiarism issues.
Comment: Abstracts are pretty well always freely available online. I can't imagine how that could possibly be a breach of copyright or plagiarism, particularly if it comes with a link to the journal or database.
Answer: A link-only answer is problematic when the user then has to follow the link to find the right answer, for the following reasons:

A lot of people browsing might be unable, and many would be unwilling, to follow a link away.
We're trying to build a body of awesome content here. While it's great to link to awesome content elsewhere, it's even better to summarise it here too: that way, economics.SE can become a known substantial repository for expert knowledge.
When new people do happen by, typically from a web search, we'd like them to stay and contribute quality content. If, when they arrive for the first time, all we do is send them elsewhere to find their answer, our rate of accumulation of new members of the community will suffer.
Summarising the link adds indexable content that search engines can use to help other people with similar questions to find our content here.

So, we should discourage link-only answers, with the usual tools: commenting to give guidance on best practice; down-voting; and flagging as "not an answer".
As an  additional note while we're on the subject, it's best if journal links are via DOI (using one of the major DOI linkers such as dx.doi.org) whenever possible. There's a good chance that that will be more stable in the long term than some deep link to a particular publisher or journal. And it would make it easier for SE devs to do a search & replace in the databaes, if dx.doi.org ever did go down.

Reference only answers


My www version of site is redirecting to the non www version of another site on the same nginx server

Question: I have two domains setup on one server running LEMP.
When i access the domain2.co.uk everything is fine. But when I go to www.domain2.co.uk it is redirecting to www.domain1.co.uk
nginx.conf
    user www-data www-data;
    worker_processes  4;
    events {
        worker_connections  1024;
    }
    http {
        include       mime.types;
        default_type  application/octet-stream;
        sendfile        on;
        tcp_nopush      on;
        tcp_nodelay     off;
        keepalive_timeout  5;
        gzip  on;
        gzip_comp_level 2;
        gzip_proxied any;
        gzip_types      text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
        include /usr/local/nginx/sites-enabled/*;
    }

../sites-enabled/domain1.co.uk
server {
            listen   80;
            server_name  www.domain1.co.uk;
            rewrite ^/(.*) http://domain1.co.uk/$1 permanent;
       }
server {
            listen   80;
            server_name domain1.co.uk;
            access_log /home/me/public_html/domain1.co.uk/log/access.log;
            error_log /home/me/public_html/domain1.co.uk/log/error.log;
            location /  {
                        root   /home/me/public_html/domain1.co.uk/public/;
                        index  index.php index.html;
                        # WordPress supercache &  permalinks.
                        include /usr/local/nginx/conf/wordpress_params.super_cache;
                        }
            # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
            location ~ \.php$
                    {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include /usr/local/nginx/conf/fastcgi_params;
            fastcgi_param SCRIPT_FILENAME /home/me/public_html/domain1.co.uk/public/$fastcgi_script_name;
                        }
       }

../sites-enabled/domain2.co.uk
server {
        listen 80;
        server_name  www.domain2.co.uk;
        rewrite ^/(.*) http://domain2.co.uk/$1 permanent;
}
server {

            listen 80;
            server_name domain2.co.uk;

            access_log /home/me/public_html/domain2.co.uk/log/access.log;
            error_log /home/me/public_html/domain2.co.uk/log/error.log;

            location /
            {

                root   /home/me/public_html/domain2.co.uk/public/;
                index  index.php index.html;

                # Basic version of WordPress parameters, supporting nice permalinks.
                # include /usr/local/nginx/conf/wordpress_params.regular;
                # Advanced version of WordPress parameters supporting nice permalinks and WP Super Cache plugin
                include /usr/local/nginx/conf/wordpress_params.super_cache;
            }

            # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
            #
            location ~ \.php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include /usr/local/nginx/conf/fastcgi_params;
            fastcgi_param SCRIPT_FILENAME /home/me/public_html/domain2/public/$fastcgi_script_name;
            }
      }

Comment: You've probably have some error in www.domain2.co.uk domain: missed ';', non-printable character, etc. Try re-writing it from scratch in a new file.
Comment: Any chance that the script has a redirect coded into it as well as nginx?
Comment: @rvs I tried what you suggested and it never resolved the issue.
Comment: @Jack M not sure I understand what you mean?
Comment: You are passing control from nginx to wordpress or some other .php file.  Are those scripts doing a redirect?
Comment: Make sure you're testing the redirect with curl -I and not a browser.  A browser may have cached an incorrect 301 if you had a problem in the past, and sometimes they'll continue to use that cached 301 long after the server configuration has been corrected.
Comment: @Jack Wodpress is a fresh bare minimal install. It was installed and configured on domain2.co.uk and works fine. It's just when I checked that the www version would correctly 301 to domain1.co.uk I come across the issue.
Comment: @kolbyjack - thank you that done the trick. Curl confirmed it was redirecting correctly, so I cleared the cache and bingo! If you want to add it as answer I will mark it as the correct one. Thanks!
Answer: Make sure you're testing the redirect with curl -I and not a browser. A browser may have cached an incorrect 301 if you had a problem in the past, and sometimes they'll continue to use that cached 301 long after the server configuration has been corrected.


Sharding MongoDB internationally with data stored based on location

Question: We're looking to set up data centers globally and switch to a NoSQL database like MongoDB to support having our data distributed over these data centers (and as a pleasant side effect, introduce more redundancy, failover etc).
However, the reason for global data centers is primarily to speed response times for our users in nearby countries, rather than the failover features. The web application is designed to be used on a company scale, and few of these companies operate on a global scale. As such, as many users on one side of the world will never need to access data from those users on the other side, it would be nice if the data could be kept on the servers that are local to the majority of the users.
I had hoped that I could use the sharding features of mongodb to have the data distributed globally like this, while still allowing for access and maintenance from a single location (which would be slow, and query the international servers). Unfortunately, the only reference I can find to this type of behavior is a mention of "intelligent homing" on a MongoDB blog bost and nothing else. While it would be possible to just sync everything globally, it seems rather inefficient and unmetered bandwidth isn't an option in at least one of the countries.
Can mongodb support this kind of behavior? Any further information on how to get this kind of set up working (or why I should not get this set up working as it'll make kittens die etc) would be much appreciated.
Answer: Some of this already in place with MongoDB, see a decent write up here:
http://www.mongodb.org/display/DOCS/Data+Center+Awareness
In terms of read-routing, there are some implementations in the drivers, but it is not built in.  The feature complete version of localized data reads is intended to be released with 2.2
If you would like to take a look at the two most closely related core server issues, you can take a look here:
https://jira.mongodb.org/browse/SERVER-3062
https://jira.mongodb.org/browse/SERVER-3358
And, of course, you can then vote on the feature to bump it up the list :)
Comment: Thanks a lot for this information :) sorry for taking so long to respond, I don't often log in to server fault! Much appreciated.


Why $\zeta(-1)=-\frac{1}{12}$ does not mean the sum from $1$ to infinity is $-\frac{1}{12}$

Question: Since $\zeta(-1)=\frac{1}{1^{-1}}+\frac{1}{2^{-1}}+\frac{1}{3^{-1}}+\cdots=-\frac{1}{12}$, why do we still say that $\sum^\infty_{n=1}n\rightarrow+\infty$?
Comment: Because $\zeta(-1)\ne\sum_{n=1}^\infty n$.
Comment: $\zeta(-1)$ is not $\frac{1}{1^{-1}}+\frac{1}{2^{-1}}+\cdots$. The equation $\zeta(s) = 1^{-s}+2^{-s}+\cdots$ is only valid for $Re(s)>1$.
Comment: You might find [this blog post I wrote once](http://davidlowryduda.com/?p=1551) about this question useful.
Comment: This question appears regularely and the "conclusion" seems to have an influence to the string theory. The tragedy : Mathematics is necessary to quantify physical results. But unfortunately, modern physics tries to interpret mathematical results (especially, if they are "beautiful") in a physical way. But Mathematics can, of course, not replace the understanding of physics.
Comment: This leads to tremendous problems, but instead of rethinking about this method, the problems turn into sensational physical "realities". This is especially the case in astronomics.
Comment: Note the linked question with 172 upvotes ! The discussion seems to result in the acceptance of the above equation because it can be derived from the extension of the riemann-zeto-function. I agree with Daniel Fischer, who calls this a "misused result".
Answer: First of all, it is NOT TRUE that
$$\zeta(-1) = \frac{1}{1^{-1}} + \frac{1}{2^{-1}} + \dots$$
The Riemann Zeta function is only defined as
$$\zeta(s) = \sum_{i=1}^\infty \frac{1}{n^s}$$
for values of $s$ for which the real part of $s$ is greater than one.
For other values, we can calculate the analytic continuation of $\zeta$ to define the function on the entire complex plane, but that means that we are expanding the definition beyond what it originally was.

You need to understand where our definitions come from:

First, we have infinite sequences.
From infinite sequences, we construct infinite series, and we define when these series converge.
Then, we take a very specific family of infinite series, and we construct a function that sums them.
Then, we expand the definition of this function to other numbers.

Now, if we take a series and ask "does it converge", we cannot say "yes because Riemann's zeta says so". We have an earlier definition, and to answer convergence, we need to use that definition.

So, why does $$\sum_{i=0}^\infty i$$
diverge? Simply. Take the original definition of convergence of series, and the answer becomes:
Because $$\sum_{i=0}^\infty a_i$$
is defined as $$\lim_{N\to\infty} \sum_{i=0}^N a_i$$
And the sequence in the case when $a_i = i$ diverges toward $\infty.$
Comment: @avid19 Personally, I will sleep on mi right side covered on a blanket. How will you sleep?
Comment: +1 Upvoted to counter vandal (?) downvote.
Comment: @avid19 This perfectly answers the question of why the sum is $\infty$. I intentionally left out any mention of Ramanujan's summation and Riemann's zeta functions because they have nothing to do with the fact that the sum is $\infty.$
Comment: An answer should use the phrase "analytic continuation".
Comment: @avid19 No. If the question was "Why is $\zeta(-1) = -\frac{1}{12}$" ten the answer should involve that phrase. Anyway, the question was changed, and I will now edit my answer.
Comment: @avid19 I know. That was my intent. I wanted OP to clearly show, in his question, what he did wrong. I did not want to *assume* where his confusion came from. I hoped OP would change the question. And I think the original answer was incomplete, yes, but not completely wrong, as you say. But anyway, we don't agree, and this is the internet, so nothing surprising.
Comment: I am the downvoter. This does not answer the question at all.
Comment: @5xum that isn't quite his/her question though.
Comment: I upvoted your answer after you addressed the source of confusion. Before it didn't address OP's confusion at all.
Comment: @5xum How can we possibly sleep tonight knowing some stranger on the internet might be *wrong*? :)
Comment: @5xum Again with missing the point. :)


Problem when $x=\cos (a) +i\sin(a),\ y=\cos (b) +i\sin(b),\ z=\cos (c) +i\sin(c),\ x+y+z=0$

Question: Problem: If $$x=\cos (a) +i\sin(a),\ y=\cos (b) +i\sin(b),\ z=\cos (c) +i\sin(c),\ x+y+z=0$$ then which of the following can be true:
1) $\cos 3a + \cos 3b + \cos 3c = 3 \cos (a+b+c)$
2) $1+\cos (a-b) + \cos (b-c) =0$
3) $\cos 2a + \cos 2b +\cos 2c =\sin 2a +\sin 2b +\sin 2c=0$
4) $\cos (a+b)+\cos(b+c)+\cos(c+a)=0$
Try: I tried taking $x=e^{ia},y=e^{ib},z=e^{ic}$ and then i tried expressing each option in euler form
FOR EXAMPLE:
1) $-3/2 e^{-i a-i b-i c}-3/2 e^{i a+i b+i c}+1/2 e^{-3 i a}+1/2 e^{3 i a}+1/2 e^{-3 i b}+1/2 e^{3 i b}+1/2 e^{-3 i c}+1/2 e^{3 i c}$
2) $1/2 e^{i a-i b}+1/2 e^{i b-i a}+1/2 e^{i b-i c}+1/2 e^{i c-i b}+1$
3) $1/2 e^{-2 i a}+1/2 e^{2 i a}+1/2 e^{-2 i b}+1/2 e^{2 i b}+1/2 e^{-2 i c}+1/2 e^{2 i c}$
4) $1/2 e^{-i a-i b}+1/2 e^{i a+i b}+1/2 e^{-i a-i c}+1/2 e^{i a+i c}+1/2 e^{-i b-i c}+1/2 e^{i b+i c}$
Now after all this i'm stuck!!Please help!! How should i proceed?
Comment: Note that $Re(e^{ia})=\cos(a)$ and $Im(e^{ia})=\sin(a)$. Perhaps you can prove the above assertions by looking at real and imaginary parts?
Answer: HINT:
For $(1),$
Using If $a,b,c \in R$ are distinct, then $-a^3-b^3-c^3+3abc \neq 0$.,
we have $x^3+y^3+z^3=3xyz$
Now $x^3=e^{i(3a)}=\cos3a+i\sin3a$
and $xy=e^{i(a+b)}=\cos(a+b)+i\sin(a+b),xyz=\cdots$
For $(3),(4)$
$x+y+z=0\implies\cos a+\cos b+\cos c=\sin a+\sin b+\sin c=0$
So, $x^{-1}+y^{-1}+z^{-1}=?$
Now $x^2+y^2+z^2=(x+y+z)^2-2(xy+yz+zx)=(x+y+z)^2-2xyz(x^{-1}+y^{-1}+z^{-1})=?$
Comment: In the 3 rd and 4 th option i need x^2+y^2+z^2=0,and xy+yz+zx=0,but in no way i can find these equalities from x+y+z=0,any ideas?Am i on the right track.(the first option is correct..i verified)
Comment: @SanchayanDutta, Let me update the answer
Comment: Ok thanks :)....
Comment: @SanchayanDutta, Please find the updated answer
Answer: A hint:
You have three unit vectors in the plane, summing up to $0$. How does the figure look like when you add them geometrically as you add forces?


Inner join returns repeated registries

Question: well, I'm very new at this, so here is my problem..
I'm trying to make some sort of multiple restaurant menu database, and after so much struggle with the structure, I got one.
this is the overall structure.
Clients
ID (int 10, PK)
mombre(varchar)
etc etc.(etc)

menucat
menuID (int 10, FK references clients.ID)
IDcat  (int 10, PK)
nombre

menuitem
ID (int 10, PK)
catID (int 10, FK references IDcat)
nombre

problem:

i have this query so far:
SELECT c.ID
     , c.nombre
     , mc.nombre
     , mi.nombre
FROM clientes as c
     , menuitem as mi
     , menucat
  JOIN menucat as mc
    ON mc.IDcat = mi.cat Id
 GROUP
    by mc.IDcat

this brings me: mc.nombre and mi,nombre fine, as intended.
BUT, c.ID and c.nombre repited as if it where only one registry... how can i formulate this query so it brings my two clients with their respective menus?
sorry for my poor english and my poor skill to write here.
thanks. btw I'm using phpmyadmin SQL console
Comment: Use proper query!!!  You query is not even valid.  What's the purpose of `GROUP BY` without aggregation???  All those columns must be in `GROUP BY`.
Answer: SELECT c.ID , c.nombre , m.nombre , i.nombre
FROM Clients AS c
INNER JOIN menucat AS m
  ON m.menuID = c.ID
INNER JOIN menuitem AS i
  ON i.catID = m.IDcat

This will return ALL menu items with their associated menus and clients. (Assuming they are associated)
Consider renaming the columns in your table to make the references in your database easier. For instance the FK constraint on menucat that references clients.ID should be on a column called ClientID or something similar. Not on one called menuID since it is relating to a client, not a menu.
It would also help if you gave us an example of what you want to return.
Comment: thanks man, what you said was exactly what i wanted, thanks a lot!

Inner join returns repeated registries


How do I call methods in a class that I created dynamically with NSClassFromString?

Question: The reason I am doing dynamic class loading is because I am creating a single set of files that can be used across multiple similar projects, so doing a #import and then normal instantiation just won't work. Dynamic classes allows me to do this, as long as I can call methods within those classes. Each project has this in the pch with a different "kMediaClassName" name so I can dynamically load different classes based on the project I'm in:
#define kMediaClassName @"Movie"

Here is the code I am using to get an instance of a class dynamically:
Class mediaClass = NSClassFromString(kMediaClassName);
id mediaObject = [[[mediaClass alloc] init] autorelease];

Then I try to call a method within that dynamic class:
[mediaObject doSomething];

When I then type this into Xcode, the compiler shows a warning that the class doesn't have this method, even though it does. I can see it right there in my Movie.h file. What is going on? How do I call a method from a dynamically instantiated class?
And what if I need to pass multiple arguments?
[mediaObject loadMedia:oneObject moveThe:YES moveA:NO];

Thanks for the help in advance.
Answer: you can declare a protocol, like so:
@protocol MONMediaProtocol

/*
  remember: when synthesizing the class, you may want
  to add the protocol to the synthesized class for your sanity
*/

- (BOOL)downloadMediaAtURL:(NSURL *)url toPath:(NSString *)path loadIfSuccessful:(BOOL)loadIfSuccessful;

/* ...the interface continues... */

@end

in use:
Class mediaClass = NSClassFromString(kMediaClassName);
assert(mediaClass);

id<MONMediaProtocol> mediaObject = [[[mediaClass alloc] init] autorelease];
assert(mediaObject);

NSURL * url = /* expr */;
NSString * path = /* expr */;

BOOL loadIfSuccessful = YES;

BOOL success = [mediaObject downloadMediaAtURL:url toPath:path loadIfSuccessful:loadIfSuccessful];

Comment: I was going to recommend using a protocol too, especially since it seems like he has many classes with the same method names.
Comment: After realizing that I need to pass multiple arguments as well as return an object, I think implementing a protocol is most likely the way to go. I'll try to use this.
Answer: Well it might be there, but the Compiler doesn't know about it because it assumes that mediaClass is just some Class object, but nothing specific. NSClassFromString() is a runtime function and thus can't give the compiler a hint at compile time about the object.
What you can do:

Ignore the warning
Use [media performSelector:@selector(doSomething)];

And btw, this is wrong:
Class mediaClass; = NSClassFromString(kMediaClassName);

it should be:
Class mediaClass = NSClassFromString(kMediaClassName);

Comment: What if I need to pass multiple arguments to the method? Example: `[mediaObject loadMedia:oneObject moveThe:YES moveA:NO];`
Comment: Then use NSInvocation like Joe Blow already suggested, its your best bet in this case.
Comment: You can always use objective-c runtime functions to accomplish that. Please see my answer ;)
Answer: An easier and fancier solution than NSInvocation :)
Class mediaClass = NSClassFromString(kMediaClassName);
if(mediaClass){
    id mediaObject = class_createInstance(mediaClass,0);
    objc_msgSend(mediaObject, @selector(doSomethingWith:andWith:alsoWith:), firstP, secondP,thirdP);
}

Explanation:
class_createInstance(mediaClass,0); does exactly the same as [[mediaClass alloc] init];
if you need to autorelease it, just do the usual [mediaObject autorelease];
objc_msgSend() does exactly the same as performSelector: method but objc_msgSend() allows you to put as many parameters as you want. So, easier than NSInvocation right? BTW, their signature are:
id class_createInstance(Class cls, size_t extraBytes)
id objc_msgSend(id theReceiver, SEL theSelector, ...)

For more info you can refer the Objective-C Runtime Reference
Comment: http://stackoverflow.com/questions/4896533/invoke-selector-with-scalar-argument/4900859#4900859
Comment: This is awesome, thank you. On the iPhone I just needed to make sure I imported the following: #import
#import
Comment: it can do the job, but it's far too dangerous for my taste. see bbum's response in JustSid's link for the explanation.
Answer: As Joe Blow says, NSInvocation will help you here, though NSObject has a couple of shortcut methods that you can use: -performSelector:, -performSelector:withObject:, and -performSelector:withObject:withObject:.


How to change color of Toggle fullscreen view button

Question: I want to change Buttons color(Toggle fullscreen view) in Google Maps.
Please let me know how it can be done.
Comment: You can't with any documented method. Create your own buttons.
Answer: Go to Google Maps and open browser options
More Tools -> Development Tool -> Console
Type in console line:
document.getElementById("your button id").style.backgroundColor = "color"

To find your control, right click on it and press explore.
I don't find the fullscreen view, but to change the background color of the search box you can execute:
document.getElementById("searchbox_form").style.backgroundColor = "red"

Maybe it helps.


how to model the JS in angular

Question: I have this json
    var myNameSpace = angular.module('myApp',[]);
    function MyController($scope){
    $scope.phoneBookData = [{ name : "book1",
                 contacts : [{   "name" : "con1",
                                 "age" , 20 },
                                 {"name" : "con2",
                                 "age" : 30

                            },
                     { "name" : book2,
                         contacts : [{   "name" : "con11",
                                 "age" , 25 },
                                 {"name" : "con22",
                                 "age" : 40

                            } }]
     }

The HTML should look like label for the name and table for the contacts

     <li class ="phone books" ng-repeat="item in phoneBookData"
     {{item.name}}

it didn't work do I need to add more ng-repeat?
Comment: You're missing a closing `` tag - and format your post please, it's very hard to read.
Comment: Closing li tag is not very necessary, but an ul would definitely not hurt.  Also, format code pls, and add plunkr.
Comment: @MihalyKR -- Closing it is necessary...
Comment: You're right - now I see what you mean, overlooked that it doesnt have the closing bracket. Looked like it only misses the  part.
Answer: Along with needing to fix all the typos, yes you do need another ng-repeat for the contacts array

var myNameSpace = angular.module('myApp',[]);
myNameSpace.controller('MyController', function ($scope){
  $scope.phoneBookData = [{
    name : "book1",
    contacts : [{
      "name" : "con1",
      "age": 20
    },{
      "name" : "con2",
      "age" : 30
    }]
  },{
    "name" : "book2",
    contacts : [{
      "name" : "con11",
      "age": 25
    },{
      "name" : "con22",
      "age" : 40
    }]
  }];
});

       {{item.name}}

{{contact.name}}

{{contact.age}}

Answer: Your code is full of errors. You are spelling the name of your controller two different ways which is likely your problem. Your json is also broken. Working code
    var myNameSpace = angular.module('myApp',[]);
        function MyController($scope){
        $scope.phoneBookData = [{ name : "book1",
                                   contacts : [{   "name" : "con1",
                                                   "age" , 20 },
                                               {"name" : "con2",
                                                 "age" : 30

                                                },
                                                { "name" : book2,
                                                   contacts : [{   "name" : "con11",
                                               "age" , 25 },
                                     {"name" : "con22",
                                     "age" : 40

                                } }]
         }

     <li class ="phone books" ng-repeat="item in phoneBookData"
     {{item.name}}

Comment: You could also fix HTML.
Answer: Insane number of errors in such a small code:

MyController != MyControler
"name" : book2 = improper JSON (should be "name" : "book2" unless book2 is a variable)
<li class ="phone books" ng-repeat="item in phoneBookData" - needs closing
count the open and closed square braces in $scope.phoneBookData ([ and ]), don't even want to talk about the curly ones - again, you need to close what you open

 Are you sure you want the name as an element attribute. Shouldn't it be
{{item.contacts.name}}
 instead?

 The same as above

Most of those errors are shown in a browser console. Or you could see them in the source if it was formatted for humans.
To get the contacts in the table for each book, you need another ng-repeat for it.
I strongly suggest learning JavaScript and HTML before working in AngularJS.

how to model the JS in angular


Como colocar um valor default em um campo int no mysql

Question: Gostaria que o próprio SGBD, no caso MySQL colocasse um valor default em uma coluna da minha tabela, como acontece no MSSQL, isso é possível?
Por exemplo, uma das colunas da tabela é um campo flag, queria que ao criar uma linha ele colocasse 0 nesta campo, caso não viesse nada no comando INSERT.
Tem como fazer isso?
No MSSQL eu usaria o comando:
ALTER TABLE SaidaVeiculos
 ADD CONSTRAINT DF_FlagAutorizado DEFAULT(0) FOR FlagAutorizado;

E no mysql, qual é o comando?
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Sim é possível, como descrito na documentação oficial do MySQL, exemplo:
CREATE TABLE t1 (
  i     INT DEFAULT -1,
  c     VARCHAR(10) DEFAULT '',
  price DOUBLE(16,2) DEFAULT 0.00
);

Referencia: 11.6 Data Type Default Values
Com o comando ADD COLUMN:
ALTER TABLE table_name ADD COLUMN column_name INT NULL DEFAULT 0

Com o comando ALTER COLUMN:
ALTER TABLE table_name ALTER COLUMN column_name SET DEFAULT 'literal';

Outros exemplos:
ALTER TABLE products ALTER COLUMN stocks integer SET DEFAULT 0;

ALTER TABLE products ALTER available SET DEFAULT true;

Referencia: How to alter a column and change the default
Referencias:

SQL DEFAULT Constraint
Changing a Column's Default Value
How to alter a column and change the default
11.6 Data Type Default Values
How to Add a Default Value to a Column in MySQL


Ligação de voz entre dois pontos

Question: Gostaria de estudar sobre, ler como é feito e todos detalhes possíveis sobre realizar ligações de voz entra dois pontos A e B
Igual funciona essas ligações entre usuários como o viber, WhatsApp, facebook fornecem.
É possível usando PHP HTML5 JavaScript ?
Answer: Sobre o PHP:
Não vou dizer que é impossível fazer PHP, mas talvez seja um duro caminho, pois será necessário que algo capture o áudio das pessoas na conferencia, salve em documentos estes dados e as pessoas que houvem a conferencia ficam esperando novos bytes serem adicionados ao servidor, isto pode ser muito custoso para desenvolver e para o servidor.

Relatado: Como fazer live stream basico com HTML5 vídeo API e PHP?

Sobre o HTML5 ou JavaScript API:
Nativamente não é possível fazer streaming de comunicação, será necessário um plugin especifico.

Nota: O Google Chrome Canary (para desenvolvedores) já suporta isto

Conforme está resposta do SOen algumas tecnologias estão sendo desenvolvidas, porém não foram implementadas e provavelmente irão demorar de implementar devido as dificuldades, já que são coisas consideradas muito "novas" (me refiro ao HTML/JavaScript integrar tantas funcionalidades "diversificadas" que antes nem se imaginava em ser algo "nativo"):

WebRTC (Pode ser instalado na maioria dos browsers modernos)
Device API
media capture
API

http://www.adobe.com/products/adobe-media-server-family.html
Comment: "[PHP] não é uma tecnologia recomendada para transmissão de dados do gênero (Streaming)" - por que? Se você não cita o(s) motivo(s) fica parecendo que é só sua opinião.
Comment: @GuilhermeNascimento Muito bom. +1 para para reparar o negativo sem motivo que te deram.
Comment: @AndréRibeiro Obrigado pelo comentário, eu entendi. Editei a resposta, me diga se é aceitável agora. Obrigado mais uma vez.
Comment: Boa resposta! Mas usaríamos PHP para transmitir tipo com websockets
Comment: @GabrielHenrique Seria bem custoso ao servidor fazer tal processo, a não ser que você queira transmitir os "endereços apenas". Você pode até conseguir usar PHP para isto, mas provavelmente o seu servidor não irá aguentar um dia.
Comment: Ao dar um voto negativo por favor justifique, não irei ficar chateado, só gostaria de saber aonde posso melhorar.
Answer: Qualquer linguagem que suporte socket pode ser utilizada para transmitir voz, umas possuem maior facilidade outras nem tanto.
De modo geral as aplicações citadas por você possuem um servidor central que funciona como ponto de retransmissão para os clientes, "pra que isso é necessário ?"
Segurança - Os clientes não precisam ter uma porta aberta no PC de cara para a internet, imagina você ter que fazer redirecionamento de portas e configuração de nat se estiver atras de um roteador.
Controle - E se uma destas empresas precisar legalmente Espionar/escutar/grampear um usuário ? isso só será possível caso exista um nível de controle, nestes casos as transmissões precisam passar pelo servidor central, outro tipo de controle seria recodificar o audio em codecs para consumir a menor banda possível, não enviar transmissão durante a ligação no caso de silencio em um dos lados para mais uma vez poupar banda, etc.
A arquitetura é simples:
Cliente(A) <------> SERVIDOR <------> Cliente(B)
O Servidor sim precisam ter uma ou várias portas abertas de cara para a internet (de modo geral portas UDP) para que os clientes consigam se conectar, então indiscutivelmente neste servidor central você vai precisar desenvolver em alguma linguagem (java, php, perl, python, C, etc), o core central precisa ficar em listem nas portas definidas por você, deve ser capaz de suportar várias conexões simultâneas na mesma porta de forma concorrente/threads ou seja ele deve ser capaz de executar várias tarefas simultaneamente (ligações de vários clientes acontecendo ao mesmo tempo). O Servidor é o responsável por receber os frames de voz no lado do clienteA e reenviar para o ClienteB
Os clientes devem ser capaz de fechar comunicação socket com o servidor (conectar ao servidor) e transmitir os blocos de voz capturados pelo microfone em um buffer de tamanho fixo (2048, 4096, etc), deste modo os dados saem via socket do clienteA para o servidor central que reenvia esta transmissão para o clienteB.
Esta é a ideia básica por traz de qualquer ligação de voz feita sob IP, claro existem maneiras de requintar e melhorar o processo como tentar tirar do servidor central um pouco de carga e deixar a codificação/decodificação do áudio para ser feita no cliente.
Você deve ter notado que trabalhando com socket o seu servidor não precisa ser escrito na mesma linguagem que os clients.
Você pode sair do conceito e tentar escrever o básico sem ter um servidor central, para inciar faça uma comunicação ponto a ponto em uma rede interna e porque não via internet, tudo que vai precisar para estes passos é fazer que ambos os IPs se conectem diretamente por socket, começe enviando texto igual um chat, seu próximo passo será enviar áudio através do buffer, ao invés de texto você pode querer experimentar enviar um array em float point para ser codificado e tocado durante o recebimento dos frames pelo socket no clienteB.

Ligação de voz entre dois pontos


Microsoft.CSharp.RuntimeBinder.RuntimeBinderException when I try to access Model in View

Question: I have problems in a typical place.
When I access to Model or any dynamic variables (through ViewBag) in View,
I get Microsoft.CSharp.RuntimeBinder.RuntimeBinderException.
Example
View (View/Assignments/Assignments.cshtml):
@using DocMaster.Models
@model List<IGrouping<string, User>>
...

  @foreach (var dep in Model)
  {

      @dep

        @foreach (var user in dep)
        {

            @user.Surname @user.Name @user.Patronymic

        }

  }

Controller (Controllers/AssignmentController.cs):
public class AssignmentController : Controller
{
    private  PgDb db = new PgDb();

    [HttpGet]
    public ActionResult Assignments(Guid docId)
    {
        var departments = db.Users.OrderBy(x => x.Surname).GroupBy(x => x.Department.Name).ToList();

        return View(departments);
    }
}

StackTrace
Строка 76:

Строка 77:

Строка 78:                                 @foreach (var dep in Model)
Строка 79:                                 {
Строка 80:

Исходный файл: C:\Users\ruslan\source\repos\Documentics\DocMaster\Views\Assignment\Assignments.cshtml    Строка: 78

Трассировка стека:

[RuntimeBinderException: Не удается выполнить привязки исполняющей среды по нулевой ссылке]
   CallSite.Target(Closure , CallSite , Object ) +115
   System.Dynamic.UpdateDelegates.UpdateAndExecute1(CallSite site, T0 arg0) +629
   ASP._Page_Views_Assignment_Assignments_cshtml.Execute() in C:\Users\ruslan\source\repos\Documentics\DocMaster\Views\Assignment\Assignments.cshtml:78
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
   System.Web.WebPages.StartPage.RunPage() +17
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +64

Answer: Are you sure that
        var departments = db.Users.OrderBy(x => x.Surname).GroupBy(x => x.Department.Name).ToList();

is returning a value because the error is insisting that you have a null reference somewhere in the code and I'm assuming that's where it is with the code giving. Debug the controller method and find out where the null reference is.


Using same type for LINQ-to-SQL mapping on different tables

Question: I have a LINQ-to-SQL data context in which two tables exist with different names but identical structures. One table (called CallRecords) holds live/current data, and the other (CallRecordsArchive) holds older records - but with the same field names as the live one.
With the basic mapping LINQ to SQL creates two classes CallRecord and CallRecordsArchive - but since they are the same I'd like to avoid this if possible? That way I don't have to write two queries for each instance?
I did consider creating a JOIN view but with millions of rows in both tables it would be a performance nightmare.
Answer: The way I've dealt with this is to create an interface for the common aspects of both tables and have both of the generated classes from your data context implement that interface through the use of the a partial class definition. This way when you want to deal with the type as a single concept you can always refer to it as the interface.
Comment: This would work for C# but unfortunately my datacontext is in VB.NET, and VB.NET's interface implementation does not permit this, since you have to tag the methods as "Implements [myinterface].[mymethod]", which won't work as the code is auto-generated by .NET
Answer: try to use inherit for this issue
check this link for more details.
one more
I hope it is help you.
Comment: Thanks for the pointers: the first is more the reverse of my situation (one table, multiple classes, where I want multiple tables, same class). I can't use mapping files as I have the DBML and 99% of the tables are generated from this. I was trying to figure out if I could get the SQLMETAL generator that creates the code to re-use the CallRecord type for both tables. I think I may have to write them as stored procedures that return tables
Comment: LINQ to SQL does not support this form of inheritance. It doesn't matter if you use SQLMetal, the designer, or manual attributes. @jpierson's is the option you would need to use in LINQ to SQL. Note, with the view option, you will need database triggers or stored procs for any updates/inserts so that the DB engine can pick the right table.
Comment: You can make an indexed view instead if the two tables have data that should be mutually exclusive.


Problemas com conexão com o banco do MS Access

Question: Pessoal desenvolvi uma aplicação web cujo banco de dados é do MS Access, pois bem, quando o usuário faz login eu envio os dados por ajax para a classe java para fazer a validação de login e senha, o problema é que quando o sistema vai conectar no banco minha classe de conexão da o seguinte erro "java.sql.SQLException: No suitable driver found for jdbc:ucanaccess://banco_dados\softTech.accdb"
Até ai ok não está achando um driver, porém resolvi fazer um teste e criei um método "public static void main" na minha classe de conexão, e chamei o mesmo método de validação de login, a classe ficou da seguinte forma:
<code>public static Connection conectar() {
    Connection conexao = null;
    try {
        conexao = DriverManager.getConnection("jdbc:ucanaccess://banco_dados\\softTech.accdb");
    } catch (Exception e) {
        System.out.println("Erro na conexão com o banco " + e.toString());
    }
    return conexao;
}

public static void main(String[] args) {
    try {
        Funcionario f = new Funcionario();
        f.setLoginFuncionario("TESTE");
        f.setSenhaFuncionario("TESTE");
        String resultado = new FuncionarioDAO().validaLogin(f);
        System.out.println(resultado);
    } catch (Exception e) {
        System.out.println(e.toString());

    }
}
</code>
Ao executar esta classe é que a coisa fica estranha, pois a conexão é feita normalmente, não sei o que pode estar havendo preciso de ajuda
O erro que dá é este:

java.sql.SQLException: No suitable driver found for jdbc:ucanaccess://src/banco_dados/softTech.accdb

mas como eu disse o driver foi inserido sim, e quando testo direto pela classe ele não dá erro nenhum.
Answer: Tente adicionar Class.forName() :
<code>  public static Connection conectar(){
     Connection conexao = null;
         try  {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
    conexao  = DriverManager.getConnection("jdbc:ucanaccess://banco_dados\\softTech.accdb");
             }
             catch (Exception e) {
        System.out.println("Erro na conexão com o banco " + e.toString());
    }
    return conexao;
}
</code>
O problema aqui é de que as versões antigas do Java costumavam conectar o ODBC com o MS-Acess e o ODBC driver foi removido nas versões atuais do Java.
Comment: Olá Falion, dando uma olhada melhor na mensagem de erro percebi o seguinte trecho " net.ucanaccess.jdbc.UcanaccessSQLException: given file does not exist: banco_dados\softTech.accdb" ou seja pelo jeito a minha aplicação não esta encontrando meu arquivo access, isso quer dizer que ou eu estou colocando o arquivo no lugar errado dentro do projeto (se for isso onde seria o ideal colocar ?), ou então eu estou escrevendo o caminho de maneira errada (se for isso como deveria ser então ?), desde já obrigado !
Comment: Olá amigo,tente escrever o caminho inteiro até o .accdb,exemplo :  'jdbc:ucanaccess://c://folder/softTech.accdb' isto pode corrigir o seu erro,pois geralmente o Java consiste em dar erros deste tipo por não haver um caminho correto até o local.
Comment: Se te ajudei,coloque como +1 :)
Comment: por exemplo, usou o DSN para a conexão?
sempre que há MS na jogada tem que usar mais de um caminho pra o arquivo
crie um alias para o arquivo e exporte junto na duplicação/instalação. resolve sempre ....


Drawing a Billboard Quad at point in OpenGL

Question: I'm working on a game engine, and I want to be able to draw a billboarded (i.e. rectangular to the screen) quad with the center-bottom of the quad being determined by a single point.
Comment: No reason you can't create a tag yourself...
Comment: I don't have the requisite Reputation to do so
Answer: In OpenGL, there is the concept of transformation matrices. These govern the positioning of the objects on the screen. From them, it is possible to read vectors (directions) that point "up" and "right". These are commonly called up-vector and right-vector (and the third may be called look-vector). How to get them is described here.
Once you have them, making a billboarded quad is very simple.
<code>P - right * .5 + up
+-------------+ P + right * .5 + up
|             |
|             |
|             |
|      P      |
+------+------+ P + right * .5
P - right * .5
</code>
These are the coordinates (P is the governing position, at the bottom center of your BB). You can draw such quad the same way as any other quad.


Confusion over $a_k = (1+\frac{1}{k})^k = e$

Question: I'm currently just watching an MIT lecture about differentiating exps and logs and it mentions that $a_k = (1+\frac{1}{k})^k = e.$
I've seen the proof and "understand" that $\lim_{k \to \infty} \ln(a_k) = 1$ s0 the limit of $a_k = e$.
The problem is when I read $e = \lim_{k \to \infty}  (1+\frac{1}{k})^k$,  it looks like it says $e = 1$ because I read it as $e = (1+(0))^\infty = 1$, and I'm having a hard time working out where the confusion is.
Thanks.
Comment: Stating $a_k=e$ is quite different from stating $\lim_{k\to +\infty}a_k = e$.
Comment: The form $1^\infty$ is indeterminate. See [this](http://math.stackexchange.com/questions/319764/1-to-the-power-of-infinity-why-is-it-indeterminate)
Comment: I think you may want to revisit the definition of a limit. Simple plug and play can with "$\infty$" will more than likely be misleading
Comment: This might be helpful: http://math.stackexchange.com/q/2067849/9464
Comment: Hm, but what is $1.00001^\infty$?
Comment: Thanks guys. The indeterminate explanation cleared things up for me, appreciated.
Answer: Note that $\lim_{k\to\infty}\left(1+\frac1k\right)^k$ is a limit of the indeterminate form $1^\infty$. If $k=100$, then $1+\frac1k =1.01$ and $1.01^{100}\approx 2.70481382942153$.
As mentioned in the OP, we can exploit the continuity of the exponential function and write
$$\lim_{k\to\infty}\left(1+\frac1k\right)^k=\lim_{k\to\infty}e^{\log\left(1+\frac1k\right)^k}=e^{\lim_{k\to\infty}\log\left(1+\frac1k\right)^k}=e^{\lim_{k\to\infty}k\log\left(1+\frac1k\right)}\tag 1$$
Then, recalling that $\frac{1}{k+1}\le\log\left(1+\frac1k\right)\le \frac1k$, we arrive at the anticipated result.
Note that in $(1)$, we transformed the indeterminate form $1^\infty$ into the indeterminate form $e^{\infty \times 0}$.


Entity Framework, Get element from related table based on includes

Question: I recognize that this question has been asked in various forms before, but none of them that I have read quite give me what I need.
Question: Given the model below, and only knowing the client ID, how can I get a List that consists of the Uid of each activity that the client is permitted to perform?

I start with code something like the code below, but don't know where to go from there. I assume that it has something to do with a select statement - but my ignorance of LINQ is overwhelming me :)
public List<string> GetClientAndPermittedActivities ( int clientId )
{
    var permittedActivities = ReadAllRaw()
        .Where(c => c.Id == clientId)
        .Include("ClientType")
        .Include("Role")
        .Include("PermittedActivities")
        .Include("Activities");

}

internal IQueryable<TE> ReadAllRaw ()
{
    return base.ReadAll();
}

// READ (ALL)
internal IQueryable<T> ReadAll ()
{
    return DbSet;
}

private void SetContext ( DbContext context )
{
    this.Context = context;
    this.DbSet = Context.Set<T>();
}

Comment: What is `ReadAllRaw()`? Is `Uid` string?
Comment: Yes, sorry - ReadAllRaw just returns the dbset for the context, and yes, Uid is a string. I added that to my question for clarity - thanks for the catch.
Answer: You can just 'chain' your includes together with your navigation properties.
public List<string> GetClientAndPermittedActivities(int clientId)
{
    var permittedActivities =
        ReadAllRaw()
            .Include("ClientType.Role.PermittedActivities")
            .Where(c => c.Id == clientId)
            .ToList();
}

That should get you all the PermittedActivities.
EDIT
If you add
using System.Data.Entity;

to your class, you can use lambdas to create your statements.
public List<string> GetClientAndPermittedActivities(int clientId)
{
    var permittedActivities =
        ReadAllRaw().Include(x => c.ClientType.Role.PermittedActivities.SelectMany(pa => pa.Activities.Uid))
            .Where(c => c.Id == clientId)
            .ToList();
}

And with this you receive your requested Activity.Uid.
Comment: Should be there according to your diagramm. But you could also just select the ActivityId from the PermittedActivity. I think you need to use the NavigationProperty names.
Comment: Thank you, that is a good start and taught me something that I didn't know. However, that only gets me to permitted activities - not to Activity.Uid where I need to be. If needed, I guess that I can foreach on the permitted activities and manually add to the list?
Comment: @SteveJackson I'm not 100% sure, but can you try `.Include("ClientType.Role.PermittedActivities.Activities")`? I think that should work.
Comment: Add a .Select(client => client.ClientType.Role.Select(role => role.PermittedActivity.Activity.Uid) after the Where().
Comment: Thank you user3411327, however, I tried that and I don't get Activity in my auto complete. I think it has to do with the fact that the navigation property isn't a list? Also, should I be using entity names or navigation property names for my include statement?
Answer: Should be something like
from c in Client
where c.ClientId = clientId
from p in c.ClientType.Role.PermittedActivities
select p.Activity.Uid

As you see, you just start at Client and then follow the associations: n - 1 is represented by a dot . and 1 - n by a new from statement.
This is called query syntax, or comprehensive syntax. Most of the times this produces more succinct code than fluent syntax (Client.Where(c => ...), although there are things you can only do with the latter.
Comment: Thank you so much Gert, that was exactly what I was after.
Answer: Your method can looks like this:
public List<string> GetClientAndPermittedActivities(int clientId)
{
    return ReadAllRaw()
            .Where(c => c.Id == clientId)
            .SelectMany(
                           ct => ct.ClientType
                                   .Role
                                   .PermittedActivities,
                           (s, c) => c.Uid
                       )
            .ToList();
}

Comment: Thank you Hamlet, I really appreciate your taking the time , +1 for sure. I give a slight nod on the answer to Gert, simply because it was a bit cleaner and he was kind enough to give some further explanation. Nonetheless, it was a close call and I really do appreciate your time.
Comment: Actually, it turns out that this response was ultimately the one that I used as it was most accurate in the context. Thus, I'm switching this to the answer. Nonetheless, I am grateful for all the help from everyone.
Comment: Though I can't seem to make it look pretty, here is my final codes for anyone reading this later:                                      var permittedActivities = ReadAllRaw()
                .Where(c => c.Uid == clientUid)
                .SelectMany(
                    ct => ct.ClientType.Role.PermittedActivities,
                    (s, c) => c.Activity.Uid
                ).ToList();


What is the limiting distribution of $Y_n = \sqrt{n}(\bar{X}_n-1)$ as $n \to \infty$?

Question: Let $X_1,\cdots,X_n$ be independently and identically distributed with pdf $f(x)=e^{-x}, 0 < x < \infty$. Let $Y_n = \sqrt{n}(\bar{X}_n-1)$.
What is the limiting distribution of $Y_n$ as $n \to \infty$?
My work:
I decided to try an mgf approach. Clearly, $X_1,\cdots,X_n \sim Exp(1)$, so $M_{X_i}(t)=\frac{1}{1-t}, t < 1$. After a bit of work, I found that
$M_{Y_n}(t)=[e^{t/\sqrt{n}}(1-\frac{t}{\sqrt{n}})]^{-n}, t < \sqrt{n}$. This does not appear to resemble a known distribution's mgf. Should I change my approach?
Updated:
I think I'm supposed to solve the problem using an mfg method. Now I am getting this:
$M_{y_n}(t)=[[1 + \frac{t}{\sqrt{n}} + (\frac{t}{\sqrt{n}})^2\cdot1/2! + \cdots]-[\frac{t}{\sqrt{n}} +(\frac{t}{\sqrt{n}})^2+(\frac{t}{\sqrt{n}})^3\cdot 1/3!+\cdots]]^{-n}$, which resembles some work that we have done in class, but I am not too sure how I can evaluate this.
Additional Update:
Due to Glen_b's comment, I attempted using CLT. Here is my updated "updated work."
Since $X_i \sim Exp(1), i=1,\cdots,n$, then $E(X_i)=1, Var(X_i)=1$. So,
$\sqrt{n}(\bar{X}_n-1) \to N(0,1)$ in distribution by Central Limit Theorem, which matches the answers provided below.
Comment: Are you allowed to invoke the Central Limit Theorem?  (Even if not, it tells you immediately what the limiting distribution is, which can guide your demonstration.)
Comment: @edison (i) regarding to your discussion with whuber -- what does the CLT say? (ii) On the other hand if (as I had previously assumed) you can't invoke the CLT, you have already expanded $M$ (though as I say I am not checking your work), what you'd need next is to use facts about limits.
Comment: No, it's incredibly easy to deal with. What's $\mu_Y$? What's $\sigma_Y$? Write down a standardized $\bar{Y}$ ...
Comment: Hint: $\bar{X}_n$ has a Gamma distribution
Comment: If you're using the mgf approach (NB I have not checked your mgf is correct), what happens to the function in the limit as $n\to \infty$?
Comment: @StijnDeVuyst So, I get than $Y_n$ is a location-scale Gamma, where the mgf of a $Gamma(\alpha, \beta) =[1-\beta t]^{-\alpha}$. However, I do not know how to evaluate $Y_n$ as $n \to \infty$ given this information.
Comment: @StijnDeVuyst I updated the post with new work.
Comment: @Glen_b-ReinstateMonica Since I do not know how to further expand $M_{Y_n}(t)$, I cannot successfully evaluate the mgf as $n \to \infty$.
Comment: @whuber I believe I could. How would that be used to find the limiting distribution, though?
Comment: @Glen_b-ReinstateMonica This makes sense- thank you for your help. I assumed that I couldn't use CLT because $Y_n$ would be incredibly hard to manipulate in order to employ CLT.
Comment: @Glen_b-ReinstateMonica I added an updated answer using CLT. Thank you for pointing out its ease. I was over-thinking it.
Comment: You can post it as an answer, since it answers your question
Answer: In your updated version, you will get $\left[1 - \frac{t^2/2}{n} +o(\frac{1}{n})\right]^{-n} = \left[1 + \frac{t^2/2}{n} +o(\frac{1}{n})\right]^{n}$
and the limit of that is $e^{t^2/2}$, which is the moment generating function of a standard normal distribution with mean $0$ and variance $1$, much as you might expect from the central limit theorem
Comment: @Edison This is [Little o notation](https://en.wikipedia.org/wiki/Big_O_notation#Little-o_notation) and here means means that the remainder when divided by $\frac1n$ tends to $0$ as $n$ increases so eventually very much smaller in magnitude than $\frac1n$ or $\frac{t^2/2}{n}$.  The equality is similar to saying $\frac{1}{1-x} = 1+x +\cdots$ but here we have $\frac{t^2/2}{n}$ rather than $x$
Comment: What is $o(\frac{1}{n})$? Sorry, I am not familiar with this notation. Additionally, how do you get that equality?
Comment: Thank you for linking the Wikipedia article- that was very helpful. I get that $\lim_{n\to\infty} \left(1+\frac{x}{n}\right)^n = e^x$, but how come we can neglect $o(\frac{1}{n})$? Also, how did you know to keep the $-\frac{t^2/n}{n}$ term out of $o(\frac{1}{n})$?


How to disable row sorting in dgv?

Question: How to disable row sorting by user (so by clicking on column headers) in data grid view in windows forms?
I know you can disable column sorting, but I can't find any method that disables row sorting. I could use a hidden field with the correct index. So even if the user reorders rows, it will be saved correctly in the databank (by reordering List by hidden indexfield). But that seems kinda messy. There has to be a build in method or property for this, right?
Thanks in regards
Answer: It's kind of tricky you should implement the column_added event :
<code>Private Sub DGV_ColumnAdded(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles DataGridViewOrganigramme.ColumnAdded
        DGV.Columns(e.Column.DisplayIndex).SortMode = DataGridViewColumnSortMode.NotSortable;
End Sub
</code>
Hope this helps.

How to disable row sorting in dgv?


Unshelving in TFS: What does it mean?

Question: Here's the part I get: When you shelve in TFS, it makes a server copy of the changes so they are not lost, but does not check them into the source code trunk/branch you are working on.
Question: Under what circumstances would you use the "unshelve" feature?  Does it mean it will remove the shelveset from the TFS server? Can you do a get from a shelveset?  Or is it really just a diff description between the shelveset and the "real" source code?
Answer: Unshelving is how you restore the shelveset to your machine so you can keep working on it.  It doesn't change the shelveset on the server (to do that you need to shelve things again and use the same shelveset name).
One example for how I use it is to move changes between machines while I'm working on them.  I'll shelve it on my desktop machine, then unshelve it on the laptop and then continue working on the laptop.
You can also use it to share changes with someone (for code reviews or other reasons).  You shelve your changes, then the other person can go and unshelve it to see what you've done.
Unshelving doesn't actually change the shelveset or anything else on the server.  It's just a get operation.
Comment: A colleague sends me a review, I unshelve his changes to run them and check them. Once I am done and send back his review. How do I get rid of his changes? In other words, how do I undo the unshelving? Do I have to right-click and undo on each one of the files he changed?
Comment: @Ciwan, you need to shelve your code before unshelving his. Then when you're finished with his, unshelve your code.
Comment: I always had doubts, thanks for the explanation. helped me a lot.@Herms.
Comment: Alternatively, if you have checked in your code then you can do an undo pending changes after you have reviewed your colleague's code.
Answer: Herms is spot on.  Read his answer.
One important caveat: if you've done a Get since the shelveset was created, Unshelve will only rollback the local version of files contained in the shelveset.  Thus, it's quite likely you'll have an inconsistent workspace.
A good practice is to always re-run Get after you Unshelve.  This ensures you don't waste time on phantom build errors that are actually just side effects of being in a half-new/half-old state.  It will also require you to resolve any conflicts between the shelveset contents and the latest server revisions proactively, instead of only discovering them @ Checkin time.
Answer: I use shelve to back up code-in-progress, just on the off chance my hard drive crashes or whatnot. I don't even have to worry about the code building, never mind working, since the work won't be seen by any other developers on my team (unless they go looking for it).
Unshelve pends the changes back in your workspace. Removing the shelveset from the server is a Delete.
Following on to what Richard Berg said, the power tools' version of unshelve actually includes a get and resolve.
Comment: Unfortunately, 'tfpt unshelve' is very buggy in my experience.
Comment: I don't use it often myself. It's easier to do a get afterwards. I would use it in one case - if I needed to move un-checked-in code to a different (but very similar!) branch.
Comment: its not buggy. Its a process. We cannot expect TFS to keep exact code in place. But i think tfs will do its job close to 95%-100% when it unshelves.

Unshelving in TFS: What does it mean?


How can I change the redirect that happens after a node is edited?

Question: Normally, after a node is edited, the user is sent to the node's display page.  I would like to change this so that the user is sent to a different page.  Is there a module for this or is there a native setting that I can use?
Answer: You have a few options.
If you want to install a module and use a GUI you should be able to do that with Rules.  Just install the module, and setup a new rule to react on saving new content.
If you do not plan on using Rules for anything else, it is probably wiser to just use a hook_form_alter in your custom module.  Just edit the forms $form_state['redirect'] in a submit callback. Something like:
function test_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='MY_FORM') {
    array_push($form['#submit'], 'test_userlogin_submit');
  }
}

function test_userlogin_submit(&$form, &$form_state){
  $form_state['redirect'] = 'MY/NEW/PATH';
}

Comment: Great, that is something that you can do with rules.


Set the default language of Google document while file creation with Google DRIVE API

Question: I can create files on Google Drive and the language is automatically set for me while using drive.google.com.
But I am having issues while creating files using Google Drive API via my application.(google-api-services-drive-v2-rev192-1.20.0.jar)
The default language of the document is not set.
This is causing issues with the voice typing being grayed out.

Here is how I createFile in my application:
<code>    public static File createFile(Car car) {
    System.out.println("CREATING FILE");
    try {

        File body = new File();
        body.setTitle("Document for " + car.getCar_name()
                + ".docx");

        body.setMimeType(GOOGLE_DOCOCUMENT_MIME_TYPE);
        body.setEditable(true);

        Permission ownership = getOwnerShipPermission();
        Permission unlockedFile = getUnlockedFilePermission();
        java.io.File fileContent = null;
        fileContent = CarServiceReportTemplateFactory.createCarServiceReportTemplateFile(car);

        FileContent mediaContent = new FileContent(MS_WORD_DOCUMENT_MIME_TYPE, fileContent);
        File file = driveservice.files().insert(body, mediaContent).execute();
        String fildid = file.getId();
        driveservice.permissions().insert(fildid, unlockedFile).execute();
        fileContent.delete();
        return file;

    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
}
</code>
I did have a look at the drive api file category but I cannot find anything related to setting default language.
Interestingly, when I execute the "Try it" simulator, the generated file seems to have a  language setup by default.
However, when I try it in my application, the language isn't set up by default...Hence the voice typing is grayed out.
This is what I have tried:
<code>  String timedTextLanguage = "English (United Kingdom)";

  File file = driveservice.files().insert(body, mediaContent).setTimedTextLanguage(timedTextLanguage).execute();
</code>
Comment: I have noticed the drive client jar file has a newer version.
Could it be this?
Comment: If you check the v2 version of the Google Drive API. The only option that can change the language of a file is by using [Files: insert](https://developers.google.com/drive/v2/reference/files/insert) method, this method has an optional parameter `timedTextLanguage` that set the language of the text. Try this parameter if it can help you. For more information, check also this related [SO question](http://stackoverflow.com/questions/12106138).
Comment: Hi Kendi, THank you for your help.
I did try the timedTextlanguage with no luck. Can i basically pass "English" as a string parameter?
Comment: I tried to pass en-GB, English, english, en as a parameter & I am still having issues.
Answer: It is the Microsoft Word document causing these issues.
But I still don't know why the language isn't set as it is uploaded to Google Drive.


Hooking into an update of the db system table

Question: Essentially I want to be able to monitor all updates to the db system table, by catching all updates to the db system table (for a particular theme's record). We have encountered some odd bugs whereby all themes are periodically (and apparently randomly) disabled, and I need to be able to log further information whenever this theme is disabled. What is the best way to approach this?
Alternatively is there a way to hook into the function for whenever a theme is enabled/disabled?
Answer: You should be able to use hook_themes_disabled().
The following code in a module will put themes being disabled into the Drupal logs:
function MYMODULE_themes_disabled($theme_list) {
  foreach ($theme_list as $key => $themename) {
    watchdog('MYMODULE', '%themename was disabled.', array('%themename' => $themename), WATCHDOG_NOTICE);
  }
}

EDIT:  Forgot to mention this, but hook_themes_enabled() is used in exactly the same way, so you could easily just modify the hook above to check when a theme is enabled.


freeipa server home directory automount

Question: I have installed freeipa-server on centos and enrolled an ubuntu server to it, I have a freebsd server which is our storage server(I am going to enrolled the freebsd (storage server) to this freeipa-server), I want to host the home-directory of the users on it and want to know if the home-directory can be auto-mounted when the user logs in to any machine which is enrolled to this freeipa-server. I am also wondering if the home-directories can be created automatically when the users get created on the freeipa-server.
Does any one know if its possible ?
Comment: Doesn't your own screenshot already answer the "Is it possible"?
Comment: I didn't understand what you mean, can you please elaborate ?
Answer: 'Home directory' field is used for specifying the local home directory on the host, e.g. <code>/home/username</code>, the location where a shell would default to after login.
Auto-mounting a network-provided share to that directory is possible, same as without FreeIPA. Auto-creation of new network mount on a first login is not possible without compromising security of your networking storage. A system you are logging into has no permissions to create a new network volume at your remote server. You need to consider that.

freeipa server home directory automount


WPF Designer Problem loading elements showing cryptic error message

Question: I am working on a rather old project and in VS2017 WPF Designer I some strange message. We are using some self-developed localization module. But I have no clue where to find more information about this file shghxl30.tmp file it is looking for.
Comment: I tried to start VS with admin rights after experiencing those errors again. Now everything is fine.
Answer: Welcome to SO.
Most of the times I've seen this all I had to do was switch from Debug to Release (or vice-versa if I was already in Release), rebuild all and then switch back again. Sometimes it requires a quit-and-relaunch of visual studio, and every once in a blue moon a complete reboot.
If that doesn't do the trick then try deleting your bin and obj folders, and also try disabling your virus checker.
Comment: This happens all the time since I am on VS2017, so many quits and reboots happened all the time.
Comment: Maybe virus checker is the root cause... company policies, so unfortunately I cannot change it.


Equivalente ao list() do PHP em Javascript

Question: Existe alguma função do Javascript equivalente ao list() do PHP?
Suponha este JSON:
{
   "ALERTA":[
      {
         "TITULO":"Erro!",
         "MENSAGEM":"Seu nome parece estar incorreto"
      },
      {
         "TITULO":"Erro!",
         "MENSAGEM":"Seu nome parece estar incorreto"
      }
   ]
}

Em PHP existe a possibilidade de usar o list junto ao foreach, afim converter um índice, de uma array, para uma variável.
foreach($json['ALERTA'] as list($titulo, $mensagem)){
   // $titulo será "Erro!"
   // $mensagem será "Seu nome parece estar incorreto"
}

Isso faz com que não precise usar os índices $variavel['TITULO'] e $variavel[MENSAGEM], em seu lugar utilizo apenas $titulo e $mensagem.
Em Javascript/JQuery apenas conheço (e uso) deste método:
$.each(json['ALERTA'], function (nome, data) {
   // data['TITULO'] será "Erro!"
   // data['MENSAGEM'] será "Seu nome parece estar incorreto"
});

Porém queria ELIMINAR o uso de índices ['TITULO'] e ['MENSAGEM'], apenas por questões estéticas.
Desejo um resultado próximo a isto:
$.each(json['ALERTA'], function (nome, list(titulo, mensagem)) {
   // titulo ser "Erro!"
   // mensagem ser "Seu nome parece estar incorreto"
});

Dessa forma, como no PHP, não iria usar o índice. Existe alguma função equivalente list() do PHP em Javascript, qual seria ela? Se não, existe outra solução para eliminar o uso de índices nesse caso (sem ser um novo loop)?
Answer: Há uma maneira de fazer isso usando JavaScript moderno (ES6). Falei sobre essa técnica Destructuring assignment aqui, nesta resposta. Também podes ler mais sobre isso na MDN:Destructuring assignment.
Se combinares essa técnica com o (também novo) for of podes atribuir os valores dessas propriedades on the fly assim:
for (let { TITULO, MENSAGEM } of json.ALERTA) {
    console.log(TITULO, MENSAGEM);
}

Exemplo: http://www.es6fiddle.net/irizeyxz/
Se precisas de suporte para Browsers antigos podes converter isso com o Babel. Crias o código que precisas em ES6 e depois convertes. Neste caso o código do exemplo ficaria assim:

"use strict";

var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
    for (var _iterator = json.ALERTA[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
        var _step$value = _step.value;
        var TITULO = _step$value.TITULO;
        var MENSAGEM = _step$value.MENSAGEM;

        console.log(TITULO, MENSAGEM);
    }
} catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
} finally {
    try {
        if (!_iteratorNormalCompletion && _iterator.return) {
            _iterator.return();
        }
    } finally {
        if (_didIteratorError) {
            throw _iteratorError;
        }
    }
}

Para fazer isso com código à moda antiga podes fazer assim:
Array.prototype.lista = function() {
    var args = [].slice.call(arguments);
    var cb = args.pop();
    this.forEach(function(el) {
        var params = args.map(function(prop) {
            return el[prop];
        });
        cb.apply(this, params);
    });
}

e depois para usar:
json.ALERTA.lista('TITULO', 'MENSAGEM', function(tit, msg) {
    console.log(tit, msg);
});

jsFiddle: https://jsfiddle.net/x7hxmzpd/


Dados não estão sendo excluidos do banco de dados

Question: Fiz um form, onde, quando o usuário clicar no botão excluir, o valor inserido no imput 'id', seja excluido do banco de dados. Desde já obrigado pela ajuda.
Segue meu formulario.
  <form name="Form_CRUD" method="post" action="consulta.php" >

            <input type="hidden" id="id_input" class="form-control" name="id">
            Nome
            <input type="text" id="nome_input" class="form-control" name="nome">

            Sobrenome
            <input type="text" class="form-control" id="sobrenome_input" name="sobrenome">

        <button type="submit" name="Add"  class="btn btn-primary">Adicionar</button>
        <button type="submit" name="Upd" class="btn btn-primary">Alterar</button>
        <button type="submit" name="Del" class="btn btn-primary">Excluir</button>

    </form>
    <?php

    $validarenvio = isset($_GET['s']) ? $_GET['s'] : '';

    if ($validarenvio == '1') :
    ?>

            Sucesso!
            Cadastro realizado com sucesso

        <?php  endif; ?>
    <?php
    if($validarenvio == '2'):
    ?>

        Sucesso!
            Alterado com sucesso!

    <?php  endif; ?>
    <?php
    if($validarenvio == '3'):
    ?>

        Sucesso!
            Excluido com sucesso!

    <?php  endif; ?>
    <?php
    if($validarenvio == '0'):
    ?>

            Erro!
            Erro de envio verifique!

    <?php  endif; ?>

Segue minha consulta.php:
                    <?php
                    require_once ('classes/conecta.php');
                    $idCli = trim($_POST['id']);
                    $nomeCli = trim($_POST['nome']);
                    $sobrenomeCli = trim($_POST['sobrenome']);
                    $insert = "INSERT INTO clientes_cli";
                    $insert .= " (nome_cli, sobrenome_cli)";
                    $insert .= "VALUES ('$nomeCli', '$sobrenomeCli')";
                    $Obj_Conexao = new CONEXAO();

                    $erro = 0;
                    $up = "UPDATE clientes_cli";
                    $up .= " SET nome_cli = '$nomeCli', sobrenome_cli = '$sobrenomeCli'";
                    $up .= "WHERE cod_cli = $idCli";

                    $del = "DELETE From clientes_cli";
                    $del .= "WHERE cod_cli = $idCli";

                    if (isset($_POST['Add'])){
                            header('Location: index.php?s=1');
                            $inserir_dados = $Obj_Conexao->Consulta($insert);
                            exit;
                    } else if (isset($_POST['Upd'])) {
                            header('Location: index.php?s=2');
                            $alterar_dados = $Obj_Conexao->Consulta($up);
                            exit;
                    } else if (isset($_POST['Del'])){
                            header('Location: index.php?s=3');
                            $Deletar_dados = $Obj_Conexao->Consulta($del);
                            exit;
                    } else {
                            header('Location: index.php?s=0');
                            exit;
                    }
                    ?>

Answer: 1- Qual retorno vc esta obtendo desta operação?
2- Operações de DELETE devem ser feitas sempre com o campo PK da tabela por motivo de segurança. Este campo 'cod_cli' e a PK de sua tabela? Caso não seja verifique nas configs do seu DB se esta permitindo exclusão sem usar PK.
3- O ideal seria realizar a exclusão ANTES do header location!
Comment: Gabriel, sim minha 'cod_cli' é minha PK sim.
Comment: Fiz a alteração  do seu item três e não funfou!
Comment: A mensagem ao usuario está respondendo confome o programado. Mas no banco de dados não ocorre nenhuma ação.


is there any alternative method for taking second order derivative in signals?

Question: Eg:
1.Z=1+i*5 (in quadratic form),
2.s(t)=Zexp(iw*t), (i'm multiplying two signals)
now, i want to take second order derivative, yes i know the usual way like this,
Equation
but is there any other alternative form to find 2nd order derivative?,
and by doing that i want to extract my original signal ("z", which's given above ) does any one have idea about this ?
I tried this way it's worked but i want reduce it more complex.
After double derivative i will calculate instantaneous angular frequency like this W=(mean((y'')^2)/mean((s(t))^2)) and i will get result as I=2*mean[(s(t)*cos(w*t))] and I=-2*mean[(s(t)*sin(w*t))] this both I and Q are our original signal Z=1+i*5
Comment: You would get answers more easily if instead of making us read a really long article, you would just explain what you mean by "the usual way".
Comment: @MattiP. no, you no need to read full article, i'm just referring only the equation of second order derivative **(y'')** by using this one can calculate the curvature of the signal. But how to find curvature of the signal without 2nd derivative of **"s(t)"**  and at the same time i want extract or demodulate my original signal **(Z)**, u got my question ?
Comment: So you have measured a signal, right? You have a time series, a long series of numbers? And you want to calculate the second time derivative of that?
Comment: If you have a time series, your derivatives will anyway be numeric and approximate, and you have to use the values of the time series to calculate the time derivative. The way you calculate it is called a stencil. In the article that you linked, one such stencil is described. Is there a reason why you don't want to use it?
Comment: @MattiP. yes u r right, i have the signal which is **s(t)=Zexp(iw*t)** this nothing but original signal **(Z)** and carrier signal, yes i have time series too, where `t=[(T/80)*i]`, i=0..M-1,M=512;
Comment: You can calculate the time derivative with a finite difference. Here are some stencils for that purpose: https://en.wikipedia.org/wiki/Finite_difference_coefficient
Comment: Also this you can read: https://en.wikipedia.org/wiki/Five-point_stencil
Comment: So was there any particular reason why you don't want to use the normal three-point stencil, which you pointed out in the article?
Comment: @MattiP. yes i want avoid complexity of this derivative actually i want to do all this math operation in micro controller so it's more simple if the equation is less complex!
Comment: Well, I think the stencil in the article is the most simple one. Do you need to do the differentiation "live" or only after the measurements? Because if you do it live, you would have to use a backwards difference.
Comment: Yes i have to do it in live! i went through those wiki documents but it's only an approximation, instead of going for approximation if we find a simple way to extract that original signal it would be really good because for me the **(y'')** are more simple equation compare than that wiki documents. if u see **y''** it's just involves less complexity and i need to add few more points after double derivative
Comment: @MattiP. continuation of by previous comment....i will calculate _instantaneous angular frequency_ like this `W=(mean((y'')^2)/mean((s(t))^2))` and i will get result as `I=2*mean[(s(t)*cos(w*t))]` and `I=-2*mean[(s(t)*sin(w*t))]` this both `I` and `Q` are our original signal **Z**
Answer: Assuming you have a time series of values $s_k$, there are two ways of approaching this.

Analytical method:
If you know exactly that your signal is of the form
$$
s(t) = Ze^{i \omega t} = Z \cos{\omega t} + iZ \sin{\omega t}
$$
Then you can just calculate the derivative:
$$
\frac{d^2 s}{dt^2} = -Z\omega^2  e^{i\omega t} = -\omega^2 s(t)
$$
Or, in simple terms, you just have to multiply the original signal by $-\omega^2$. Then the second derivative $y$ in every point is
$$
y_k = -\omega^2 s_k
$$
Approximate method:
If you don't know that your signal is exactly of the mentioned form, you have to indirectly measure the second time derivative, by calculating it at each point. The most straightforward way is the finite difference method, and for live calculation you have to use the backwards difference. If we set the second derivative to be $y$ and use the first-order accurate backwards difference
$$
y_k \approx \frac{1}{\Delta t^2}\left(s_k - 2s_{k-1} + s_{k-2} \right)
$$
This method uses only the "history" of the signal ($s_{k-1}$ and $s_{k-2}$). It's rather simple but gives an approximate answer. In this equation, $\Delta t$ is the time step used.
Comment: It's absolutely working fine for derivative but after that i want i want calculate instantaneous angular frequency like this `W=(mean((y'')^2)/mean((s(t))^2))` and i will get result as `I=2*mean[(s(t)*cos(w*t))]` and `I=-2*mean[(s(t)*sin(w*t))]` this both I and Q are our original signal `Z=1+i*5`  and i found some way to replace sin and cosine terms. But is there any alternative way to find mean or maybe some other method to reconstruct our **Z**,
Comment: I think in general, if you want the frequency, you should take the Fourier transform of the signal.
Comment: I i'm aware of that but FT is more complected to do in MCU, can we go in the flow of `yk=-W^2*sk`, from this, is it possible to extract our original signal `Z=1+i*5` ?


Find the expected value

Question: f the first roll in a game of craps is neither a natural nor craps, the player
can make an additional bet, equal to his original one, that he will make his
point before a seven turns up. If his point is four or ten he is paid off at 2 : 1
odds; if it is a five or nine he is paid off at odds 3 : 2; and if it is a six or eight
he is paid off at odds 6 : 5. Find the player's expected winnings if he makes
this additional bet when he has the opportunity.
For this one, I thought there would be 36 total possibilities. So, I thought for 4 or 10, the chance is
4/36. Also, for 5 or 9, we would get 3/36, and for 6 or 8, we would get 6/36. Then after using the epexted
value formula, I kept getting the wrong answer. How should we find the correct expected value?
Comment: Is a craps a dice? What do you mean by paying into 2:1 odds? Can please you rephrase your question to make it more clear
Comment: What happens if the first roll is 3?
Comment: Summarising the rules for those unfamiliar with the game might help.
Answer: Let $Y =$ The result of the first roll.
$P(Y \in \{7,11\}) = \frac {8}{36}\\
P(Y \in\{2,3,12\}) = \frac {4}{36}\\
P(Y \in\{4,5,6,8,9,10\}) = \frac {24}{36}$
That takes care of the come out.
For the subsequent rolls
Let $X$ be the result of the last roll
That $X$ is being rolled is conditional on the probability that the game isn't over yet.
$P(X = Y) = \frac {3^2 + 4^2 + 5^2 + 5^2 + 4^2 + 3^2}{36\cdot24} = \frac {100}{864}$
$P(X = 7) = \frac {6}{36}$
Probability of the game ending on that roll.
$P(X =Y or X= 7) = \frac {244}{864}$
the probability that that you win assuming the game does not end on the come-out roll.
$\frac {P(X=Y)}{P(X\in\{Y,7\})} = \frac {100}{244}$
$P(Win, all scenarios) = \frac {8}{36} + \frac {24}{36}\frac {100}{244}$
$P(Lose, all scenarios) = \frac {4}{36} + \frac {24}{36}\frac {144}{244}$
If $W_1$ is the money staked on the pass line. $E[X] = W_1(P(win) - P(loss))$
What about the additional wagers?
If you choose to "back up" your bet and wager addition money, call it $W_2$ as it turns out $E[W_2] = 0$
Lets pick a one example
$Y = 4.$  The odds that are offered to you are 2:1
$\frac {P(X=4)}{P(X=\{4,7\})}=\frac {3}{9}\\
\frac {P(X=7)}{P(X=\{4,7\})} = \frac {6}{9}\\
E[W_2] = W_2(2\cdot\frac {3}{9} - 1\cdot \frac 69) = 0$
And this is the case for all 6 of your potential points.
Since this is the about the only wager in the casino that does not actually favor the house, many gamblers will insist that you should always back up your craps wager to the maximum that the house will allow.
Comment: Tha nk u for your help!

Find the expected value