How to represent a general vector modulus with Einstein summation convention?

Question: Say we have a basis $\mathbf{S}$ for $\Bbb{R}^n$ $$\mathbf{S}={\{\vec{e_1}; \vec{e_2};..;\vec{e_n}\}}$$
where $i \in[1;n];\  i \land n\in\Bbb{N^+}$. A vector $\vec{x}$ is thus written as
$$\vec{x}=\sum_{i=1}^na_i\vec{e_i} =a_i\vec{e_i},\ \ \ a_i\in\Bbb{R}$$
using Einstein's summation convention. Denote the components of the $i^\text{th}$ basis vector as
$$\begin{bmatrix}e_{1i} \\ e_{2i} \\ . \\ .\\e_{ni}\\\end{bmatrix}_{[\mathbf{S}]}.$$
Therefore, the modulus $|\vec{x}|$ takes the form
$$|\vec{x}|=\sqrt{\sum_{j=1}^n\left(\sum_{i=1}^na_ie_{ji}\right)^2}.$$
Question: How can one represent this double sum in Einstein's shorthand?
I am only able to drop one of the captital sigmas, i.e.,
$$|\vec{x}|=\sqrt{\sum_{j=1}^n\left(a_ie_{ji}\right)^2}.$$
Comment: When you write the components of the $i^th$ basis vector, is that the components of the basis with respect to itself?
Comment: @snulty: the components of the $i^\text{th}$ basis vector are indeed meant with respect to itself. But other answers are welcome, too. The more general the answer, the better.
Answer: Given a vector $v^i$ the square root of $v_iv^i=v^iv^jg_{ij}$ is the modulus, where $g_{ij}$ is the metric. In the Euclidean case the metric is just $\delta_{ij}$.


How to avoid nested promises with multiple Mongoose operations?

Question: I'm sorry I know there are already some posts treating the nesting promises problems in NodeJS, but I still can't figure this one.
I'm using Express and Mongoose and I want to find an Object ID, then save an Object, and then update another Object but I don't understand how should I do better than this since these are dependant promises :
        // Get Client object ID from email
        Client.findOne({ email: req.body.clientEmail })
          .exec()
          .then((client) => {
            // Then add Client ID to program and save
            const program = new Program(req.body);
            program.Client = client._id;
            program.save()
              // Finally add the program to the existing coach user
              .then((program) => {
                Coach.updateOne({ _id: req.session.userId }, { $push: { programs: program._id } },
                  function (err, coachUpdated) {
                    if (err) return handleError(err);
                    console.log(coachUpdated);
                  })
              })
              .then(() => { res.send('New program added!'); });
          })

Thanks in advance
Comment: Possible duplicate of [How to avoid nested promises?](https://stackoverflow.com/questions/50318627/how-to-avoid-nested-promises)
Comment: Instead of nesting a `.then` in another `.then`, `return` the second Promise, and consume it in the next *outer* `.then`
Comment: learn about async and await
Comment: try to use async/await instead of Promises, it will help you get your data correctly
Answer: Along with async/await. use try/catch block.
async function findClientAndUpdateCoach(req, res) {
    try {
        const client = await Client.findOne({ email: req.body.clientEmail }).exec();

        const program = new Program(req.body);
        program.client = client._id;
        const result = await program.save() // Must be asynchronous in nature to prevent blocking..

        Coach.updateOne({ _id: req.session.userId }, { $push: { programs: program._id } },
            function (err, coachUpdated) {
                if (err) return handleError(err);
                console.log(coachUpdated);
                res.send('New program added!');
            });
    }
    catch (err) {
        return handleError(err);
    }

    findClientAndUpdateCoach(req, res);

Answer: Simple, use async/await I would do something like
const client = await Client.findOne({ email: req.body.clientEmail })
          .exec();
const program = new Program(req.body);
program.Client = client._id;
const {_id} = await program.save();
//If this is not a promise. you can still use `promisify` from `utils` standard node.js lib to make it a promise
// and then call it with await. :)
Coach.updateOne({ _id: req.session.userId }, { $push: { programs: _id } },
    function (err, coachUpdated) {
      if (err) return handleError(err);
      console.log(coachUpdated);
})
//You can choose to place it inside the callback above.
res.send('New program added!');

Note: The outer wrapping function should be prefixed with async like async function (req, res) {...


Oblique asymptote for: $f(t) = \frac{t^2\arctan t}{t-4}$?

Question: Say a function $$f(t) = \frac{t^2\arctan t}{t-4}$$
Obviously, this has a vertical asymptote at $t = 4$. However, the oblique asymptote, if there is one, I can't seem to find.
What I do is I put the oblique asymptotes equation to $y = kt + m$. I can then say that $k = \lim_{t\rightarrow\pm\infty}\frac{f(t)}{t}$ however, this equals infinity as $\lim_{t\rightarrow\pm\infty}t\arctan t = +\infty$.
Can I now safely assume there is no oblique asymptote? That's what I assumed until Wolfram told me otherwise.

Answer, as explained below by Hippalectryon
The mistake I made in the above text was to divide every term in my function by $t$, which is obviously incorrect. The correct equation after dividing $f(t)$ with $t$ is:
$$\frac{f(t)}{t} = \frac{t^2\arctan t}{t(t-4)}$$
Therefore we get
$$\displaystyle k = \lim_{t\rightarrow\pm\infty}\frac{f(t)}{t}=\lim_{t\rightarrow\pm\infty}\frac{t^2\cdot\arctan(t)}{t\cdot(t-4)}=\lim_{t\rightarrow\infty}\arctan(t)=\pi/2$$
Answer: $\displaystyle k = \lim_{t\rightarrow\pm\infty}\frac{f(t)}{t}=\lim_{t\rightarrow\pm\infty}\frac{t^2\cdot\arctan(t)}{t\cdot(t-4)}=\lim_{t\rightarrow\infty}\arctan(t)=\pi/2$
Comment: I feel like while all the important information is in this answer, just a little bit more effort to fit it into the context of the question would make it way clearer.
Comment: @BenMillwood While he made it clear to me, I will edit my post to make the details of his answer more clear for any future viewers.
Comment: @Hippalectryon Sorry, you shouldn't have had to ask for it. I was too focused on my maths. Thank you for the help.


With Drush, what's the correct procedure to install Commerce Kickstart, Drupal, and the sample store data as a new site?

Question: In my opinion, the install documentation is a bit lacking when answering this question.
http://www.drupalcommerce.org/commerce-kickstart-2/install
I want to avoid the browser all together and install commerce_kickstart and configure the sample store all via the command line with Drush.
What's the correct way to do this? Download Drupal; Download commerce_kickstart which creates a profile directory, and then 'drush si commerce_kickstart ... ' ?
Answer: Commerce Kickstart differs from the standard core installation profile, by having extra installation steps. These steps are illustrated in the offical Commerce installation docs - they ask questions about store features and whether or not to install the sample store data.
Installation via drush does indeed work, however it does NOT offer these extra-step choices to the user. Instead it assumes you want the sample store.
So installation via drush is straight-forward. Assuming you have downloaded and unpacked the distribution archive file, just cd to the Drupal root, and run drush site-install commerce_kickstart.
Take some time to review the options described by drush help site-install. Most likely you will need to pass in a few more options, such as database credentials. A typical installation command will look something like this:
drush site-install commerce_kickstart --account-pass=admin --account-name=admin --db-url=mysql://root:pass@localhost/db_name --notify
Note that the Commerce Kickstart takes a lot more time than the standard core install profile. It sets up over 100 modules, several content/product types, and imports the sample store data. drush site-install will tell you "This takes a few seconds...", but it took 10 minutes on my machine :-)
Answer: You don't have to install Drupal and commerce kickstart separately. Commerce Kickstart distribution itself contains the latest Drupal.
Only command that you need is drush dl commerce_kickstart
Comment: This doesn't really answer the question about installation of the sample store. `drush dl` just downloads the distribution; it doesn't carry out the installation.


How to update billing_email in Woocommerce (if empty)

Question: Email address not mandatory on our checkout page.
We want to update billing_email to our custom email if the customer does not provide an email.
Here is my code:
add_action('woocommerce_thankyou', 'set_email_for_guest');
function set_email_for_guest( $order_id ) {
    $email = get_post_meta( $order_id, 'billing_email', true );
    if(empty($email)){
            update_post_meta( $order_id, '_billing_email', 'email@example.com' );
    }
}

Answer: I believe the hook that you should use is not woocommerce_thankyou. Instead, you should choose from one of the following hooks which both worked for me in WordPress 5.6.1 with WooCommerce 5.0.0 (which are both the latest releases as of writing):
And note that these hooks pass $data as the second parameter which is an array of the POST-ed/submitted (and processed) form data. However, the first parameter is a WC_Order instance and an order ID, respectively.
Option 1: Use woocommerce_checkout_create_order
add_action( 'woocommerce_checkout_create_order', 'set_email_for_guest', 10, 2 );
function set_email_for_guest( $order, $data ) { // first param is a WC_Order instance
    if ( empty( $data['billing_email'] ) ) {
        $order->update_meta_data( '_billing_email', 'email@example.com' );
    }
}

Option 2: Use woocommerce_checkout_update_order_meta
add_action( 'woocommerce_checkout_update_order_meta', 'set_email_for_guest', 10, 2 );
function set_email_for_guest( $order_id, $data ) { // first param is an order/post ID
    if ( empty( $data['billing_email'] ) ) {
        update_post_meta( $order_id, '_billing_email', 'email@example.com' );
    }
}

So just choose whichever hook you prefer, but the first one above runs first.
Answer: You have an error in the meta key:
add_action( 'woocommerce_thankyou', 'set_email_for_guest' );
function set_email_for_guest( $order_id ) {
    $email = get_post_meta( $order_id, '_billing_email', true ); // '_billing_email' instead 'billing_email'

    if( empty( $email ) ) {
        update_post_meta( $order_id, '_billing_email', 'email@example.com' );
    }
}

Comment: I test that also, not work, unfortunately.
Comment: wp_update_user( array ( 'ID' => $current_user->ID, 'billing_email' => $user_email ) ) This maybe you are looking.?
Comment: @mujuonly I don't want to update the user profile, I just want to put the email address for the orders that the user doesn't provide an email. sometimes user is guest
Answer: You want to update billing_email to custom email if the user does not provide a billing email on checkout.
So it would be a possible solution to the problem to give the email field on your checkout page a default value. This default value can be the customer email if logged in, or as in your example a hard coded value. This way you will always have a value in this field.
add_filter( 'woocommerce_checkout_fields', 'set_billing_email_default_value' );

function set_billing_email_default_value($fields) {
    $fields['billing']['billing_email']['default'] = 'firstname.lastname@example.com';
    return $fields;
}

Addition:
If you want to make it read only, so the user can not edit the default value, you can set this in the fields custom attributes.
$fields['billing']['billing_email']['custom_attributes'] = array('readonly'=>'readonly');

Comment: Thanks for your answer @rank. But with your solution customer can remove/change the default value. I looking for a way that the user can't change/remove the value.
Comment: You can make the field read only, I edited my answer. Hope it helps


Why is the equation of line through 2 points in projective space is their cross product

Question: Can anyone give intuition that why the equation of line passing through two points in projective space is given by their cross product?
Comment: This only works in the projective *plane*.
Comment: You wrote "projective *space*." This only works in a two-dimensional one.
Comment: That's what I am asking
Answer: The cross product of two lines gives the equation of the plane that contains them in your space $k^3$, when you goes to the projective $\mathbb P^2_k$, it means the line through both points.
Answer: In $\mathbb P^2$, a point $\mathbf p$ is on a line $\mathbf l$ iff $\mathbf l^T\mathbf p = 0$. If you interpret this equation in terms of inhomogeneous vectors in a three-dimensional Euclidean space, it's the familiar condition that two vectors are orthogonal iff their Euclidean scalar product—relative to the standard basis, their dot product—vanishes. So, the vector that represents the line through two points $\mathbf p$ and $\mathbf q$ is orthogonal to their homogeneous coordinate vectors. This is exactly what the cross product gives you. You can also reach this conclusion by examining the scalar triple product and what it means for it to vanish.


org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465

Question: I have a Maven project, use JSF 2.2, Tomcat 7 and use Apache Commons for sending e-mail.
Here is my code
try {
    // Create the email message
    HtmlEmail email = new HtmlEmail();
    email.setSmtpPort(465); //email.setSslSmtpPort("465");
    email.setSSLOnConnect(true);
    email.setHostName("smtp.gmail.com");
    email.addTo("email@example.com", "test");
    email.setFrom(getEmail(), getName());
    email.setSubject(getSubject());
    email.setHtmlMsg("Test"); // set the html message
    email.setTextMsg(getText());// set the alternative message
    email.send();// send the email
} catch (EmailException e) {
    logger.error("Exception sending email: ", e);
} catch (Exception ex) {
    logger.error("Exception sending email: ", ex);
}

When I tried to run the code in Tomcat 7, I got the following exception:

org.apache.commons.mail.EmailException: Sending the email to the
  following server failed : smtp.gmail.com:465
Comment: The standard `javax.mail` API has nothing like `HtmlEmail`. It belongs to Apache Commons.
Answer: This is going to be because the SMTP relay requires authentication, you must login with a gmail user / pass before you can use the relay.
I have never used commons email before, but after some googling, i found this for sending an email through gmail.
HtmlEmail email = new HtmlEmail();

String authuser = "user";
String authpwd = "pass";

email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));

