Existence and Uniqueness of the exponential interpolation

Question: Suppose function has the form $$f(x) = ae^{bx}+ce^{dx}$$
where $a,b,c,d $ are real variables. Given four real numbers $x_1,x_2,x_3,x_4$, and four corresponding values $y_1,y_2,y_3,y_4$.
Whether can we find $a,b,c,d$ such that $$f(x_j)=y_j,j=1,2,3,4$$
Comment: first derivative has at most one root, so can't have zig zag
Answer: No, this is in general not possible.
Here is a simple counter example:
Consider a case where two of the chosen points would be $(1,0)$ and $(1,0)$.
This gives:
$$
f(-1) = a e^b + c e^d = 0
$$
$$
f(1) = a e^{-b} + c e^{-d} = 0
$$
Obviously the function $f(x)=0$ would be valid. For a non-trivial solution, one of the values $a$ or $c$ needs to be non-zero. Without loss of generality, we examine the case $a\neq 0$. If we rewrite the two equations, we get
$$
-c/a = e^{b-d} = e^{d-b}
$$
from which it follows that $d=b$ and $c=-a$. Consequently, we find that
$$
f(x)=a e^{bx} - a e^{-bx} = 2 a \sinh bx
$$
With $f(1)=0$ this gives $b=0$ and we find that again $f(x)=0$. Hence any other additional point $(x_3,y_3)$ with $y_3 \neq 0$ would make it impossible to find a solution for $a,b,c,d$.
Hence, in general there is no solution.
A more general way of looking at the question is to consider the derivative of the function $f(x)$:
$$
f'(x) = a b e^{b x} + c d e^{d x}
$$
If we look for the solutions $f'(x)=0$, we find that there is at most a single solution for $x$. (Ignoring the trivial function $f(x)=0$). Hence, any four points $(x_i,y_i)$ with $x_1<x_2<x_3<x_4$ and where the corresponding $y$ alternatingly increase and decrease, could never be fitted by a function of this particular form.


Should I learn harmonium to learn western singing?

