how to add a phony target halfway through a make file

Question: I am looking at a pre-existing, working, complex makefile for a project which will both build and deploy the code on multiple OS's.
I'm looking at some separate IDE support (Visual Studio) for the build process (i.e. half the make will already be done), so need to insert a phony target for the deploy action such that the old flow (make all) still works, including the deloy step, but that make deploy will just do the final deployment step for those using the IDE.
Not being familiar with make, I'm having difficulty seeing how/if make allows such an entry point and if so how to implement it.
The current code has:
$(BUILT_INS): git$X
    $(QUIET_BUILT_IN)$(RM) $@ && \
    ln $< $@ 2>/dev/null || \
    ln -s $< $@ 2>/dev/null || \
    cp $< $@

whose actions are the deployment step.
So conceptually I think I need
.PHONY: deploy
$(BUILT_INS): git$X
  deploy

deploy:
    $(QUIET_BUILT_IN)$(RM) $@ && \
    ln $< $@ 2>/dev/null || \
    ln -s $< $@ 2>/dev/null || \
    cp $< $@

which is clearly not right, because the phony target can't be an action.
In summary; How to create an entry point into a makefile to do the rule's actions? (a critical desire is to avoid duplicating the action code)
Answer: Your "conceptually" solution has many more problems than using a target as a recipe (which you're right, won't work, but you could fix by using $(MAKE) deploy as the recipe to invoke a recursive make); the other thing is that this:
$(BUILT_INS):
        ... using $@ ...

means run that recipe one time for each word in the BUILT_INS variable, and each time the automatic variable $@ will be assigned to that word (the target).
Your replacement:
deploy:
        ... using $@ ...

does an entirely different thing: it runs the recipe one time, with the value of $@ set to deploy.  Not going to work.
The simple answer to your question is that you just declare a new target deploy that lists the targets you want to run as prerequisites:
.PHONY: deploy
deploy: $(BUILT_INS)

Now when you run make deploy it will try to build the BUILT_INS targets, and run the install rule for each one.
However, my suspicion is that this will be a problem for you, depending on what the git$X prerequisite is... it might cause a big part of the rest of your makefile to run as well.  But, you don't give any information about that so I can't say.
ETA Sure enough, git$X is a problem.  So, it appears you want VS to generate your git$X file (which will be git.exe presumably).  Then you want to run make deploy to copy it.  The trick here is to keep make from rebuilding git$X when you use the deploy target.  You can do something like this; replace the rule that builds git$X with:
.PHONY: deploy
deploy: $(BUILT_INS)

ifeq (,$(filter deploy,$(MAKECMDGOALS)))
git$X: git.o GIT-LDFLAGS $(BUILTIN_OBJS) $(GITLIBS)
        $(QUIET_LINK)$(CC) $(ALL_CFLAGS) -o $@ $(ALL_LDFLAGS) git.o \
            $(BUILTIN_OBJS) $(LIBS)
endif

This creates a new target deploy which depends on the BUILT_INS targets, as I show above.  Then, I enclose the rule to create git$X inside a test so that if you run make deploy that rule is not defined.  Now make doesn't know how to build git$X at all, so if it doesn't exist then make deploy will fail, but if it does exist then make will copy it, without trying to rebuild it.
Comment: I'd had a look at something like that, but realised that the thing I didn't want to happen was for the `BUILT_INS` to be built (as dependancies) by the make file - I simply want the the list of names to feed into the deploy action - all very awkward to achieve.
Comment: Well, presumably they already exist when you run `make deploy`, otherwise it cannot work.  If they exist, then make won't try to rebuild them -- _unless their prerequisites are out-of-date_!  This is exactly what I was referring to by my comment above about `git$X` (whatever that is).  Without knowing what the prerequisites of the `BUILT_INS` targets are we can't provide a solution.
Comment: Unfortunately the `BUILT_INS` may be out of date or missing (rather than `git$X` which will be newly built), because of the independence of the tools, hence the desire to find a way of inserting an entry point. The full makefile is here https://github.com/git/git/blob/master/Makefile#L1678 - this is the final step after the git executable is built when it is linked or copied to the built-ins, so having built that executable with VS one just wants to do that deployment, but as you see 'it's complicated'.
Comment: I don't understand how you can call a `deploy` rule which you want to just install the `BUILT_INS`, if some of them are missing.  My understanding of what you're trying to do is build the `BUILT_INS` targets using Visual Studio, not make, but then install them with make by running a separate target that does the install bit.  That's why I said above _they already exist when you run `make deploy`_ ... because VS must have already created them.
Comment: The odd thing which you may have noticed is that the `BUILT_INS` aren't actually 'built', rather they are linked or copied *by that rule* from the `git$X` dependency, so given a new 'git$X` (externally built by VS) I need to then run that script to 'duplicate' that 'git$X` into the `BUILT_INS`, preferably using the same piece of script to avoid future maintenance hassles of keeping separate script parts synchronised.
Comment: Also the `git$X` depends on a previous rule that depends on a separate macro variable `BUILTIN_OBJS`, so it can end up a bit circular (see #L601 as linked above).
Comment: The *ETA* section regarding the `MAKECMDGOALS` variable looks a good method. The one other thought I had (after more browsing) was the inverse of http://stackoverflow.com/q/2784557/717355 and add a `DEPLOY_ONLY=1` on the command line (instead of the debug target) and then append that to the appropriate `git$X` target to break the invocation of the rule you'd identified. I'll try them !


Differentiating a definite integral

Question: I am unsure of how to differentiate the follow expression:
$$
\frac{d}{dt} \int_\tau^t \Phi(t,\alpha)\cdot A(\alpha)\cdot x(\alpha) d\alpha
$$
where $\Phi(t,\alpha)$ and $A(\alpha)$ are matrices.
Comment: Formally, you just interchange differentiation and integration. To justify the interchange, use Leibniz' rule https://en.wikipedia.org/wiki/Leibniz_integral_rule.
Answer: Without knowing more about $\Phi$ and $A$ (and $x$ too), nothing much can be said, but Leibniz rule might help:
$$\frac{\operatorname d \;}{\operatorname d t}\int_c^t \Phi(t,\alpha)\cdot A(\alpha)\cdot x(\alpha)\operatorname d \alpha \;=\; \int_c^t \frac{\partial\; \Phi(t,\alpha)}{\partial\; t}\cdot A(\alpha)\cdot x(\alpha)\operatorname d \alpha + \Phi(t,t)\cdot A(t)\cdot x(t)$$
Comment: For the second term, did you mean $\Phi(t,t)\cdot A(t)\cdot x(t)$?
Comment: Yes, @truhoang .  Thank you.

Differentiating a definite integral


NullPointerException exception on file uploading in struts2

Question: I am working on struts2 application where i have to upload file and save it into database.
but each time it is showing NullPointerException my code is here
Stack trace is-
java.lang.NullPointerException
    dao.Clientdao.registration(Clientdao.java:31)
    action.client.Clientaction.execute(Clientaction.java:18)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:314)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485)
    org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)

model class is
import java.io.File;
public class Clientmodel {
private String Aggrement;
private String  date;
private String rate;
private String maturitydate;
private String detail;
private String taxno;
private File imagefile;
public File getImagefile() {
    return imagefile;
}

public void setImagefile(File imagefile) {
    this.imagefile = imagefile;
}

public String getRate() {
    return rate;
}

public void setRate(String rate) {
    this.rate = rate;
}

public String getDetail() {
    return detail;
}

public void setDetail(String detail) {
    this.detail = detail;
}

public String getTaxno() {
    return taxno;
}

public void setTaxno(String taxno) {
    this.taxno = taxno;
}

public String getAggrement() {
    return Aggrement;
}

public void setAggrement(String aggrement) {
    Aggrement = aggrement;
}

public String getMaturitydate() {
    return maturitydate;
}

public void setMaturitydate(String maturitydate) {
    this.maturitydate = maturitydate;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

}

struts.xml
  <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
       <constant name="struts.enable.DynamicMethodInvocation" value="true"/>
             <constant name="struts.devmode" value="true"/>
             <package name="loginmodel" extends ="struts-default">

        <action name="clientlogin"  class="action.client.Clientaction" >
           <interceptor-ref name="exception"/>
            <interceptor-ref name="i18n"/>
            <interceptor-ref name="fileUpload">
            <param name="allowedTypes">text/plain</param>
            <param name="maximumSize">10240</param>
        </interceptor-ref>
            <interceptor-ref name="params">
                <param name="excludeParams">dojo\..*,^struts\..*</param>
            </interceptor-ref>
            <interceptor-ref name="validation">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
            <interceptor-ref name="workflow">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>

            <result name="input">/Registration/clientregistration.jsp </result>
           <result name ="success">/Registration/success.jsp  </result>

          </action>

         </package>
</struts>

clientregistration.jsp
<%@ page language ="java" contentType ="text/html; charset=ISO-8859-1" pageEncoding ="ISO-8859-1"%>
<%@ taglib uri ="/struts-tags" prefix="s"%>
<%@ taglib uri ="/struts-dojo-tags" prefix="sx" %>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>

<sj:head jqueryui="true" jquerytheme="redmond" />

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>CLIENT</title>
<link rel="stylesheet" type="text/css" href="css/emp.css">

  CLIENT REGISTRATION FORM

  <s:form action ="clientlogin" method="post" enctype="multipart/form-data">

<s:select  name="Aggrement" label ="Type of Aggrement" list ="{'ORAL', 'written'}  "/>
<sj:datepicker  name="date" label="Aggrement DATE" changeMonth="true" changeYear="true"/>

 <s:select name ="rate" list="{'1','2','3'}" label ="Aggrement rate"/>
<s:textarea  name ="detail" label ="Aggrement Detail"></s:textarea>
 <s:textfield name ="taxno" label="Tax No "></s:textfield>
 <s:file name ="imagefile" label ="Upload Document"  />