email.setHostName("smtp.gmail.com");

// properties to configure encryption
email.getMailSession().getProperties().put("mail.smtps.auth", "true");
email.getMailSession().getProperties().put("mail.debug", "true");
email.getMailSession().getProperties().put("mail.smtps.port", "587");
email.getMailSession().getProperties().put("mail.smtps.socketFactory.port", "587");
email.getMailSession().getProperties().put("mail.smtps.socketFactory.class",   "javax.net.ssl.SSLSocketFactory");
email.getMailSession().getProperties().put("mail.smtps.socketFactory.fallback", "false");
email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");

Comment: Thanks, I changed the code but now i get the excpetion _org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:25_
Comment: i have the same


Is Task == Lazy?

Question: public Data GetCurrent(Credentials credentials)
{
    var data = new Lazy<Data>(() => GetCurrentInternal(credentials));
    try
    {
        return data.Value;
    }
    catch (InvalidOperationException ex)
    {
        throw ex.InnerException;
    }
}

If I change the call to the following:
var data = new Task<Data>(() => GetCurrentInternal(credentials));

Is there anything change? Should I prefer Task over Lazy? What about Dispose() and catch(Exception) ?
Comment: Don't be lazy, read the documentation... https://msdn.microsoft.com/en-us/library/dd321424(v=vs.110).aspx
Comment: You are doing your taxes. `Lazy` is "I might not need to compute my charitable contributions this year so I am going to put off doing that work as long as possible, in the hopes that I don't have to do it at all. But if I do have to, I will remember the result I computed so that I don't have to do it again."  `Task` is "my darling, while I am doing this other calculation can you work out our charitable contributions? Let me know when you're done, and I may or may not end up using your work. Regardless, once you're done, remember what the result was."
Comment: `Task` and `Lazy` are completely different classes and concepts - unrelated to each other. What behaviour do you want?
Comment: When you rethrow an inner exception like you do in your code you lose the stack trace making it hard to understand where the original exception occured. In general, don't rethrow exceptions like that. Either 1) catch it and handle it, 2) catch it and rethrow it as a new exception with the caught exception as the inner exception or 3) if you really want to rethrow the original exception (like if you want to log during exception unwinding) use `throw` in the `catch` block without specifying any exception to rethrow the original exception.
Comment: Why do you want to use `Lazy` in first place? It make no sense to initialize local variable. See [this](http://stackoverflow.com/q/6847721/1997232).
Comment: If you use `Task` it will throw an `AggregationException` that wraps any exceptions thrown by the enclosed code.
Comment: Using a Task like that doesn't compile so the entire question seems a bit hypothetical.
Comment: It compile if I change `.Value => .Result`
Comment: What's your query about `Dispose` and `catch`?
Comment: Here OP seems really lazy to check in the specification.
Comment: @ivan_petrushenko, care to answer my question? I am curious who told you to write such method or where did you get the idea to ask then such a un-deliberated (in my opinion) question which many think is a good one.
Comment: @juharr Thanks, for constructive answer
Comment: @MartinLiversage Thank you very much!
Comment: I learnt a lot from the contrast with F#'s Async in this article http://tomasp.net/blog/csharp-async-gotchas.aspx/
Comment: See also http://stackoverflow.com/questions/33872588/caching-the-result-from-a-n-async-factory-method-iff-it-doesnt-throw/33874601
Answer: Similarities
Both Lazy<T> and Task<T> promise to do some work later and return a result of type T.
Differences
Lazy<T> promises to do its work as late as possible if it is required at all, and does so synchronously.
Task<T> however can do its work asynchronously while your thread does other work, or blocks awaiting result.
Lazy<T> will bubble up any exception caused by the lambda when you call .Value.
Task<T> will keep any exception caused by the lambda and throw it later when you await task. Or if you task.Wait() it may wrap the exception in an AggregationException. I refer you to this for more info on catching exceptions thrown by tasks: Catch an exception thrown by an async method and this http://stiller.co.il/blog/2012/12/task-wait-vs-await/
Comment: there is another similarty: both does no sense in the supplied code.
Comment: Right, that's a bug in the analyzer that really ought to be fixed. It should suppress the warning when the disposable is a task.
Comment: @ivan_petrushenko Probably not please read  http://blogs.msdn.com/b/pfxteam/archive/2012/03/25/10287435.aspx
Comment: @ivan_petrushenko Just suppress the CA warning.  It's not going to stop you from compiling the code.
Comment: And I need to call Dispose if I use Task inside finally. Am I right?
Comment: CA2000 Dispose objects before losing scope. ... before all references to it are out of scope.
Comment: @weston Code Analysis is part of Visual Studio.  It use to be in a separate MS product called FXCop.
Comment: @juharr yes, but if I will use `Lazy` I will not suppress anything
Comment: @ivan_petrushenko So?  Are you saying that should be listed as a difference?
Comment: @ivan_petrushenko The two classes are different tools for different jobs. Don't let CA dictate which is appropriate for you.
Comment: @juharr didn't know that thanks. Bit shocking that Task causes this warning.
Answer: No, Lazy<T> is not the same as Task<T>.

Lazy<T> is an implementation of the concept of lazy evaluation:

It represents a T value that will be computed synchronously at first access, which may or may not occur at all.
Evaluation happens at first access, and subsequent accesses use a cached value. Memoization is a closely related concept.
The first access will block in order to compute the value, while subsequent accesses will yield the value immediately.

Task<T> is related to the concept of a future.

It represents a T value that will be computed (typically asynchronously) at the creation of its promise, even if nobody ends up actually accessing it.
All accesses yield a cached value that has been or will be computed by the evaluation mechanism (the promise) at a prior or future time.
Any access that occurs before the computation of the value has finished will block until the calculation is complete. Any access that occurs after the computation of the value has finished will immediately yield the computed value.

All that being said, Lazy<T> and Task<T> do have something in common that you may have already picked up.
Each of these types is a unary generic type that describes a unique way to perform a particular computation that would yield a T value (and that computation can conveniently be passed as a delegate or lambda). In other words, each of these types is an example of a monad. You can find some very good and simple explanations of what a monad is here on Stack Overflow and elsewhere.
Comment: Oh, it's a monad all right -- or, more accurately, a comonad. The C# type system has no problem creating types that use the monad pattern. The concept that the C# type system lacks is there is no way to say "I'd like to make a method whose arguments are only generic types that match the monad pattern".
Comment: @Thomas Great answer!
Answer: Task and Lazy are completely different concepts.
You use Task to do asynchronous operations. Some boring MSDN:

The Task class represents a single operation that does not return a
  value and that usually executes asynchronously. Task objects are one
  of the central components of the task-based asynchronous pattern first
  introduced in the .NET Framework 4. Because the work performed by a
  Task object typically executes asynchronously on a thread pool thread
  rather than synchronously on the main application thread, you can use
  the Status property, as well as the IsCanceled, IsCompleted, and
  IsFaulted properties, to determine the state of a task. Most commonly,
  a lambda expression is used to specify the work that the task is to
  perform.

Lazy is used for deferred initialization of an object. It means, that your object gets initialized only when you call lazyObj.Value.

Use lazy initialization to defer the creation of a large or
  resource-intensive object, or the execution of a resource-intensive
  task, particularly when such creation or execution might not occur
  during the lifetime of the program.
To prepare for lazy initialization, you create an instance of Lazy.
  The type argument of the Lazy object that you create specifies the
  type of the object that you want to initialize lazily. The constructor
  that you use to create the Lazy object determines the
  characteristics of the initialization. Lazy initialization occurs the
  first time the Lazy.Value property is accessed.
Comment: `Task` need not be asynchronous, `TaskCompletionSource` as one example.
Comment: @YuvalItzchakov that is true. Not necessarily for task to be async.

Is Task == Lazy?


Como validar um CEP utilizando o jQuery.validate

Question: Não estou conseguindo validar um CEP digitado pelo usuário.
eu adicionei o seguinte código dentro do jquery.validete.js
jQuery.validator.addMethod("cep", function(value, element) {
  return this.optional(element) || /^[0-9]{2}.[0-9]{3}-[0-9]{3}$/.test(value);
}, "Por favor, digite um CEP válido");

Porém se eu digitar: 11.111-111 ele aceita, quando na verdade este CEP não existe.
Comment: Bem vido ao SOpt Guilherme. Edite sua pergunte e agrupe seu código usando a opção de adicionar código, também sugiro um tour para aprender a perguntar: https://pt.stackoverflow.com/tour
Answer: Altere a expressão regular para:
/^[0-9]{5}-[0-9]{3}$/

O valor entre chaves define a quantidade de vezes que os caracteres entre colchetes vai se repetir, dessa forma a validação do valor 11.111-11 com /^[0-9]{2}.[0-9]{3}-[0-9]{3}$/ está correta
Comment: e teria como eu verificar se um CEP digitado realmente existe??
Comment: para isso você precisa consultar um serviço externo, existem perguntas aqui no site sobre o assunto: [CEP da minha cidade, onde posso encontrar fonte aberta, atualizada e confiável?](http://pt.stackoverflow.com/q/54539/13561) e [Como buscar um endereço por CEP nos Correios?](http://pt.stackoverflow.com/a/27267/13561)
Answer: Vou utilizar o webservice gratuito http://viacep.com.br/
assim ele me retornará um JSON http://viacep.com.br/ws/01001000/json/
que eu irei salvar em um objeto.
Obrigado @Sanção.
Comment: Guilherme, como você pegou o valor do JSON? e é possível preencher um campo automaticamente?


Get response from XML request in PHP

Question: What I'm trying to do is get the XML response into a PHP array so I can insert elements from the response into my database.  Here's what I've tried...
I have my code below:
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'myURL');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('Content-Type: application/atom+xml',
            'Authorization: Bearer ACCESS_TOKEN',
            'GData-Version: 2',
            'X-GData-Key: key=DEVELOPER_KEY'));
        $re = curl_exec($ch);

        // $xml = new SimpleXMLElement($data);
        // echo $xml;

        curl_close($ch);
        $xmldoc = new SimpleXMLElement($re);

        print_r($xmldoc);