Question: I am an Indian, and I want to learn western music/singing, but my teacher says first you have to learn harmonium to learn singing. So I am confused: should I learn harmonium, because as far as I know, harmonium is good for Indian classical, and I want to learn western singing. So what should i do?
I am also thinking of buying a musical instrument. So please clear my doubts on it with harmonium.
I will buy either a harmonium or a guitar based on your answer.
Comment: @DavidW -  seems there are two different sorts of music. There's Country, and there's Western...
Comment: I'm not completely convinced that "country and western" is the type of singing you're after? However, a quick search suggests that neither Bob Wills, nor his Texas Playboys used harmonium regularly in their music.
Answer: Having an instrument like a harmonium or guitar while learning to sing is very helpful, but not necessary. It is helpful, because it can guide your pitch, giving you a sound to which to match your voice. It can also be used to provide accompaniment to your singing.
Keyboard instruments and guitar are perhaps the most common instruments to learn along with (western) singing, but the specific instrument is not so important; it's more important you have something that you enjoy hearing and playing.
Also, you need not learn another instrument before you learn to sing. Both can be learned together.
Answer: The vast majority of Western music (played on many instruments) is based on 12tet tuning, which is rather different from traditional Indian tuning. I guess the harmonium comes into the second category. The guitar is in the first. And the guitar seems to be quite a prevalent accompanying instrument for Western music. The harmonium more so for Indian classical.
I'd suggest that the guitar is probably easier to get started on - attestation to thousands of beginners from the 60s onwards - although your teacher obviously has other views. Perhaps they only play harmonium, which would mean you could progress more quickly on that with their help. Being usually 'just tuned', it matches subtle differences in the intervals one might sing, making them sound 'more musical', whereas the guitar will produce some intervals which won't sound quite as musical to some ears.
Comment: From a quick read of the wikipedia article suggests that harmoniums are mostly made with the Western 12-note scale (and thus don't quite fit into traditional Indian music). So it may not be a complete disaster - it'd just be an organ-like keyboard instrument.


How to find cross correlation of a response variable with three independent predictor variables for time series data to identify useful lags?

Question: I have a time series data y (response variable) which I want to predict using 3 independent time series data x1, x2 and x3. My goal is to build a multivariate regression model for which I want to identify useful lags of x1, x2 and x3 (also possibly lags of y) that might be useful predictors for y.
Snapshot of y, x1, x2 and x3 respectively are shown below

My questions are-

If I determine cross correlation between y and x1 (without taking into account x2 and x3), y and x2 (without taking into account x1 and x3), y and x3 (without taking into account x1 and x2) separately, would that give me useful insight about how many lags of x1, x2 and x3 I should use in my regression model? What would be a better approach? Is there any way to take into account other independent variables while performing cross correation between two time series?
Since there is more than one independent variable, would prewhitening the independent variables before determining cross-correlation give me correct result? Or do I have to use spectral analysis?
independent variable x1 and x2 are not stationary. Because of that I have to make the data stationary before determining the ARMA model. Since for determining CCF, the same filter has be applied on y, should I apply the same steps that I took to make x1 stationary on y too? Or do I have to make y stationary by other separate steps? Or do I just apply the ARMA model filter?
Is it advisable to use Granger causality here do determine if y has causal relationship with x1, x2 and x3?
Another question is could you give me insight from looking at the data if y, x1, x2 and x3 have trend? Is there any test to find out trend? if my time series have trend, do I have to detrend them before determining the regression model?
Comment: 5. Do you want a regression model with autoregressive errors or just a regression model?
Comment: Actually until now I was building just a regression model. But some insight into a model with autegression error will also be helpful
Answer:
The cross correlation between the observed series is of little value . You  should use single pre-whitening to aid the initial identification. Make sure you account for anomalies in the individual x's before you form the arima filter
use pre-whitening
make each variable stationary and use the filter for each of the x's separaetely to estimate the ccf
no need to use Granger here ,, you are trying to identify an initial model
absolutely no detrending is needed to create the arima filters unless they are needed in concert with the arima model
Comment: Thank you for your answer. For question 3. I am still confused, do I have to make the response variable y stationary too? Also Suppose I am differencing x1 to make it stationary before modeling with with ARMA (1,1), so effectively it is ARIMA(1,1,1). Then since I have to use  the same filter on y, do I difference y too before applying ARMA (1,1) on it? Or do I have to make y stationary first using some other procedure? Or do I just apply ARMA (1,1) on raw y?
Comment: Use https://onlinecourses.science.psu.edu/stat510/node/75/ . The filter that is used is does not include any differencing operators as each of the series wlll already been suitably differenced by their individual differencing operator.. There are exceptional cases where it is beneficial not to difference at all and allow the transfer model to fully handle the relationship.


Searching for string input using a function bool deleteAcc(const string name1) in doubly linkedlist in C++98?

Question: All my other functions of my doubly linked list which consist of Account class and Node class are all working except this last function.
The function bool deleteAcc(string name) will take as it's argument, the string name (that the user inputs) and returns a bool result. It will then find the name in the list and delete the corresponding Account (and Node) from the list, then return True. If the Account was not in the list, it will return False.
This is my code as shown below:
#include <iostream>
#include "Account.h"
#include <string>
#include "Node.h"
using namespace std;

bool deleteAcc(const string name1);

int main(){

    string name;
    int k;
    cout << "How many accounts do you want to enter? ";
    cin >> k;

    Node* head = NULL;
    //Node* tail = NULL;

    for (int i = 0; i < k; i++) {
        string name;
        double balance;

        cout << "Enter account name: ";
        cin >> name;

        cout << "Enter account balance: ";
        cin >> balance;

        Account account(name, balance);

        Node* newNode = new Node(account);

        if (head == NULL) {
            // The list is empty, so set both head and tail to the
            // new node
            head = newNode;
            // tail = newNode;
        } else {
            // The list is not empty, so add the new node to the
            // tail
            newNode->setNext(head);
            //newNode->setPrevious(head); // Update previous pointer
            // of newNode to point to the previous last node (i.e.,
            // tail)
            head = newNode;
        }
    }

    // Print the list
    cout << "Account balances:" << endl;
    cout << endl;

    Node* currentNode = head;

    while (currentNode != NULL) {
        cout << currentNode->getData() << endl;
        currentNode = currentNode->getNext();
    }

    cout << "Enter the account name you want to delete: ";
    cin >> name;
    deleteAcc(name);

    // Deallocate memory
    currentNode = head;

    while (currentNode != NULL) {
        Node* nextNode = currentNode->getNext();
        delete currentNode;
        currentNode = nextNode;
    }

    return 0;
}

bool deleteAcc(const string name1)
{
    Node* currentNode = head;
    Node* previousNode = NULL;

    while (currentNode != NULL){
        if (currentNode->getData().getName() == name1) {
            if (previousNode == NULL) {
                // The node to be deleted is the head node
                head = currentNode->getNext();
            }
            else {
            // The node to be deleted is in the middle of the list
            previousNode->setNext(currentNode->getNext());
            }

        delete currentNode;
        return true;
        }

        // Update the previous node and move to the next node
        previousNode = currentNode;
        currentNode = currentNode->getNext();
    }

    // The account was not found in the list
    return false;
}

The problem is that head inside the deleteAcc(name) function is outside of the scope so is it even possible to answer this question with just a single argument string inside the bool deleteAccount(string name)????
Please help. Thanks
I have tried many times to find how to solve this problem like declaring head at the top of the file before int main() like this:
Node* head = NULL;

int main(){
    // functions and variables here
}

but it does not produce the desired result of showing an output.
Comment: Why do you define `head` as a global variable? What does `currentNode->getData()` return, and is it printable?
Comment: @trincot, because the compiler keeps complaining that head was our of scope when I used my function bool deleteAcc(const string name1) which is defined outside of the int main(). so that is why I defined it as a global variable. but I think that is why it does not produce an output. currentNode->getData() return (name, balance) as stored in Account object and yes it is printable.
Answer: In most cases, in addition to having a Node class/struct, you'd also have another class/struct to represent the doubly linked list, and that class would  hold the head node, as well as any other functions relevant to the list. See this example:
class Dllist {
    private:
        Node *head;
        int size;
    public:
        bool insertAcc(const string &name1);
        bool deleteAcc(const string &name1);
        Node *findAcc(const string &name1);
        // ...
};

Then, your deleteAcc function (as well as any other function defined as part of Dllist) would have access to head.
As you've written the code now, I'm inferring from this comment that you've set up the list entirely within main: // other functions and variables written here. If that's the case, then the only way that you'd have access to head without adding an additional parameter to the deleteAcc function would be to make head a global variable, which I'd strongly discourage.
On another node, your title has the phrase "doubly linked list", but it looks like your deleteAcc function is only modifying the forward link (i.e. calling ->setNext. For the list to maintain its status as a doubly linked list, you need to make sure that both the forward and backwards links are set appropriately.
Update: I'm responding to your comment here because the formatting is better:

@fireshawdow52, I have edited my code and put all of my code in my post. Also, it is a doubly linked list but the previous question before this, tell us to reverse order the printout of the list so I came to that conclusion that tail will not be needed anymore because it is causing compilation error.

Your tail member is absolutely needed for the structure to be doubly linked. However, newNode->setPrevious(head) won't work, as that'll result in both getNext() and getPrevious() returning the same Node. You'll want head->setPrevious(newNode) after the call to newNode->setNext(head). The reason has to do with how you're constructing your list.
Consider that we want to add three Accounts, and they'll be named "Account 1", "Account 2", and "Account 3". Here is how your list will look after the addition of each account.
After adding Account 1
     head
      |
      v
|           |
| Account 1 |
|           |

After adding Account 2
     head
      |
      v
|           |      |           |
| Account 2 | ---> | Account 1 |
|           |      |           |

After adding Account 3
     head
      |
      v
|           |      |           |      |           |
| Account 3 | ---> | Account 2 | ---> | Account 1 |
|           |      |           |      |           |

Given the above, if you uncomment the line newNode->setPrevious(head), then your final list will look like this, with each node having two pointers pointing to the same node, which is not how a doubly linked list should be set up:
     head ____________     ____________________
      |   |           |    |                  |
      v   |           v    |                  v
|         | |      |       |   |      |           |
| Account 3 | ---> | Account 2 | ---> | Account 1 |
|           |      |           |      |           |

With head->setPrevious(newNode), then you ultimately get:
     head
      |
      v
|           |      |           |      |           |
| Account 3 | ---> | Account 2 | ---> | Account 1 |
|           | <--- |           | <--- |           |

This is because, for instance, when you set the next pointer for "Account 2", head is still "Account 1", and adding a previous pointer to that node is the inverse of newNode->setNext(head).
Comment: @fireshawdow52, I have edited my code and put all of my code in my post. Also, it is a doubly linked list but the previous question before this, tell us to reverse order the printout of the list so I came to that conclusion that tail will not be needed anymore because it is causing compilation error.


Python: Is it safe to run a single python script by multiple interpreters?

Question: I have a long-running python script script.py.
Will it cause any issues if I invoke that script one-after the another through terminal:
python script.py  -----first invocation
python script.py  -----second invocation before the first gets over.
Since python is a interpreted language, will there be any interference between these two scripts?
Or is it safer to make a copy of the script and then run it?
Comment: I think this is too broad to answer without you showing us what is in `script.py` I would vote to close this personally.
Comment: The two answers on this question have quite aptly resolved my query. So I believe this is not a very broad question. I would vote to keep this open personally.
Comment: I'm glad you got an answer. It is a very broad question still though.
Answer: There is no danger from the source code; each invocation will read the file separately, allocate its own local variables, etc.  However, there may be interference if the script uses any external references, such as writing to a common file.
Comment: Thanks for your answer. Both yours and Dan Farrell's answer basically say the same thing.  But since the other answer is more verbose, I've marked it as accepted.
Thanks again!
Answer: That depends entirely on what the script does.
In the simplest sense, the answer is no - though the two invocations run the same code, they don't inherently share any state and they can run side by side.  Just like any program on your computer, ( for example, bash shell in separate terminals ), independent invocations have their own process space.
The only case your scripts might interfere with each other is if they both use shared resources.  For example, if script.py created a file called /tmp/state.py then obviously the two invocations would conflict.


PySpark and delta tables merge is not supported temporarily

Question: I get this error in PySpark when I try to sql merge a delta table:
py4j.protocol.Py4JJavaError: An error occurred while calling o64.sql.
: java.lang.UnsupportedOperationException: MERGE INTO TABLE is not supported temporarily.
        at org.apache.spark.sql.errors.QueryExecutionErrors$.ddlUnsupportedTemporarilyError(QueryExecutionErrors.scala:744)
        at org.apache.spark.sql.execution.SparkStrategies$BasicOperators$.apply(SparkStrategies.scala:875)
        at org.apache.spark.sql.catalyst.planning.QueryPlanner.$anonfun$plan$1(QueryPlanner.scala:63)
        at scala.collection.Iterator$$anon$11.nextCur(Iterator.scala:486)
        at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:492)
        at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:491)
        at org.apache.spark.sql.catalyst.planning.QueryPlanner.plan(QueryPlanner.scala:93)
        at org.apache.spark.sql.execution.SparkStrategies.plan(SparkStrategies.scala:71)
        at org.apache.spark.sql.catalyst.planning.QueryPlanner.$anonfun$plan$3(QueryPlanner.scala:78)
        at scala.collection.TraversableOnce$folder$1.apply(TraversableOnce.scala:196)
        at scala.collection.TraversableOnce$folder$1.apply(TraversableOnce.scala:194)
        at scala.collection.Iterator.foreach(Iterator.scala:943)
        at scala.collection.Iterator.foreach$(Iterator.scala:943)
        at scala.collection.AbstractIterator.foreach(Iterator.scala:1431)
        at scala.collection.TraversableOnce.foldLeft(TraversableOnce.scala:199)
        at scala.collection.TraversableOnce.foldLeft$(TraversableOnce.scala:192)
        at scala.collection.AbstractIterator.foldLeft(Iterator.scala:1431)
        at org.apache.spark.sql.catalyst.planning.QueryPlanner.$anonfun$plan$2(QueryPlanner.scala:75)
        at scala.collection.Iterator$$anon$11.nextCur(Iterator.scala:486)
        at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:492)
        at org.apache.spark.sql.catalyst.planning.QueryPlanner.plan(QueryPlanner.scala:93)
        at org.apache.spark.sql.execution.SparkStrategies.plan(SparkStrategies.scala:71)
        at org.apache.spark.sql.execution.QueryExecution$.createSparkPlan(QueryExecution.scala:504)
        at org.apache.spark.sql.execution.QueryExecution.$anonfun$sparkPlan$2(QueryExecution.scala:165)
        at org.apache.spark.sql.catalyst.QueryPlanningTracker.measurePhase(QueryPlanningTracker.scala:192)
        at org.apache.spark.sql.execution.QueryExecution.$anonfun$executePhase$1(QueryExecution.scala:224)
        at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:775)
        at org.apache.spark.sql.execution.QueryExecution.executePhase(QueryExecution.scala:224)
        at org.apache.spark.sql.execution.QueryExecution.$anonfun$sparkPlan$1(QueryExecution.scala:165)
        at org.apache.spark.sql.execution.QueryExecution.withCteMap(QueryExecution.scala:75)
        at org.apache.spark.sql.execution.QueryExecution.sparkPlan$lzycompute(QueryExecution.scala:158)
        at org.apache.spark.sql.execution.QueryExecution.sparkPlan(QueryExecution.scala:158)
        at org.apache.spark.sql.execution.QueryExecution.$anonfun$executedPlan$2(QueryExecution.scala:178)
        at org.apache.spark.sql.catalyst.QueryPlanningTracker.measurePhase(QueryPlanningTracker.scala:192)
        at org.apache.spark.sql.execution.QueryExecution.$anonfun$executePhase$1(QueryExecution.scala:224)
        at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:775)
        at org.apache.spark.sql.execution.QueryExecution.executePhase(QueryExecution.scala:224)
        at org.apache.spark.sql.execution.QueryExecution.$anonfun$executedPlan$1(QueryExecution.scala:175)
        at org.apache.spark.sql.execution.QueryExecution.withCteMap(QueryExecution.scala:75)
        at org.apache.spark.sql.execution.QueryExecution.executedPlan$lzycompute(QueryExecution.scala:171)
        at org.apache.spark.sql.execution.QueryExecution.executedPlan(QueryExecution.scala:171)
        at org.apache.spark.sql.execution.QueryExecution.$anonfun$writePlans$5(QueryExecution.scala:308)
        at org.apache.spark.sql.catalyst.plans.QueryPlan$.append(QueryPlan.scala:606)
        at org.apache.spark.sql.execution.QueryExecution.writePlans(QueryExecution.scala:308)
        at org.apache.spark.sql.execution.QueryExecution.toString(QueryExecution.scala:323)
        at org.apache.spark.sql.execution.QueryExecution.org$apache$spark$sql$execution$QueryExecution$$explainString(QueryExecution.scala:277)
        at org.apache.spark.sql.execution.QueryExecution.explainString(QueryExecution.scala:256)
        at org.apache.spark.sql.execution.SQLExecution$.executeQuery$1(SQLExecution.scala:102)
        at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$6(SQLExecution.scala:135)
        at org.apache.spark.sql.catalyst.QueryPlanningTracker$.withTracker(QueryPlanningTracker.scala:107)
        at org.apache.spark.sql.execution.SQLExecution$.withTracker(SQLExecution.scala:232)
        at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$5(SQLExecution.scala:135)
        at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:253)
        at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:134)
        at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:775)
        at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:68)
        at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.applyOrElse(QueryExecution.scala:112)
        at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.applyOrElse(QueryExecution.scala:108)
        at org.apache.spark.sql.catalyst.trees.TreeNode.$anonfun$transformDownWithPruning$1(TreeNode.scala:519)
        at org.apache.spark.sql.catalyst.trees.CurrentOrigin$.withOrigin(TreeNode.scala:83)
        at org.apache.spark.sql.catalyst.trees.TreeNode.transformDownWithPruning(TreeNode.scala:519)
        at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.org$apache$spark$sql$catalyst$plans$logical$AnalysisHelper$$super$transformDownWithPruning(LogicalPlan.scala:30)
        at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.transformDownWithPruning(AnalysisHelper.scala:267)
        at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.transformDownWithPruning$(AnalysisHelper.scala:263)
        at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.transformDownWithPruning(LogicalPlan.scala:30)
        at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.transformDownWithPruning(LogicalPlan.scala:30)
        at org.apache.spark.sql.catalyst.trees.TreeNode.transformDown(TreeNode.scala:495)
        at org.apache.spark.sql.execution.QueryExecution.eagerlyExecuteCommands(QueryExecution.scala:108)
        at org.apache.spark.sql.execution.QueryExecution.commandExecuted$lzycompute(QueryExecution.scala:95)
        at org.apache.spark.sql.execution.QueryExecution.commandExecuted(QueryExecution.scala:93)
        at org.apache.spark.sql.Dataset.<init>(Dataset.scala:221)
        at org.apache.spark.sql.Dataset$.$anonfun$ofRows$2(Dataset.scala:101)
        at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:775)
        at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:98)
        at org.apache.spark.sql.SparkSession.$anonfun$sql$1(SparkSession.scala:618)
        at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:775)
        at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:613)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:282)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
        at py4j.ClientServerConnection.run(ClientServerConnection.java:106)
        at java.lang.Thread.run(Thread.java:750)

Here is the sql merge query:

merge into re_obu_logistic_status_cockpit_report
        using (
                select *
                from   re_data_to_merge
              ) info_to_merge
        on    (
                re_obu_logistic_status_cockpit_report.date = info_to_merge.date
                and re_obu_logistic_status_cockpit_report.status_id = info_to_merge.status_id
                and re_obu_logistic_status_cockpit_report.materialnumber = info_to_merge.materialnumber
                and re_obu_logistic_status_cockpit_report.sales_partner_id = info_to_merge.sales_partner_id

              )
        when  matched
          then update set re_obu_logistic_status_cockpit_report.status = info_to_merge.status
                         ,re_obu_logistic_status_cockpit_report.sales_partner_name = info_to_merge.sales_partner_name
                         ,re_obu_logistic_status_cockpit_report.obu_count = info_to_merge.obu_count
                         ,re_obu_logistic_status_cockpit_report.obu_count_pct = info_to_merge.obu_count_pct
                         ,re_obu_logistic_status_cockpit_report.dan_last_changed_tsz = info_to_merge.dan_last_changed_tsz
                         ,re_obu_logistic_status_cockpit_report.dan_last_changed_epoch = info_to_merge.dan_last_changed_epoch

        when  not matched
          then insert (
                        re_obu_logistic_status_cockpit_report.date
                       ,re_obu_logistic_status_cockpit_report.status_id
                       ,re_obu_logistic_status_cockpit_report.status
                       ,re_obu_logistic_status_cockpit_report.materialnumber
                       ,re_obu_logistic_status_cockpit_report.sales_partner_id
                       ,re_obu_logistic_status_cockpit_report.sales_partner_name
                       ,re_obu_logistic_status_cockpit_report.obu_count
                       ,re_obu_logistic_status_cockpit_report.obu_count_pct
                       ,re_obu_logistic_status_cockpit_report.dan_last_changed_tsz
                       ,re_obu_logistic_status_cockpit_report.dan_last_changed_epoch

                      )
          values      (
                        info_to_merge.date
                       ,info_to_merge.status_id
                       ,info_to_merge.status
                       ,info_to_merge.materialnumber
                       ,info_to_merge.sales_partner_id
                       ,info_to_merge.sales_partner_name
                       ,info_to_merge.obu_count
                       ,info_to_merge.obu_count_pct
                       ,info_to_merge.dan_last_changed_tsz
                       ,info_to_merge.dan_last_changed_epoch

                      )