 <s:submit align="center"></s:submit>
</s:form>

client dao is
package dao;

import java.sql.Blob;
import java.sql.SQLException;
import model.Clientmodel;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;

public class Clientdao {

java.sql.Connection connection =null;
PreparedStatement pst = null;
ResultSet rs =null;

private java.sql.Connection getConnection() throws SQLException{
    java.sql.Connection conn;
conn = Connectionfactory.getInstance().getConntection();
return conn;

}

public int registration(Clientmodel model){

    int i= 0;
   try{
      String str  = "insert into " + "clientdata(Aggrement,aggrementDate,rate,maturitydate,detail,taxno,image)"+
                     "values(?,?,?,?,?,?)";

       connection =getConnection();

   pst =(PreparedStatement) connection.prepareStatement(str);
     pst.setString(1, model.getAggrement());
     pst.setString(2, model.getDate());
     pst.setString(3, model.getRate());
     pst.setString(4, model.getMaturitydate());
     pst.setString(5, model.getDetail());
     pst.setString(6, model.getTaxno());
     pst.setBlob(7,(Blob) model.getImagefile());

     i = pst.executeUpdate();
     System.out.println("Result " +i);
   }
  catch (SQLException se){
    se.printStackTrace();
   }
   return i;

}
}

Comment: You can't do that in any case, a `File` is just a filesystem pointer. You need to actually _read_ the file.
Comment: Where is the exception ?
Comment: And your action class?
Comment: What is the stack trace of the exception?
Comment: It seems a real question to me (now, at least), voted for reopening. Btw your problem is that you need to read the File to obtain the bytes and inject it in the query, according to your database and to the library you are using to perform the insert (I use LobHandler with Spring, you will need to find another, more classic, way... search for this on google)
Answer: Implement the ModelDriven interface and return the object of overridden method to you model class in your Action class .


Nginx proxy doesn't work as expected

Question: I'm using dokku (small heroku) on host with nginx, my container is using apache and it's exposing port 8052.
This is configuration inside of .conf which is enabled and works fine:
LISTEN 8052
<VirtualHost *:8052>
    ServerAdmin veeenex@localhost

    DocumentRoot /var/www
    <Directory />
        Options +FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/>
        Options +FollowSymLinks +ExecCGI
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

    FCGIWrapper /phpfarm/inst/php-5.2/bin/php-cgi .php
    AddHandler fcgid-script .php