I'm just not sure how to get it into a variable/array?
Thanks in advance!
Comment: It's in an object.  What is the result of `print_r($xmldoc);`?  That will show you how to work with it.  What do you want to do with it?
Comment: $xmldoc = new SimpleXMLElement($re);   Throws an error
Comment: Are you 100% sure that your $re contains valid XML?  What does the echo $re look like?
Comment: I'm downvoting this question because you appear to have been around on the site a while, so have presumably seen good and bad questions, and this one is really lacking in essential information: you showed us the code you tried, but told us nothing about the output you got until someone specifically asked, and then still didn't tell us what error message you saw. Nonetheless, check my answer below which may solve your problem.
Answer: You have to set the CURLOPT_RETURNTRANSFER option to true on your CURL handle, otherwise CURL's default behaviour is to spit the retrieved content straight to output, and return a boolean success flag, which is why echo $re shows 1 (true becomes '1' when converted to a string).
See the curl_setopt and curl_exec manual pages for details.
You should also learn how to turn on error messages if you haven't already (but only in your development copy!), and pay attention to what they say, not just that they happen. If you don't understand the error, paste the exact message into a question here (or just into a search engine), as someone else may well be able to explain what it is trying to tell you.

Get response from XML request in PHP


Strategy for reusing GWT DatePicker in Javascript algorithm

Question: in my GWT application I use a Javascript library to provide users with a SQL Where string builder capability - used to support 'advanced search'.
The javascript sources currently just provide a plain html text field for the date.  If I was in pure JS I'd incorporate one of the many 3rd party date selector libraries.
But,  I've already got the GWT date-editor there in the client (to support other UI capabilities).
Can anyone recommend a strategy for incorporating the GWT popup editor in my legacy javascript?  Because of GWT compiler obfuscation I don't think I can reliably predict the name of the GWT date editor component classes.
I suppose it's a balance between pushing the config from GWT, or pulling from the javascript sources.
cheers,
Ian
Answer: First, create in your html the place where you want the date picker to go, like so:

Create a new entry point, called something like Integration
package com.example.integration.client;

import java.util.Date;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.datepicker.client.DateBox;

/**
 * Entry point classes define onModuleLoad().
 */

public class Integration implements EntryPoint {

   @Override
   public void onModuleLoad() {

    //create date box
    DateBox dateBox = new DateBox();

    //set the value for the form submit
    dateBox.getTextBox().getElement().setId("dateValueField");

    //we need to override the default format
    dateBox.setFormat(new DateBox.DefaultFormat() {

        private DateTimeFormat dtf = DateTimeFormat.getFormat("MM/dd/yyyy");

        @Override
        public void reset(DateBox dateBox, boolean abandon) {
            super.reset(dateBox, abandon);
        }

        @Override
        public Date parse(DateBox dateBox, String text, boolean reportError) {
            return super.parse(dateBox, text, reportError);
        }

        @Override
        public String format(DateBox dateBox, Date date) {
            if(date == null) return "";
            return this.dtf.format(date);
        }
    });

    //add to the span
    RootPanel.get("dateBox").add(dateBox);
   }
}

You should probably put this in a new module, something like com.example.integration.Integration.gwt.xml.
  <module rename-to='integration'>

    <inherits name='com.google.gwt.user.User'/>

    <inherits name='com.google.gwt.user.theme.clean.Clean'/>

    <entry-point class='com.example.integration.client.Integration'/>

    <source path='client'/>
    <source path='shared'/>
  </module>

Now that you've done this you'll need to do the standard GWT dance to add the compiled code to your HTML.  Your final HTML should look something like:

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <link type="text/css" rel="stylesheet" href="Integration.css">
   <title>Web Application Starter Project</title>

        Your web browser must have JavaScript enabled
        in order for this application to display correctly.

    <form id="form">

        Old Style Date:<input type="text" id="sometext" value="MM/DD/YYYY"/>

        New Hotness:

    </form>

There will be a form item (text input box) in your form now with the id of 'dateValueField'.  This will submit just like a regular form element.
So, some of this advice should be able to get you on your way.  Good luck.
Note, there are some smaller and easier javascript libraries (including some jQuery stuff) that can do this much easier.
Comment: Hi Chris, I'm afraid my dev and I need a little more hand-holding. Would you mind making contact (email@example.com) - I may be able to sponsor a couple of hours of your time.  Ian.


issues while using @RunWith Annotation and powerMock

Question: Initially I was using only Mockito in junits so I was using SpringJUnit4ClassRunner.class in @RunWith annotation ie
@RunWith(SpringJUnit4ClassRunner.class)

due to which spring dependency injection was working fine and was getting a bean through
@Autowired

Someservice someservice ;

But now, I have also integrated PowerMock in it.
So as per doc , I have replaced class mentioned in @RunWith annotation with
@RunWith(PowerMockRunner.class)

but now, someservice is coming out to be null. Is there a way to use both SpringJUnit4ClassRunner.class and PowerMockRunner.class in @RunWith annotation
Answer: I know this thread is old, but it's good to add that since 2014 and this pull request, you can use the @PowerMockRunnerDelegate annotation to "delegate" the run context to SpringJUnit4ClassRunner (or any other runner really).
Above code would look like :
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PrepareForTest(X.class);
public class MyTest {

    // Tests goes here
    ...
}

With this annotation, you don't need the PowerMock rule anymore !
Answer: You have to use the PowerMockRule.
@RunWith(SpringJUnit4ClassRunner.class)
@PrepareForTest(X.class)
public class MyTest {
    @Rule
    public PowerMockRule rule = new PowerMockRule();

    // Tests goes here
    ...
}

For a full example of the Spring Integration Test with PowerMock and Mockito, you could checkout this maven project.
svn co http://powermock.googlecode.com/svn/tags/powermock-1.4.12/examples/spring-mockito/
cd spring-mockito/

Look at the dependecies to powermock.
less pom.xml

and then run the test
mvn test

and you should get the following test results :
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0

Comment: @gontard http://powermock.googlecode.com/svn/tags/powermock-1.4.12/examples/spring-mockito/ -- this link is no longer working.
Comment: Hey gontard, I have tried your solution but when I was executing my junit I was getting an exception that PowerMockRule "rule" should be public so I made it public and now I am getting the javassist.NotFoundException. Any thoughts? exeption java.lang.RuntimeException: javassist.NotFoundException: $Proxy88
 at org.powermock.core.classloader.MockClassLoader.loadUnmockedClass(MockClassLoader.java:187)
 at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:147) ....
Comment: @bhuvan i don't know, perhaps it is [this issue](http://code.google.com/p/powermock/issues/detail?id=350). I complete my answer too.


Nginx equivalent to mod_security and related

Question: I'm looking for a way to get my nginx to have reasonable abilities for auto-blocking various malicious requests.
E.g. since it doesn't serve any php scripts, any request for a php URLs that script kiddies seem to direct to my server should result in an immediate (temporary) ban of that IP.
Answer: update, mod_security now available for nginx:
http://www.modsecurity.org/projects/modsecurity/nginx/index.html
Answer: You can try fail2ban. It scans log files and can update firewall rules to ban specific IP. Also, it can execute any other action if needed.
Answer: As far as I know Naxsi is the only web application firewall solution for Nginx at the moment. It does not rely on signatures, but instead it detects unexpected characters in the HTTP communication. It also comes with a learning daemon that can be used to generate profiles for your applications.


AWS Amplify Graphql Unauthorized Error - Not Authorized to access [...] on type [...]

Question: I have an AWS Amplify App using Cognito auth
These are the affected Models/Schemas:
type Objective
@model
    id: ID!
    ..
    employee: Profile @belongsTo
    tenant: String
}

type Profile
@model
    id: ID!
    ..
    objectives: [Objective] @hasMany
    tenant: String
}

When I try to Query for list or get, the API returns the objective with all fields except employee (set to null) and also the following error message:
GraphQLResponseError
message:
"Not Authorized to access employee on type Objective"
Any Idea what I am missing?
I use tenant-based custom logic using customized .vtl templates in amplify which uses the authfilter (similar to the owner based approach generated by amplify). This works great with the Exception of trying to get the employee (Profile) field.
the logic looks a bit like the following:
## [Start] Authorization Steps. **
$util.qr($ctx.stash.put("hasAuth", true))
#set( $isAuthorized = false )
#set( $primaryFieldMap = {} )
#if( $util.authType() == "User Pool Authorization" )
    #if( !$isAuthorized )
        #set( $authFilter = [] )
        #set( $ownerClaim0 = $util.defaultIfNull($ctx.identity.claims.get("sub"), null) )
        #set( $currentClaim1 = $util.defaultIfNull($ctx.identity.claims.get("username"),
        $util.defaultIfNull($ctx.identity.claims.get("cognito:username"), null)) )
        #if( !$util.isNull($ownerClaim0) && !$util.isNull($currentClaim1) )
            #set( $ownerClaim0 = "$ownerClaim0::$currentClaim1" )
            #if( !$util.isNull($ownerClaim0) )
                $util.qr($authFilter.add({"owner": { "eq": $ownerClaim0 }}))
            #end
        #end
        #set( $role0_0 = $util.defaultIfNull($ctx.identity.claims.get("sub"), null) )
        #if( !$util.isNull($role0_0) )
            $util.qr($authFilter.add({"owner": { "eq": $role0_0 }}))
        #end
        #set( $role0_1 = $util.defaultIfNull($ctx.identity.claims.get("username"),
        $util.defaultIfNull($ctx.identity.claims.get("cognito:username"), null)) )
        #if( !$util.isNull($role0_1) )
            $util.qr($authFilter.add({"owner": { "eq": $role0_1 }}))
        #end
        ## begin custom auth with tenantId
        #if( $groupsInToken.contains("tenant-admin") )
            #foreach( $group in $groupsInToken )
                $util.qr($authFilter.add({"tenant": { "eq": $group }}))
            #end
        #end
        ## end custom auth
        #if( !$authFilter.isEmpty() )
            $util.qr($ctx.stash.put("authFilter", { "or": $authFilter }))
        #end
    #end
#end
#if( !$isAuthorized && $util.isNull($ctx.stash.authFilter) )
    $util.unauthorized()
#end
$util.toJson({"version":"2018-05-29","payload":{}})
## [End] Authorization Steps. **

The 'groupsInToken' will contain the corresponding tenant (id) supplied by a pretoken generation lambda.
This exact approach works fine for all Queries.
Just this Profile Object within the Objective payload seems to not be working with this approach and i can't figure out why.
Answer: After almost giving up i found the Solution...
When you Query for an Nested Object "Objective.employee" one would assume that Amplify first executes the "Objective.auth.1.req.vtl" and then the "Employee.auth.1.req.vtl" and then decides whether access is granted or not.
This is in fact not the case as Amplify generates a new Query/mutation called "Objective.employee.auth.1.req.vtl"
So if you ever encounter the Issue

Not Authorized to access x on type y

try to check the x.y.auth velocity template!
Comment: Its always after you almost give up :)


Multiple domains mail header not personalized