I restarted a new EMR cluster, removed the delta tables from S3, then I relaunched the python application. I also restarted the EC2 instance asking the EMR cluster to run the application.
Answer: This was due to wrong " character in the spark-submit command:
The wrong spark-submit was:
spark-submit \
  --master yarn \
  --driver-memory 8g \
  --executor-memory 8g \
  --executor-cores 8 \
  --packages io.delta:delta-core_2.12:2.0.0 \
  --conf "spark.sql.extensions=io.delta.sql.DeltaSparkSessionExtension" \
  --conf "spark.sql.catalog.spark_catalog=org.apache.spark.sql.delta.catalog.DeltaCatalog" \
  --conf "spark.sql.legacy.parquet.datetimeRebaseModeInRead=CORRECTED" \
  --conf "spark.sql.legacy.parquet.int96RebaseModeInWrite=CORRECTED" \
  --conf "spark.sql.legacy.timeParserPolicy=LEGACY" \
  --conf spark.rpc.askTimeout=600s \
  main.py

The correct spark-submit is:
spark-submit \
  --master yarn \
  --driver-memory 8g \
  --executor-memory 8g \
  --executor-cores 8 \
  --packages io.delta:delta-core_2.12:2.0.0 \
  --conf "spark.sql.extensions=io.delta.sql.DeltaSparkSessionExtension" \
  --conf "spark.sql.catalog.spark_catalog=org.apache.spark.sql.delta.catalog.DeltaCatalog" \
  --conf "spark.sql.legacy.parquet.datetimeRebaseModeInRead=CORRECTED" \
  --conf "spark.sql.legacy.parquet.int96RebaseModeInWrite=CORRECTED" \
  --conf "spark.sql.legacy.timeParserPolicy=LEGACY" \
  --conf spark.rpc.askTimeout=600s \
  main.py


Converting UIImage into const char*?

Question: I need to convert a UIImage into const char * because I am using protobuffer from google and structure of message accepts this type of parameter. I started with parsing the image into NSData:
UIImage *image = [UIImage imageNamed:@"sign_up_button"];
NSData *imageData =  UIImagePNGRepresentation(image);
const char *test = (const char*)[bytesString bytes];