    LogLevel warn
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

And this is configuration on host
upstream katalog.domain.eu {
  server 172.17.0.3:8052;
}

server {
  listen      [::]:80;
  listen      80;
  server_name katalog.domain.eu;
  access_log  /var/log/nginx/katalog.domain.eu-access.log;
  error_log   /var/log/nginx/katalog.domain.eu-error.log;

  location    / {
    proxy_pass  http://katalog.domain.eu;
    proxy_http_version 1.1;
    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Proto $scheme;
    proxy_redirect http://172.17.0.3:8052 https://katalog.domain.eu;

  }

  include /home/dokku/katalog.domain.eu/nginx.conf.d/*.conf;
}

It's working  - because I can see the website on http://katalog.domain.eu, but if you click on any form, that makes action (POST,...) url like http://katalog.domain.eu/index changes to http://katalog.domain.eu:8052/index
I've already tried different proxy_set_headers but none of them worked.
I don't want to open another port on server, to fix this.
Comment: If it is a redirect causing this, you may need to add more proxy_redirect rules. See [this document](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_redirect) for details.
Comment: You appear to be over-using the name `katalog.domain.eu` in the nginx config. Use a simpler name for the `upstream`.
Answer: You need to check the page where the form is located, and see what is the URL where it makes the POST request in it.
If that is http://katalog.domain.eu:8052, you need to change the application generating that page so that it generates the correct URL.
proxy_redirect changes only the Location and Refresh HTTP headers in the proxied response. It does not change anything in the actual content of the response. This is because the actual content could be anything (HTML, XML, binary data etc.), and running search & replace operations on it is practically impossible.
Comment: Url is relative like `/index`. I'll try changing all urls to `http://katalog.domain.eu/index`

Nginx proxy doesn't work as expected


Casting object to type without generics

Question: public class ErrorCode
{
    public int HttpStatus { get; private set; }
    public string JsonErrorCode { get; private set; }
    public Type ExceptionT { get; private set; }

    public ErrorCode(string pJsonErrorCode, int pHttpStatus, Type pExceptionType)
    {
        this.HttpStatus = pHttpStatus;
        this.JsonErrorCode = pJsonErrorCode;
    }

    public void ThrowException(string pMsg)
    {
        throw Activator.CreateInstance(ExceptionT, pMsg);
    }
}

So, as you can see i am trying to create an instance of the given type. I cannot use Generics. because i have a dictionary that creates a pool of error codes.
Protocol.ErrorCodes.Add
(
    ErrorCodeType.ElementClickIntercepted,
    new ErrorCode
    (
        "element click intercepted",
        400,
        typeof(ElementClickInterceptedException)
    )
);

The above code doesn't work since the type being created is of type object and does not derive from system.exception
The above code won't work with generics since the dictionary needs to understand what is being built. I am not sure what to do here. my dictionary has about 50 different exceptions. Thoughts?
Comment: You could use an interface, and use generics in the actual implementations of the interface... then your dictionary could be defined as `Dictionary` (where `IErrorCode` is an interface)
Answer: You need to cast the instance created to Exception
public class ErrorCode
{
  public int HttpStatus { get; private set; }
  public string JsonErrorCode { get; private set; }
  public Type ExceptionT { get; private set; }

  public ErrorCode(string pJsonErrorCode, int pHttpStatus, Type pExceptionType)
  {
    this.HttpStatus = pHttpStatus;
    this.JsonErrorCode = pJsonErrorCode;
    this.ExceptionT = pExceptionType;
  }

  public void ThrowException(string pMsg)
  {
    throw (Exception)Activator.CreateInstance(ExceptionT, pMsg);
  }
}

You can replace Exception by ElementClickInterceptedException or anything needed.
Test
var error = new ErrorCode("test", 1, typeof(ArgumentException));
try
{
  error.ThrowException("error");
}
catch ( Exception ex )
{
  Console.WriteLine(ex.Message);
}

Fiddle Snippet
Output
error

Comment: This does not work because it will cast it as an exception and not a ElementClickInterceptedException
Comment: So you can use ElementClickInterceptedException instead if it inherits from some Exception.
Comment: yes but the object doesn't know about ElementClickInterceptedException. The question states that i have a ton of exceptions to deal with.
Comment: At first glance, there is no solution to this thing since the throw keyword requires an instance of exception type and you can not dynamicaly cast the CreateInstance result, from what I know, unless you use generics.
Answer:
I cannot use Generics. because i have a dictionary that creates a pool of error codes.

Yes, you really can, and it is the right solution. You just need to declare a base interface for your lookup dictionary.
public interface IErrorCode
{
    int HttpStatus { get; }
    string JsonErrorCode { get; }
    void ThrowException(string pMsg);
}

public class ErrorCode<T> : IErrorCode where T : Exception
{
    public int HttpStatus { get; private set; }
    public string JsonErrorCode { get; private set; }

    public ErrorCode(string pJsonErrorCode, int pHttpStatus)
    {
        this.HttpStatus = pHttpStatus;
        this.JsonErrorCode = pJsonErrorCode;
    }

    public void ThrowException(string pMsg)
    {
        var exception = (T)Activator.CreateInstance
        (
            typeof(T),
            new object[] { pMsg }
        );
        throw exception;
    }
}

//Declare the dictionary with the interface, not the concrete type
Protocol.ErrorCodes = new Dictionary<ErrorCodeType,IErrorCode>();

Protocol.ErrorCodes.Add
(
    ErrorCodeType.ElementClickIntercepted,
    new ErrorCode<ElementClickInterceptedException>
    (
        "element click intercepted",
        400
    )
);

If you need to work with any element in the list, you can use the interface-- you should not have to cast anything.
To get the HTTP status:
var status = Protocol.ErrorCodes[key].HttpStatus;

To get the Json error code:
var errorCode = Protocol.ErrorCodes[key].JsonErrorCode;

In general your code should not be depending on concrete instances but on interfaces (per the "D" in SOLID).
Comment: The pointing of adding to the interface is so that you do not have to cast. I've edited the example to illustrate.
Comment: This does not work for me, as i have functions returning errorcode objects, where i dont know what interface to give to the generic type. This also casts everything as an exception. So when throwing errors it just throws exceptions instead of ElementClickInterceptedExceptions.
Comment: public static ErrorCode GetErrorCode(ErrorCodeType pType)
        {
            Protocol.ErrorCodes.TryGetValue(pType, out ErrorCode errorCode);
            return errorCode;
        }
Comment: Notice how this function returns an error code based on the key. Well, i very well can't return the value while knowing the key and its exception
Comment: Add `ErrorCode`, and anything else you need, to the common interface.
Comment: this doesn't solve the issue of... well there is no point in adding the interface since you are casting everything as its parent object.

Casting object to type without generics


how to remove the contents of a column without deleting the column

Question: I am trying to delete the contents of a column but would like to keep the column.
For instance I have a table like.

Numbers1
Numbers2
Numbers3
Numbers4
Numbers5

five
four
three
two
two

six
seven
eight
nine
ten

nine
seven
four
two
two

seven
six
five
three
one

I would like to remove all the contents of column b but I want to keep column Numbers2
the desired output be like

Numbers1
Numbers2
Numbers3
Numbers4
Numbers5

five

three
two
two

six

eight
nine
ten

nine

four
two
two

seven

five
three
one
Answer: try:
df['Numbers2']=''  #empty string

df['Numbers2']=np.nan #nan

Answer: Simply assign an "empty" value (NaN, empty string, None, whatever you want):
df['Numbers2'] = float('NaN')

output:
  Numbers1  Numbers2 Numbers3 Numbers4 Numbers5
0     five       NaN    three      two      two
1      six       NaN    eight     nine      ten
2     nine       NaN     four      two      two
3    seven       NaN     five    three      one

With empty string:
df['Numbers2'] = ''

  Numbers1 Numbers2 Numbers3 Numbers4 Numbers5
0     five             three      two      two
1      six             eight     nine      ten
2     nine              four      two      two
3    seven              five    three      one

Answer: update it with a empty string
df['Numbers2']=""

Answer: First, you could delete the column with df = df.drop('Numbers2', axis=1)
Second, replace the column with df['Numbers2'] = ""


Complex sql query: grab multiple IDs from tableOne based on field from tableTwo, update into tableTwo

Question: in a quandary here..
I've got one table, let's call it bookshelves. The table has these fields:
[shelf_id, title, latest_books]
Then I've got a table for books with the fields:
[book_id, shelf_id, title, date_added]
Each book is assigned to a shelf. Here's what I want to do...
for every bookshelf, look in books for books assigned to that bookshelf, grab the book_id from those books and feed them into the bookshelves field 'latest_books' separated by commas. To complicate things further(?) I only want five book_id's per shelf. I could do with just one from each if that made it easier..here's the query I can use to manually do this one by one:
update bookshelves
set latest_books =
    (select book_id from books
        where shelf_id = 1
        order by date_added DESC
        limit 0,1)
where shelf_id = 1;

Both the bookshelves and books tables have tens of thousands of records so..I can do it one by one but I'll be at it all year.
I'm working in MySQL on CentOS. I'm cool using scripting or whatever.
Answer: Okay so I figured it out..it helped to type it out in detail here...
I exported the bookshelves ids to a csv then put them into an array in a bash script.
shelves=(
1
...
...
99999
)

for i in "${shelves[@]}"
do
        query='update bookshelves set latest_books = (select book_id from books where shelf_id = '$i' order by date_addet desc limit 0,1) where latest_books = "" and shelf_id = '$i' ;'
        mysql -uxxxx  -pxxx database_name -e "$query"

done

Ran the script on a test db a couple times and looks to have done what I needed.


Definition of pull back operation

Question:
Let $\varphi:U \rightarrow V$ be a differentiable map between open sets $U \subset \mathbb{R}^n$ and $V \subset \mathbb{R}^m$. Define the pull back operation $\varphi^*: \Omega^{k}(V) \rightarrow \Omega^k(U)$.

I said this is just
$$\varphi^*\omega = \sum_{1 \leq i_1<\cdots < i_k \leq m}c_{i_1, \cdots i_k}(f_1(x_*), \cdots f_m(x_*)) df_{i_1} \wedge \cdots \wedge df_{i_k} \in \Omega^k(U)$$
where $x_* = (x_1, \cdots x_n)$.
Is this correct?
Comment: Whether it's correct depends on how $\varphi$ and $\omega$ are related to the (subscripted) $c$'s and $f$'s.
Comment: $c$'s are constants and $f$'s are multivariable functions. Like that?
Answer: The best way is to start by the definition. Let's begin with $1$-forms so that we can understand what's the reasoning behind it. Recall that $\omega \in \Omega^1(U)$ is simply a way to associate at each point a linear function of one single vector. In other words if $p \in U$ then $\omega(p) \in T^\ast_p U$. Our problem is: $\varphi$ transforms $U$ into $V$, is there a way to produce one-forms on $U$ from those at $V$? In other words, how could we transform the forms back, pull them back. The idea is pretty straightforward: we already now that $\varphi_\ast$ (the pushforward) pushes the vectors to the corresponding tangent space at $V$, so the most possible reasonable way to define this pullback operation is by setting:
$$\varphi^\ast(\omega)(v)=\omega(\varphi_\ast(v))$$
In other words: the action of the 1-form $\varphi^\ast(\omega)$ on some vector $v \in T_pU$ is the same as the action of $\omega \in \Omega^1(V)$ on the pushed vector. Think a bit about it, there's a natural correspondence between the vectors on each tangent space, and this natural correspondence induces a natural correspondence between the 1-forms.
Now for $k$-forms. Recall that a $k$ form $\omega \in \Omega^k(U)$ is an association of an alternating $k$-tensor at each point of $U$. In that sense, for each $p \in U$, $\omega$ associates one alternating function of $k$ vectors $\omega(p)$. So, we use the same reasoning, we push the $k$ vectors to the corresponding tangent space at $V$ and apply the form there (since we know the form there). This is simply:
$$\varphi^\ast(\omega)(v_1, \dots, v_k)= \omega(\varphi_\ast(v_1), \dots, \varphi_\ast(v_k))$$
So this is the pullback you want with motivations on the way. At each point $p \in U$ the field $\varphi^\ast(\omega)$ will associate a function of $k$ vectors. We know how to apply $\omega(\varphi(p))$, so what we do? We push the vectors to $T_{\varphi(p)} V$ and and apply $\omega(\varphi(p))$ on the pushed vectors. Now you can compute it in terms of local coordinates using the expression of the pushforward in local coordinates.
From your question I didn't understand if you wanted the definition or the expression in local coordinates. By the way this is the definition. Anything more I can help you let me know. Good luck!
Obs: these are very good notes to read about it.
EDIT: About the equation provided in the question. There are a few relations that can be proved rather easily directly from the definition of the pullback made above. If $\varphi : U \to V$ is a smooth map and if $\omega, \omega_1, \omega_2  \in \Omega^k(V)$ and if $f : V \to \mathbb{R}$ then we have:

$\varphi^\ast(\omega_1 + \omega_2) = \varphi^\ast(\omega_1)+\varphi^\ast(\omega_2)$
$\varphi^\ast(f\omega) = (f\circ \varphi)\varphi^\ast(\omega)$
$\varphi^\ast(\omega_1 \wedge \omega_2) = \varphi^\ast(\omega_1) \wedge \varphi^\ast(\omega_2)$

Also if $y^i : V \to \mathbb{R}$ are the coordinate functions on $V$, we have:

$\varphi^\ast(dy^i) = d\varphi^i$

Now consider that the coordinate functions of $\varphi$ are $f^i$ and that we have $\omega \in \Omega^k(V)$ given by:
$$\omega = \sum_{i_1 < \cdots < i_k}{c_{i_1 \dots i_k}dy^{i_1}\wedge \cdots \wedge dy^{i_k}}$$
Apply the pullback to this thing and use properties 1 - 4, you'll get:
$$\varphi^\ast \omega = \sum_{i_1 < \cdots < i_k}{(c_{i_1 \dots i_k}\circ \varphi)df^{i_1}\wedge \cdots df^{i_k}}$$
And since the coordinate functions of $\varphi$ are $f^i$ this is rewritten as what you gave at first:
$$\varphi^\ast \omega (p) = \sum_{i_1 < \cdots < i_k}{c_{i_1 \dots i_k}(f^1(p), \dots, f^m(p))df^{i_1}\wedge \cdots \wedge df^{i_k}}$$
Recalling just that $\varphi^\ast$ is a function defined on $U$ and letting the ranges of the indices be understood in context. Also look on the properties being used: first we use 1 and put the pullback inside the sum, then we use 2 and compose the coordinate functions of $\omega$ with $\varphi$, then we use 3 to write the pullback of that whole wedge product as the wedge product of the pullbacks and finally we use 4 to write the pullback of each differential of coordinate as the differential of the corresponding coordinate of $\varphi$.
I hope this helps you out. Good luck!
Comment: So what exactly does my formula show? Because I don't have all this written in my lecture notes, just that formula.
Comment: I've added an edit explaining how to derive the formula. There's the need to use a few properties. Prove then before deriving the formula yourself, you'll get a lot of practice working with differential forms.

Definition of pull back operation


Rewrite Rule from Apache to Nginx

Question: Can anyone help me with rewriting this?
I have these rules:
    RewriteCond %{HTTP_USER_AGENT} baiduspider|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|showyoubot|outbrain|pinterest [NC,OR]
    RewriteCond %{QUERY_STRING} _escaped_fragment_
    RewriteRule ^(?!.*?(\.js|\.css|\.xml|\.less|\.png|\.jpg|\.jpeg|\.gif|\.pdf|\.doc|\.txt|\.ico|\.rss|\.zip|\.mp3|\.rar|\.exe|\.wmv|\.doc|\.avi|\.ppt|\.mpg|\.mpeg|\.tif|\.wav|\.mov|\.psd|\.ai|\.xls|\.mp4|\.m4a|\.swf|\.dat|\.dmg|\.iso|\.flv|\.m4v|\.torrent))(.*) /api/prerender/$2 [P,L]

And I need that to be rewritten to nginx.
Basically, let's assume this URL
http://example.com/?_escaped_fragment_=/item/123

should be rewritten to
http://example.com/api/prerender/?_escaped_fragment_=/item/123

I hope you understand.
Answer: Try:
location / {
  if ($http_user_agent ~* "baiduspider|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|showyoubot|outbrain|pinterest") {
    rewrite ^/(?!.*?(\.js|\.css|\.xml|\.less|\.png|\.jpg|\.jpeg|\.gif|\.pdf|\.doc|\.txt|\.ico|\.rss|\.zip|\.mp3|\.rar|\.exe|\.wmv|\.doc|\.avi|\.ppt|\.mpg|\.mpeg|\.tif|\.wav|\.mov|\.psd|\.ai|\.xls|\.mp4|\.m4a|\.swf|\.dat|\.dmg|\.iso|\.flv|\.m4v|\.torrent))(.*) /api/prerender/$2 break;
  }
}

Rewrite Rule from Apache to Nginx


Recuperar variável de URL e repassar em AJAX

Question: Gostaria de saber se tem como após recuperar uma variável da URL passar para outra página e retornar o resultado em um load. Estou usando o seguinte script que recupera normalmente a variável, mas não passa para página seguinte. É apenas para entenderem melhor o que preciso.
Na URL http://noticias.php?categoria=23, pego a variável normalmente mas no load vem a informação que a página resposta.php não recebeu a variável.  Gostaria de passar para outra página antes de mostrar o resultado no load. Qual seria a forma correta?
$(document).ready(function()
{
    $('#teste').html("");
    var variaveis=location.search.split("?");
    var quebra = variaveis[1].split("=");
    var categoria = + quebra[1];
    var URL='resposta.php';
    var dataString = 'categoria=' + categoria ;

    $.ajax({
        type: "POST",
        url: URL,
        data: dataString,
        cache: false,
        success: function(html){
            $('#teste').load('resposta.php');
        }
    });
});
</script>

Comment: usa o window.location pra vc receber os parametros
Comment: receber estou recebendo eu preciso reenviar antes de mostrar o resultado no load
Answer: A forma correta de enviar para o parâmetro data é desta forma.
Jquery
$.ajax({
    type: "POST",
    url: URL,
    data: categoria,
    cache: false,
    success: function(html){
       $('#teste').load('resposta.php');
    }
});

ou em formato de um Array
Jquery
$.ajax({
    type: "POST",
    url: URL,
    data: { meuVar : categoria },
    cache: false,
    success: function(html){
       $('#teste').load('resposta.php');
    }
});

E no PHP receberia desta forma
PHP
$categoria = $_POST["meuVar"];

Answer: Não sei se isso tbm ajuda, mas da para passar o valor por get com o $.ajax assim:
var URL='resposta.php?'+dataString;

$.ajax(
{
url: URL,
cache: false,
success: function(html){
    $('#teste').load('resposta.php');
}
});

Se não me engano, pode tirar o type do $.ajax pq por padrão ele já trabalha com GET.


theming username field in user-register form

Question: i'm trying to theming my user register form. i would like to have a custom function for the username part. So, i'm doing
<code>$form['account']['name']['#theme'] = 'my_custom';
</code>
i define my hook_theme and just for testing purpouses, this is my custom function
<code>function theme_my_custom( $variables ){
  return 'testing code...'
}
</code>
My problem is when i go to user/register, i still can see the label for my username. Only the input is replaced by the code of my function. I would expect replace the element entirely, but this is not happening.
Any clues? Thanks.
Answer: As you can see on the Form API reference page, '#theme' Only affects the input box itself. To remove other things generated by the form API, you'll have to clear the array -
<code>$form['account']['name']['#title'] => '';
$form['account']['name']['#description'] => '';
</code>
or just
<code>$form['account']['name'] = array(...);
</code>
To reset existing elements.
Answer: or you may use #after_build property for your form elements.


Proving that for p.d. matrices A and B that $\|A(A+B)^{-1}\|_2<1$

Question: Let $A$ and $B$ be positive definite real matrices. It seems obvious to me that it should be true that
$$\|A(A+B)^{-1}\|_2<1.$$
My heuristic argument is that
$$\|A(A+B)^{-1}\|_2< \|A(A+\lambda_{\min}(B) I)^{-1}\|_2 = \max\left\{\frac{\lambda_i(A)}{\lambda_i(A)+\lambda_{\min}(B)}\right\}<1.$$
However, I'm not able to justify the first inequality.
Answer: This is actually false. If $\|x\|=1$, then
$$
\|A(A+B)^{-1}x\|^2 = \langle A(A+B)^{-1} x, A(A+B)^{-1} x \rangle =\langle x,
(A+B)^{-1}A^2(A+B)^{-1} x \rangle \\
= 1 - \langle y, ((A+B)^2 - A^2 ) y \rangle ,
$$
with $y=(A+B)^{-1}x$. So your claim is equivalent to $(A+B)^2-A^2$ being a positive definite matrix, and this will not follow from your assumptions.
The key fact is that the function $t\mapsto t^2$ is not operator monotone (there used to be a Wikipedia article on this, which I don't seem to be able to locate).
Comment: So if I add the assumption that $A$ and $B$ are symmetric, then $AB$ is positive semidefinite and my statement is true. Since $(A+B)^2-A^2 = B^2 +2AB$, where $B^2$ is positive definite and $AB$ has no negative eigenvalues by http://math.stackexchange.com/a/113859/10117. Do you agree?
Comment: No. You already assumed that $A,B$ are symmetric (as part of positive definite). Please read up on "operator monotone functions."


Pegar o valor do atributo "data-" com jquery

Question: Boa tarde, estou fazendo uma atividade de html + js(com jquery), preciso pegar o valor do atributo "data-" quando o botão for clicado. Segue o código:
html:

      Foto
      Produto
      Descrição
      Tipo
      Alocação
      Quantitativo

      Luva
      feitos para usar individualmente
      EPC
      Prateleira 2/Linha 1
      <button type="button" class="quantitative-btn">Ver Quantitativo</button>

      print
      345tyuiop
      EPC
      Prateleira 1/Linha 1
      <button type="button" class="quantitative-btn">Ver Quantitativo</button>

js:
$(() => {
  $(document).on('click', '.quantitative-btn', (e) => {
    e.preventDefault();
    var id = $(this).parent().parent().find('td').data('name');
    alert(id);
  });
});

Quando o botão é clicado, ele aparece "null". Como posso resolver isso?
Answer: Você pode tentar:
$('.quantitative-btn').on('click', function(){
     var name = $(this).parent().data('name');
     alert(name);
});

Comment: Amigo, eu testei aqui e funcionou
Resultado: https://snipboard.io/G0BibL.jpg
Codigo: https://snipboard.io/rCMa1R.jpg
Comment: Tinha esquecido de apagar o cache da página na atualização, mas obrigado, funcionou.
Comment: disponha amigo.
Comment: Olá Allex, no alert ele retorna "Undefined"...


Probabilities and joint pdf

Question: I'm supposed to compute $P(Y>1/2)$ for the joint pdf
$$f_{X,Y}(x,y)=\begin{cases}12(y-x^2),&0<x<y<1\\0,&\text{elsewhere.}\end{cases}$$
and  figured that I can do this if I use the given information by rewriting it as $P(1/2 < Y < 1),$ which would allow me to solve the problem by integration.
$$12\int_{0.5}^1\left[\int_{0.5}^y\big(y-x^2\big)\,dx\right]dy=0.5625.$$
Firstly, I'm not sure if I've gotten the integral right. Secondly, I believe this solves for
$P(1/2 ≤ Y ≤ 1),$ not $P(1/2 < Y < 1).$ Can someone help me clarify this problem?
Comment: Please add the [tag:self-study] tag & read its
[wiki](https://stats.stackexchange.com/tags/self-study/info). Then tell us what you understand thus far, what
you've tried & where you're stuck. We'll provide hints to
help you get unstuck. Please make these changes as just
posting your homework & hoping someone will do it for you
is grounds for closing.
Answer: Your density function is not normalized, since
$$12\int_{0}^1\left[\int_0^y\big(y-x^2\big)\,dx\right]dy=3.$$
You need to divide by $3$ to get a normalized density function, which would be
$$f_{X,Y}(x,y)=\begin{cases}4(y-x^2),&0<x<y<1\\0,&\text{elsewhere.}\end{cases}$$
Your integral is incorrect, because $x$ has to be allowed to vary all the way from $0$ to $y,$ based on the density definition. To compute your desired probability, you need to calculate
$$4\int_{0.5}^1\left[\int_0^y\big(y-x^2\big)\,dx\right]dy=0.854167.$$
Comment: Well, thats a detail that I wouldnt have figured out, thanks Adrian.

Probabilities and joint pdf


Como resolver conflito de merge automaticamente, sem precisar editar os arquivos manualmente?

Question: Primeiro vou mostrar o cenário atual, e em seguida a tentativa de merge e explicação do problema:
Montagem do cenário
Tenho um arquivo (arq.txt) contendo uma linha (abc), devidamente commitado.
Fiz uma alteração adicionando outra linha, e agora o arquivo ficou assim:
abc
def

Fiz o commit, e o repositório ficou assim:
$ git log --format=oneline --decorate
8b0d355e7187765df9e9bb4b91a8d87966c3783d (HEAD -> master) segundo commit
f1b3dcbae69f2fdf95487f0a8bf76a5c16c8690d primeiro commit

Ou seja, no primeiro commit, o arquivo só tinha abc, e no segundo commit eu adicionei a linha def:
$ git diff f1b3dcb 8b0d355
diff --git a/arq.txt b/arq.txt
index f2ba8f8..85137a6 100644
--- a/arq.txt
+++ b/arq.txt
@@ -1 +1,2 @@
-abc
\ No newline at end of file
+abc
+def
\ No newline at end of file

Depois criei um branch, a partir do primeiro commit:
$ git branch feature f1b3dcb
$ git checkout feature # ou git switch feature, para Git >= 2.23.0

Assim, o conteúdo do arquivo passou a ser novamente abc. Então adicionei outra linha:
abc
feature

Fiz o commit e agora temos:
$ git log --format=oneline --decorate
1db4fecea229b9d63f52a22e86e2a38c438fc9f1 (HEAD -> feature) adicionar feature
f1b3dcbae69f2fdf95487f0a8bf76a5c16c8690d primeiro commit

Tentativa de merge
Em seguida, voltei para o branch master e tentei fazer o merge com o branch feature, mas deu conflito (pois ambos alteram a mesma linha do arquivo):
$ git checkout master
$ git merge feature
Auto-merging arq.txt
CONFLICT (content): Merge conflict in arq.txt
Automatic merge failed; fix conflicts and then commit the result.

Como resultado, o arquivo arq.txt ficou assim:
<<<<<<>>>>>> feature

Eu sei que posso resolver assim e assim (ou seja, editando o arquivo e fazendo o commit em seguida).
Mas a pergunta é: tem como resolver o conflito automaticamente, sem precisar editar o arquivo manualmente?
Comment: E mais uma vez, antes que alguém estranhe que eu mesmo respondi minha própria pergunta, isso é [**perfeitamente aceitável e dentro das regras**](/help/self-answer). Inclusive, a [página de fazer pergunta](/questions/ask) tem uma [opção para postar a própria resposta junto com a pergunta](https://i.stack.imgur.com/gPEQw.png). Claro que se alguém tiver outra solução, com certeza deve postá-la. O objetivo é trazer este conhecimento para o site (pois fiz uma busca e até encontrei coisas relacionadas, mas nada explicando em detalhes as opções da resposta abaixo).
Comment: já que respondeu, poderia marcar como aceita :-), ou espera alguma mais completa?
Comment: @Danizavtz O sistema só deixa  aceitar minha própria resposta depois de dois dias. Independente disso, se alguém tiver outra solução, pode postar sem problemas
Comment: @Danizavtz E só pra deixar claro, se outra resposta for melhor, mais completa, etc, a aceitarei sem problemas (afinal, esse é o critério para aceitação, independente de quem postou). Eu respondi com base no que conheço (é assim que eu resolveria o problema), mas como eu não sei tudo, claro que pode aparecer alguém com uma solução melhor (inclusive, gostaria muito que aparecesse). Afinal, essa é - pelo menos espera-se - a grande vantagem de sites como esse, aproveitar o conhecimento coletivo e aprender com ele.
Answer: Você pode alterar as opções de estratégia do merge. A documentação explica todas as possibilidades, mas neste caso poderíamos escolher se vou ficar com a versão que está no master (segunda linha contém def) ou no branch feature (segunda linha contém feature), usando a opção --strategy-option (ou o equivalente -X).
Por exemplo, se eu escolher ficar com a versão que está no master (segunda linha do arquivo será def, ignorando a alteração feita no branch feature), basta fazer:
git merge feature --strategy-option=ours

# ou
git merge feature -X ours

Mas se eu quiser a versão que está no branch feature (segunda linha do arquivo será feature, ignorando a linha def do branch master):
git merge feature --strategy-option=theirs

# ou
git merge feature -X theirs

Basicamente, como estou no branch master fazendo merge com o feature, então "ours" indica a versão do master, enquanto "theirs" indica a versão do branch que estou mergeando (no caso, o branch feature).
Com isso, não aparece mais a mensagem de conflito e o merge é concluído sem erros.

Se eu quiser que o arquivo contenha ambas as alterações (tanto a linha contendo def quanto a linha contendo feature), aí não tem jeito, tenho que tentar fazer o merge para causar o conflito e depois editar o arquivo manualmente. E na minha opinião faz sentido, pois se dois branches diferentes alteraram o mesmo arquivo no mesmo lugar, talvez não seja uma boa ideia juntar ambas as alterações automaticamente.
Pode até ter situações em que faça sentido, mas por experiência própria eu diria que na grande maioria dos casos é melhor revisar manualmente esses trechos. Afinal, se for para juntar, qual linha deveria vir antes? Ou ambas seriam juntadas em uma linha só? Em qual ordem? Etc. Vale lembrar que isso é diferente de ter alterações em pontos diferentes do arquivo, pois ao se fazer o merge nesses casos, seria "óbvio" que ambas devem estar no resultado final (e nestes casos nem teria conflito). Mas estamos falando do caso em que houve duas alterações distintas na(s) mesma(s) linha(s).
O Git (ao menos na versão atual) não fornece uma maneira de fazer isso automaticamente, e o jeito é você mesmo resolver o conflito (olhando e editando o arquivo) antes de proceder com o merge.

Evidentemente, isso é para os casos mais simples, como o citado na pergunta. Para situações mais complicadas, a documentação cita as várias outras alternativas (por exemplo, se um branch só adicionou espaços no final de uma linha, há opções para ignorar; se deve considerar ou ignorar arquivos renomeados; etc). Mas quanto a resolver conflitos automaticamente, sem precisar editar o arquivo, as soluções ficam restritas às opções ours e theirs.

Atenção: não confundir a opção ours com a estratégia ours.
Na solução acima, eu usei a opção (tanto que na linha de comando eu uso --strategy-option=ours). Mas existe também a estratégia (--strategy=ours). A diferença é que a estratégia nem sequer olha para o que o outro branch fez.
Por exemplo, vamos supor que, além de ter modificado o arquivo arq.txt, o branch feature também adicionou outro arquivo (other.txt).
Se fizermos o merge com a opção ours (git merge feature --strategy-option=ours), a resolução do conflito usará a versão do arquivo arq.txt que está no master (ou seja, a segunda linha é def), e o arquivo other.txt será adicionado ao master (afinal, não houve conflito para este arquivo, então usa-se o que estava no branch feature).
Mas se fizermos o merge com a estratégia ours (git merge feature --strategy=ours), o arquivo arq.txt também ficará como está no master (ou seja, a segunda linha é def), mas o arquivo other.txt não será adicionado ao master. Isso porque a estratégia ours ignora as alterações feitas no outro branch.
Já o theirs é somente uma opção, pois não existe uma estratégia com o mesmo nome (ou seja, só pode ser usado com --strategy-option).

Relacionado:

Como efetuar PULL mantendo as alterações do HEAD?
Existe alguma forma forçar a sobrescrita do stash em cima das modificações atuais?


Explanation of Interpolate Hermite method

Question: I've currently got this bounty running on how to resample audio data with the intention of increasing the pitch.
Many solutions have been made and I have to admit I'm feeling a bit overwhelmed by the choices and information.
I was directed to this solution and found this chunk of code:
public static float InterpolateCubic(float x0, float x1, float x2, float x3, float t)
{
    float a0, a1, a2, a3;
    a0 = x3 - x2 - x0 + x1;
    a1 = x0 - x1 - a0;
    a2 = x2 - x0;
    a3 = x1;
    return (a0 * (t * t * t)) + (a1 * (t * t)) + (a2 * t) + (a3);
}

public static float InterpolateHermite4pt3oX(float x0, float x1, float x2, float x3, float t)
{
    float c0 = x1;
    float c1 = .5F * (x2 - x0);
    float c2 = x0 - (2.5F * x1) + (2 * x2) - (.5F * x3);
    float c3 = (.5F * (x3 - x0)) + (1.5F * (x1 - x2));
    return (((((c3 * t) + c2) * t) + c1) * t) + c0;
}

This seems like something simple enough that I can wrap my head around, but I'm wondering how I input the amount I would want to increase my pitch by. Which leads me to the following questions:

The t argument of the first method takes a number between 0 and 1. Is this the factor by which I increase the pitch? Would that make 1 an increase of pitch of %100 (essentially double the speed)?.
If the above theory is correct am I able to input a factor of more then 1? If not, how would I be able to do this?
If by stating the above I've clearly shown that I'm totally off track would someone please help clairfy how I control the amount of increase in pitch using this method?

Thank you so much.
Answer: These are functions that do the following: Given a discrete sequence of samples, interpolate smoothly between them. That is: suppose your original data is x(0), x(1), x(2), etc. You want (let's say) to make it 1.234 times faster. Then you want samples x(0), x(1/1.234), x(2/1.234), x(3/1.234), etc. And you want these to look like samples from a nice smooth signal that goes through the sample points you have.
Both of these functions should be used as follows. You want to interpolate between x(n) and x(n+1). To get a value you can call x(n+t), call them with arguments x(n-1), x(n), x(n+1), x(n+2) and t. When t=0 you'll get x(n); when t=1 you'll get x(n+1); you shouldn't (except maybe at the ends of your data) use arguments that aren't between 0 and 1.
So, to speed up or slow down your signal, sample at times [integer]/[speed factor]; for each time t, take n-1,n,n+1,n+2 such that n <= t <= n+1, and call the interpolator with values x(n-1),x(n),x(n+1),x(n+2) and t-n. And see how it sounds :-).
Comment: Better than I could say it myself.
Answer:
Interpolation is a way to find new data points between discrete values.
The diagram above shows five values. X0, X1, X2, X3, X4. The values are for these five points are known. The in-between values aren't known and can only be approximated by interpolating from the known data points. Different interpolation algorithms will give different results.
For example, to find the value of the red dot (shown between the X1 and X2 values) we can use interpolation. The t specifies the point you wish to find. t will always be a value between 0 and 1. In this case t will be approximately 0.25.
The simplest interpolation method is linear interpolation. It is essentially the same as drawing a straight line between two points.
Linear Interpolation
y = x1 + (x2 - x1) * t

Cubic interpolation and hermite interpolation both function similary to linear interpolation except they use more data points to calculate curves instead of straight lines.
To understand what these functions are doing, it could be helpful to plot the functions in a graphing application.
To answer your questions:

t has no relationship to pitch. It specifies the location of the in-between point the interpolation algorithm will calculate the value for.
NA.
These functions calculate values between discreet points. By themselves they do not pitch shift audio but they could be used in the algorithm that does.


How do we record and sync four multiple audio tracks for a video?

Question: I and my friends are thinking about doing a podcast on YouTube, but the main problem is that we want a clear audio and can't use the different collar mic because that would be hectic to arrange those multiple audios with the video and it is the whole lot of work. So, if you have any solution about that please do tell.
Comment: Producing good quality audio for video is a lot of work. That's a bit like a law of nature for creative works: the best ones usually show the most effort. You could have one mic for all four people but it seems like you are aware that it won't sound as good.
Comment: Why not record them simultaneously?
Answer: You need a camera that can send and sync with SMPTE time-code, and a four track recorder that also has time-code syncing (you may be able to do this in a DAW). The time-code is embedded in the video and all audio tracks, allowing you to have coordinated playback. The tracks will still have to be mixed before publishing.
edit:
Thinking about it, and as Todd commented about simplicity, another option that doesn't require any mic setup is the current generation of cameras with high definition audio and multi-track recording built in, such as the "Zoom Q8".  I'm not recommending that particular product, but as an example of the class. I have used a smaller version for filimg students for youtube, and the omni-directional setting on the mic picks up the whole room very well, and the products are audio based, unlike some cameras that have awful built in sound.
You don't have any control of the mix, so what you get is what you get, but may be fine for a pod cast, depending on the scope of the project.
Comment: This might be overkill for a podcast. Just a mixer and four lav mics going to the mixer and then the output of the mixer going into the camera input would be fine. The reason why I didn't post that as an answer is, "[we] *can't use the different collar mic because that would be hectic to arrange those multiple audios with the video and it is the whole lot of work*", which to me is like saying, "we want to do something without having to do it".
Comment: ... or a clapper & manual sync ;)
Comment: Sure it's probably overkill, but the advantage to using timecode is that the mixing can be done after the recording and everything will still sync up. Mixing live into a  camera requires either setting up the mixer levels well and hoping for the best, or having an extra person monitor the levels.  Timecode generation is the easiest way to do post production on video, but does require either a timecode generator, or hardware and software that works well with each other.
Comment: And I found more info on timecode than probably necessary: https://soundrolling.com/timecode/
Comment: Everything will only sync up if the software supports it and you use a timecode standard that is supported by the software and you use the same timecode standard on all devices. Manual clapper sync relies on matching playback rates of the video and audio, which would *seem* to be a given but can actually be a problem because editing software can interpret playback rates differently. Setting the camera for 24 fps video and 48 kHz audio and then recording separately at 48 kHz with a manual clapper (which could literally just be a hand clap) might be the best bet.
Comment: Regarding sync, using audio software that supports a video track may be more successful than using video software that supports audio tracks because the required editing resolution for video is a frame (perhaps 1/60th of a second) while the editing resolution for audio could be as fine as one sample (max. 1/44100th of a second). Without getting into details of specific software, audio software is more likely to have the finest sync resolution.
Comment: There are hardware timecode generators that you can attach to cameras now, apparently. Timecode data format is included in .wav files, so most audio software has the ability to use it.  ProTools, for example uses it for video, but the software doesn't generate it.  Rather than a hand clap, why not a metronome?
Answer: You don't need anything complicated here; this is YouTube 101.
If you're recording audio separately from the video, start everything recording -- including the on-camera audio -- and clap your hands loudly in range of all the microphones, ideally equidistant from each of them.
That spike in audio can be used as a time marker in all the sources to line them up in post. There will be a slight delay from the mic(s) that were a bit farther away, but you should be able to sync them up close enough. Then, simply cut out the clap section from the finished product.


Install on Websphere 22.214.171.124/Oracle 22.214.171.124 fails

Question: I have sucessfully deployed MobileFrist and MaximoAnywhere to Websphere 8.5 and Oracle 188.8.131.52 (using the Anywhere.war)
After deploying to Websphere 220.127.116.11 and Oracle 22.214.171.124 and the Anywhere-2.4.war) when I try to log in I get the error ...
The server was unable to process the request from the application. Please try again later.
On the client log there is
<code>an errorFailed to load resource: the server responded with a status of 500 (Internal Server Error)
Logger.js:202 Cancel processing requested
dojo.js:2 klass "
    ----------------------------------------
    rejected at Object.WL.Client.invokeProcedure.onFailure (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/js/platform/auth/UserAuthenticationManager.js:359:25)
    at Object.options.onFailure (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/worklight/worklight.js:8632:29)
    at Object.onInvokeProcedureFailure [as onFailure] (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/worklight/worklight.js:8544:14)
    at klass.window.WLJSX.Ajax.WLRequest.WLJSX.Class.create.onFailure (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/worklight/worklight.js:3577:26)
    at klass.window.WLJSX.Ajax.WLRequest.WLJSX.Class.create.onWlFailure (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/worklight/worklight.js:3529:12)
    at http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/worklight/worklight.js:958:20
    at klass.window.WLJSX.Ajax.Request.WLJSX.Class.create.respondToReadyState (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/worklight/worklight.js:1184:28)
    at klass.window.WLJSX.Ajax.Request.WLJSX.Class.create.onStateChange (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/worklight/worklight.js:1117:9)
    at XMLHttpRequest.<anonymous> (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/worklight/worklight.js:958:20)
    ----------------------------------------
Error
    at Promise.then._7cd.then (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/dojo/dojo.js:2:275189)
    at declare.loginClickHandler (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/js/platform/handlers/LoginHandler.js:76:4)
    at null.<anonymous> (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/js/platform/ui/control/UserInterface.js:860:47)
    at HTMLButtonElement.<anonymous> (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/dojo/dojo.js:2:285161)
    at Function.on.emit (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/dojo/dojo.js:2:557950)
    at null.<anonymous> (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/js/platform/ui/control/UserInterface.js:126:16)
    at null.<anonymous> (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/dojo/dojo.js:2:285161)
    at HTMLFormElement.<anonymous> (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/dojo/dojo.js:2:285161)
    at HTMLFormElement.<anonymous> (http://localhost:9080/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/dojo/dojo.js:2:599634)"
</code>
On the server I get the following error
<code>[10/1/15 12:11:28:025 BST] 0000003e TpaeCustomAut I   processRequest() - Request URI=/MaximoAnywhere/apps/services/api/WorkExecution/common/init
[10/1/15 12:11:28:565 BST] 0000003e TpaeCustomAut I   processRequest() - Request URI=/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/js/platform/ui/control/images/mdpi/header_disconnected.png
[10/1/15 12:11:29:618 BST] 0000003e TpaeCustomAut I   processRequest() - Request URI=/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/js/platform/ui/control/images/mdpi/header_app_noBack.png
[10/1/15 12:11:29:624 BST] 0000003e TpaeCustomAut I   processRequest() - Request URI=/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/js/platform/ui/control/images/mdpi/header_overflow_OFF.png
[10/1/15 12:11:29:642 BST] 0000003e TpaeCustomAut I   processRequest() - Request URI=/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/js/platform/ui/control/images/mdpi/header_back_OFF.png
[10/1/15 12:11:29:684 BST] 0000003e TpaeCustomAut I   processRequest() - Request URI=/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/js/platform/ui/control/images/mdpi/header_split_cancel_OFF.png
[10/1/15 12:11:30:830 BST] 0000003e TpaeCustomAut I   processRequest() - Request URI=/MaximoAnywhere/apps/services/loguploader
[10/1/15 12:11:30:836 BST] 0000003e TpaeCustomAut I   processRequest() - Request URI=/MaximoAnywhere/apps/services/loguploader
[10/1/15 12:11:30:922 BST] 0000003e TpaeCustomAut I   processRequest() - Request URI=/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/js/platform/ui/control/images/mdpi/ibmLogoDark.png
[10/1/15 12:11:30:973 BST] 0000003e TpaeCustomAut I   processRequest() - Request URI=/MaximoAnywhere/apps/services/preview/WorkExecution/common/0/default/js/platform/ui/control/images/mdpi/status_error.png
[10/1/15 12:11:36:453 BST] 0000003e TpaeCustomAut I   processRequest() - Request URI=/MaximoAnywhere/apps/services/api/WorkExecution/common/query
[10/1/15 12:11:36:454 BST] 0000003e TpaeCustomAut I   processRequest() - Request URI=/MaximoAnywhere/apps/services/api/WorkExecution/common/query
[10/1/15 12:11:36:455 BST] 0000003e ServletWrappe E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0068E: Uncaught exception created in one of the service methods of the servlet GadgetAPIServlet in application IBM_Worklight_project_runtime_MaximoAnywhereMobileFirst. Exception created : com.worklight.server.auth.api.WorkLightAuthenticationException
    at com.worklight.core.auth.impl.AuthenticationContext.checkAuthentication(AuthenticationContext.java:604)
    at com.worklight.core.auth.impl.AuthenticationContext.processRealms(AuthenticationContext.java:469)
    at com.worklight.core.auth.impl.AuthenticationContext.pushCurrentResource(AuthenticationContext.java:443)
    at com.worklight.core.auth.impl.AuthenticationServiceBean.accessResource(AuthenticationServiceBean.java:75)
    at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeProcedureInternal(DataAccessServiceImpl.java:440)
    at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeProcedure(DataAccessServiceImpl.java:140)
    at com.worklight.gadgets.serving.handler.BackendQueryHandler.getContent(BackendQueryHandler.java:95)
    at com.worklight.gadgets.serving.handler.BackendQueryHandler.doPost(BackendQueryHandler.java:56)
    at com.worklight.gadgets.serving.GadgetAPIServlet.doGetOrPost(GadgetAPIServlet.java:148)
    at com.worklight.gadgets.serving.GadgetAPIServlet.doPost(GadgetAPIServlet.java:108)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:738)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1700)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1635)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:149)
    at com.worklight.core.auth.impl.AuthenticationFilter$1.execute(AuthenticationFilter.java:215)
    at com.worklight.core.auth.impl.AuthenticationServiceBean.accessResource(AuthenticationServiceBean.java:76)
    at com.worklight.core.auth.impl.AuthenticationFilter.doFilter(AuthenticationFilter.java:220)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:125)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:80)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:908)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:965)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:508)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:181)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3994)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:945)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1592)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:191)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:454)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:516)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:307)
    at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:84)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1662)

[10/1/15 12:11:36:456 BST] 0000003e Authenticatio E com.worklight.core.auth.impl.AuthenticationFilter doFilter FWLSE0048E: Unhandled exception caught: com.worklight.server.auth.api.WorkLightAuthenticationException
com.ibm.websphere.servlet.error.ServletErrorReport: com.worklight.server.auth.api.WorkLightAuthenticationException
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:172)
    at com.worklight.core.auth.impl.AuthenticationFilter$1.execute(AuthenticationFilter.java:215)
    at com.worklight.core.auth.impl.AuthenticationServiceBean.accessResource(AuthenticationServiceBean.java:76)
    at com.worklight.core.auth.impl.AuthenticationFilter.doFilter(AuthenticationFilter.java:220)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:125)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:80)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:908)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:965)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:508)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:181)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3994)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:945)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1592)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:191)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:454)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:516)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:307)
    at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:84)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1662)
Caused by: com.worklight.server.auth.api.WorkLightAuthenticationException
    at com.worklight.core.auth.impl.AuthenticationContext.checkAuthentication(AuthenticationContext.java:604)
    at com.worklight.core.auth.impl.AuthenticationContext.processRealms(AuthenticationContext.java:469)
    at com.worklight.core.auth.impl.AuthenticationContext.pushCurrentResource(AuthenticationContext.java:443)
    at com.worklight.core.auth.impl.AuthenticationServiceBean.accessResource(AuthenticationServiceBean.java:75)
    at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeProcedureInternal(DataAccessServiceImpl.java:440)
    at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeProcedure(DataAccessServiceImpl.java:140)
    at com.worklight.gadgets.serving.handler.BackendQueryHandler.getContent(BackendQueryHandler.java:95)
    at com.worklight.gadgets.serving.handler.BackendQueryHandler.doPost(BackendQueryHandler.java:56)
    at com.worklight.gadgets.serving.GadgetAPIServlet.doGetOrPost(GadgetAPIServlet.java:148)
    at com.worklight.gadgets.serving.GadgetAPIServlet.doPost(GadgetAPIServlet.java:108)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:738)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1700)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1635)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:149)
    ... 27 more
 [project MaximoAnywhere]
                                 com.ibm.websphere.servlet.error.ServletErrorReport: com.worklight.server.auth.api.WorkLightAuthenticationException
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:172)
    at com.worklight.core.auth.impl.AuthenticationFilter$1.execute(AuthenticationFilter.java:215)
    at com.worklight.core.auth.impl.AuthenticationServiceBean.accessResource(AuthenticationServiceBean.java:76)
    at com.worklight.core.auth.impl.AuthenticationFilter.doFilter(AuthenticationFilter.java:220)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:125)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:80)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:908)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:965)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:508)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:181)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3994)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:945)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1592)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:191)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:454)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:516)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:307)
    at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:84)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1662)
Caused by: com.worklight.server.auth.api.WorkLightAuthenticationException
    at com.worklight.core.auth.impl.AuthenticationContext.checkAuthentication(AuthenticationContext.java:604)
    at com.worklight.core.auth.impl.AuthenticationContext.processRealms(AuthenticationContext.java:469)
    at com.worklight.core.auth.impl.AuthenticationContext.pushCurrentResource(AuthenticationContext.java:443)
    at com.worklight.core.auth.impl.AuthenticationServiceBean.accessResource(AuthenticationServiceBean.java:75)
    at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeProcedureInternal(DataAccessServiceImpl.java:440)
    at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeProcedure(DataAccessServiceImpl.java:140)
    at com.worklight.gadgets.serving.handler.BackendQueryHandler.getContent(BackendQueryHandler.java:95)
    at com.worklight.gadgets.serving.handler.BackendQueryHandler.doPost(BackendQueryHandler.java:56)
    at com.worklight.gadgets.serving.GadgetAPIServlet.doGetOrPost(GadgetAPIServlet.java:148)
    at com.worklight.gadgets.serving.GadgetAPIServlet.doPost(GadgetAPIServlet.java:108)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:738)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1700)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1635)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:149)
    ... 27 more

[10/1/15 12:11:36:466 BST] 0000003e webapp        E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[GadgetAPIServlet]: java.lang.RuntimeException: com.ibm.websphere.servlet.error.ServletErrorReport: com.worklight.server.auth.api.WorkLightAuthenticationException
    at com.worklight.core.auth.impl.AuthenticationFilter.doFilter(AuthenticationFilter.java:272)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:125)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:80)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:908)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:965)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:508)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:181)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3994)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:945)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1592)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:191)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:454)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:516)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:307)
    at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:84)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1662)
Caused by: com.ibm.websphere.servlet.error.ServletErrorReport: com.worklight.server.auth.api.WorkLightAuthenticationException
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:172)
    at com.worklight.core.auth.impl.AuthenticationFilter$1.execute(AuthenticationFilter.java:215)
    at com.worklight.core.auth.impl.AuthenticationServiceBean.accessResource(AuthenticationServiceBean.java:76)
    at com.worklight.core.auth.impl.AuthenticationFilter.doFilter(AuthenticationFilter.java:220)
    ... 24 more
Caused by: com.worklight.server.auth.api.WorkLightAuthenticationException
    at com.worklight.core.auth.impl.AuthenticationContext.checkAuthentication(AuthenticationContext.java:604)
    at com.worklight.core.auth.impl.AuthenticationContext.processRealms(AuthenticationContext.java:469)
    at com.worklight.core.auth.impl.AuthenticationContext.pushCurrentResource(AuthenticationContext.java:443)
    at com.worklight.core.auth.impl.AuthenticationServiceBean.accessResource(AuthenticationServiceBean.java:75)
    at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeProcedureInternal(DataAccessServiceImpl.java:440)
    at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeProcedure(DataAccessServiceImpl.java:140)
    at com.worklight.gadgets.serving.handler.BackendQueryHandler.getContent(BackendQueryHandler.java:95)
    at com.worklight.gadgets.serving.handler.BackendQueryHandler.doPost(BackendQueryHandler.java:56)
    at com.worklight.gadgets.serving.GadgetAPIServlet.doGetOrPost(GadgetAPIServlet.java:148)
    at com.worklight.gadgets.serving.GadgetAPIServlet.doPost(GadgetAPIServlet.java:108)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:738)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1700)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1635)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:149)
    ... 27 more
</code>
Any suggestions, or has anyone sucessfully managed to deploy to this arrangement.
Thanks,
Keith
Comment: Just an update on this ... I can successfully deploy on Apache/MySQL.
Answer: Yes, this is a known bug with WebSphere 7 and Worklight.  There's a web module setting that has to be applied to prevent these 500 exceptions from being propagated down to the worklight engine.
http://www-01.ibm.com/support/docview.wss?uid=swg1PM74090
Comment: I was already on 22.214.171.124, I just needed to add the custom property to the Webcontainer, restart and this solved my problem.

Install on Websphere 7.0.0.37/Oracle 11.2.0.1 fails


Prove that $DL(x)=L(x)$.

Question: By Fréchet derivative prove that $DL(x)=L(x)$ where $L:\Bbb R^m\to \Bbb R^n$ is a lineal application.
My try:
We have,
$$\begin{align*}\dfrac{L(a+h)-L(a)-DL(a)h}{||h||}&=\dfrac{L(a)+L(h)-L(a)-DL(a)h}{||h||}\\ &= \dfrac{L(h)-DL(a)h}{||h||}\end{align*}$$
How do I make it store to $ L(h) $ when $ h \to 0 $, I'm stuck on that.
Answer: Hint: The derivative of any function, at any point where it exists, is unique. So for $f: \mathbb{R}^m\to \mathbb{R}^n$ an arbitrary map and $\Lambda: \mathbb{R}^m\to \mathbb{R}^n$ is a linear map such that
$$\lim_{h\to0}\dfrac{|f(x+h)-f(x)-\Lambda (h)|}{|h|}=0,$$
then ($f$ is differentiable at $x$ and) $\Lambda=Df(x)$.

Given the hint, in your situation you need to show that
$$\lim_{h\to0}\dfrac{|L(x+h)-L(x)-L(h)|}{|h|}=0.$$

Alternatively one can think of linear approximations:
$$f(x+h)=f(x)+\Lambda(h)+\text{o}_{_{h\to 0}}(|h|),$$
where $\text{o}_{_{h\to 0}}(|h|)$ is some function decaying faster than $|h|$ does as $h\to0$, e.g. the function that is constantly $0$.

Prove that $DL(x)=L(x)$.


Windows Phone: Load HTML source with HTTPWebRequest

Question: I need to download the entire desktop-site HTML code with my WP7 app. I used the following code in normal Win32 apps which isn't working in WP. Especially, I can't find at GetReponse property of HtttpWebReqest. And I can't use WebBrowser as it's not loading the desktop site, only mobile site. Any help?
        request = HttpWebRequest.Create(URL)
        response = request.GetResponse
        sr = New IO.StreamReader(response.GetResponseStream)

        Source = sr.ReadToEnd

Answer: In wp7 only async request are allowed. Maybe WebClient would be the easiest for you.
Here is an example:
private void loadFeedButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
    WebClient webClient = new WebClient();

    webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);

    webClient.DownloadStringAsync(new System.Uri("http://windowsteamblog.com/windows_phone/b/windowsphone/rss.aspx"));
}

// Event handler which runs after the feed is fully downloaded.
private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null)
    {
        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            // Showing the exact error message is useful for debugging. In a finalized application,
            // output a friendly and applicable string to the user instead.
            MessageBox.Show(e.Error.Message);
        });
    }
    else
    {
       this.State["feed"] = e.Result;
    }
}


Squid gives always tcp_miss reverse proxy

Question: I added installed latest squid3 in front of apache as reverse proxy. The problem is that it gives always tcp_miss, in fact I have not yet found a single TCP_HIT message in the log file, and most of the content is static. Relevant config values for cache_dir and refresh_pattern are default ones, directory /var/spool/squid3 exists and has some files/folders. I have 100+G free storage, but reconfigure gives warning "WARNING cache_mem is larger than total disk cache space!", which does not make any sense to me.
I have googled a lot and seen with similar problems, but none of them has helped.
Comment: Can you pastebin your config? /etc/squid3/squid.conf Did you actually create the cache_dir's or were they already there? (squid3 -z etc). Is this still a problem? Do you have any always_direct directives? Have a look at: http://nixforums.org/viewtopic.php?p=927998#927998
Answer: If you don't explicitly set cache_mem to a value higher than the cache_dir MBytes param (the first value after the path string), then you'll get this message:
WARNING cache_mem is larger than total disk cache space!

Here's what I used, which doesn't throw the warning:

cache_dir aufs /var/spool/squid 1024 16 256
  cache_mem 1 GB


JavaScript plugin fire more than once

Question: So I have a javascript plugin
;(function(window){
//some functions
function plugin(el, options){
}
plugin.prototype = {
//other functions
}
})(window);

however this is not so important.
Then I call this plugin like this
document.addEventListener('DOMContentLoaded', function() {
  var el = document.querySelectorAll('[data-tooltip]')
  for(i = 0; i < el.length; i++){
    new tooltipizeIt(el[0], { effect : 'fade-and-move', theme : 'custom', width : 200, position : 'right'});
    new tooltipizeIt(el[1], { theme : 'light', effect : 'fade', width : 120, position : 'top'});
    new tooltipizeIt(el[2], { effect : 'scale', theme : 'dark', position : 'bottom'});
    new tooltipizeIt(el[3], { effect : 'no-effect', theme : 'custom', position : 'top', width : 135});
    new tooltipizeIt(el[4], { effect : 'fade-and-move', theme : 'light', position : 'bottom', width : 400});
    new tooltipizeIt(el[5], { effect : 'fade-and-move', theme : 'light', position : 'left', width : 400, ajax : true});
  }
}, false);

As you see i called this plugin six times , but plugin fires six times for every el element, if I call it seven times, will fire seven time and so on.
known someone why and if is there a solution to fix this?
EDIT
I added one image , as you see plugin creates six tooltips for the same element
Comment: And why wouldn't it, you're iterating over the elements, calling it six times for each element ?
Comment: if I call it like this `new tooltipizeIt(el[i], { effect : 'fade-and-move', theme : 'custom', width : 200, position : 'right'});`, once for every element it will fire once, but for example if i want to call it for tw elements, Eg `new tooltipizeIt(el[0], { //some options'});
    new tooltipizeIt(el[1], { //some other options});` first with some options and second with another options it will fire twice for every element , so 2*2 =4 time fires, is that right? if so my fold, i didn't know-it
Answer: I agree with @adeneo it is doing exactly what you're telling it to do.
Because of your for loop it will always make 6*el.length calls.
Specifically each of the first 6 elements with data-tooltip will have the same call happen to it 6 times. This is just the way for loops work.
For example, the first element will have this specific call happen 6 times:
new tooltipizeIt(el[0], { effect : 'fade-and-move', theme : 'custom', width : 200, position : 'right'});

While the second one will have this specific all happen 6 times:
new tooltipizeIt(el[1], { theme : 'light', effect : 'fade', width : 120, position : 'top'});

And so on.  If there is ever a 7th element it will not get called at all.  Likewise, if there are less than 6 elements attributes it will fail because you are directly accessing each one and el[5] will be undefined.
Here is a demonstration of how this kind of thing works but more detail will be needed to truly make your code do what you want.  Hopefully comparing this code to the output will help you to understand the concepts involved here.

// This is a simple call to show some output
function log(message) {
  $("#log").text($("#log").text() + message + '\n');
}

//
// Here's the real stuff
//

// Create an array with six values, much like your example.
var el = ['A', 'B', 'C', 'D', 'E', 'F'];
log("el has " + el.length + " items in it.")

// Loop for as many items as there are in the array.
for (var i = 0; i < el.length; i++) {
  log("  This message is in the loop so it will happen " + el.length + " times.")
  log("  This message is also in the loop so it will also happen " + el.length + " times.")
}

log("");
log("That was " + el.length + " * 2 or " + (el.length * 2) + " messages.")

log("")
log("In your example you actually used each item but you didn't like this...")

for (var i = 0; i < el.length; i++) {
  log("  Do something to " + el[0] + ".")
  log("  Do a second something to " + el[1] + ".")
  log("  Do a third something to " + el[2] + ".")
  log("  Do a forth something to " + el[3] + ".")
  log("  Do a fifth something to " + el[4] + ".")
  log("  Do a sixth something to " + el[5] + ".")
}

log("");
log("That was " + el.length + " * 6 or " + (el.length * 6) + " messages.")

log("")
log("You wanted it to do 6 different things, leaving the loop out would do that.")

log("  Do something to " + el[0] + ".")
log("  Do a second something to " + el[1] + ".")
log("  Do a third something to " + el[2] + ".")
log("  Do a forth something to " + el[3] + ".")
log("  Do a fifth something to " + el[4] + ".")
log("  Do a sixth something to " + el[5] + ".")

log("");
log("That was 6  messages.")

log("")
log("Of course that only works if there are exactly 6 items.  Try to do that with 7 items and things get wonky.")

log("  Do something to " + el[0] + ".")
log("  Do a second something to " + el[1] + ".")
log("  Do a third something to " + el[2] + ".")
log("  Do a forth something to " + el[3] + ".")
log("  Do a fifth something to " + el[4] + ".")
log("  Do a sixth something to " + el[5] + ".")
log("  Do a seventh something to " + el[6] + ".")

log("")
log("This just showed undefined but in more complex code it might break all together.")

log("")
log("Had there been 7 items this would all have gone differently.")

el = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
log("el has " + el.length + " items in it.")

log("  Do something to " + el[0] + ".")
log("  Do a second something to " + el[1] + ".")
log("  Do a third something to " + el[2] + ".")
log("  Do a forth something to " + el[3] + ".")
log("  Do a fifth something to " + el[4] + ".")
log("  Do a six something to " + el[5] + ".")

log("");
log("That was still 6 messages because there were exactly 6 calls.")

log("  Do something to " + el[0] + ".")
log("  Do a second something to " + el[1] + ".")
log("  Do a third something to " + el[2] + ".")
log("  Do a forth something to " + el[3] + ".")
log("  Do a fifth something to " + el[4] + ".")
log("  Do a six something to " + el[5] + ".")

log("");
log("It is more likly that you intened to one thing to each item.")
for (var i = 0; i < el.length; i++) {
  log("  Do something to " + el[i] + ".")
}

log("");
log("That was " + el.length + " messages.")

log("");
log("Notice that the same thing was done to each item.")

I think you are better off describing what you are trying to accomplish here.
Comment: I'm not a javascript guru so thanks for your clear explanation , I get it now.

JavaScript plugin fire more than once


Given that no 1 turned up at the first two throws, what is the probability that at least three throws will be necessary for a 1 or 6 to appear?

Question: Question: A die is thrown as long as necessary for a 1 or a 6 to turn up. Given that no 1 turned up at the first two throws, what is the probability that at least three throws will be necessary?
Answer: $\frac{16}{25}$
what I did:
Since the first 2, nothing turned up I assumed the probability was $\frac{4}{6}$ and for the 3rd try I assume it will show up so the probability is $\frac{2}{6}$ I then subtracted it to $1$ to get the probability since it says at least three throws but it yields a wrong value. Thank you for any help
$$1-\frac{4}{6}\frac{4}{6}\frac{2}{6}=\frac{23}{27}$$
Comment: What is an ace? Is that rolling a $1$? or two $1$s in a row? I've never heard that term
Comment: @ZubinMukerjee I assumed it is 1, never heard of it too
Comment: Pst:  You are given that an 'ace' does not occur on the first two throws, *however*, that does not mean that a six does not.
Comment: @GrahamKemp "Given that no ace turned up at the first two throws" Doesn't that imply that there were at least two throws? So, it does rule out the possibility of there being a six on the first throw, but it doesn't rule out the possibility of there being a six on the second throw .. right?
Comment: The wording of this question is a bit of a headache! We need help from the [English Language & Usage Stack Exchange](https://english.stackexchange.com/), haha
Answer: The reason your answer is wrong is that you are ignoring the part that "no ace turned up at the first two throws". So we know that in the first 2 throws there was no ace (I assumed "ace" mean 1). So for those 2 first throws the probability should only cover no 6 appearing so it will be 4/5.
So the overall probability will be:
4/5 * 4/5 = 16/25
Note that since the question wants "at least" 3 throws any number of throws equal or bigger than 3 is good and since the probability never occurring a 1 or 6 in infinite throws is 0 so the probability is equal to 16/25.
Comment: Doesn't the fact that "no ace turned up at the first two throws" imply that there could not have been a $6$ on the first throw? Because if there was a $6$ on the first throw, then there wouldn't even have been a second throw! ("die is thrown as long as it is necessary for an ace or $6$ to show up")
Comment: @ZubinMukerjee Actually no, it only limits the sample space. What I mean is that the sequence (6,2,4) is still valid in sample space, it is just not desired.
Comment: Is it in the sample space? After the first $6$, the die is no longer rolled ... or maybe I am reading the question too literally?
Comment: @ZubinMukerjee Maybe I could rephrase my answer like this: The sequences (6) or (4,6) are still valid in the sample space (since the only restriction is no 1 in the first 2 possible throws) and so their probability should be considered.
Comment: Im having some difficulties understanding when it says "did not show up" does that mean you alter the probability by removing it to the number of possible outcomes?
Comment: @Ralph You can think of it like "invalid in sample space" so the occurrence of 1 in the first 2 throws is invalid (think of it like it happens you should ignore it at all)
Comment: @Alithewise ohhh ok ok thanks!
Answer: Rephrase the question:   A die is thrown until a 1 or 6 show.   What is the probability of this happening on the third or later throw, when given that a 1 will not show on the first two throws?
Ie: What is the probability something other than a 1 or 6 show on the first two throws when guaranteed that a 1 will not?
Comment: Did you mean to make this a comment? But yes, I agree that the question needs to be rephrased
Answer: To solve this question let us first find what is the probability that we don't meet the condition in three throws.
Since we know there was no 1 in first two throws(you didn't consider this) the probability of us failing in two moves is
 $$P(Failure)= \frac{4}{6-1}.\frac{4}{6-1} $$
Now, As we need at least three throws we just have to ensure that it fails for two throws.
Hence,
      the required probability is,$$P(n)=P(Failure)=\frac{4.4}{5.5}=\frac{16}{25}=0.64$$


Group repeating dates in Views

Question: I have this scenario:
The contenttype "event" has a date-field (with repeat-options). All repeating events are repeated for a certain timespan once a week.
I want to achieve this views-block:

Show me all repeating events (got this to work with condition
eventdate:rrule not empty).
Group by Event-Id and don't show me every repeating event (because
the description text of the event contains the human-readable
repeat-logic ... e.g. every tuesday at 12.00)

My Problem is:
I activated "Use aggregation" in the view and wanted to group the events by node-id, but the date field (field_data_field_event_date_field_event_date_value) is automatically added to the "GROUP BY"-SQL part when i do this (and i can't remove it)
Am I using the wrong approach?
Comment: Have you seen this question: [How to use Recurring Dates with Views properly?](http://drupal.stackexchange.com/q/17015/594)
Comment: Yes - I saw this, but the solution of this problem is my starting point :)
Answer: I ran into similar problems and managed to fix it by enabling Aggregation on the view plus enabling 'Distinct'.
Comment: Please add "some more details" (instructions) to your answer. That should help to have it not show up in the "Low quality posts" review queue ... Just trying to get you going on this site, ok?

Group repeating dates in Views