Question: I've got a dedicated server (Ubuntu 14.04) with Postfix/Dovecot on IP 22.214.171.124
I'm hosting 4 domains: 2 on IP 126.96.36.199, 1 on IP 22.214.171.124 and 1 on IP 126.96.36.199. Each one of these domains got a DNS record (A domain.com/mail.domain.com, MX record, SPF etc) pointing at their own IP address.
The problem is whenever I send an email and check out the email's header I see:
> X-Spam-Last-External-IP: 22.214.171.124
> X-Spam-Last-External-HELO: server.hostname.com
> X-Spam-Last-External-rDNS: Default Domain on 18.104.22.168
> Received: from server.hostname.com (Default Domain [220.127.116.11])
etc..

Is it not possible to show each time domain's related information instead of server information? For example 220.127.116.11 IP and mail.domain2.com hostname etc?
Answer: I don't think it's possible to have one postfix process listen on all addresses but use multiple hostnames for eg HELO headers, because the SMTP protocol doesn't support any way for the client to specify the hostname.
Consider for a moment HTTP Virtual hosting as a similar scenairo, perhaps the one you have in mind.  The client resolves the hostname, then makes an HTTP request, specifying the hostname in the Host header.  This header is what makes virtual hosting possible.
Now consider HTTPS.  Until relatively recently, there was no way to host multiple HTTPS virtual hosts on a server because the Host header was part of the encrypted payload, and thus the TLS session had to be established before the Host header would be sent.  But since the certificate provided by the server was dependent on the Host name used, this meant that an IP address had to be dedicated to each distinct HTTPS server name ( or more accurately, each https certificate common name.  Wildcards could match multiples ).
Relatively recently the SNI extension was added to HTTPS to alleviate that problem, so now the Host header is available to the server before the TLS session is established.
OK, let's jump back to SMTP.  An SMTP client doesn't specify a particular server name when it connects.  The server actually identifies itself before the host asks anything!
$ telnet  gmail-smtp-in.l.google.com. 25
Trying 22.214.171.124...
Connected to gmail-smtp-in.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP 11si20717228qkl.61 - gsmtp

There is, however, something you can do in your situation, but it's rather inconvenient.  You can run multiple postfix servers, each listening on a dedicated IP, and each configured to respond with the appropriate name.  It is in my understanding the only way to achieve what you want, and analogous to running https servers on dedicated IPs in the pre-SNI days.
Hope it helps.
Answer: You'd need a Postfix setup using "multiple instances" for that. Each instance would bing to it's specific IP (and only that IP), for both incoming and outgoing mail.
http://www.postfix.org/MULTI_INSTANCE_README.html
Theoretically, one could define dedicated "smtp" transports in master.cf (each bound to exactly one IP) - but there would be no easy way of telling Postfix which IP to use for an outgoing mail.


returning a refcursor with error code and message from postgres function

Question: I have a postgres function that returns a refcursor :
CREATE OR REPLACE FUNCTION ngfcst.meta_user_preference_error_test_go(--need to add -- inout o_errcode varchar, inout o_errmsg varchar--
    i_login character varying,
    i_pref_type character varying DEFAULT NULL::character varying)
    RETURNS refcursor
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
DECLARE
ref refcursor='o_user_pref_cur'; -- Declare a cursor variable
declare
    err_context text;
BEGIN

if i_pref_type is NULL THEN
    OPEN ref FOR
    select * from ngfcst.ORG_USER_PREFERENCE where login=i_login;
else
    OPEN ref FOR
    select * from ngfcst.ORG_USER_PREFERENCE oup where oup.login=i_login and oup.pref_type=i_pref_type;
end if;

RETURN ref; -- Return the cursor to the caller
exception
 when others then
        GET STACKED DIAGNOSTICS err_context = PG_EXCEPTION_CONTEXT;
        RAISE WARNING 'Error Name:%',SQLERRM;
        RAISE WARNING 'Error State:%', SQLSTATE;
        RAISE WARNING 'Error Context:%', err_context;
        CALL ngfcst.ins_error_logs( SQLSTATE,  err_context, '','','ngfcst.meta_user_preference_error_test');
       return -1;

END;
$BODY$;

now i am able to get any error through the exception block, but my requirement is to return the error code and error message in case we encounter any error. this is to be done by 2 extra out params o_errcode and o_errmsg.
when i try this i get the error
ERROR:  function result type must be record because of OUT parameters
SQL state: 42P13

how do i get the cursor in case of successful query and the error message and error code in case of any exception.
i need to implement this so that the calling block gets an error code <> 0 in case of any error and i immediately stop the process and log the error (which i am doing through ins_error_logs procedure)
Answer: Use three OUT parameters. An example:
CREATE FUNCTION meta_user_preference_error_test_go(
   IN  i_login     text,
   OUT o_errcode   text,
   OUT o_errmsg    text,
   OUT o_cursor    refcursor,
   IN  i_pref_type text DEFAULT NULL
) RETURNS record LANGUAGE plpgsql
AS $$BEGIN
   o_errcode := '0';
   o_errmsg  := 'SUCCESS';
   o_cursor  := 'o_cursor';
   OPEN o_cursor FOR SELECT 42;
END;$$;

BEGIN;

SELECT * FROM meta_user_preference_error_test_go('login');

 o_errcode | o_errmsg | o_cursor
-----------+----------+----------
 0         | SUCCESS  | o_cursor
(1 row)

FETCH ALL FROM o_cursor;

 ?column?
----------
       42
(1 row)

COMMIT;

Comment: Hi Laurenz, I see you are very fluent in Postgresql. I have tried to follow many documentations as well as trainings, but I am not able to get a in-depth knowledge. Can you please suggest some study materials that can guide through advanced Postgresql and pl/pgsql
Comment: Any suggestions Laurenz?
Comment: Read the PostgreSQL documentation. That is the only thing I ever read. It contains everything and is very clear.


Scaling a svg image while keeping the offset position.

Question: I have an svg image of a map that i have to scale up to make it zoom in. Javascript has a function to scale up SVG images. However the svg scale function uses the upper left corner as center when zooming.
So to counter this the usual trick is to shift the svg 50% to the left and 50% up so that the center moves to the upper left corner. Then scale the image and again move the image back.
Edit: I think this article might say what i need to do but i do not know enought about matrices: http://www.cs.rit.edu/~icss571/clipTrans/2DTransBack.html#BACK3.0
Edit3: Here is some more information about the problem:
http://commons.oreilly.com/wiki/index.php/SVG_Essentials/Transforming_the_Coordinate_System#svgess-CHP-5-FIG-9
The logic behind it looks like this.
var bbox = mapGroup.getBBox(); // the element of the svg image i want to scale up/down.
// finding center of element
var cx = bbox.x + (bbox.width/2); // x is the offset of the element horizontally
var cy = bbox.y + (bbox.height/2);  // y is the offset of the element vertically

// Shift the image so that the middle is in the upper left corner taking into account the amout of scaling;
mapGroup.attr('transform', 'translate(-' +(cx-(scale*cx)) + ', -' + (cy-(scale*cy)) + ')');
// scale the image
mapScaleGroup.attr('transform', 'scale('+ scale +')');
// Shift the image back again
mapGroup.attr('transform', 'translate(' + (cx-(scale*cx)) + ', ' + (cy-(scale*cy)) + ')');

This Works perfectly when i only want to hit the center of the image, however i have added a drag functionality that causes the offset to change. This causes problems as you can see here:
http://nho-municipality-map.divshot.io/
Zoom to see how it should be or drag the map and then zoom to see the mistake.
So I think the key to the problem lies ether in this part: cx = bbox.x + (bbox.width/2) or this part (cx-(scale*cx))
How do i take the custom offset into account?
Edit2: Here is all the information i get from the bbox.
Comment: No, then the position jumps all over the place :-/
Comment: Quick preliminary question: If you replace `cx-(scale*cx)` by `cx` and `cy-(scale*cy)` by `cy` throughout (i.e., both before and after scaling), does the code do what you expect?
Comment: I see. :S Second question (since I'm not fluent in SVG): What do `cx` and `cy` represent? Are they coordinates of the center of the image with the origin $(0, 0)$ at upper left? That is, are `bbox.x` and `bbox.y` equal to $(0, 0)$ before the user does any dragging, and are they not $(0, 0)$ after the user drags the map? Or does `bbox` refer to an SVG element the user has clicked? (Or is their meaning something else...?)
Comment: bbox.x and bbox.y is [0,0] before the image is dragged. the cx value that i calculate above seems to be the center of the image/svg yes :)
Answer: This doesn't directly answer the question, just explains the underlying mathematical theory.
Let $(x, y)$ denote Cartesian coordinates in the plane, $(x_{0}, y_{0})$ the center of expansion, and $\alpha > 0$ the scale factor.
Define $S(x, y) = (\alpha x, \alpha y)$ to be scaling (centered at the origin), and let $T(x, y) = (x + x_{0}, y + y_{0})$ be translation by $(x_{0}, y_{0})$. The inverse transformation of $T$ is $T^{-1}(x, y) = (x - x_{0}, y - y_{0})$.
Scaling centered at $(x_{0}, y_{0})$ can be viewed in either of two ways:
First, as the composition $TST^{-1}$. (Composition is read right to left, so this means "do $T^{-1}$, then $S$, then $T$".) Geometrically, translate the plane so that $(x_{0}, y_{0})$ is sent to the origin $(0, 0)$, then scale by $\alpha$, then translate the origin back to $(x_{0}, y_{0})$. This is the sequence of operations suggested by my first comment, i.e., by

var bbox = mapGroup.getBBox(); // the element of the svg image i want to scale up/down.
// finding center of element
var cx = bbox.x + (bbox.width/2); // x is the offset of the element horizontally
var cy = bbox.y + (bbox.height/2);  // y is the offset of the element vertically
// Shift the image so that the middle is in the upper left corner taking into account the amout of scaling;
mapGroup.attr('transform', 'translate(-' + cx + ', -' + cy + ')');
// scale the image
mapScaleGroup.attr('transform', 'scale('+ scale +')');
// Shift the image back again
mapGroup.attr('transform', 'translate(' + cx + ', ' + cy + ')');

Second, by working out formulas for the composition:
\begin{align*}
T^{-1}(x, y) &= (x - x_{0}, y - y_{0}), \\
ST^{-1}(x, y) &= \bigl(\alpha(x - x_{0}), \alpha(y - y_{0})\bigr), \\
TST^{-1}(x, y) &= \bigl(x_{0} + \alpha(x - x_{0}), y_{0} + \alpha(y - y_{0})\bigr)
  = \bigl(\alpha x + (x_{0} - \alpha x_{0}), \alpha y + (y_{0} - \alpha y_{0})\bigr).
\end{align*}
This is the formula referenced in the web link. The following (your original code with the first translate removed) should accomplish this:

var bbox = mapGroup.getBBox(); // the element of the svg image i want to scale up/down.
// finding center of element
var cx = bbox.x + (bbox.width/2); // x is the offset of the element horizontally
var cy = bbox.y + (bbox.height/2);  // y is the offset of the element vertically
// Shift the image so that the middle is in the upper left corner taking into account the amout of scaling;
// scale the image
mapScaleGroup.attr('transform', 'scale('+ scale +')');
// Shift the image back again
mapGroup.attr('transform', 'translate(' + (cx-(scale * cx)) + ', ' + (cy-(scale * cy)) + ')');