But when I print the result this is what i get:\xff\xd8\xff\xe0 what is wrong because the result must be a long string with encoded characters.
Comment: You see the escaped characters because they fall outside of the printable character range. The string `test` contains the PNG representation of the image in binary form.
Comment: If you need a 0-terminated string of printable characters, you can base64-encode your data
Comment: @AminNegm-Awad No offense taken
Comment: @user1781290 How can use base64-encode I know this return `NSString`, from this to make another convert into const char*?
Comment: @user1781290 I do not think that he can choose the format.
Comment: @AminNegm-Awad Maybe I do not know protobuffer, it was only a suggestion. geonl Look into NSData if you want to use base64 encodings
Comment: This was no critic to your suggestion. I just wanted to say that this will not solve the whole problem.
Answer: "Printing" char* aborts, when \0 is reached. This is a possible content of image data. You cannot "print" it. You cannot handle the data as a C-string at all, because C-strings are 0-terminated. Do not use any function that expects a C-string. It will fail.
Store a length instead and handle it as "byte data".
Comment: Or he can use `– initWithBytes:length:encoding:` et al., because they take a length parameter. (`NSString` stores the raw data *not* 0-terminated but length-based.)
Comment: True, though he can print each char in a `for` loop since he knows the length of the array. For debugging purposes i mean.
Comment: ok, I understand now, it's more clear. I start to make debug because the image what arrived on the server is corrupted and can't be opened.
Comment: You should really pass the "string" (it's a byte array) as raw as possible. For debugging purpose follow user1781290's hint.
Comment: @AminNegm-Awad I tried with `– initWithBytes:length:encoding:` but the result was nil, this was a big mystery for me.
Comment: `NSString *stringBytes =[[NSString alloc] initWithBytes:imageData.bytes length:imageData.length encoding:NSASCIIStringEncoding];
    const char *test = [stringBytes UTF8String];`
Comment: NSASCIIStringEncoding is a problem, because the data will contain bytes outside ASCII (which is 7 bit only).
Comment: @AminNegm-Awad Ok, for me this thinks are a little stranger. I tested also `NSUTF8StringEncoding` but still the result is `nill`. Do you have any idea?
Comment: Ah, I see the problem. Not every byte combination is valid UTF8. Try to use user1781290's suggestion for debugging (base64 encoding).
Comment: ok, I will make a shot with this, but I don't put to many hopes in this bullet (debugging).Thanks

Converting UIImage into const char*?


display dropdown value select options using React Hooks

Question: I am trying to get the startVisit value from a dropdown select using useEffect in React Hooks.
But I don't want to show select startVisit value in endVisit dropdown.
How can i handle it?  how can i do?
Code:
  const [endVisitOptions, setEndVisitOptions] = useState(!startVisit);

  useEffect(() => {
    console.log("1",startVisit);
    console.log("2",visits);

    for(let x in startVisit)
    {
      console.log(startVisit[x]);
    }

//your code logic here

    setEndVisitOptions(endVisitOptions);
  }, [startVisit]);

                <Dropdown
                    __key="visitId"
                    __value="title"
                    clearable={false}
                    label="Start Visit"
                    onChange={handleRecurringFormChange}
                    options={visits}
                    property="startVisit"
                    value={startVisit}
                  />

                  <Dropdown
                    __key="visitId"
                    __value="title"
                    clearable={false}
                    label="End Visit"
                    onChange={handleRecurringFormChange}
                    options={endVisitOptions}
                    property="endVisit"
                    value={endVisit}
                  />

Output data:

Dropdown UI data:
Comment: can you paste the full code on how you are passing the options to the end visit ? Is it maintained in state ?
Comment: yes code is mention @Shyam
Comment: are you making an api call to get the `endVisitOptions` ?
Comment: https://drive.google.com/file/d/1UKGq0H1N5VONHGzXglY0-M0BfdcHqtIH/view?usp=sharing you can check this file @Shyam
Comment: `endVisitOptions ` is usestate where i save `endVisit` value which display only endVisit.. @Shyam
Comment: i am confused here . how you are getting the drop down values to the select . I mean the list of options for the select . Also what is the initial start and end visit options . Its difficult to help without seeing the full code .
Comment: can you do it dummy data value `startVisit` and `endVisit` as shown output data. @Shyam
Answer: you may want to filter the visits to not contain the startVisit before calling setEndVisitOptions.
if (startVisit) {
  const filteredData = visits.filter(v => v.visitId !== startVisit.visitId);
  setEndVisitOptions(filteredData)
}

Comment: It is possible just only show the `forward` value of `startVisit` in dropdown @Abhay have you get my point? I don't want to display the old value like `a` `b` `c` if select `b` just show the `b` `c` in dropdown.
Comment: It would be possible to show only the 'forward' value. If the array is sorted then you can find the index of currently selected value with indexOf or findIndex and slice the array from that index, refer array.prototype.slice in MDN.
BTW, could you please consider accepting the answer if it's fine? Thanks.
Comment: yes can i you add the `'forward'` value. code.. it will be highly appreciated @Abhay
Comment: First you can get the index -
const currValIndex = visits.findIndex(v => v.visitId !== startVisit.visitId);
and then slice the array with that index
const forwardValues = visits.slice(currValIndex);
then set that as end visits
setEndVisitOptions(forwardValues);


Method of finding inverse of a Matrix using minimal polynomials

Question: Using a piece from my last question I want to show how to find $A^{-1}$ as a polynomial expression in $A$ of degree < $\deg m_A$ where the leading coefficient of the polynomial is $\dfrac{-1}{m_A(0)}$ where $m_A$ is the minimal polynomial of $A$.
Comment: if $f(x)$ is the minimal polynomial and $A$ is the matrix, what is $f(A)?$
Comment: $f(A) = 0$ correct? I am looking at a theorem in my book.
Comment: Yes. It is the lowest degree polynomial that does that. And it appears that you are calling the coefficient of $I$ in the minimal polynomial $m_A(0).$ Write it out, solve for $I,$ and see what happens.
Answer: If $m_A(x)=x^m+a_{m-1}x^{m-1}+\cdots+a_1x+a_0$ then since $m_A(A)=0$ implies
\begin{align*}
&A^m+a_{m-1}A^{m-1}+\cdots+a_1A+a_0I=0\\
&\implies a_0I=-(A^m+a_{m-1}A^{m-1}+\cdots+a_1A)\\
&\implies a_0I=A(-A^{m-1}-a_{m-1}A^{m-2}-\cdots-a_1)\\
&\implies I=A\left(-\dfrac{1}{a_0}A^{m-1}-\dfrac{a_{m-1}}{a_0}A^{m-2}-\cdots-\dfrac{a_1}{a_0}\right)\\
&\implies A^{-1}=-\dfrac{1}{a_0}A^{m-1}-\dfrac{a_{m-1}}{a_0}A^{m-2}-\cdots-\dfrac{a_1}{a_0}
\end{align*}


Can two profile types be created with one role?

Question: I have created two profile types Self Employee and Salaried Employee for the role Employee.
I want to present these profile forms inside the user account edit form. For that, I'm using the Account Profile module. However, it's only showing the Self employee form.
Is it possible to show multiple profiles for role?
Comment: https://www.drupal.org/project/account_profile
Comment: So what is the question? You're not clearly stated the problem.
Comment: The question is can two profile types be created with one role drupal 7
Answer: Yes, with Account Profile, multiple profiles can be embedded for given role. In order to make this happen, you need to:

Make sure both profile types have the Show this profile as part of user account form. checked on profile settings page (i.e. the edit links in /admin/structure/profiles).
Make sure the role in question has both the Edit own profile & View own profile permissions set for each profile type.


Find infimum of the set $A=\left \{ \frac{1}{n+1}, n \in \mathbb{N} \right \}$.

Question: Find infimum of the set $A=\left \{ \frac{1}{n+1}, n \in \mathbb{N} \right \}$.
I know that this is a basic exercise in Analysis.
I want to show that $infA=0$.
For any $n\in \mathbb{N}:\frac{1}{n+1}>0,$ so $0$ is an lower bound of $A$.
Let's say that there is a lower bound $L$ of $A$ such that $L>0$.
From Archimedean property there is $n_{o}\in \mathbb{N}$ such that $\frac{1}{n_{o}}<L$
So I found an element of $A$ lower than the lower bound $L$ (Proof by contradiction)
My question is: Can I use $\frac{1}{n_{o}}$ as an element of $A$ or should I write an element in the form $\frac{1}{n+1}$?
Moreover, $0$ is not min, right?
Comment: 1. You are correct in stating that $\frac{1}{n_0}$ is within $A$ since you can simply write $n_0 = m + 1$ for some $m \in \mathbb{N}$.
2. You are correct in stating that $0$ is not a minimum of $A$ since it cannot be attained by an element in $A$
Comment: You can write $\frac{1}{n_0}$ as $\frac{1}{n_1 + 1}$ for $n_1 = n_0 - 1$, which is still a natural number. And yes,  there is no minimum of this set.
Answer: Since $\frac1{n+1}<\frac1n$ and $\frac1{n+1}\in A$, you're done.
And indeed $0$ is not $\min A$, since $0\notin A$.


What is _once's true meaning in file manipulation?

Question: I have a doubt that makes me very confused, it's about require_once. I saw a question on StackOverflow about it but I'm still not sure I understand...
I know the difference between require and include is that using require, the script will issue a fatal error and stop execution, while include does not. But there is something that I have been asking myself, the true meaning of _once, most people say something like: PHP will check if the file has already been included, and if so, not include (require) it again. How will the script be required only once? I don't understand this, because in my point of view PHP scripts are not like CSS that our browser downloads and is saved on the machine, so then not needing to download again, I think that every time a PHP script is executed, it will do its job again, there is no way to understand that it has already been required just as browsers understand that we have already downloaded CSS files.
What is the real meaning of _once? And could someone please give me an example, because I don't really understand it, I'm a beginner, I don't even know if I'm asking a proper question
If possible demonstrate some code so that I finally understand
Answer: Imagine this scenario.  It's nice to be able to include the same file as you can use it multiple times with different outcomes:
display.php
echo $var;

index.php
$var = 'Hello ';
include('display.php');

$var = 'World ';
include('display.php');

This outputs:

Hello
World

However, sometimes this will cause problems.  This could be an include in different files, so you need to include_once, but to illustrate:
functions.php
function display($var) { echo $var; }

index.php
include('functions.php');
display('Hello ');

  //more code

include('functions.php');
display('World ');

Generates a fatal error:

Fatal error: Cannot redeclare display() (previously declared in index.php:1) in index.php on line 6

So if you have hundreds of files and some include others depending on some logic/program flow but some files can only be included once (as seen above) then that is the use case.


Let $A,B\subseteq \mathbb{R}$ such that $\forall b\in B ~ \exists a_n$ where $a_n \in A$ and $a_n\to b$ as $n\to\infty$. Prove $\sup(B)\leq \sup(A)$

Question:
Question: Let A and B be two non-emty bounded sub-sets of $\mathbb{R}$
  with the following proposition: $\forall_{b\in B}\exists_{(a_n)}$.
  $(a_n)$ is made up of elements of A such that $a_n\to b$ as
  $n\to\infty$

I don't know what to do with the sequence part.

To be proven: $\sup(B)\leq \sup(A)$.

My attempt:
Suppose $a\in A$ and $b\in B$.
Then $a\leq sup(A)$ and $b\leq sup(B)$
If $b<a$ then $b\leq \sup(B)\leq a\leq \sup(A)$
Suppose $\sup(B)>\sup(A)$.
Then $\exists_{a\in A}$ such that $a>\sup(A)-\frac{\epsilon}{2}$.
And $\exists_{b\in B}$ such that $b>\sup(B)-\frac{\epsilon}{2}$.
But if $\sup(B)>\sup(A)$, then $b>a$. But $b<a$. So contradiction. So $\sup(B)\leq \sup(A)$.
Hope someone will take a look, thanks in advance!
Comment: Hint:  Let $t>\sup A$.  Show that it follows that  $t \geq \sup B $.  Therefore ...
Comment: Take *any* number   $t$ that is larger than $\sup A$.  Then show that  $t\geq\sup B$.  This is a standard way to prove an inequality.   Suppose  I want to show that $X\leq Y $.  I  can  do this by showing that $X$ is less than any number  larger  than  $Y$.
Comment: You have successfully proved [in the post you deleted] that if $t$ is any number larger than $\sup A$ it is true that $\sup B \leq t$.  Therefore  $\sup B \leq \sup A$.  QED.  [Tidy the exposition a bit.  "Suppose that $b$ is an arbitrary element of $B$.  Then there is a sequence $a_n\to b$ of elements of $A$.  Since each $a_n\sup A$, then how can $\sup B \leq t$ lead to $\sup B \leq \sup A$ if $t$ is never equal to $\sup A$?
Comment: This needs to be obvious to you, so work on it.  It is so frequently used in analysis that any time spent now will be well worth it.  Consider it this way:  I am thinking of a number, say $x$.  About that number I can promise you only this fact.  If you choose *any* number $t$ that is strictly larger than $10$ then I promise you that $x<t$.  No other information.  Can you tell me anything at all about my number $x$?  [Note the *any* number--you are forgetting that in your confusion here.]
Comment: Then I will definitely spend some time on that!! It's just that notices that there is a possibility that $t=\sup B$ (because $\sup B\leq t$), so then $\sup A<\sup B$. So then it would be more logic, to me, to say that $\sup A\leq\sup B$. But I think that I shouldn't think that way, as $\sup B \leq t$ doesn't necessarily imply that it has to be equal at some point. But so if $x\leq t$ and $y<t$, then $x\leq y$?
Comment: Would you like to check another proof of mine maybe? http://math.stackexchange.com/questions/1598667/real-analysis-supremum-proof
And thank you for your help!
Comment: You are trying to deduce something from *one* value of $t$.  What you need to think about is that you have infinitely many $t$ available, especially those values of $t$ that are only a small bit larger than $\sup A$.
Comment: I will keep that in mind! How did you even come up with the idea? Do you have some good literature on real-analysis?
Comment: Good perhaps?  Free though:  http://classicalrealanalysis.info/documents/TBB-AllChapters-Landscape.pdf
Comment: Thanks, will definitely check it out.
Answer: The sequence part tells you that every point of $B$ is an adherent point of $A$. Thus $B\subset \overline{A}$. where $\overline A$ stands for the closure
of $A$ in $\mathbb R$, i.e. the smallest closed subset of $\mathbb R$ containing $A$.
$B\subset \overline A\Rightarrow \overline B\subset \overline{\overline A}$
 but $\overline{\overline A}=\overline {A}$. Hence,
$\overline B\subset \overline A$
And,
$\overline B\subset \overline A\Rightarrow \sup(B)\leq \sup(A)$.
since:
(1) $\sup(X)$ is an increasing function of subset $X\subset E$ of an ordered set $E$.
$\overline B\subset \overline A\Rightarrow \sup(\overline B)\leq \sup(\overline A)$.
(2) $\overline A$ is closed and bounded (since $A$ is bounded)  (then compact) having $\sup(\overline A)=\max(\overline A)=\sup(A)$, idem for $\overline B$.
Comment: A minor misstatement:  "The sequence part tells you that every point of $B$ is *either also in $A$ or else* an accumulation point of $A$."
Comment: If $B$ and $A$ contain exactly one point I don't think I would be inclined to talk about "accumulation points."  Maybe your text does.  Me, I would edit your statement that "An accumulation point of $A$ is the limit of a convergent sequence" to read instead "An accumulation point of $A$ is the limit of a convergent sequence *of distinct points* of $A$".
Comment: Due to the ambiguous status of the notion of accumulation point, I will replace it for what it was meant here: an adherent point of set $A$. Explictely: a point $x\in \mathbb R$ such that every open set containing $x$ intersects $A$. Every point of $A$ is adherent to $A$, i.e. $A\subset \overline A$. If $A$ is $\{a\}$ its closure (or adherence) = $\overline A=\{a\}$. Consider the stationary sequence $a_n=a\ \forall n\in \mathbb N$. Thanks for comments.
Comment: The Source Of All Supreme Knowledge (i..e., Wiki) agrees with your switch to using "adherent point" in place of "accumulation point."    Defy the Wiki Gods at your peril.
Answer: I'm afraid your proof is not right. You need to use the assumption given in the problem. Let's have a look at your proof. You write:

Suppose $a∈A$ and $b∈B$.
Then $a≤\sup(A)$ and $b≤\sup(B)$
If $b<a$ then $b≤\sup(B)≤a≤\sup(A)$

Your conclusion that $b\leq a$ doesn't follow from what you write. You only have that $b<a$, and $b\leq\sup(B)$, which does not imply $\sup(B)\leq a$.
You write:

Suppose sup(B)>sup(A).
Then ∃a∈A such that $a>\sup(A)−\frac ϵ2$.
And ∃b∈B such that $b>\sup(B)−\frac ϵ2$.
But if sup(B)>sup(A), then $b>a$. But $b<a$. So
contradiction.

I don't know how you obtained a contradiction here. You conclude that $b>a$, but that this contradicts $b<a$, which seem to come out of nowhere.
I would do it as follows: Let $x = \sup(B)$, and let $\epsilon>0$. Take $b\in B$, such that $b > x-\frac\epsilon 2$, and let $(a_n)$ be a sequence of elements from $A$, such that $a_n\to b$. Then the sequence $a_n$ comes within $\frac\epsilon 2$ of $b$ from some point on, meaning that it comes within $\epsilon$ of $x$ from some point on. Use this to argue that $\sup(A)\geq x$.
Comment: @DeLorean it is because the sequence $a_n$ converges to $b$. When a sequence converges to a number, than sequence becomes arbitrarily close to that number. In particular, the sequence is within a distance of $\frac\epsilon 2$ from $b$ from some point and onwards, i.e. there exists an $N$, such that for all $n\geq N$, we have $|a_n-b|<\frac\epsilon 2$.
Comment: I don't think i got it, why does the sequence $a_n$ come within $\frac{\epsilon}{2}$ of b from some point on?
Answer: Its very simple:
Assume that $\beta:=\sup B>\sup A=:\alpha$. Then $\mu:={\alpha+\beta\over2}$ satisfies $\beta>\mu>\alpha$. By definition of $\beta$ there is a $b\in B$ with $b>\mu$, and by the special assumption in the question there is an $a\in A$ with $a>\mu$ as well – contradicting the definition of $\alpha$.


How to add javascript to theme_preprocess_user_login

Question: I have working code in my theme's template.php file that adds "autofocus" to my modal login form, but Firefox ignores ajax autofocus fields (only applies autofocus on pageload). So I'm trying to add some js to set focus when the modal login form is called. I currently add autofocus via:
function mytheme_preprocess_user_login(&$variables) {
  $variables['form']['name']['#attributes']['autofocus'] = array('autofocus');
  $variables['rendered'] = drupal_render_children($variables['form']);
}

And I'm trying to add js to set focus as a fallback this way:
function mytheme_preprocess_user_login(&$variables) {
  $variables['form']['name']['#attributes']['autofocus'] = array('autofocus');
  $variables['form']['#attached'][js][] = path_to_theme() . "/js/focus.js";
  $variables['rendered'] = drupal_render_children($variables['form']);
}

but this doesn't seem to add the js as expected. How can I add either inline or external javascript to my modal login form?
Answer: A preferred solution I would use for adding/editing forms would be to use a module hook.
function MODULE_form_user_login_alter(&$form, &$form_state, $form_id) {

  $form['#attached']['js'] = array(
    drupal_get_path('theme', 'THEME') . '/js/focus.js',
    '/* inline js here */' => array( 'type' => 'inline')
  );
}

Answer: I couldn't get any of the dynamic insertion of javascript to work at all, so I ended up adding the following to my site-wide javascript file:
$(document).delegate(
  'form#user-login',
  'DOMNodeInserted',
  function(){ $('input#edit-name').focus();
});

This is, of course, wrapped in the proper (function ($) { Drupal.behaviors.mytheme = { ... namespacing, etc.
Answer: Use the standard drupal_add_js https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7
drupal_add_js(drupal_get_path('theme', 'THEME') .'/js/focus.js', 'file');
drupal_add_js('(function ($) { ... })(jQuery);', array('type' => 'inline', 'group' => JS_THEME));

Comment: This does not seem to actually attach any javascript via preprocess hook.
Comment: To be fair I wasn't too sure myself.  I tried it too and I couldn't get it to work.


What is the statistical steady state of this poisson process?

Question:
Suppose there is an island with some amount of people. The arrival of new people on the island follows a Poisson process with rate parameter $\lambda$. Suppose further that the time until a person departs the island is exponential with rate constant $\mu$. Assume all arrival and departure times are independent. An event is the arrival of a new person or departure of an existing person.
a) Suppose there are $n$ people on the island at time $t$. What is the probability distribution of time until the next event?
b) What is the probability that the next event is a departure?
c) Assume a statistical steady state exists. What is the expected number of people  in this steady state?

Attempt
Assuming my attempt on a) and b) is correct, I would like to understand better how to approach c).
For a), let $T$ be the time until the next event. Then
$$ P(T<s) = 1 - e^{-s(\lambda + \mu n)}$$
so the density is given by
$$ (\lambda + \mu n)e^{-s(\lambda + \mu n)}.$$
Hence $T$ is exponential with rate constant $(\lambda + \mu n)$.
For b), I discretized time and examined
$$ P( T = k \, \Delta s \cap N_{t+k\,\Delta s} = N_t ) $$
where $N_{t+k\,\Delta s} = N_t$ is the number of new people in time $k \,\Delta s$. This leads to
$$ P( \text{Next event is a departure} ) =
\frac{\lambda + \mu n }{ 2\lambda + \mu n}.$$
Which seems to make sense, since for large $n$, the probability that the next event is a departure is large.
Now, for part c), I'm not sure how to marry the two concepts above to arrive at a formula for the statistical steady state. I expect I need to arrive a formula for a time $t$ and take $t \to \infty$. If my solutions for a) and b) are right, is there a logical way to use them to produce the answer for c)?
Comment: You have two Poisson processes with rates $\lambda$ and $n\mu$ added together. The chances that the next event is departure is $\frac {n\mu}{n\mu +\lambda}$. For steady state, write down equation that signify zero change of probability density at every point.
Comment: Steady state is $Pois(\frac \lambda\mu)$, so average number of people is $\frac\lambda\mu$
Comment: Distribution-free argument: Rate of change of $n$ people is $\lambda-n\mu$.. In steady state, expected rate of change must be zero - hence $n=\lambda/\mu$.
Comment: @A.S. I'd like to understand both your approaches. How do you arrive at a rate of change of $n$ people of $\lambda - n \mu$? On your first comment, what is the equation that signifies zero change of probability density? If this is the density of the number of people on the island, how do you find that density from the given processes?
Comment: When population is $n$, people arrive at rate $\lambda$ and leave at rate $n\mu$, so total rate of change is $\lambda-n\mu$. In steady stated, expected rate of change is zero, so $\lambda-E(n)\mu=0$. To find steady state distribution, write down balance equation (which is detailed balance in this case): $\pi_iP_{i,i+1}=\pi_{i+1}P_{i+1,i}$ to immediately get Poisson relation for $\frac {\pi_{n+1}}{\pi_n}$.
Comment: In the above example, $P$'s should be $Q$'s - that is rates of change, not probabilities of steps.
Answer: Let $\{N(t):t\geqslant0\}$ be the number of people on the island at time $t$, and $\{X_m:m=1,2,\ldots\}$ be time of the $m^{\mathrm{th}}$ event.
Since the arrival and departure processes are Markovian, $N(t)$ is a continuous-time Markov chain with embedded Markov chain $X_m$, having transition probabilities
$$
\mathbb P(X_{m+1}=j\mid X_m=i) = \begin{cases}
\frac\lambda{\lambda+i\mu},& j=i+1\\
\frac{i\mu}{\lambda+i\mu},& j=i-1.
\end{cases}
$$
So given $N(t)=n$, it follows that
$$\mathbb P(T>s) = e^{-(\lambda+n\mu)s},\ s>0. $$
Let $q_{ij}$ be the transition rate from state $i$ to state $j$. If a stationary distribution $\pi$ exists, then $\pi$ must satisfy the global balance equations $$\sum_{j\in S\setminus\{i\}}\pi_i q_{ij} = \sum_{j\in S\setminus\{i\}}\pi_j q_{ji} $$
for each $j\in S$ (here the state space is $S=\{0,1,2,\ldots\}$). Since
$$
q_{ij} = \begin{cases}
\lambda,& i=j+1\\
(i+1)\mu,& i=j-1,
\end{cases}
$$
the balance equations are given by
$$\lambda\pi_n = (n+1)\mu \pi_{n+1},\ n\geqslant 0, $$
which yields the recurrence
$$\pi_n =\left(\frac\lambda\mu\right)^n\left(\frac1{n!}\right)\pi_0,\
n\geqslant0. $$
Set $\rho = \frac\lambda\mu$. From $\sum_{n=0}^\infty \pi_n=1$ it follows that
$$\pi_0\sum_{n=0}^\infty\frac{\rho^n}{n!}=1, $$
and hence
$$\pi_n = \frac{e^{-\rho}\rho^n}{n!}. $$
By inspection, $\pi$ is a Poisson distribution with parameter $\rho$, and so $$\lim_{t\to\infty}\mathbb E[N(t)] = \rho. $$
Alternatively, we can compute the stationary distribution directly from the transition rates. For each $i,j\geqslant 0$, define the generator (or transition rate matrix) by
$$
G_{ij} = \begin{cases}
q_{ij},& i\ne j\\
-\sum_{j\ne i}q_{ij},& i=j
\end{cases}
$$
Let $P(t)$ be the matrix with entries $\mathbb P(N(t)=j\mid N(0)=0)$.Then $P$ satisfies the differential equations
\begin{align}
[P'(t)]_{ij}&=[P(t)G]_{ij}, P(0) = \mathsf I,\quad t>0\\
[P'(t)]_{ij}&=[GP(t)]_{ij}, P(0) = \mathsf I,\quad t>0
\end{align}
i.e. the Kolmogorov forward and backward equations. The solution is given by
$$P(t) = e^{tG} = \sum_{n=0}^\infty \frac{(tG)^n}{n!}, $$
and so for any $j\in S$, $$\lim_{t\to\infty}P(t)_{ij} = \pi_j $$ is the stationary distribution of $N(t)$.
Now, to actually compute $\pi$, we use the following result:
$$\pi = \pi P \iff \pi G=0. $$
(This is a good exercise to prove.). Here the generator matrix is given by
$$G_{ij} = \begin{cases}
\lambda,& i=j-1
-(\lambda+i\mu),& i=j
(i+1)\mu,& i=j+1,\end{cases}
$$
so we have
\begin{align}
-\lambda\pi_0 + \mu\pi_1=0&\implies \pi_1 = \rho\pi_0,\\
\lambda\pi_0 - (\lambda+\mu)\pi_1 + 2\mu\pi_2&\implies \pi_2 = \frac{\rho^2}{2!}\pi_0,
\end{align}
and for $n\geqslant 2$, induction yields
$$\pi_n = \frac{\rho^n}{n!}\pi_0. $$
As before,
$$\pi_0\sum_{n=0}^\infty\frac{\rho^n}{n!}=1\implies \pi_0 = e^{-\rho}  $$
and hence
$$\pi_n = \frac{e^{-\rho}\rho^n}{n!}. $$
Comment: how did you arrive at the mass functions as functions of time "i", $\lambda / (\lambda + i \mu)$ and $i \mu / (\lambda + i \mu)$? I don't have this in my answers.
Comment: Also, I'm a little unsure of how you derived the balance equation?
Comment: Those are the transition probabilities in the embedded Markov chain of the CTMC. I'll add some detail in the post about the balance equations.
Comment: Thanks, that would be helpful so that I can review your answer again in more detail.


How do I reference the id of an element I am creating programmatically?

Question: I'm creating a chat app, and I want to list all of the chatrooms listed in the data with a map function. When the user selects a certain room from the list, the main page updates to show the messages for the selected room.
I'm having issues using the created button's id for its onClick event. I've tried using this, this.id, and even the index provided in the map function because the id's are the same as the indexes; however, my setSelectedRoom doesn't seem to like the function.
i should work, but I get the error of 'Too many re-renders'. I'm not entirely sure how to get past this issue. Any ideas?
The map function is necessary so that the page can update when new chatrooms are added, so how do I avoid the 'Too many re-renders' error?
{props.chatData.map((val, i) => {
      return (
           <Button className={`room-${i}`} id={i} onClick={setSelectedRoom(i)}>#{val.name}</Button>
      )
})}

Comment: youre already given the id so use it
Comment: @Joe I can't select the id though. It's undefined
Comment: document.onload or angular.element(document).ready
Answer: I could give you an idea. Try something like this,
{
  props.chatData.map((val, i) => {
    return (
      <Button className={`room-${i}`} id={i} onClick={() => setSelectedRoom(i)}>
        #{val.name}
      </Button>
    );
  });
}

also, I think id is a HTML props and we cannot access it. Try using other names like chatID and you can access it through this.props.chatID.
JSX Expression is executed immediately, so whenever it renders, it calls itself infinite times. That's why wrap it with another function.


There exists a sequence $(y_n) \in \ell_2$ such that $(x_n / y_n) \in \ell_2$ for every $ (x_n) \in \ell_1$?

Question: I'm trying to figure out if there exists a sequence $(y_n) \in \ell_2$ such that $(x_n / y_n) \in \ell_2$ for every $(x_n) \in \ell_1$. There some obvious reductions to this problem: we have to consider $y_n \neq 0$ for every $n \in \mathbb{N}$. Moreover, $(y_n) \notin \ell_1$, because it would imply $(1)_n = (y_n/y_n)_n \in \ell_2.$ I think it is necessary that $(y_n) \notin \ell_p$ for any $p<2,$ but I don't know if this condition is sufficient.
Anyone can help me? Thank you.
Comment: Assume some $y$ works: then $y \rightarrow 0$. Take $x_n=\sqrt{|y_n|} \in \ell^1$. Then $\frac{x_n}{|y_n|}=|y_n|^{-1/2}$ is unbounded thus not $\ell^1$.
Comment: @Mindlack if $(y_n) \in \ell_2$ and $x_n = \sqrt{|y_n|}$, then $(x_n) \notin \ell_1.$ You can assure that $x_n = |y_n|^2 \in \ell_2.$ !
Comment: Ok, maybe this would work: If there exists such an $y \in \ell_2,$ observe that $|y_n|^2 \in \ell_1$, so $x_n = |y_n|^2/y_n \in \ell_1,$ but $|x_n| = |y_n|$, so $(y_n) \in \ell_1$, and this cannot happen.
Comment: Can the sequence $y$ depend on $x$ or should the same $y$ work for all $x$?
Comment: If $(y_n)$ depends on $(x_n)$ is trivial as long as you can define a square root. I would like to know if there exists a $(y_n)$ that works for all $x.$
Comment: @Mindlack $|y_n|^{-1/2}$ is definitively bounded for $n\to\infty$
Comment: @Javier González: yes, I was very mistaken. Thank you for pointing this out.
Answer: This may be a long-winded, but I think it works: Suppose such a sequence $y = (y_n)$ exists, then we may define $T : \ell^1\to \ell^2$ by
$$
T((x_n)) = (x_n/y_n)
$$
We claim that $T$ is continuous: Suppose $x^k \to x$ in $\ell^1$ and $T(x^k) \to z$ in $\ell^2$, then for any $n\in \mathbb{N}$,
$$
\lim_{k\to \infty} |z_n - \frac{x^k_n}{y_n}|^2 \leq \lim_{k\to \infty} \|z - T(x^k)\|_2^2 = 0
$$
$$
\Rightarrow \lim_{k\to \infty} |y_nz_n - x^k_n|^2 = 0
$$
But
$$
\lim_{k\to \infty} |x_n - x^k_n| \leq \lim_{k\to \infty} \|x - x^k\|_1 = 0
$$
So
$$
z_n = \frac{x_n}{y_n} \quad\forall n\in \mathbb{N}
$$
Hence, $T(x) = z$, so $T$ is bounded by the closed graph theorem. Hence, there is $M> 0$ such that
$$
\|T(x)\|_2 \leq M\|x\|_1 \quad\forall x\in \ell^1
$$
Applying this to the `standard basis' $e_n \in \ell^1$, we conclude that
$$
\frac{1}{|y_n|^2} \leq M \quad\forall n\in \mathbb{N}
$$
Since $M > 0$, this implies that
$$
|y_n|^2 \geq \frac{1}{M} \quad\forall n\in \mathbb{N}
$$
contradicting the assumption that $(y_n) \in \ell^2$. Thus, no such sequence $(y_n)$ can exist.


Jquery captura ID da div no scroll e muda o título

Question: Tenho uma página com um título e várias divs com assuntos diferentes e IDs próprias, gostaria que ao descer a tela, o jquery captura a ID que esta visivel e coloca no título.
Comment: Quando dizes "coloca no título" queres dizer no "`dentro da ``?
Answer: Para pegar o primeiro ID usando jquery você teria poderia usar o código abaixo, que te traria um objeto:
código 1
<code>$( 'tag[id!=""]:visible:first' );
</code>
Onde a tag seria onde o id esta. Se o id identifica uma div, então no lugar da tag vc coloca div. O mesmo para input.
Para modificar o título você pode usar o código:
código 2
<code>$( 'title' ).text("novo título");
</code>
Caso a sua tag no código 1 fosse um input, então você implementar o código 2 da seguinte maneira. Ex:
<code>$( 'title' ).text( $( 'input[id!=""]:visible:first' ).val() )
</code>
Se quiser você pode dar uma olhada na documentação do jquery


Linux rename with a variable character?

Question: I have a list of files eg.
page-1.htm
page-2.htm
page-32.htm

How do I use rename to be like this:
page-01.htm
page-02.htm
page-32.htm

I am new to this and having trouble understanding the examples online.
I want to do something like the following where the ? is a variable character:
rename 's/page-?.htm$/page-0?.htm/' *

Answer: ? mean "any character".
So, your page-1.htm will be rename because it's match with pattern page-?.htm but page-32.htm don't
for your problem, you can use find | replace method, like this:
find -name 'page_?.htm' | rename 's/page_/page_0/'

I know it's doesn't what you really want, but it's temp solution

Linux rename with a variable character?


What is the reason that the Adam Optimizer is considered robust to the value of its hyper parameters?

Question: I was reading about the Adam optimizer for Deep Learning and came across the following sentence in the new book Deep Learning by Bengio, Goodfellow and Courville:

Adam is generally regarded as being fairly robust to the choice of hyper parameters, though the learning rate sometimes needs to be changed  from the suggested default.

if this is true its a big deal because hyper parameter search can be really important (in my experience at least) in the statistical performance of a deep learning system. Thus, my question is, why is Adam Robust to such important parameters? Specially $\beta_1$ and $\beta_2$?
I've read the Adam paper and it doesn't provide any explanation to why it works with those parameters or why its robust. Do they justify that elsewhere?
Also, as I read the paper, it seems that the number of hyper parameters they tried where very small, for $\beta_1$ only 2 and for $\beta_2$ only 3. How can this be a thorough empirical study if it only works on 2x3 hyper parameters?
Comment: Now that the book is out, the Adam authors have confirmation of how great their algorithm is. Reminds me of '89 Bay Area earthquake. News radio station made unconfirmed report of # of fatalities on highway collapse - said they were seeking confirmation from governor's office. Then they got the governor on the phone and asked if he could confirm # of fatalities. He said that's what he heard. The radio station then reported that they now had confirmation from the governor. It turns out that the governor meant that he heard it, as it turns out, on that radio station. So, circular confirmation.
Comment: And so self-promotion becomes fact.
Comment: Send an email to the authors of the book who made the claim. Ask them what the claim is based on.
Comment: @MarkL.Stone he only said he said it because the abstract said it. Hardly a convincing argument. Maybe next time I will e-mail the authors of the actual paper.
Comment: @MarkL.Stone in his defense, he might have been to busy to answer properly and I only contacted 1 of the 3 authors. Maybe I could contact the others but I'm not sure if they will answer given (at least) one is a professor. With the hype in DL I bet he gets 300 e-mails daily.
Answer: In regards to the evidence in regards to the claim, I believe the only evidence supporting the claim can be found on figure 4 in their paper. They show the final results under a range of different values for $\beta_1$, $\beta_2$ and $\alpha$.
Personally, I don't find their argument convincing, in particular because they do not present results across a variety of problems. With that said, I will note that I have used ADAM for a variety of problems, and my personal finding is that the default values of $\beta_1$ and $\beta_2$ do seem surprisingly reliable, although a good deal of fiddling with $\alpha$ is required.
Answer: Adam learns the learning rates itself, on a per-parameter basis. The parameters $\beta_1$ and $\beta_2$ don't directly define the learning rate, just the timescales over which the learned learning rates decay.  If they decay really fast, then the learning rates will jump about all over the place. If they decay slowly, it will take ages for the learning rates to be learned. But note that in all cases, the learning rates are determined automatically, based on a moving estimate of the per-parameter gradient, and the per-parameter squared gradient.
This is in huge contrast with stock vanilla Stochastic Gradient Descent, where:

learning rates are not per-parameter, but there is a single, global learning rate, that is applied bluntly, across all parameters

(by the way, this is one reason why data is often whitened, normalized, prior to being sent into nets, to try to keep the ideal per-parameter weights similar-ish)

the learning rate provided is the exact learning rate used, and wont adapt over time

Adam is not the only optimizer with adaptive learning rates. As the Adam paper states itself, it's highly related to Adagrad and Rmsprop, which are also extremely insensitive to hyperparameters. Especially, Rmsprop works quite nicely.
But Adam is the best in general. With very few exceptions Adam will do what you want :)
There are a few fairly pathological cases where Adam will not work, particularly for some very non-stationary distributions. In these cases,
Rmsprop is an excellent standby option.  But generally speaking, for most non-pathological cases, Adam works extremely well.
Comment: this is not a "deeper question". This is it seems one of the most important point of the paper, no? The whole point is that it does things by "itself" but then there are these other hyperparameters that seems to be magically robust. Thats the issue I have. Its seems to me to be related to the core of the paper unless I got misunderstood the point of Adam.
Comment: I don't get it, why is Adam robust to values of $\beta_1,\beta_2$. There seems to be no study whatsoever to back it up. Seems folks "wisdom" as far as I can tell.
Comment: Yes, if you mean, 'is there an opportunity here to research deeper into why?', well... maybe.
Comment: @HughPerkins what about their extensions: AdaMax, AdamW?
Comment: "There are a few fairly pathological cases where Adam will not work, particularly for some very non-stationary distributions." <- any references here?


How to find all subgroups of a group in GAP

Question: With the next group:
gap> G:=Group((1,2,3,4),(1,2));

Group([ (1,2,3,4), (1,2) ])

gap> Order(G);

24

gap> Elements(G);

[ (), (3,4), (2,3), (2,3,4), (2,4,3), (2,4), (1,2), (1,2)(3,4),
  (1,2,3), (1,2,3,4), (1,2,4,3), (1,2,4), (1,3,2), (1,3,4,2),
  (1,3), (1,3,4), (1,3)(2,4), (1,3,2,4), (1,4,3,2), (1,4,2),
  (1,4,3), (1,4), (1,4,2,3), (1,4)(2,3) ]

Is there any function to list the subgroups of G?
Thanks, and sorry if the question looks so easy, i'm a newbie in GAP.
Comment: Please see [How do I get the subgroups of my group?](http://www.gap-system.org/Faq/faq.html#7.7) from GAP F.A.Q
Comment: Also http://math.stackexchange.com/q/460727/ and http://math.stackexchange.com/q/1368608/
Comment: Thanks Alexander , I could not find the information in the oficial website.
Comment: You're welcome! I am debating whether this should be closed as a duplicate of [this question](http://math.stackexchange.com/questions/460727/computing-conjugacy-classes-of-subgroups-in-gap) or renamed to "How to find all subgroups of a group in GAP" and answered properly here...
Comment: Ok Alexander, I've renamed it now.
Comment: Alexander in order to this question, I've found the function "Subgroups()" in the package SONATA. This function give a list of subgroups of a group. Is it correct?
Comment: Great - that's why I tend to think that this question is needed here and should be answered properly:) Both `Subgroups` from SONATA and even `AllSubgroups` in GAP work only with toy examples. As soon as one tries them on larger groups, thee became very inefficient, and one should use `ConjugacyClassesSubgroups` or other functions listed in [F.A.Q.](http://www.gap-system.org/Faq/faq.html#7.7) This also promotes good way of thinking - don't ask GAP for more, if you need e.g. class representatives or normal subgroups only.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/32843/discussion-between-angel-blasco-and-alexander-konovalov).
Answer: One should think in terms of conjugacy classes of subgroups:
gap> G:=Group((1,2,3,4),(1,2));
Group([ (1,2,3,4), (1,2) ])
gap> cc:=ConjugacyClassesSubgroups(G);
[ Group( () )^G, Group( [ (1,3)(2,4) ] )^G, Group( [ (3,4) ] )^G,
  Group( [ (2,4,3) ] )^G, Group( [ (1,4)(2,3), (1,3)(2,4) ] )^G,
  Group( [ (3,4), (1,2)(3,4) ] )^G, Group( [ (1,3,2,4), (1,2)(3,4) ] )^G,
  Group( [ (3,4), (2,4,3) ] )^G, Group( [ (1,4)(2,3), (1,3)(2,4), (3,4) ] )^G,
  Group( [ (1,4)(2,3), (1,3)(2,4), (2,4,3) ] )^G,
  Group( [ (1,4)(2,3), (1,3)(2,4), (2,4,3), (3,4) ] )^G ]

For example, Group( [ (1,3)(2,4) ] )^G means a conjugacy class of a subgroup Group( [ (1,3)(2,4) ] ). The 1st element of the returned list in this example is Group( () )^G - the conjugacy class of the trivial subgroup, but in general the order in which the classes are listed depends on the method chosen by GAP, so you should not rely on it being always the 1st.
Now take, for example, the 2nd conjugacy class from this list. It contains 3 subgroups:
gap> c:=cc[2];
Group( [ (1,3)(2,4) ] )^G
gap> Size(c);
3

We can use Representative to get the representative of the class
gap> Representative(c);
Group([ (1,3)(2,4) ])

and AsList to get all subgroups from this class:
gap> AsList(c);
[ Group([ (1,3)(2,4) ]), Group([ (1,4)(2,3) ]), Group([ (1,2)(3,4) ]) ]

GAP also has a function AllSubgroups (since GAP 4.5), but it is intended primarily for use in class for small examples, and quickly becomes inefficient for larger groups. Instead of using AllSubgroups one should think algorithmically. Do you need all subgroups or only up to conjugacy? Do you want only normal subgroups, or maximal, or maybe of a particular order or isomorphism type? In this case, look at:

NormalSubgroups
IsomorphicSubgroups
RepresentativesPerfectSubgroups
RepresentativesSimpleSubgroups
ConjugacyClassesMaximalSubgroups
ConjugacyClassesPerfectSubgroups

If only $p$-subgroups are needed, it is often faster to compute the subgroup lattice of the Sylow $p$-subgroup (see SylowSubgroup), and then use conjugation to find more, if it is not normal.
Furthermore, LatticeByCyclicExtension and SubgroupsSolvableGroup accept optional arguments which allow to put restrictions on computed subgroups. In the latter case functions SizeConsiderFunction and ExactSizeConsiderFunction may be used.
For more advanced techniques, see also the Chapter "Tables of Marks" and in particular Section "Accessing Subgroups via Tables of Marks" - but that will work only for groups whose tables are contained in the tables of marks library.
Further reading:

How do I get the subgroups of my group from GAP F.A.Q.
Computing Conjugacy Classes of Subgroups in GAP
$p$-subgroups in GAP


Edge/structure matching for image registration

Question: I am working on image registration between LWIR & RGB images. I am able to extract the edges from both images.
RGB_Edges, LWIR_Edges
Now, I want to match the edges of these images to calculate homography.
I tried to match each edge of RGB with LWIR image separately using template matching (OpenCV) but it didn't worked.
Therefore, can anyone please suggest some methods to mach the edges/structures from both images that can be helpful to compute homography?
I will really appreciate any suggestion/help.
Thanks.
Answer: These two images are already fairly well aligned.
Due to the large thickness and irregularity of the edges, I doubt you can do much better.

If you have the option of operator supervision, point at corresponding points in the two images (four pairs are enough for an homography).
For an automated approach, you can try to thin the strokes then to find (approximate) line segments in both images. For a certain number of segments in one image, find the segment which is (approximately) parallel, close and facing with a significant overlap in the other. You can expect that these segments are in correspondence.
Next, you can you can obtain corresponding points by forming the intersections between some segments in each image (take segments that are close but as perpendicular as possible).
As this procedure will suffer from outliers, model fitting by RANSAC is probably a good option.


Browser Bookmarklet To Pull & Store Selected Text From Active Window

Question: Firstly, I should make it clear that I am not a programmer (merely working out the details of an upcoming project). So please go easy on me if some questions sound silly.
Basically, I have a requirement to create a browser bookmarklet. This can be dragged on to the user's status bar. So this is how it should work : when I am on any particular webpage, I can select some chunk of content from the page and click on the bookmarklet. On doing this, the bookmarklet should save all the selected data in my database.
Now, what I would like to know is if this is possible if I also want to store all formatting, hyperlinks,etc from the selected text. For instance, the portion of webpage I select on a browser window may include some images, links, bold text and three paragraphs. Is it possible for me to capture all of these by a simple click of a bookmarklet?
Thanks a lot for the help.
PS : I tried searching for this information on this website, but no answers seem to delve with this specific problem.
Answer: You can get some of the way by extracting the selected HTML. To get CSS formatting as well, you'd need some fairly heavy processing, which is beyond the scope of my answer. You'll also need to send the selected HTML to the server, for which you'll need to use Ajax.
The Ajax part is fairly simple. There are tons of tutorials around on how to post a value to the server using Ajax. However, you need to be aware that it will only work on a page from the same domain as the server you're posting to, so this may negate the point of doing this as a bookmarklet, since it can't just be used anywhere on the web.
Here's a function that gets the current selected HTML in all major browsers:
<code>function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}

alert(getSelectionHtml());
</code>


Is is possible to access views from a module file?

Question: I have created a view in drupal. My question is, is it possible to access the contents of the view or value stored in the view from the module file..
Need any details or code plss comment.
Comment: It's not appropriate to ask us to write your code for you - please update the question with the research you've already done, the code you've tried yourself, and what didn't work/error messages. Thanks
Answer: You can use drupal function views_get_view_result($name, $display_id = NULL)
$name : name of the view
$display_id : On the edit page for the view in question, you'll find a list of displays at the left side of the control area . e.g. 'MASTER', 'Page'
This function will return An array containing an object for each view item.

Reference :https://api.drupal.org/api/views/views.module/function/views_get_view_result/7
Comment: can we access it in a custom module??
Comment: Yes you can access it in custom module.
Comment: should i add it as a hook in my custom module??. can u please elaborate
Comment: Where do u want to use the function?
Comment: in my custom .module file....
Comment: @Ajmal Please make some effort to solve the problem yourself; update your question with the code you've tried, what you expect to happen, what did happen, and any error messages you receive. As it is the question is dangerously close to being closed as we specifically don't provide tutorials in response to vague requests, and don't operate a support forum. Thanks
Comment: Hi @Clive, really I'm not expecting a coding for this question.I have tried some confusing stuffs which may deviate the visitors answering this question. In order to be crisp and clear I asked this question without coding, I need to know whether it was possible or not??. have anyone tried it before??. this is what I need from this question. Please apologize me if I have talked anything wrong...