Given that the first doesn't work, the second shouldn't, either, but the two should fail to work in the same way.
If both pieces of code do fail in the same way, my guess would be that the problem is in the definitions of cx and cy. With either block of code above, cx and cy should be the SVG coordinates of the center of expansion.
If they don't fail in the same way, there's something fundamental I don't understand about how SVG handles affine transformations.
Comment: Just read thoroughly through this now and it makes sense. I removed the first translate and the map behaves exactly the same. I also think that i define cx and cy incorrectly, and i believe it has something to do with the offset being wrong. I'll test it a bit and get back to you. Thank you!
Comment: ok, so there is definatly something wrong with the definition of `cx` and `cy`. but how do i figure out what they should be? I'll try to add more information to the question above.
Comment: [Chapter 2](http://commons.oreilly.com/wiki/index.php/SVG_Essentials/Coordinates) of the O'Reilly book looks relevant. If I'm reading Chapter 2 correctly, transformations don't change anything internal to the SVG element, they only change the `viewBox` (which determines what portion of the SVG maps to the canvas). Perhaps you want the center of the `viewBox` instead of the `mapGroup`...?
Comment: That sounds reasonable, I'll try to find out how to get the center of the viewbox


É incorreto (ou problemático) criar um struct com array de strings?

Question: Não sei bem qual a maneira ideal para se criar uma estrutura (struct) que contenha um array de string, no caso tenho uma estrutura assim:
#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    char nome[81];
    char atores[81][100];
} Filme;

int main()
{
    Filme x[1000];

    return 0;
}

Ao executar isto simplesmente o programa finaliza (crash), então depurei com GDB para tentar entender o que poderia ser a causa e obtive somente a mensagem:

Program received signal SIGSEGV, Segmentation fault.

Presumo que seja erro meu por estar usando de maneira que a memória exceda ou talvez não consiga gerenciar, pois ao executar isto Filme x[1000] são criados muitas estruturas, quando crio algo menor, por exemplo Filme x[20], o problema não ocorre.
Então eu pensei em criar uma estrutura para os atores separada e referenciar/relacionar elas através de uma ID (que no caso seria o próprio index do item), algo como:
typedef struct
{
    char nome[81];
} Filme;

typedef struct
{
    int filmeref;
    char ator[81];
} Atores;

isto seria "correto"?
Answer: É aquela coisa de sempre, tudo depende. Onde vai usar? Qual o objetivo? Como vai manipular isso?
Tamanhos
Uma instância da estrutura Filme terá sempre mais de 8KB de tamanho, não importa se precisar bem menos, ou se precisar de mais, não ter onde colocar. É isto que deseja? É improvável.
Pensa em um banco de dados. Você quer usar char ou varchar? Nesse caso usou char. Mais ainda, se uma coluna pode ter N elementos prefere que isto seja colocado em: outra tabela; normalizando ou ainda com um formato variável; como XML, JSON, ou algo parecido até mesmo um próprio? Ou algo fixo? É isso que fez.
Mas tem casos que pode ser interessante fazer assim.
Deve-se questionar também se quer realmente criar um array com 1000 elementos. São mais de 8MB ocupados, e se quiser mais de 1000 filmes, não tem como. Claro pode criar outro maior e copiar tudo, o que não é algo tão trivial.
Se quiser manipular algo assim em uma aplicação real, pode ser tornar bem complicado ou desperdiçar recursos. Isto serve para algo muito simples, que se tem controle ou em exercício.
Alocação
Uma das coisas que provavelmente faria é ter um array de ponteiros para elementos de Filme, provavelmente alocados no heap. Provavelmente o próprio array deveria ser alocado no heap com malloc() no lugar de usar na stack. Tem um monte de links em outra pergunta. Mas precisa analisar bem qual é a melhor estratégia de alocação.
É provável que neste caso haveria benefícios em usar indireções em tudo. Mas depende de fatores que não podem ser definidos só por esta descrição. Provavelmente terá ponteiro de ponteiro.
Crash
Para resolver o crash pode gerar um executável com uma pilha maior para caber tudo, geralmente a pilha padrão é de 1MB. Mas ainda é uma solução, provavelmente, ruim, a pilha não deveria ser abusada assim na maioria dos casos.
Se não mudar a arquitetura geral então a solução proposta de separar as estruturas não ajudará muito, embora já seja um ganho por ser normalizado, agora haverá menos desperdício e poderá atender filmes com mais de 100 atores. Demorará mais para estourar, mas ainda terá problemas se continuar alocando na stack.
A stack é para coisas bem pequenas, ou pra um teste rápido, ou ainda quando se tem muito domínio do seu uso e precisa demais daquilo. Eu já fiz coisas onde abusei do stack e defini um de 4GB :), mas isto não é comum.
Modelagem
Ainda assim há um erro conceitual de modelagem já que o ator está vinculado ao filme, portanto haverá dezenas de Jerry Lewis cadastrados, quando só existe 1 Jerry Lewis. É o problema que eu falo sempre sobre orientação a objetos onde as pessoas seguem as receitas dos livros e modelam tudo errado. Seria melhor ter uma lista de identificadores de atores no filme e só uma instância daquele ator.
Mas aí voltamos ao problema da falta de normalização (segunda forma, a primeira estaria sendo respeitada). Então a solução seria ter uma lista separada de atores (só os IDs que apontam para a ficha do ator em si). Essa lista poderia ser um array, ou uma lista ligada com o primeiro elemento já colocado na estrutura do filme, ou uma árvore se precisar de certas características, ou uma tabela de espalhamento, ou outra estrutura que atenda melhor a demanda, cada um com suas vantagens e desvantagens. Se optar por uma lista dinâmica baseado em array terá que bolar estratégias de crescimento.
Há uma forma de manter uma única estrutura para todos os atores dos filmes, ou seja, em vez de ter uma lista por elenco, terá todo mundo junto, aí teria que ter uma chave e valor, com o ID do filme e o ID do ator, isso é uma lista de amarração. Em bancos de dados relacionais tradicionais é a única forma de fazer de forma sã.
A não ser que pegue uma biblioteca pronta terá que fazer tudo na mão, inclusive gerenciar a memória.
De qualquer forma fica claro para um caso real que a stack é inviável para isso tudo.
Uma ideia:
typedef struct {
    const char *nome;
    //outros campos
} Filme;

typedef struct {
    const char *nome;
    //outros campos
} Ator;

Cada nome, de Filme ou de Ator ficará no heap com malloc() (veja a diferença).
Cada Filme ou cada Ator seriam alocados individualmente do heap, sempre com malloc(), claro, a não ser que precise de uma estratégia mais personalizada, o que é raro e bem avançado. As pessoas confundem essa coisa de array físico e array formado por elementos referenciados.
A lista Filmes e a lista Elencos (esta é uma estratégia, que se liga bem com DB relacional) também ficaria no heap, provavelmente como um array, mas não necessariamente. No caso de Filmes teriam apenas ponteiros para cada Filme. E Elencos variaria, mas poderia ser uma estrutura assim:
typedef struct {
    Filme *filme;
    Ator *ator;
} AmarracaoFilmeAtor;

Coloquei no GitHub para referência futura.
Se optar por um array por filme aí poderia usar o ponteiro para o ator direto no array (no heap), o que pode ser um ganho, mas complica um pouco algum gerenciamento, aí um dos campos do Filme seria um ponteiro para a lista Elenco desse filme. Conceitualmente gosto mais disto. Inclusive um dos motivos de eu fazer experimentos com desenvolvimento de banco de dados é justamente ter este tipo de liberdade (NoSQL seria solução óbvia se não tivesse certos custos que não quero pagar).
Conclusão
Nada disso parece muito correto.
Também pode interessar:

Qual a diferença entre ponteiro e referência?
Quando devo escolher entre utilizar ou não um ponteiro ao criar um objeto?
Na prática, qual a utilidade dos ponteiros em C?
Qual a diferença entre escopo e tempo de vida?
O que impede um array de ser inicializado com um tamanho variável em C?
Qual a diferença entre ordered, unordered e sorted?
Comment: Nossa, sensacional, ainda mais quando levou a questão para o lado da modelagem, que de fato realmente é o meu problema principal. Vou ler tudo com calma. Fico realmente agradecido.


Kotlin+SpringBoot [Iniciante] Não consigo criar metodo Post

Question: Eu nem queria recorrer ao Stack em um problema tão simples, mas já esta se arrastando a dias e consegui implementar o metodo GET com uma certa facilidade, estou aprendendo kotlin e java, não estou conseguindo implementar o metodo POST, já testei no POSTMAN o GET e retornou ok,  mas queria incluir o metodo POST para acrescentar "NOVOS LIVROS, AUTORES E EDITORAS", tentei varias sentenças, mas por ser iniciante estou muito perdido.
<code>package com.example.blog

import org.springframework.web.bind.annotation.*

data class Relatorio(
        val titulo: String,
        val autor: String,
        val serie: String
)

@RestController
@RequestMapping("/bradesco")
class BradescoController {

    @GetMapping()
    public fun relatorio(): Relatorio {
        val result = Relatorio(
                "Bradesco Prime, O Comeco",
                "Luis Carlos",
                "Coletanea Bradesco"
        )
                return result
}
    @PostMapping
    @RequestMapping("/bradesco")
    public fun relatorio2() {
        "titulo" = "A historia de Luis Carlos"
        return "Atualizado";

    }
    }
</code>
Answer: O @RequestMapping é uma anotação usada para definir uma URL que vai ser solicitada:
<code>@RequestMapping("/foo")
public fun foo() {
    return "Foo";
}
</code>
você está criando a URL: /foo
A anotação em questão quando aplicada em nível de classe (quando colocada acima da classe controladora) não é necessária, porém ao ser colocada ela transforma todos seus métodos em URLs relativas.
<code>@RestController
@RequestMapping("/bar")
class BarController{
    @PostMapping("/foo")
    public fun foo() {
        return "Foo";
    }
</code>
Neste caso você está criando uma URL /foo no caminho relativo de /bar
Logo seu POST fica com o caminho: /bar/foo
Vale lembrar que o @PostMapping é uma maneira mais simples de implementar o @RequestMapping no método POST.
Answer: Complementando a resposta do @Brenno Serrato, se você quer utilizar um POST para acrescentar novos livros, eventualmente você vai precisar receber esse livro que precisa acrescentar no Body da sua requisição.
Isso pode ser feito dessa forma:
<code>@RestController
@RequestMapping("/book")
class BookController(private val bookService: BookService) {