How find the of minimum $ab+bc+\frac{\sqrt{2}}2ac$ for $a^2+b^2=4,b^2+c^2=8$

Question: let $a,b,c$ are real numbers and such $a^2+b^2=4,b^2+c^2=8$, find the minimum of
$$ab+bc+\dfrac{\sqrt{2}}{2}ac$$
if this problem ask find the maximum
we  can use $AM-GM$
$$ab+bc+\dfrac{\sqrt{2}}{2}ac=\dfrac{1}{Ax}Aa\cdot xb+\dfrac{1}{Bz}Bb\cdot zc+\dfrac{\sqrt{2}}{2Cv}va\cdot Cc\le \dfrac{1}{Ax}(A^2a^2+x^2b^2)+\dfrac{1}{Bz}(B^2b^2+z^2c^2)+\dfrac{\sqrt{2}}{2Cv}(v^2a^2+C^2c^2)$$
But  for mimimum I can't solve it.Thank you
for mimimum  I have some idea
let $$a=2\cos{x},b=2\sin{x},b=2\sqrt{2}\cos{y},c=2\sqrt{2}\sin{y}$$
and $\sin{x}=\sqrt{2}\cos{y}$
then $$ab+bc+\dfrac{\sqrt{2}}{2}ac=4\sin{x}\cos{x}+4\sqrt{2}\sin{x}\cos{y}+4\sin{y}\cos{x}$$
my nice methods
$$ab+bc+\dfrac{\sqrt{2}}{2}ac=\dfrac{\sqrt{2}}{4}(a+\sqrt{2}b+c)^2-3\sqrt{2}$$
Comment: See the huge and complex solution in terms of roots of polynomials of higher degrees obtained with Mathematica [here](http://rapidshare.com/files/474289857/OP.pdf) as an exported PDF file.
Comment: See the numerical solution obtained with Maple by $$ DirectSearch:-GlobalSearch(a*b+b*c+(1/2)*sqrt(2)*a*c, \{a^2+b^2 = 4, b^2+c^2 = 8\}):$$ $$[[-4.2426407302032, [a = -.605847245180419, b = 1.90602969015315, c = -2.08974899972977], 1203], $$ $$[ -4.24264072959487,[a = 1.90604189905156, b = .605808830413558, c = -2.76278767211529],  2197],$$ $$ -4.24264072950065, [a = -1.90604163386125, b = -.605809665561305, c = 2.76278748876704], 1380], $$ $$-4.24264072905823,[a = .605811571196014, b = -1.90604102804011, c = 2.08973865774724], 1542]]$$
Comment: I think Mathematica solves the system of 5 equations formed with the Lagrange multipliers, reducing the one to an equation of higher degree.
Comment: The answer, btw, is $-3 \sqrt{2}$.
Comment: @ Robert : Why do you think so? Can you identify $a, b,$ and $c$?
Comment: The parametrization of the intersection of the two cylinders reduces the problem to two variables. Its solution can be reduced to an equation of degree 4. I have never seen any application of [the explicit formulas](http://en.wikipedia.org/wiki/Quartic_function) for its solutions. It makes no principal difference with the solution of the algebraic system in 5 unknowns $a, b,c, \mu, \lambda.$
Answer: Looks like a job for Lagrange multipliers...
let $$F(a,b,c,\lambda,\mu) = ab + bc + \frac{\sqrt{2}}{2} ac + \lambda (a^2 + b^2 - 4) + \mu(b^2 + c^2 - 8)$$
and solve $\dfrac{\partial F}{\partial a} = \dfrac{\partial F}{\partial b} = \dfrac{\partial F}{\partial c} = \dfrac{\partial F}{\partial \lambda} = \dfrac{\partial F}{\partial \mu} = 0$
Comment: Thank you,I think this problem have other nice methods,Thank you
Comment: oh,Thank I have find nice methods,Thank you everyone


how i do use puppet variable in facter custom facts

Question: how i can inherit variable from puppet manifest in facter custom fact? in this case $job_name varible. I want use same custom fact with different envs.
if $facts['hostname'] =~ /.*name.*/ {

$job_name = 'test'

        file {  "/opt/$job_name":
                ensure => directory,
                owner  => 'root',
                group  => 'root',
                mode   => '0775',
             }

        file { "/opt/$job_name/version.$job_name":
                ensure => present,
                owner  => 'root',
                group  => 'root',
                mode   => '0644',
                #notify => Exec["update_test"],
                source => "puppet:///modules/test/version.$job_name",
             }

     if $facts['check_version'] == "aasdadsadasd" {

        file {  "/opt/$job_name/bla2":
                ensure => directory,
                owner  => 'root',
                group  => 'root',
                mode   => '0775',
             }

     }

my custom fact rb code is
require 'facter'
Facter.add(:check_version) do
  setcode do
    Facter::Core::Execution.exec("/bin/cat /opt/$job_name/version.$job_name")
  end
end

thanks in advance
Answer: If you want to use a manifest variable in a custom fact, you can't. This is because facts are evaluated on the client before the catalog (collection of manifests) is compiled. So at the point that your custom fact is run, the variable $job_name doesn't actually exist yet.


rails ignores my redirect

Question: Rails is ignoring my redirect.
Use Case:

user navigates to his account and selects the option to display his subscription status
app lists his current subscription and the option to cancel it
user cancels the subscription
app updates the subscription record and should redirect the user back to the subscriptions action
-> but rails ignores this last step... any ideas what I am doing wrong?

Routes
map.resources :users, ..., :member => { ..., :subscriptions => :get, :subscribe => :post, :unsubscribe => :put}

Controllers:
  def subscriptions
    @tradesman = User.find_by_id(params[:id])
    @subscription = @tradesman.current_subscription || Subscription.new
    @all_subscriptions = Subscription.find(:all)
  end

  def subscribe
    @tradesman = User.find_by_id(params[:id])
    @subscription = current_user.subscriptions.build(params[:subscription])
    @subscription.update_attributes(:started_at => Time.zone.now)
    @subscription.save
    redirect_to :action => 'subscriptions', :id => @tradesman.id
  end

  def unsubscribe
    @tradesman = User.find_by_id(params[:id])
    @subscription = @tradesman.current_subscription
    @subscription.update_attributes(:ended_at => Time.zone.now)
    @subscription.save
    redirect_to :action => 'subscriptions', :id => @tradesman.id
  end

View:

  <%= render :partial => "my_account_leftbar" %>
  <% form_for @subscription, :url => subscribe_user_path(current_user) do |f| %>

        <% @all_subscriptions.each do |subscription| %>

Start: <%= subscription.started_at %>

        <% end %>

        <% if @subscription.new_record? %>

            <%= f.check_box :subscription_type %>

            <%= f.submit "Subscribe", :class => "button mr8" %>

        <% else -%>
        <%= f.check_box :subscription_type, :value => @subscription.subscription_type, :disabled => true %>

            <% form_for @subscription, :url => unsubscribe_user_path(current_user) do |f| %>

            <%= f.submit "Unsubscribe", :class => "button mr8" %>

            <% end %>

        <% end %>

  <% end %>

Comment: Found the bug in the view where I nested the 'unsubscribe' form within the 'subscribe' form - what didn't make sense. I rearranged my view (separated those two forms, one in the 'if' part and the other in the 'else' part. Works fine now.
Comment: Will post the new view as soon as stackoverflows allows it..
Answer: Use redirect_to instead of render (last method call in your unsubscribe action).
Comment: Thanks for your input. Sorry, I actually tried redirect_to (and it didn't work). I also tried previously render (which doesn't work either) but forgot to replace it. So: redirect_to doesn't work
Answer: Found the bug in the view where I nested the 'unsubscribe' form within the 'subscribe' form - what didn't make sense.
I rearranged my view (separated those two forms, one in the 'if' part and the other in the 'else' part. Works fine now:

  <%= render :partial => "my_account_leftbar" %>
  <% @all_subscriptions.each do |subscription| %>

Start: <%= subscription.started_at %>

  <% end %>

    <% if @subscription.new_record? %>
    <% form_for @subscription, :url => subscribe_user_path(current_user) do |f| %>

            <%= f.check_box :subscription_type %>

            <%= f.submit "Subscribe", :class => "button mr8" %>

    <% end %>
    <% else -%>
    <% form_for @subscription, :url => unsubscribe_user_path(current_user) do |f| %>
    <%= f.check_box :subscription_type, :value => @subscription.subscription_type, :disabled => true %>

      <%= f.submit "Unsubscribe", :class => "button mr8" %>

    <% end %>
    <% end %>

rails ignores my redirect


$X$ a normed space. $(x_n) \subset X$ s.t. $|f(x_n)| < M_f$ for all $n$ and $\forall f \in X^{\ast}$ then there is $C$ s.t. $\|x_n\| \le C$

Question: Let $X$ a normed vector space and $(x_n) \subset X$ such that  $|f(x_n)| < M_f$ for all $n$ and $\forall f \in X^{\ast}$, where $M_f$ is a constant depending on $f.$ (Here we are assuming that if $f \in X^{\ast}$ then $f$ is continuous). Then there is $C>0$ s.t. $\|x_n\| \le C~\forall n \in \mathbb{N}.$
It seems natural how to proceed. I can take the sup on the set $X^{\ast}$ considering only $f$ such that $\|f\| = 1$. Then we have
$$\|x_n\| \le \sup_{\{f \in X^{\ast}: \|f\| = 1\}}M_f.$$
The problem is, how can I be sure that $\|x_n\| \le \sup_{\{f \in X^{\ast}: \|f\| = 1\}}M_f < \infty?$
Thanks
Comment: The Banach-Steinhaus theorem may prove useful in this situation.
Comment: what is $M_f$? Just some constant?
Comment: sorry! Yes, it is a constant that depends on $f$.
Comment: thank you! @minimalrho, I dindnt see this theorem yet. This relief's me.
Answer: This is just the Banach-Steinhaus Theorem applied to the dual space $X^*$ which is always a Banach space, even if $X$ is only a normed space.
For $x \in X$ let $\hat x \in X^{**} = (X^*)^*$ be defined via $\hat x(f) = f(x)$ for all $f \in X^*$. Then, for all $n \in \mathbb{N}$ and $f \in X^*$ we have
$$
|\hat{x_n}(f)| = |f(x_n)| \leq M_f,
$$
i.e. the family of operators $(\hat{x_n})_{n \in \mathbb{N}}$ is pointwise bounded.
Banach-Steinhaus gives you that the family is uniformly bounded, i.e. there exists some $C > 0$ such that
$$
\|\hat{x_n}\| \leq C,
$$
for all $n \in \mathbb{N}$.
But $X$ is isometrically isomorphic to a subspace of its Bi-dual, i.e. $\|\hat{x_n}\| = \|x_n\|$.


Issue with positioning an absolute div

Question: Hey guys I am having trouble styling my navigation so that is will always be at the same position on a page no matter the browser....
I have the following:
<code>#Mainmenu {
    width: 44%;
    font-family: Helvetica, Arial, Sans-Serif;
    font-weight: bold;
    font-size: .9em;
    list-style: none;
    position: absolute;
    left: 35em;
    top: 4.7em;
    right: 0;

}
</code>
This is positioned, exacly where I want it in chrome and firefox but not in IE.  Also if I change resolution it changes the positioning a little.  I want to know how I can always have it at the same spot it is suppose to.
Let me know if you need anything else!
David
update:
http://jsfiddle.net/MVpkP/ - is the styles that I have in it and the layout.

The one above this is Chrome and the one I want it to remain like, that's how I want it styled.
Comment: Can you jsfiddle it so that we can test it out in IE?
Comment: what information do you want?
Comment: just put the code http://jsfiddle.net here the relevant code so that we can test it out...
Comment: @arpitSrivastava I added it, but thats not really how it looks.
Comment: @ArpitSrivastava I just added images
Answer: Put this in your header
<code> <!--[if IE]>
   <link rel="stylesheet" type="text/css" href="IE.css" />
 <![endif]-->
</code>
Create an additional css file for IE and adjust your IE css accordingly.
Answer: you should either use % on your left/right/top, or put this element inside another element.
for example:
<code>#Mainmenu {
width: 44%;
font-family: Helvetica, Arial, Sans-Serif;
font-weight: bold;
font-size: .9em;
list-style: none;
position: absolute;
left: 3%;
top: 1.5%;
right: 0;
}
</code>
As for putting it in another element:
<code>#wrap{
width: 700px;
margin:0 auto;
 }

<div class="wrap">
     your menu stuff...
</div>
</code>
either of those should solve your problem
Comment: The top one did not work for me...what do you mean for the wrap one?
Comment: if you set a wrapper element. and then use absolute on inside element without stating top/right/left it will be absolute, but will be relative to the wrapper element. and if you'll want to change its position you can then margin-left/ right.
Comment: would the  be easier?
Comment: this will also work its up to your preference in many cases a separate css files is required, i just prefer trying to have 1 css file.

Issue with positioning an absolute div


What's the rule for Pascal's Triangle?

Question: The numbers in the 5th row are" 1,4,6,4,1". If I want to know the numbers in the 72nd row, how can i get the numbers?
The 72nd row should be: 1, 71, ..... ...... ,71, 1.
The odd-number (2n-1) row should be: 1, (2n-2), .... ...., (2n-2),1
The even-number (2n) row should be: 1, (2n-1), .... .... , (2n-1), 1

The Pascal's Triangle
the 1st row: 1
the 2nd row: 1, 1
the 3rd row: 1, 2,1
the 4th row: 1,3,3,1
the 5th row: 1, 4,6,4,1
the 6th row: 1,5,10,10,5,1
etc.
Comment: The $k$th element of the $n$ row is the binomial coefficient $\binom nk$.  That's what makes Pascal's triangle interesting.  (Here we start counting the elements of a row at $0$).
Answer: As written in the comments, if you're  looking for the number in the $n$th row and $k$th column of Pascal's triangle (note that the first row is $n=0$ and the first column is $k=0$), you can use the formula
$${n \choose k}=\frac{n!}{k!(n-k)!}$$
For example, we know that the first column of the $72$nd row will have a $1$, but we can prove this because
$${72 \choose 0}=\frac{72!}{0!(72-0)!}=1$$
Continuing on, we have
$${72 \choose 1}=\frac{72!}{1!(72-1)!}=72$$
$${72 \choose 2}=\frac{72!}{2!(72-2)!}=\frac{72 \times 71 \times 70!}{2 \times 70!}=2556$$
and so on, until $k=72$.
NOTE: If you'd like to know what ${n \choose k}$ represents, it's the number of ways you can select $k$ items from $n$ items, with order not mattering. Each way is called a combination. For example, there are $5$ vowels in the English alphabet, and if I want to know how many combinations of $3$ vowels are possible, I compute ${5 \choose 3}=\frac{5!}{3! \times 2!} = 10$ possible combinations. When I say "order not mattering," in this case that means that, for example, A E O and O A E are considered the same.