    @PostMapping
    fun save(@RequestBody book: Book): Book {
        return bookService.save(book);
    }

}
</code>


Recuperar item de um Picker

Question: Estou com um projeto no Xamarin Forms e quero recuperar um item selecionado de um Picker.
O Picker esta sendo alimentado por uma lista de Objetos na sua propriedade "ItemSource" e estou mostrando os valores dessa lista com a propriedade "ItemDisplayBindind".
O que eu quero agora é enviar o item selecionado no Picker lá para minha ViewModel, alguem pode me dizer como fazer isso?
Answer: Nessa resposta, cuja pergunta possui um pouco mais de detalhes sobre a implementação em questão, você pode ver um exemplo de como usar esse recurso.
Basicamente, você pode usar a propriedade SelectedItem do Picker para fazer o binding com sua View Model.
Como você não compartilhou o código, também não sei como dar uma resposta específica, mas seria algo mais ou menos assim:
Na view model criar a propriedade que representa o item selecionado:
public class MinhaViewModel : INotifyPropertyChanged
{
    ...
private Objeto objetoSelecionado;
public Objeto ObjetoSelecionado
{
    get { return objetoSelecionado; }
    set
    {
        if(objetoSelecionado != value)
        {
            objetoSelecionado = value;
            OnPropertyChanged("ObjetoSelecionado");
        }
    }
}

...

}
No XAML da página, fazer o Binding com a propriedade equivalente:
<Picker SelectedItem="{Binding ObjetoSelecionado}"
        ItemsSource="{Binding ListaObjetos}"
        ...
        />

Espero ter ajudado.
Comment: Olá Diego, obrigado por responder. Deu certo, consegui pegar o valor selecionado na minha ViewModel, agradeço demais.
Comment: @Q.Wesley Que bom, fico feliz em poder ajudar. Bom desenvolvimento!

Recuperar item de um Picker


How to remove elements of a list where its string contains sub strings from another list

Question: I have a string like this:
var str = "DAVID CORPORATION"

then i have a list of substrings that i dont want in the str.
var describers = new List<string> {"CORP", "INC", "LTD", "TECH", "ENGINEER", "LLC","MICROELE"};

then i split the str here into a list:
var strList = str.Split(' ').ToList();

now i want to remove all items of that list that contains the substrings in describers. I found this way to do it a million times all over the internet.
strList.RemoveAll(x => describers.Contains(x));

This does not work because all it does is check if the describers contain the whole word of the strList. I need it to work in reverse.
This doesn't work but its an algorithm of how i want it to work.
strList.RemoveAll(x => x.Contains(describers.Any()));

Cannot convert from 'bool' to 'string'

of course, but how to i remove the item in strList that contains the substring item from describers.
..and only in a linq.lamba. I am trying to stay away foreach/for/do loops.
Answer: You can do the following using Any:
strList.RemoveAll(x => describers.Any(d => x.Contains(d)));


Manipulation of calculus notation

Question: I'm trying to get my calculus back up to scratch after not using it for 20 odd years. During my research, I've just seen this on https://physics.info/kinematics-calculus/:
$$a = \frac{dv}{dt}$$
$$dv = a\ dt$$
$$\int_{v_0}^v dv = \int_0^{\Delta t} a\ dt$$
Is this a valid manipulation of the calculous notation? My understanding is that the d/dt syntax is just notational, so I'm surprised to see it being treated as if the dt and dv where just algebraic variables that can be manipulated in this way.
Specifically, multiply both side by $dt$ is a surprise. Supposing for example we had this:
$$a = \frac{d}{dt}\ f(x)$$
Now, if I do the same thing as above, I get this:
$$d\ f(x) = a\ dt$$
Which looks like nonsense.
Comment: Well, if I can multiple through by it, then I should also be able to do anything else with it that I can do with a variable, right? Such as take a square root. So my question is really aimed at understanding if that's really valid mathematically, and what the limits are when manipulation this notation.
Comment: It seems correct to me.
Comment: It is valid through the chain rule
Comment: I've updated the question to better explain my source of confusion
Comment: Are you basically just asking whether it is sensible to multiply by $dt$
"?
Answer: It is fine, mostly. Infinitesmals are really defined under any number system, even when one considers proffs in calculaus/analysis, one deals with epsilon-delta proofs that skirt arounf the issue of infinitesmals.
Mathematically however, that is treating those quantities as manipulated 'variables' one could write $dy=f'(x)dx$ as the mathematical definisiont of the infinitesmal $dy$ as the differential is the infinitesmal difference between two successive values of a fucntion.
What is also required is a consideration of the idea of a separable equation, namely, that $dy$ and $dx$ are just notation here. And, more importantly, they are not necessary for separation of variables.
A separable equation is of the form
$$g(y)y′=f(x)$$
Comment: I disagree that the infinitesimal distance between two points is a "mathematical definition" of what $dx$ means. I have never seen such a definition but would be happy to be shown one.
Answer: The short answer is no, don't do it and it doesn't make sense. You are safe in treating it is just a heuristic that works to simplify some calculations. Since it isn't a defined  operation (unless the author has defined exactly what it means somewhere else), you can rewrite arguments without using it.
There is a framework, namely differential geometry, where these operations are given meaning, but it involves learning a whole new language - that of differential forms.

Manipulation of calculus notation


Is this group abelian?

Question: I tried to show that the following group is abelian by manipulation the relations but they didn't work. Please show me the right way. The group is $$G:=\left<x,y \mid xyxy^2=yxyx^2=1\right>$$
Comment: You're welcome!
Comment: Yea abelian @NancyR
Comment: Does the notation above mean 'for every pair, is is true that ...' or 'for every pair of distinct elements ...' ?
Answer: HINT:  From $xyxy^2 = 1$, you get $xyx = y^{-2}$.  Try substituting this into $yxyx^2 = 1$.
Comment: Excellent hint/answer. +1
Answer: Sorry for this kind of answer. @Tara's hint is enough but mine is base on Van Kampen diagram.
Comment: Rats, also this one is nice though not so elementary as Tara's...+1
Comment: Very nice! ++++
Comment: @DonAntonio: Thanks Don. I really ouldn't draw so I arranged it on a paper and this is one of my paintings. Thanks again. :)
Answer: Hint: You can identify $xyxy^2$ as a subword of $yxyx^2$. In details:

 $$\begin{array}{ll} yxyx^2=1 & \Rightarrow xyxyx^2=x \\ & \Rightarrow (xyxy^2)y^{-1}x^2=x \\ & \Rightarrow y^{-1}x^2=x \\ & \Rightarrow y^{-1}x=1 \\ & \Rightarrow x=y \end{array}$$

So $G \simeq \langle x \mid x^5=1 \rangle \simeq \mathbb{Z}_5$.
Comment: Noooo!  Please please please don't provide full answers to questions where someone (especially me =] ) has given a nice little hint, and the answer with the hint has been accepted.  It spoils all the fun.
Comment: OK, now I don't mind. =]  Thanks!
Comment: it's not so bad, Tara. In fact, your hint is almost a complete answer as it follows from it at once that the group is cyclic (and generated by $\,x\,$)...
Comment: @DonAntonio: Yeah, I know.  I've just had this happen quite a few times, sometimes when there was a little more to do.  This wouldn't have bothered me much if hadn't been for those other times.
Comment: @TaraB: I always like this kind of answer. I remembered I saw it for the first time done by Brian. It really help the OP reflect about hints. But as always, Mouse can't wait not to move on gray area and... ;-)
Comment: @BabakS.:  You mean answers with a 'spoiler' box?  Seirios added that after I complained.  I think it's good too.  I only found out you could do that when someone suggested I use it in an answer on the computer science site.  It doesn't seem to be used as much here.
Comment: @Seirios:  How about you make the spoiler box not include the first line of your answer?  That way it can be partially a 'hint' answer, too.
Comment: @TaraB: Yes. I saw that before and after you did. Nice job Seirios. +1
Comment: @Seirios:  Sorry, far too many comments here now, but I just noticed that you seem to have multiplied both sides by $x$ for no particular reason.  You don't actually ever use that extra $x$.  So you could shorten your proof by two lines without it.
Comment: @TaraB: Thank for your comments, I improved my answer.
Comment: @Seirios:  Oh, I'm sorry.  I thought I was probably being stupid (I'm quite tired today), and now that you've edited your answer, I see where you used the extra $x$ before and I actually like the old version better.  This one is only shorter because you 'skipped' a bit at the end.
Comment: @TaraB: I have no preference, so I edited to write my old argument.
Comment: Sorry for all the comment mess.  Also +1. =]

Is this group abelian?


How to fix a div height

Question: I'm working on a chat control app and my issue is like this.
I enter the text, this is used to make a rest call, get the response, and add it to the chat window.
Currently my issue is like this, the chat window gets bigger and the page gets a scroll along with the chat box(div). Can someone please let me know how can I stop this increment in the entire page.
In simple terms my requirement is the chat window will have an initial height say X and the user asks a query, the response gets pitched into the chat window, the user asks another and the same thing happens, but the page shouldn't get a scroll, instead the chat window should(This is already happening in my code).
Below is my code.

<meta charset="utf-8" />
<meta name="viewport"
    content="width=device-width, initial-scale=1, maximum-scale=1" />
<meta name="description" content="" />
<meta name="author" content="" />

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<title>Bootstrap Chat Box Example</title>

<link href="assets/css/bootstrap.css" rel="stylesheet" />

<link href="assets/css/font-awesome.css" rel="stylesheet" />

<link href="assets/css/style.css" rel="stylesheet" />

My Bot

                        User Name

                        Logout

Compliance Avatar

                        CHAT HISTORY

                            <button type="button" class="btn btn-info dropdown-toggle"
                                data-toggle="dropdown" aria-expanded="false">
                                 Toggle
                                    Dropdown
                            </button>

Hello, Welcome!. You can ask me
                            questions on Compliance Policy ..

                             - Bot

                             - You

                            <input type="text" class="form-control"
                                placeholder="Enter Text Here..." id="usermsg">
                                <button class="btn btn-info" type="button" id="submitmsg">SEND</button>

Frequently Asked Questions ..

My CSS:
.hr-clas {
    border-top: 1px solid #A12EB3;
}

.chat-box-main {
    max-height:500px;
    overflow:auto;
}
.chat-box-div {
    border:2px solid #A12EB3;
    border-bottom:2px solid #A12EB3;
}
.chat-box-head {
    padding: 10px 15px;
border-bottom: 2px solid #A12EB3;
background-color: #B25AE5;
color: #fff;
text-align: center;

}

.chat-box-left {
    width: 100%;
    height: auto;
    padding: 15px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    position: relative;
    border: 1px solid #C5C5C5;
    font-size:12px;
}
.chat-box-left:after {
    top: 100%;
    left: 10%;
    border: solid transparent;
    content: " ";
    position: absolute;
    border-top-color: #C5C5C5;
    border-width: 15px;
    margin-left: -15px;
}

.chat-box-name-left {
    margin-top: 30px;
    margin-left: 60px;
    text-align:left;
    color:#049E64;
}
    .chat-box-name-left img {
        max-width:40px;
        border: 2px solid #049E64;
    }

    .chat-box-right {
    width: 100%;
    height: auto;
    padding: 15px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    position: relative;
    border: 1px solid #C5C5C5;
    font-size:12px;
}
.chat-box-right:after {
    top: 100%;
    right: 10%;
    border: solid transparent;
    content: " ";
    position: absolute;
    border-top-color: #C5C5C5;
    border-width: 15px;
    margin-left: -15px;
}

.chat-box-name-right {
    color: #354EA0;
    margin-top: 30px;
    margin-right: 60px;
    text-align:right;
}

.chat-box-name-right img {
        max-width:40px;
        border: 2px solid #354EA0;
    }
.chat-box-footer {
    background-color: #D8D8D8;
padding: 10px;
}

please let me know how can I fix this.
Current issue Images.
when the page is loaded

After I send Hi as input

Thanks
Comment: set fixed height and use overflow:scroll;
Comment: could you put absolute path of all your sytlesheets?
Answer: Given your description above something like the below should work (Very simplified)

    <textarea id="HaveYourSay"></textarea>
    <button onclick="SendChat()">Send</button>

That will allow the contents of the div to reach a height of 400px before you get the scroll bar applied to the side.
Ive not used your HTML but have kept the example above simple so that you can apply it to your own app.
Check out the JS Fiddle : https://jsfiddle.net/6nep283h/1/
Note that I have used inline styles here for simplicity - I woudln't recommend using them in your app.
Answer: Replace your class with this as below

      .chat-box-div {
        border:2px solid #A12EB3;
        border-bottom:2px solid #A12EB3;
        max-height:400px ;
    }
Answer: Try this code for your portal
.chat-box-main{
     height:200px;
     overflow-y:scroll;
}

Answer: Try this
.chat-box-main {
  max-height: 500px;
  overflow-y:scroll;
}

How to fix a div height


Proof verification and explanation in probability

Question:
Six regimental ties and nine dot ties are hung on a tie holder.
  Sergio takes two simultaneously and randomly.  What is the probability that both ties are regimental?