What's the rule for Pascal's Triangle?


What to conclude about the results if the p-value is same in 2 Kolmogorov-Smirnov tests?

Question: I am comparing observed and simulated acceleration distributions. There are 3 data sets:
1) acco = observed accelerations
2) acc15 = simulated accelerations data 1
3) acc16 = simulated accelerations data 2
I did 2 sample Kolmogorov-Smirnov test with acco & acc15, and then acco and acc16. I want to see which of the two simulated acceleration distribution is (more) similar to the observed. I guess it is important to note here that both simulations were calibrated using the observed data using different methods. Here are the test results:
> ks.test(acco$slo_v_m, acc15$saccm)

    Two-sample Kolmogorov-Smirnov test

data:  acco$slo_v_m and acc15$saccm
D = 0.23379, p-value < 2.2e-16
alternative hypothesis: two-sided

Warning message:
In ks.test(acco$slo_v_m, acc15$saccm) :
  p-value will be approximate in the presence of ties
> ks.test(acco$slo_v_m, acc16$saccm)

    Two-sample Kolmogorov-Smirnov test

data:  acco$slo_v_m and acc16$saccm
D = 0.37959, p-value < 2.2e-16
alternative hypothesis: two-sided

Warning message:
In ks.test(acco$slo_v_m, acc16$saccm) :
  p-value will be approximate in the presence of ties

You can see that both resulted in same p-value but different D statistic. What can I conclude about these data? Can I say thatacc15 is better than acc16 when compared with acco?
Comment: These p-values tell you neither distribution is anything like the reference distribution.  This is somewhat like asking us which is more like a crow: a pencil or a stick of chewing gum?
Answer: These P-values aren't the same, they are just both less than $2.2 \times 10^{-16}$. From this I would conclude:

As whuber said, neither acc15 nor acc16 is a good fit to acco.
Your software isn't very carefully coded. It's probably computing a right tail probability as 1 minus a left cumulative probability, which means it can't, in normal double-precision arithmetic, compute any P-value less than $\sim 10^{-16}$, and already looses a lot of accuracy for values greater than that.


Undefined Function Error PHP

Question: I'm writing a class and I can't figure out why I am getting this error:
PHP Fatal error:  Call to undefined method Directory::BuildDirectoryListing()
in C:\www\directory.php on line 25

It doesn't make any sense. By the error it looks like it is trying to look for a static function. Here is the code I am using:
$odata = new Directory($listing['id']);
$adata = $odata->BuildDirectoryListing();

<?php

include_once("database.php");

class Directory {

    public $listing = array();
    public $aacategories = array();

    function __construct($_listing) {

        $this->listing = $_listing;

    }

    public function BuildDirectoryListing() {

        /* function code here */

    }

}

?>

Comment: "Directory" is a reserved class in PHP: http://php.net/manual/en/reserved.classes.php
Comment: I'm not sure why that is a "-1".  It seems like anyone could have the same problem.
Answer: Directory is a PHP built-in class.
You need to namespace your code or change your class name:
Class:
<?php

namespace MyApp;

class Directory {

    public $listing = array();
    public $aacategories = array();

    function __construct($_listing) {

        $this->listing = $_listing;

    }

    public function BuildDirectoryListing() {

        /* function code here */

    }

}

?>

Creating the class:
<?php

$odata = new \MyApp\Directory($listing['id']);
$adata = $odata->BuildDirectoryListing();

?>

Answer: You are calling a static function in Directory::BuildDirectoryListing(), change this line
public function BuildDirectoryListing() {

for
public static function BuildDirectoryListing() {

Undefined Function Error PHP


side effect functions working in react and svelte

Question: as all know we put a dependency array in useEffect. But when we use the onMount method in svelte which is equivalent to useEffect, it doesn't require dependency array. Can anyone explain me why.
<code> //// React  ////

useEffect( ()=>{
         // side effects goes here //
},[])

//// Svelte  ////

onMount(  ()=>{
        // side effects goes here  //
})
</code>
Comment: `onMount` is equivalent to an empty array, not no array. To understand _why_ watch this video https://www.youtube.com/watch?v=KJP1E-Y-xyo
Comment: https://beta.reactjs.org/learn/synchronizing-with-effects
Answer: onMount is used when the component is rendered. However, in react, useEffect receives an array of dependencies and if one of these dependencies is updated, that will cause the component to re-render.
Hope that answers your question!