I have seen that the probability that, not counting the order, the two extracted are between 6 fixed and none of the other 9; therefore if $E$ is the event then:
$$\text{Pr}[E] = \frac{C_{6,2}\cdot C_{6,0}}{C_{15,2}} = 1/7$$
where
$$C_{n,k} = \frac{D_{n,k}}{P_k} = \frac{n!}{k!(n-k)!} = {n \choose k}$$
For some it is more immediate to calculate the result as: $6/15 \cdot 5/14 = 30/210 = 1/7.$
Could I please have a clear step-by-step explanation?
Comment: The two are the same, except the second is an ordered picking: "First, pick a regionalmental tie, then pick a regimental tie again from the remaining ties." Hence there are no $1/2$ factors that cancel from numerator and denominator as in the case of the choosing approach.
Comment: @AlexR. Thank you very much. Can you put, please, a more simple answer step by step? I had no intuition about these problems, and I admit it. I ask you kindly to explain it to me very simply step by step with an answer. Thank you very much.
Comment: Thank you to David G. Stork for to have edited my question.
Answer: Even though he takes the ties simultaneously, we can still calculate it as if he takes one at a time randomly without replacing the first tie.
At the beginning, there are $15$ ties, and $6$ of them are regimental. So the probability of taking a regimental tie is $\frac{6}{15}$.
For the second tie, there are only $14$ left (since he already took $1$), and if he took a regimental tie on the first pick, there are $5$ regimental ties left. So the probability of taking a regimental tie as the second tie is $\frac{5}{14}$.
To find the probability of both these events happening, just multiply the individual probabilities.
$$\frac{6}{15}\times\frac{5}{14}=\frac{1}{7}$$
So the final answer is $\frac{1}{7}$.
Answer: It uses conditional probabilities: if you denote  $A_1$ the event 'the first tie is regimental tie and $A_2$: the second tie is also a regimental tie, you seek for  $P(A_1\cap A_2)$. Now, as
$$P(A_2 \mid A_1)=\frac{P(A_1\cap A_2)}{P(A_1)},$$
you can rewrite it as
$$P(A_1\cap A_2)= P(A_1)P(A_2\mid A_1).$$
Edit:
The first method, as I understand it, counts the number of favourable cases (the regimental ties are $2$, chosen among $6$ and none among the $9$ bow ties, and divides by the total number of possible cases (any two ties among atotal of $15$).
Comment: @Sebastiano: I've added a possible explanation, but don't ssee the usefulness of  $C_{6,0}$ (which, incidentally, should be $C_{9,0}$, I think).
Comment: @Sebastiano; That's quite unimportant for me. You did well!
Comment: And how do I get the expression of the combinations using binomial coefficients? Bernard I don't remember anything :-(. Can you complete it, please?
Comment: I have undertsood your question well...but excuse very much but...I have given the check mark to the user with a low score. Alwayssssssssssssssssssssssss thank youuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu.


What kinds of things are infinite series useful for?

Question: I'm a relative beginner studying Calc II, and I haven't been very motivated while learning infinite series.
Can you give some examples of how they're used in calculus or other areas of math, or in the sciences/"real world"? Well, either that, or a way of thinking about them that you personally find intuitive/fun (I know this second part is subjective, but I think the suggestions might still be valuable for me to try).
Comment: I think by series being useful you mean power series, as they are the simplest things to work with. There are many types of series that are interesting but not useful for practical use, e.g. then common Arctan series that gives the value for $\pi$.
Comment: If you do mean power series, then Taylor series are pretty excellent.
Answer: I think one of the most important ways in which series are useful are in approximating real-world phenomena.  A simple example is the equation for a pendulum: $\ddot{\theta} = -\frac{g}{l} \sin \theta$.  This ODE doesn't have a closed-form solution but by taking the Taylor series approximation of $\sin \theta \approx \theta$ we get a very standard, easy-to-solve differential equation $\ddot{\theta} = -\frac{g}{l} \theta$.  This a "go-to" toy example in the world of physics, but series approximations are generally used when using the exact function or equation is too cumbersome and not necessary in terms of accuracy.  If you can approximate a trigonometric function to just a few polynomials, and your bridge won't get anywhere close to collapsing, then why not?
On the complete opposite end of the spectrum, series are important for infinite-dimensional spaces of functions (like Hilbert spaces, which are fundamental to the study of quantum mechanics) in which the elements are expressed in terms of convergent infinite series.  I think regardless of the area of math you stay in (as long as it's applied, numeric, or analytic in some fashion) series will play some role, somehow.  Even if it's a minor role.
Comment: Thanks- both your and @induktio's answers were helpful, but I decided to choose yours over his because the end of your first paragraph led me to explicitly realize/re-realize that the partial sums of infinite series are really just ever-closer approximations of what they converge to, which ties into the beautiful idea of limits that calculus is founded on.
Answer: For me, I have always been amazed at the relationship between infinite series and trigonometric functions. For example:
$$
\sin x = x - \frac{x^3}{3!}+\frac{x^5}{5!}+\cdots = \sum_{n=0}^\infty \frac{(-1)^nx^{2n+1}}{(2n+1)!}
$$
and
$$
\cos x = 1 - \frac{x^2}{2!}+\frac{x^4}{4!}-\cdots = \sum_{n=0}^\infty \frac{(-1)^nx^{2n}}{(2n)!}
$$
and many others. Of course, the tie-in to your question is that trigonometric functions have a very practical application in everyday life.
Comment: One should look at how useful are these series for practical computation.


Best Method to Separate Drupal Website from Customized Scripts

Question: I currently have 2 small cloud servers: (1) database server; (2) web server.
The web server hosts my Drupal 7 website plus a lot of continually running scripts that process data and hook into Drupal's API functions (e.g. node_save, taxonomy_term_save).
I would like to split up my web server into two servers so that now I have 3 servers: (1) database server; (2) Drupal website server; (3) data processing server.
Since my custom scripts tie into Drupal's API functions, I am not sure how to actually run these scripts from a completely separate server without essentially cloning the web server and just blocking public access to the website on the data processing server.
Any ideas would be greatly appreciated! Thanks!
Answer: There's no way to use Drupal Apis from a separate server. Your best bet would be to use the web service module and process your request via json.
You'll have to do more work but on second hand, you'll end up with a nifty setup that'll allow you to leverage many other frameworks such as angularjs, backbone, and even mobile development.


$(2,x)$ is not a principal ideal of the ring $\mathbb{Z}[x]$

Question:
Let $R=\mathbb{Z}[x]$ be a ring of integers with usual addition and multiplication. Consider $$I:=(2,x):=\Big\{2\alpha(x)+x\beta(x)\ :\ \alpha(x),\beta(x)\in \mathbb{Z}[x]\Big\}.$$ I have to prove that the above one is ideal but not a principal ideal.

I have proved that

$(I,+)$ is a group and
$\forall f(x)\in \mathbb{Z}[x],\ \forall\  (2\alpha(x)+x\beta(x))=g(x)\in I, f(x)g(x) \in I,g(x),f(x)\in I.$

But I am unable to prove that it is not a principal ideal.
Comment: How about this http://math.stackexchange.com/questions/36169/show-that-langle-2-x-rangle-is-not-a-principal-ideal-in-mathbb-z-x?rq=1
Answer: Suppose that $(2,x)=(p)$, this implies that $2=pq$ this implies that $p$ and $q$ are constant and $p$ divides $2$. Since $(2,x)\neq Z[X]$, $p=2$. You also have $x=2q'$. Impossible since the coefficients of $2q$ are even.


How to make my app support for multiple screen with unique alignment of all elements present on screen?

Question: i am doing a android application that having the table layout and buttons i want to support my app to multiple screens what is the precautions i have to take any help,thanks in advance
Comment: read this http://developer.android.com/guide/practices/screens_support.html
Answer: Read this:
http://developer.android.com/guide/topics/ui/declaring-layout.html
And this:
http://developer.android.com/guide/practices/screens_support.html


Varnish Cache - Sometime Hit and sometime Miss on the same page

Question: It's from the same page.  When I first load the page, it's "MISS" if I refresh the page it will "HIT"
If I go back to my website home page and come back to the same page again it's "MISS"  I refresh the page and its "HIT"
Do you know why varnish is behave like that?
I'm using varnish 3
Thanks for your help guys.
HIT
Accept-Ranges:bytes
Age:61
Cache-Control:public, max-age=3600
Connection:keep-alive
Content-Encoding:gzip
Content-Language:en
Content-Type:text/html; charset=utf-8
Date:Wed, 18 Oct 2017 01:14:40 GMT
Etag:"1508289218-0"
Last-Modified:Wed, 18 Oct 2017 01:13:38 GMT
Server:Apache
Vary:Accept-Encoding
Via:1.1 varnish
X-Content-Type-Options:nosniff
X-Drupal-Cache:MISS
X-Frame-Options:SAMEORIGIN
X-Generator:Drupal 7 (http://drupal.org)
X-UA-Compatible:IE=edge,chrome=1
X-Varnish:83548823 83548200
X-Varnish-Cache:HIT

MISS
Accept-Ranges:bytes
Age:0
Cache-Control:public, max-age=3600
Connection:keep-alive
Content-Encoding:gzip
Content-Language:en
Content-Length:22462
Content-Type:text/html; charset=utf-8
Date:Wed, 18 Oct 2017 01:13:39 GMT
Etag:"1508289218-0"
Last-Modified:Wed, 18 Oct 2017 01:13:38 GMT
Server:Apache
Vary:Accept-Encoding
Via:1.1 varnish
X-Content-Type-Options:nosniff
X-Drupal-Cache:MISS
X-Frame-Options:SAMEORIGIN
X-Generator:Drupal 7 (http://drupal.org)
X-UA-Compatible:IE=edge,chrome=1
X-Varnish:83548200
X-Varnish-Cache:MISS

Answer: What you describe really looks like cache expiration. Note that the default TTL for cache in Varnish is 120 seconds only.
You would need to adjust Varnish TTL to something higher, obviously.
Comment: Yes you right, I've now changed the TTL from 120 sec to 52w  and it fixed the problem.   Thanks so much Daniel V.  Much appreciated your help.


Query usando Mongoose in Nodejs sempre retorna null mesmo dentro de assíncrono método

Question: Eu estou tentando recuperar um documento em meu Database usando Mongoose in Node.js mas ele sempre retorna Null.
Meu problema antes era o método assíncrono , mas agora tudo está sendo executado dentro dele. E eu so estou tentando imprimir o documento recuperado do Database, mas sempre retorna isso :
#session from the database ++++++++++++++++ null

Essa é minha funçao:
function isAuthorized(sessionID, sessionIDtype, callback){
    var id = "'"+ sessionID+"'"
    sessions.findOne({'sessionIDtype': id}, function(err, sessionDoc){
        if(err) return handleError(err);
        if(sessionDoc != undefined){
            log.d("session from the database inside no if != undefined++++++++++++++++", sessionDoc)
            if(sessionDoc.date < new Date()){ //fix validation on data, expires needs to be < new Date
                callback(sessionDoc);
            }else{
                callback(undefined);
            }
        }else{
            callback(undefined)
        }
        log.d("session from the database ++++++++++++++++", sessionDoc)
    });
}

Está retornando isso no terminal:
#session from the database ++++++++++++++++ null

e nunca entra neste if:
if(sessionDoc != undefined)

Eu acho que o erro está na query, mas eu já tentei isso:
sessions.findOne({'sessionIDtype': sessionID}, function(err, sessionDoc){

e isso:
var query = {}
query["'"+ sessionIDtype +"'" ] = sessionID;
sessions.findOne(query, function(err, sessionDoc){

mas se eu substituo os valores a query é executada. Com esse codigo funciona:
 sessions.findOne({'googleUID': '12314'}, function(err, sessionDoc){

segundo a Documentação do Mongoose:
fonte :http://mongoosejs.com/docs/queries.html
O problema não são as aspas no valor :
 sessions.findOne({'key': 'value'}

O problema são as aspas da chave: para a query funcionar a primeira palavra tem que esta entre aspas,mas o valor nao precisa esta. Exem:
sessions.findOne({'key': value} //Isso funcionaria, eu ja testei.

O problema eé que eu recebo o nome do identificador e o valor pela funcao acima. Entao, eu posso so substituir o valor pelo parametro que eu recebo, mas o identificador nao. Exem:
sessions.findOne({'parametro1': value}

Nao posso fazer isso acima. Nao funcionaria.
Eu posso criar um if para cada caso, mas o codigo ficaria muito feio. Exem:
funcao(param1, value){

 if(param1 == "googleUID")

sessions.findOne({'googleUID': value}

} //Isso funcionaria

Mas e se eu tiver 10 possibilidades de identificadores? 10 if's não da!
então, como colocar aspas  no identificador?
Comment: já tentou sem as aspas na sessionID ? Geralmente o framework de dados cuida disso para ti.
Comment: Vc pode comentar aqui a parte que vc esta se referindo? Qual framework? Desculpe, sou nova nisso.
Comment: Vc esta certo. Isso funcionaria: session.findOne({'key':variable}) sem aspas no valor, mas o problema e a chave que n sei qual  é.Atualizei a questao.
Comment: E realemente me perdi no que você escreveu. "O problema são as aspas da chave", se tentar com `{'sessionIDtype': sessionID}` o que acontece?
Comment: @Caputo , vc esta certo isso funcionaria. Mas a key que eu tenho no documento n é 'sessionIDtype', sessionIDtype é a variavel que armazena o nome da minha key.Pode ser 3 diferentes nomes. Posso fazer 3 ifs, mas e se eu tivesse 10 diferentes nomes? esse é o problema. Em vez de repetir o codigo 3 vezes queria fazer somente uma vez.
Comment: E se tentar: `var condicao = new Object();` e depois `condicao[param1] = value;` e por último `sessions.findOne(condicao)`
Answer: Crie o objeto com os parâmetros primeiro, e use a notação de colchetes para ter uma chave dinâmica:
function isAuthorized(sessionID, sessionIDtype, callback){
    var parametros = {};
    parametros[sessionIDtype] = sessionID;
    sessions.findOne(parametros, function(err, sessionDoc){
        // ...
    }
}

Answer: Isto aqui vai funcionar:
sessions.findOne({sessionIDtype: sessionID}, function(err, sessionDoc){
   ...
});

Edição após seu comentário:
Que tal fazer assim então:
var criteria;

if (...) {
  criteria = {
    fbUID: '1234'
  };
} elsif (...) {
  criteria = {
    googleID: '4567'
  };
else {
  criteria = {
    twitterID: '7890'
  };
};

...

auth = isAuthorized(criteria, cb);

...
function isAuthorized(queryCriteria, callback){
    sessions.findOne(queryCriteria, function(err, sessionDoc){

Comment: Nao funciona. So funcionaria assim com aspas : sessions.findOne({'key': sessionID}). O problema e q a palavra key pode ser 3 palavras diferentes. Tipo "fbUID", "googleID", "twitterID"


Question regarding conditional and marginal distributions

Question: I've stumbled upon this figure. You can see that the shaded area represents the conditional density function:
$$f_{X_1|X_2}(x_1|x_2) = \frac{f(x_1,x_2)}{f_{X_2}(x_2)}$$
At the same time, this shaded area is the marginal distribution $f_{X_2}(x_2)$, at least as far as I can tell:
$$f_{X_2}(x_2)=\displaystyle \int_{-\infty}^\infty f(x_1,x_2)\, dx_1$$
If variables are independent, the following is true:
$${f_{X_2|X_1}\left(x_2\middle| x_1\right)=f}_{X_2}\left(x_2\right)$$
That is when it gets confusing, because based on my - obviously incorrect -  interpretation of the figure I can conclude that $f_{X_1|X_2}\left(x_1\middle| x_2\right)=f_{X_2}\left(x_2\right)$. Something has gone wrong ...
Could you please point me in the right direction? I just want to understand these concepts in a more visual way.
Answer: For any $b$ you get a conditional distribution/density $f_{X_1 | X_2}(x_1|b)=\frac{f_{X_1 ,X_2}(x_1,b)}{f_{X_2}(b)}$ for $X_1$ given $b$. You can see this, because this distribution lives on the $x_1$-Axis given $b$ on the $x_2$ axis.
$f_{X_1 ,X_2}(x_1,b)$ is the shaded slice in the figure. This is up to the $x_1$-constant $f_{X_2}(b)$ a probability distribution (to be more precise the conditional probability distribution of $X_1$ given $X_2=b$).
For the marginal distribution in general, if you vary $b$, you get a different conditional distribution for $X_1$, i.e. the shape of the distribution always looks different. But if the shape looks same for each value $b$, i.e. if $f_{X_1 ,X_2}(x_1,b)$ scales proportional in $f(b)$, which is equivalent to $\frac{f_{X_1 ,X_2}(x_1,b)}{f_{X_2}(b)}$ is always the same function in $x_1$, which is then equal to $f_{X_1}(x_1)$, then $X_1$ and $X_2$ are independent.
In general, $$f_{X_1}(x_1)=\displaystyle \int_{-\infty}^\infty f(x_1,x_2)\, dx_2=\int_{-\infty}^\infty f_{X_1|X_2}(x_1|x_2)f_{X_2}(x_2)\, dx_2$$ which means (loosely / heuristically), that you sum up all $X_1$ distributions $f_{X_1|X_2}$ over $x_2$ given $x_2$ weighted by the probability of $x_2$. Then you arrive at the marginal distribution in the background.
Comment: @ Philipp123, thanks a lot for your elaborate answer!


Webform update!

Question: I need to update webform module in my live site, I noticed the warning with doing that with the user Interface so I want to update the files manually, ( because we don't use drush ), Can I get directions for doing this update? again since the site is live and this is our first Drupal site I want to make sure from not breaking the site or having any issues!
also, I have the files in Cpanel so from where exactly should I start to upload the updated files?
is it like in the screenshot below

Thanks and appreciate any help!
Comment: What does the warning say when trying the update with the administrative interface?
Comment: "The Webform module may not update properly using this administrative interface. It is strongly recommended that you update the Webform module manually or by using Drush."  This is exactly what showing when trying the update with the administrative interface?
Answer: There is not much more to say than what is explained in the Drupal doc when you click on the links available in the warning (See Updating a Module)
Whatever the method you use for updating your module, I advise you to always test your update on a copy of your website (local environment, development server... with at least similar php version) to ensure everything works fine before updating the live website.
Regarding the update process:

if you manage your modules with Composer,

on the copy of your website, open a console,
go to the root of your website (same level as the composer.json file),
run composer update drupal/webform --with-dependencies,
run the database update script (yoursite.com/update.php).
If everything is okay, copy the composer.lock file to your prod environment,
open a console on your prod environment,
go to the root of your website and run composer install (it will update your packages and modules to the versions specified in the composer.lock file).
finally, run the database update script and check that your website works fine.

if you don't use Composer, follow the steps from the Drupal doc 11.6. Manually Downloading Module or Theme Files. First for the copy of your website and then for your prod website.

Webform update!


Convert NSData to Java String

Question: I'm developing an iOS app which make use of a web service written in java.
The app make a POST request to this web server sending an NSData object, created from a JSON, which is for example:
<7b22636c 69656e74 223a7b22 656e7669 726f6e6d 656e7422 3a227361 6e64626f 78222c22 70726f64 7563745f 6e616d65 223a2250 61795061 6c20694f 53205344 4b222c22 70617970 616c5f73 646b5f76 65727369 6f6e223a 22322e32 2e31222c 22706c61 74666f72 6d223a22 694f5322 7d2c2272 6573706f 6e73655f 74797065 223a2270 61796d65 6e74222c 22726573 706f6e73 65223a7b 22696422 3a225041 592d3233 44393230 32375545 36383337 3034304b 51434337 5859222c 22737461 7465223a 22617070 726f7665 64222c22 63726561 74655f74 696d6522 3a223230 31342d30 392d3031 5430383a 33353a34 335a222c 22696e74 656e7422 3a227361 6c65227d 7d>

so in my servlet I do
String req = request.getParameter("data");

but obviously when I try to print it I get the bytes above.
How can I convert such data into the initial JSON?
EDIT 1:
I send an NSData in this way
    NSData *confirmation = [NSJSONSerialization dataWithJSONObject:completedPayment.confirmation
                                                           options:0
                                                             error:nil];

    NSURL *url = [NSURL URLWithString:@"MY_WS"];

    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    NSString *messageBody = [NSString stringWithFormat:@"data=%@", confirmation];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody:[messageBody dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

I think I cannot send the JSON string directly...
Comment: Why you do not send the JSon?
Comment: See this:http://stackoverflow.com/questions/3774872/nsdata-to-java-string
Comment: @Yasika it's not what I need. I've already that string form. What I need is to convert a String containing bytes in a String containing a JSON!
Answer: Not sure about NSData but if you can get byte[] array you can pass it to sting constructor.
String javaStringRep = new String(theByteArray, "UTF-8");

Hope this helps.. :)

Convert NSData to Java String


How to prove $\binom{n}{4}=\sum_{i=3}^{n-1} \binom{i}{3}$?

Question: I was trying to find the number of diagonals of a nth polygon by deduction. Let $a_n$ be the number of the diagonals of thr nth polygon. Then I've got $$a_{n+1}=a_n+\binom{n}{3}$$
$$a_n=\sum_{i=3}^{n-1} \binom{i}{3}$$
But we simply know that $a_n=\binom{n}{4}$, where $a_n$ is the number of diagonals.
So we get $\binom{n}{4}=\sum_{i=3}^{n-2} \binom{i}{3}$. My question is whether it is a trivial equation or it can be generalized like $\binom{n}{k}=\sum_{i=k-1}^{n-1} \binom{i}{k-1}$. If it can be, how to prove that?
Comment: This is the Hockey-stick_identity: see https://en.wikipedia.org/wiki/Hockey-stick_identity
Comment: $$\binom nk-\binom{n-1}k=?$$ https://math.stackexchange.com/questions/1125923/proving-pascals-identity
Comment: Can be proved by induction.
Answer: We have to choose four numbers from $[n]$. Assume the largest chosen number is $i+1\in[4..n]$. The other three numbers then are arbitrary three numbers in $[i]$.
Answer: You may transform the sum into a telescoping sum using the "binomial" fact

$\binom{i}{3} = \binom{i+1}{4} - \binom{i}{4}$

Hence,
\begin{eqnarray*} \sum_{i=3}^{n-1} \binom{i}{3}
& = & \sum_{i=3}^{n-1} \left(\binom{i+1}{4} - \binom{i}{4} \right)\\
& \stackrel{\binom{3}{4} = 0}{=} & \binom{n-1+1}{4} - 0\\
& = & \binom{n}{4}\\
\end{eqnarray*}
Answer: Let $k=3$ so that $4=k+1$. The binomial coefficient $\binom n{k+1}$ counts the $k+1$-element subsets $S$ of the $n$-element set $\{0,1,\ldots,n-1\}$. Let $S$ be such a set and $i=\max(S)$. Then $k\leq i<n$, and $S=S'\cup\{i\}$ where $S'$ can be any $k$-element subset of the $i$-element set $\{0,1,\ldots,i-1\}$. So
$$\binom n{k+1}=\sum_{i=k}^{n-1}\binom ik.$$