Cannot cast onItem clicklistener inside Fragment Class form Adapter Class

Question: I have an Fragment with recycleview where I populate it with json items from internet.
It load fine and Next step I want to is open new Activity when any row is clicked. It works in activity, thus I modified the same code for fragment but for fragment it throws exception in line
       mExampleAdapter.setOnItemClickListener(getActivity());

with errror setOnItemClickListener of refrence adatper cannot be applied to Fragment activty and thus when I change line to
(ExampleAdapter.OnItemClickListener)

and when i build and run . Then app crashes with error  that Mainactivity which holds framgnet cannot be cast in to .ExampleAdapter$OnItemClickListener
Here is my whole Fragment class

public class Mynotes extends Fragment implements ExampleAdapter.OnItemClickListener{

    public static final String YTD_LINK = "link";
    private RecyclerView mRecyclerView;
    private ExampleAdapter mExampleAdapter;
    private ArrayList<ExampleItem> mExampleList;
    private RequestQueue mRequestQueue;
    String url="https://api.myjson.com/bins/16mecx";

    public Mynotes() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.activity_jsonfeed, container, false);

        mRecyclerView = view.findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new MyDividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL, 36));

        mExampleList = new ArrayList<>();
        mExampleAdapter = new ExampleAdapter(getActivity(), mExampleList);
        mRecyclerView.setAdapter(mExampleAdapter);
        mExampleAdapter.setOnItemClickListener((ExampleAdapter.OnItemClickListener) getActivity());

        parseJSON();

        return view;
    }

    private void parseJSON() {

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        myProgressBar.setVisibility(View.GONE);

                        try {
                            JSONArray jsonArray = response.getJSONArray("hits");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject hit = jsonArray.getJSONObject(i);
                                String videoTitle = hit.getString("title");
                                String link = hit.getString("link");

                                mExampleList.add(new ExampleItem(videoTitle, link));
                                mExampleAdapter.notifyDataSetChanged();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();

            }
        });

        mRequestQueue.add(request);
    }

    @Override
    public void onItemClick(int position) {
        Intent intent = new Intent(getActivity(), NewActiviyt.class);
        ExampleItem clickedItem = mExampleList.get(position);
            intent.putExtra(YTD_LINK, clickedItem.getmLink());
            startActivity(intent);

    }

    @Override
    public void onRefresh() {

    }
}

and my Adapter Class is

public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
    private Context mContext;
    private ArrayList<ExampleItem> mExampleList;
    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }

    public ExampleAdapter(Context context, ArrayList<ExampleItem> exampleList) {
        mContext = context;
        mExampleList = exampleList;
    }

    @Override
    public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.example_item, parent, false);
        return new ExampleViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ExampleViewHolder holder, int position) {
        ExampleItem currentItem = mExampleList.get(position);

         String title = currentItem.getTitle();
//        int likeCount = currentItem.getLikeCount();
//        String imageUrl = currentItem.getImageUrl();

          holder.mTextViewCreator.setText(title);
//        holder.mTextViewLikes.setText("Likes: " + likeCount);
//        Glide.with(mContext).load(imageUrl).apply(RequestOptions.circleCropTransform()).into(holder.mImageView);

    }

    @Override
    public int getItemCount() {
        return mExampleList.size();
    }

    public class ExampleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        public TextView mTextViewCreator;
//        public TextView mTextViewLikes;
//        public ImageView mImageView;

        public ExampleViewHolder(View itemView) {
            super(itemView);
//            mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
//            mImageView = itemView.findViewById(R.id.image_view);
            mTextViewCreator = itemView.findViewById(R.id.text_title);

        }

        @Override
        public void onClick(View view) {

            if (mListener != null) {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    mListener.onItemClick(position);
                }
            }

        }
    }
}

Thanks in advance.
Comment: If `Mynotes` is what implements `ExampleAdapter.OnItemClickListener`, why are you trying to pass the `Activity` to `mExampleAdapter.setOnItemClickListener()`? Don't you want the current `Mynotes` instance; i.e., `this`?
Comment: Umm instead of using getActiviyt, replacing it with this should fix the problem. But when I build and run app then when I click anywhere it don't show any actions which it was supposed to open new activity.
Comment: I'm not exactly sure what you mean by "it don't show any actions", but you forgot to set your `ExampleViewHolder` as the `OnClickListener` on the `View` there; e.g., `itemView.setOnClickListener(this);`, in the `ExampleViewHolder` constructor.
Comment: Sorry Mike,The action refrence I wrote means to say that  I want to open NewActivity class when any row is clicked.
Comment: OK, yeah, you forgot to set that `OnClickListener`.
Answer: replace getActivity with getContext when you work in fragment,
You can read more here
What is different between getContext and getActivity from Fragment in support library?
Answer: Your activity should implement ExampleAdapter.OnItemClickListener


Windows Update Service gets stuck at Stopping state whenever I check for update on the domain controller

Question: On my domain controller which is Running Windows Server 2016, whenever I check for updates, the updates start downloading and get stuck at 7% or sometimes stuck at checking for updates. I see that the Windows Update service goes from running to stopping. I rebooted multiple times.
net stop wuauserv /yes
net stop cryptSvc /yes
net stop bits /yes
net stop msiserver /yes
ren C:\Windows\SoftwareDistribution SoftwareDistribution.old
ren C:\Windows\System32\catroot2 Catroot2.old
net start wuauserv
net start cryptSvc
net start bits
net start msiserver
rmdir /S /Q C:\Windows\SoftwareDistribution.old
rmdir /S /Q C:\Windows\System32\Catroot2.old

I executed the commands and when I manually checked for updates, the updates were downloading but stuck at 8% and I now see that the Windows update service is back to Stopping state along with Update Orchestrator Service for Windows Update.
I also mounted Windows Server ISO image and ran DISM.exe /Online /Cleanup-Image /RestoreHealth /LimitAccess /Source:D:\sources\install.wim
It didn't give me any error after running but still the problem persists. The updates are stuck in "Checking for updates" and the Windows update service is stuck in Stopping state.
We have two Domain Controllers. I have daily backups from Veeam but I am hesitant to restore a DC from backup. I am not sure what would happen to AD database.
Answer: Try to donwload and install maually the latest SSU update:KB5023788: Servicing stack update for Windows Server 2016: March 14, 2023
Comment: That update is not installing.
Comment: That too remains stuck or it throw an error?
Comment: The servicing stack update finally installed but when I check for updates, it's trying to download the May update but failing with `There were problems downloading some updates, but we'll try again later. If you keep seeing this, try searching the web or contacting support for help. This error code might help: (0x8024a10a)`
Answer: I've had a similar issue (Wsus client getting error 403 (0x80244018)).
I resolved by installing the update that gave me the error (in my case march 2023) manually.


An example of continuous random variable X > 0 with finite second moment but Infinite third moment

Question: Can someone construct an example of this?
i.e., $E[X^2] < \infty$ but $E[X^3] = \infty$. Results could be in terms of pdf, or cdf, or
survival function. Justification would be appreciated
Comment: a Pareto distribution with $\alpha=3$ comes to mind, ref: https://en.wikipedia.org/wiki/Pareto_distribution.  are you looking for a specific counter example or trying to understand a concept?
Answer: So, you want
$$\int_0^\infty x^2f(x),dx$$ to exist, but
$$\int_0^\infty x^3f(x),dx$$ to be infinite.
We know that the integral $\int_1^\infty x^{-n}\,dx$ is finite if $n>1$ and infinite if $n\leq 1$. So one possibility is $f(x) \propto 1_{x\geq 1} x^{-4}$. Or, it would look a bit tidier to use  $f(x) \propto  (1+x)^{-4}$ on $x>0$.
Now we need the constant of proportionality. $\int_0^\infty (1+x)^{-4}\,dx =1/3$, so
$$f(x) = 3(1+x)^{-4}$$
Another approach is to note that a $t$ distribution with $\nu$ degrees of freedom has $\nu-1$ finite moments (https://en.wikipedia.org/wiki/Student%27s_t-distribution). Thus, a $t_3$ distribution has finite second moment but not third moment. It doesn't satisfy the non-negativity condition, but its absolute value does.


Find the minimal polynomial over a field

Question: I have two similar questions:
1). Find the minimal polynomial for  $a^{-1}$  (a to the power of minus 1) over $F_3$. $a$ is the root of the polynomial $x^3-x+1$ in $F_3[X]$
I have used the division algorithm to find an expression for $a$ but I am not sure what to do with $a^{-1}$
Comment: $a^{-1}$ is defined to be such that $a^{-1}a = aa^{-1} = 1$
Answer: If $a\ne0$ is a root of $Ax^3+Bx^2+Cx+D$, then $a^{-1}$ is a root of $A+Bx+Cx^2+Dx^3$.
Therefore,
since
the minimal polynomial of $a$ in your example is $f(x)=x^3+0x^2-x+1$,
the minimal polynomial of $a^{-1}$ is $g(x)=1+0x-x^2+x^3=1-x^2+x^3$.
Note that $g(x)=x^3f(1/x)$ and this implies that $g$ is irreducible.
Comment: A useful fact to remember
Comment: In case this is not 100% clear: If $p(x)=a_nx^n+a_{n-1}x^{n-1}+\cdots+a_1x+a_0$, then
$$x^np(\frac1x)=a_0x^n+a_1x^{n-1}+\cdots+a_{n-1}x+a_n.$$


Custom Message Encoder in WCF with support for ReaderQuotas

Question: Found the answer here (last post): http://social.msdn.microsoft.com/Forums/eu/wcf/thread/f5c0ea22-1d45-484e-b2c0-e3bc9de20915
I'm having one last issue with the implementation of my custom (TextOrMtomEncoder), which is the implementation of ReaderQuotas.
I've searched the web a lot, but I can't figure out the final piece of the puzzle.
I've got a class, which contains my implementations of the 'BindingElementExtensionElement' and 'MessageEncodingBindingElement'.
The MessageEncodingBindingElement implementation contains an override for:
T GetProperty<T>(BindingContext context)

which I 'borrowed' from the default .NET MessageEncoding implementations, like the TextMessageEncoding.
This has to be the right implementation, because MSDN says so.
The configuration is loaded fine from the web.config, I can see the ReaderQuotas properties in both my classes are set correctly, but it looks like .NET isn't reading the ReaderQuotas config from my MessageEncodingBindingElement implementation.
My guess is .NET uses the GetProperty method to load the config, because MessageVersion is requested via this method. But the problem is, T is never equal to XmlDictionaryReaderQuotas, so the ReaderQuotas is never begin requested.
The root of my question is weird btw, I'm developing on a Windows 7 x64 machine with IIS7.5. Posting 'large' files (like 100 KB) works on my machine. But when I deploy the service to Windows Server 2008 R2 (tried 2 different servers), I get the following error:

The formatter threw an exception while trying to deserialize the
  message: There was an error while trying to deserialize parameter
  http://socialproxy.infocaster.net:argument. The InnerException message
  was 'There was an error deserializing the object of type
  System.Object. The maximum array length quota (16384) has been
  exceeded while reading XML data. This quota may be increased by
  changing the MaxArrayLength property on the XmlDictionaryReaderQuotas
  object used when creating the XML reader. Line 1, position 1584.'.
  Please see InnerException for more details.

And like I said, it works on my machine :-/
Could anybody tell me how I can resolve this?
Many thanks in advance!
The WCF service config:
<system.serviceModel>
    <extensions>
        <behaviorExtensions>
            <add name="wsdlExtensions" type="WCFExtras.Wsdl.WsdlExtensionsConfig, WCFExtras, Version=22.214.171.124, Culture=neutral, PublicKeyToken=null" />
            <add name="textOrMtomMessageBehavior" type="InfoCaster.SocialProxy.lib.TextOrMtom.TextOrMtomMessageBehavior, InfoCaster.SocialProxy" />
        </behaviorExtensions>
        <bindingElementExtensions>
            <add name="textOrMtomEncoding" type="InfoCaster.SocialProxy.lib.TextOrMtom.TextOrMtomEncodingElement, InfoCaster.SocialProxy" />
        </bindingElementExtensions>
    </extensions>
    <bindings>
        <customBinding>
            <binding name="TextOrMtomBinding">
                <textOrMtomEncoding messageVersion="Soap11">
                    <readerQuotas maxDepth="32" maxStringContentLength="5242880" maxArrayLength="204800000" maxBytesPerRead="5242880" maxNameTableCharCount="5242880" />
                </textOrMtomEncoding>
                <httpTransport maxBufferSize="5242880" maxReceivedMessageSize="5242880" transferMode="Buffered" authenticationScheme="Anonymous" />
            </binding>
        </customBinding>
    </bindings>
    <services>
        <clear />
        <service name="InfoCaster.SocialProxy.SocialProxy" behaviorConfiguration="InfoCaster.SocialProxy.ISocialProxyServiceBehavior">
            <endpoint name="SocialProxyServiceEndpoint" address="" binding="customBinding" bindingConfiguration="TextOrMtomBinding" contract="InfoCaster.SocialProxy.ISocialProxy" behaviorConfiguration="InfoCaster.SocialProxy.ISocialProxyEndpointBehavior" />
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <clear />
            <behavior name="InfoCaster.SocialProxy.ISocialProxyServiceBehavior">

                <serviceMetadata httpGetEnabled="true" />

                <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
        </serviceBehaviors>
        <endpointBehaviors>
            <clear />
            <behavior name="InfoCaster.SocialProxy.ISocialProxyEndpointBehavior">
                <textOrMtomMessageBehavior />
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

Answer: Found the answer here (last post): http://social.msdn.microsoft.com/Forums/eu/wcf/thread/f5c0ea22-1d45-484e-b2c0-e3bc9de20915

Ok, I found it. You have to pass the readerquotes to the standard encoders. Unfortunantly there's no constructor for this so you have to set the property.

class TextOrMtomEncoder : MessageEncoder   {
    MessageEncoder _textEncoder;
    MessageEncoder _mtomEncoder;
    public TextOrMtomEncoder(MessageVersion messageVersion, XmlDictionaryReaderQuotas readerQuotas)
    {
      TextMessageEncodingBindingElement textEncoderBindingElement = new TextMessageEncodingBindingElement(messageVersion, Encoding.UTF8);
      MtomMessageEncodingBindingElement mtomEncoderBindingElement = new MtomMessageEncodingBindingElement(messageVersion, Encoding.UTF8);

      readerQuotas.CopyTo(mtomEncoderBindingElement.ReaderQuotas);
      readerQuotas.CopyTo(textEncoderBindingElement.ReaderQuotas);

      _mtomEncoder = mtomEncoderBindingElement.CreateMessageEncoderFactory().Encoder;
      _textEncoder = textEncoderBindingElement.CreateMessageEncoderFactory().Encoder;
    }


Left join multiple tables after migration

Question: I have here a stored procedure, we have migrated to SQL Server 2016 so that some command from previous version needed to update. But I am having trouble in some command as it is showing errors. Below is my sample code.
if @stat = '%'
   DECLARE onground_cur CURSOR for
   SELECT pkgh_type, pkgd_date, pkgd_area, pkgd_intcost, pkgd_billcost, pkgh_advcde,
      pkgh_agencde, pkgh_refno, pkgd_ae, pkgd_currency, bs_invno, bs_exinvno, pkgd_cpno
   FROM pckg_hdr, pckg_dtl, bill_sked
   WHERE pkgh_refno = pkgd_refno
      and pkgh_type in ('C', 'X')
      and pkgd_date between @dtfrom and @dtto
      and (pkgd_stat = 'I' or pkgd_stat = 'A')
      and pkgd_area like ltrim(@s_area)
      and pkgd_currency like ltrim(@p_currency)
      and pkgh_agencde like ltrim(@s_agency)
      and pkgh_advcde like ltrim(@s_advertiser)
      and pkgh_refno *= bs_pkgrefno
      and pkgd_dtlno *= bs_pckgdtlno

The part I need to update is those who have "*=" sign :
**pkgh_refno *= bs_pkgrefno and pkgd_dtlno *= bs_pckgdtlno**

What I did is :
**pckg_hdr left join bill_sked on pkgh_refno**
But when I tried the other one which is pkgd_dtlno *= bs_pckgdtlno
I cannot execute the code anymore. Also I am having trouble with left join and right join.
(spd_invno *= invh_invno and invh_invtp =* ordh_conttp)

Answer: *= is not anymore supported in today's sql server versions, use left outer join instead.
SELECT pkgh_type, pkgd_date, pkgd_area, pkgd_intcost, pkgd_billcost, pkgh_advcde,
      pkgh_agencde, pkgh_refno, pkgd_ae, pkgd_currency, bs_invno, bs_exinvno, pkgd_cpno
FROM pckg_hdr
left outer join pckg_dtl on pkgh_refno = bs_pkgrefno
left outer join bill_sked on pkgd_dtlno = bs_pckgdtlno
WHERE pkgh_refno = pkgd_refno
      and pkgh_type in ('C', 'X')
      and pkgd_date between @dtfrom and @dtto
      and (pkgd_stat = 'I' or pkgd_stat = 'A')
      and pkgd_area like ltrim(@s_area)
      and pkgd_currency like ltrim(@p_currency)
      and pkgh_agencde like ltrim(@s_agency)
      and pkgh_advcde like ltrim(@s_advertiser)


Behavior being fired on backend causes AJAX error

Question: I am using jQuery Update to bump up the jQuery version on the front end, and keep the default 1.4 on the backend.
On a custom filter form on the home page, i use jQuery on, and wrap it in a behavior so it still works after an ajax event on that page.
The problem is that for some reason, when editing the page, and adding a new field collection row when Ajax is fired, the jQuery is being called, and an error happens because jQuery on did not exist in 1.4.

VM787:31 Uncaught TypeError: $(...).on is not a function

Steps to fix...

I am using drupal_add_js but I check that if (!path_is_admin(current_path())) {//jQuery} to make sure it isnt called on the admin pages
I am certain the JS is not on the admin pages, but after ajax, it is called because its in a behavior.

Is there a way to say which behaviors should run on the admin side, and which shouldnt?
Answer: Funny how sometimes you write out the question, and it makes you think about it in a different way!
The issue is that the behavior is obviously saved somewhere and called on an ajax event, EVEN if the js is not being called on that page! This was funny behavior to me, but the quick fix (maybe not the right fix) was to check the current path, and not run the JS inside that behavior if the path had "edit" in it.
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    (function($) {

        jQuery(document).ready(function() {

        var pathname = window.location.pathname;
            // If the page does NOT contain edit
            if (! (pathname.indexOf('edit') > -1) ) {

               // All of the JS stuff....

            }
        });

    }(jQuery));
  }
};

I will leave this question open for a few days as I would be interested to see if there's a better way of doing this. Ideally some way to control which behaviors are called on which pages?


Full rank assumption in the linear regression model explanation:

Question: I need some help understanding the full-rank assumption. My book, Econometric Analysis by Greene, presents the following example:

Suppose that a cross-section model specifies that consumption, $C$, relates to income as follows:
  $$C = \beta_1 + \beta_2X_{non-labor\ income} + \beta_3X_{salary} + \beta_4X_{total\ income} + \epsilon$$  where $X_{total\ income}$is exactly equal to $X_{salary}$ plus $X_{non-labor\ income}$. Clearly, there is an exact linear dependency in the model. Now let $\beta_2' = \beta_2 + a, \beta_3' = \beta_3 + a$, and $\beta_4' = \beta_4 - a$, where a is any number. Then the exact same value appears on the right-hand side of $C$ if we substitute $\beta_2', \beta_3', \beta_4'$ for $\beta_2, \beta_3$, and $\beta_4$. Obviously, there is no way to estimate the parameters of this model.

What I do not understand of the above explanation are the second-to-last and last sentences. What do they mean? What are they trying to convey??
Comment: I only really got linear regression when I learned the linear algebra behind it. Basically, when the columns of your matrix **X** aren't independent, then the matrix $$X^{T}* X$$can't be inverted. In other words, you put that matrix formula in your calculator and you get an error--not even a *bad answer*, you get *no answer*.
Comment: Important: The problem has $\beta_4 - a$! (and not $\beta_4 + a$)--does that clear things up??
Comment: your new $\beta' s$ are only old $\beta s$ plus a constant $a$ what are that for? It is not even  a random coefficient regression.
Comment: Hey, I just tried to clean up the LaTeX a little--hopefully it will be a little clearer with the names written as subscripts...
Comment: To see what the author is getting at, try substituting in $(\beta' - a)$ for each $\beta$-value (and $\beta' + a$ for $\beta_{total\ income}$). Then, replace the term $a*X_{total\ income}$ with $a*(X_{non-labor\ income} + X_{salary})$ and notice how when you simplify the equation all the "**a**" terms cancel out.
Comment: I disagree with the author's assertion in your textbook.  It should read that there is no way to estimate the parameters of the model *uniquely*.  Using a generalized inverse it's possible to obtain *non-unique* estimates.
Answer: There is an error. It should be $\beta_4'=\beta_4-a$. If we substitute these new $\beta$s into the regression equation we get:
\begin{align}
C &= \beta_1 + \beta_2'X_{non-labor-income}+\beta_3'X_{non-labor-income}+\beta_4'X_{total-income}+\varepsilon \\
& = \beta_1 + (\beta_2 +a)X_{non-labor-income}+(\beta_3+a)X_{salary}+(\beta_4-a)X_{total-income}+\varepsilon\\
& = \beta_1 + \beta_2X_{non-labor-income}+\beta_3X_{salary}+\beta_4X_{total- income}+\varepsilon \\
& + a(X_{non-labor-income}+X_{salary}-X_{total-income})
\end{align}
and the last term is zero. So we substituted new coefficients, but the regression did not change, which means that there are multitude of coefficient values which give the same results, whereas the main regression assumption is that the coefficients are uniquely defined.
Answer: Old post but since I've been wondering about the same question here's my take on it. I came up a with the following numerical example to help me understand why the design matrix $\textbf{X}$ must be full rank.
First, with a linear model we want to solve (leaving out the error term $\boldsymbol{\epsilon}$):
$$\textbf{y} = \textbf{X} \boldsymbol{\beta}$$
where $\textbf{y}$ is vector of $n$ observation and $\textbf{X}$ is matrix of known covariates with $n$ rows and $p$ columns. We want solve to obtain the vector of $p$ coefficients $\boldsymbol{\beta}$.
Matrix $\textbf{X}$ is a transformation to pass from the vector space $\mathbb{R}^n$ of $\textbf{y}$ to the $\mathbb{R}^p$ space of $\boldsymbol{\beta}$. If $\textbf{X}$ is not full rank we cannot do this mapping uniquely, i.e. there is more than one solution for $\boldsymbol{\beta}$.
For example, with:
$$ \textbf{y} =
\begin{bmatrix}
8 \\
19 \\
27 \\
35 \\
\end{bmatrix}
\textbf{X} =
\begin{bmatrix}
1 & 2 \\
2 & 5 \\
3 & 7 \\
4 & 9 \\
\end{bmatrix}
$$
$\boldsymbol{X}$ is full rank and the model has a unique solution for $\boldsymbol{\beta} = \boldsymbol{(X^TX)^{-1}X^Ty} = [2 \ \ 3]$.
R code to reproduce this:
y <- c(8, 19, 27, 35)
X <- cbind(c(1, 2, 3, 4), c(2, 5, 7, 9))

qr(X)$rank == ncol(X) # Check X is full rank: TRUE

solve((t(X) %*% X)) %*% t(X) %*% y # Returns [2, 3]

# ---
# Alternatively, use the linear regression machinery:
lm(y ~ 0 + X[,1] + X[,2])

#    Coefficients:
#    X[, 1]  X[, 2]
#        2       3

Now, consider:
$$ \textbf{y} =
\begin{bmatrix}
8 \\
16 \\
24 \\
32 \\
\end{bmatrix}
\textbf{X} =
\begin{bmatrix}
1 & 2 \\
2 & 4 \\
3 & 6 \\
4 & 8 \\
\end{bmatrix}
$$
$\boldsymbol{X}$ is not full rank (column two is twice column 1, i.e. it's linear combination of column 1) so there are multiple solutions for $\boldsymbol{\beta}$. For example with $\boldsymbol{\beta} = [2 \ \ 3]$, or $[4 \ \ 2]$, or $[6 \ \ 1]$. R code:
y <- c(8, 16, 24, 32)
X <- cbind(c(1, 2, 3, 4), c(2, 4, 6, 8))

qr(X)$rank == ncol(X) # FALSE: not full rank

X %*% c(2, 3) == y # All these solutions return TRUE
X %*% c(4, 2) == y
X %*% c(6, 1) == y

# Try to solve:
solve((t(X) %*% X)) %*% t(X) %*% y

Error in solve.default((t(X) %*% X)) :
  Lapack routine dgesv: system is exactly singular: U[2,2] = 0


Placing rest symbols according the convention of the time signature

Question: I am preparing for a music school entry exam and I am given following problem:

In the following example, place the missing rest symbols in the brackets. It's possible, that you have to write down multiple rest symbols. Also, write the rest symbols according to the convention of the given time signature.

It's easy to calculate the missing rest values:
Bar 1: 1/8-rest
Bar 2: 5/16-rest
Bar 3: 6/16-rest
Bar 4: 3/8-rest
However, I am wondering about the words convention of the given time signature. Is there a principle which also applies to other time signatures, for example 7/8 time signature or 3/4 time signature?

I would write the following:

To me, it seems, this would be the easiest to read. Including, that each rest combined with a note is equal to a 1/4 value. (Except for Bar 1.) Is this right, or is it bad practice to put a dotted 1/8 rest after the 1/16 note?
Is the following better?

Now, I feel like, this second approach seems to be a bit more readable? :-)
Lastly, getting rid of the last dotted rest:
Comment: It's a bit cheeky of the exam question to talk about "according to the convention of the given time signature" when their own pre-supplied text violates that in bar 1!
Comment: Does this answer your question? [What is the rationale of note grouping?](https://music.stackexchange.com/questions/57289/what-is-the-rationale-of-note-grouping)
Comment: Thank you for your fast reply. Yes, this makes sense to me. But there is still some information missing for me. Is there any free music notation software, which does this right in the first place? So I would experiment with it a bit. May MuseScore?
Comment: But at the same time, it doesn't answer my question yet. Especially I have read, that it's common to write a 4/4 pause in 2/4 bar, when the whole bar will be paused. Also I am still wondering about Bar 3 in the example. Can I write two dotted 1/8 pauses, or would this be considered wrong? I neither write a dotted 1/8 after a 1/16 note, right?
Comment: Since one of the stack exchange "rules" is to have one question per post, I recommend editing this question to focus on one of the issues you bring up, and then open a second question for the other. That will also resolve any issue of it being a duplicate of the post I linked to (though it might be a duplicate of another).
Answer: The "convention of the time signature" is the definition of the time division unit, or "pulse", provided by the denominator of the time signature.
2/4 means the time division is the quarter note/crotchet. So rests (and sometimes even actual notes) should preferably be written with values based on that unit. And a rest symbol should not cross the boundaries of the time division.
So, for example for a dotted crotchet rest, you should write a quaver and a crotchet rests. The order depends on the rhythmic pattern, i.e. the crotchet should be aligned with an integer subdivision of the bar.
The rationale for this way of writing rests is that it is much easier to read, specially when reading at first sight.
So, this way:

and not (slightly more difficult to interpret at first sight):

and even less (as a rest symbol "crosses" from one time division unit to the following):

The same exact principles apply to any time signature, in relation to the respective time division unit. However you have to consider if it is a compound time signature or not. The "pulse" of a 6/8, 9/8 or 12/8, again, "by the convention of the time signature", is not a quaver but a dotted quaver (e.g. 2 pulse units of a dotted quaver in a 6/8 bar).
So, for example in a 9/8 time signature you could have:

But absolutely not!:

Note that sometimes it's good to apply this kind of reasoning to notes too, for example if there are complex syncopations. So, this simple example would be normal and acceptable, as it is not a too complex pattern:

But for a rather more complex rhythms and/or time signatures this type of writing would be preferable, as it makes evident how the rhythm pattern fits into the time division:

As a summary, for rests:

Dotted values - never use in simple times, use in compound times to fulfil a time division unit
Never "cross" time division units

Overall one should always try to write, not necessarily in the most concise or "elegant" way, but in the way the makes it easiest for a quick correct interpretation.
Comment: The second example is definitely better. I would still avoid the remaining dotted quaver pause in bar 3. Despite there being no crossing of the time signature natural unit, the same principles apply to subdivisions. Pauses for small units (quavers, semiquavers, etc.) should read as closely as possible as if they were notes grouped by stems. Check the answer identified by @aaron in a comment to your original question, you'll find clarifying examples of how to write groups of stemmed notes and pauses.
Comment: Ok, thank you! I've added another version without the dotted rest. I hope this is fine now?
Comment: Thank you for your detailed answer! I've also edited my question and added two proposals for solution. Do you think any of these would be considered right? I'd be happy hear back from you! Thank you in advance!
Comment: The first example is also bad because the middle of the bar is not visible.


Problemas com if fazendo 2 funções

Question: Tenho que fazer um código onde calculo o imc, mas se a pessoa tiver 15 anos ou menos não ser calculado, mas ainda assim está calculando
#include <stdio.h>

void main()
{
         float peso, altura, imc, idade;
         printf ("digite seu peso:\n");
         scanf ("%f", &peso);

         printf ("digite sua altura:\n");
         scanf ("%f", &altura);

         printf ("digite sua idade:\n");
         scanf("%f", &idade);

      imc = peso/(altura*altura);

               if (idade <=15);{
                  printf ("O IMC não é uma boa medida de sobrepeso para crianças!");
         }
             if (imc < 24){
                      printf ("O seu indice de Massa Corporal e %.2f e esta abaixo do peso ideal\n", imc);
             }
             if (imc >= 25 && imc <=25.99){
            printf("O seu indice de Massa Corporal e %.2f e esta normal\n", imc);
            }

        if (imc >= 26 && imc < 30){
           printf ("O seu indice de Massa Corporal e %.2f e voce esta obeso\n", imc);
           }

       else{
           printf("O seu indice de massa corporal e %.2f e voce esta com obesidade I ou superior\n", imc);
           }
}

Answer: Você estava deixando um ; depois da verificação if, exatamente aqui:  if (idade <=15);{. Com isso seu código sempre pulava para fazer o calculo, já que ele não estava dependendo do if. Segue código corrigido.
#include <stdio.h>

void main()
{
         float peso, altura, imc, idade;
         printf ("digite seu peso:\n");
         scanf ("%f", &peso);

         printf ("digite sua altura:\n");
         scanf ("%f", &altura);

         printf ("digite sua idade:\n");
         scanf("%f", &idade);

      imc = peso/(altura*altura);

               if (idade <=15){
                  printf ("O IMC não é uma boa medida de sobrepeso para crianças!");
         }
             if (imc < 24){
                      printf ("O seu indice de Massa Corporal e %.2f e esta abaixo do peso ideal\n", imc);
             }
             if (imc >= 25 && imc <=25.99){
            printf("O seu indice de Massa Corporal e %.2f e esta normal\n", imc);
            }

        if (imc >= 26 && imc < 30){
           printf ("O seu indice de Massa Corporal e %.2f e voce esta obeso\n", imc);
           }

       else{
           printf("O seu indice de massa corporal e %.2f e voce esta com obesidade I ou superior\n", imc);
           }
}

Answer: Havia um ; em if (idade <=15);{. Fiz outros ajustes, como a adição de else e o reposicionamento do cálculo de imc para executá-lo apenas quando a idade da pessoa for superior a 15, a fim de melhorar a performance.
#include <stdio.h>

void main()
{
     float peso, altura, imc, idade;
     printf ("digite seu peso:\n");
     scanf ("%f", &peso);

     printf ("digite sua altura:\n");
     scanf ("%f", &altura);

     printf ("digite sua idade:\n");
     scanf("%f", &idade);

     if (idade <= 15){
        printf ("O IMC não é uma boa medida de sobrepeso para crianças!");
     } else {

        imc = peso/(altura*altura);

        if (imc < 24){
           printf ("O seu indice de Massa Corporal e %.2f e esta abaixo do peso ideal\n", imc);
        } else
        if (imc >= 25 && imc < 26){
           printf("O seu indice de Massa Corporal e %.2f e esta normal\n", imc);
        } else
        if (imc >= 26 && imc < 30){
          printf ("O seu indice de Massa Corporal e %.2f e voce esta obeso\n", imc);
        } else {
          printf("O seu indice de massa corporal e %.2f e voce esta com obesidade I ou superior\n", imc);
        }
     }
}

Answer: void main() {
float peso, altura, imc, idade;
printf ("digite seu peso:\n");
scanf ("%f", &peso);

     printf ("digite sua altura:\n");
     scanf ("%f", &altura);

     printf ("digite sua idade:\n");
     scanf("%f", &idade);

  imc = peso/(altura*altura);

           if (idade <= 15){
              printf ("O IMC não é uma boa medida de sobrepeso para crianças!");
     }
else{
         if (imc < 24){
                  printf ("O seu indice de Massa Corporal e %.2f e esta abaixo do peso ideal\n", imc);
         }
         if (imc >= 25 && imc <=25.99){
        printf("O seu indice de Massa Corporal e %.2f e esta normal\n", imc);
        }

    if (imc >= 26 && imc < 30){
       printf ("O seu indice de Massa Corporal e %.2f e voce esta obeso\n", imc);
       }

   else{
       printf("O seu indice de massa corporal e %.2f e voce esta com obesidade I ou superior\n", imc);
       }
}
}

Problemas com if fazendo 2 funções


what is the definition of the distance between a complex number with $\mathbb{R}^{+}$?

Question: what is the definition of the distance between a complex number with $\mathbb{R}^{+}$? This is
$$
\text{dist}(z,[0,\infty)) \ \ z \in \mathbb{C}?
$$
Comment: That would be $\inf_{t \in \mathbb{R}^+} |z - t|$.
Comment: @Andrémash The other question you just added is a duplicate of [If $z\in\mathbb C\setminus[0,\infty)$, why $\text{dist }(z, [0,\infty))=:\delta>0$?](https://math.stackexchange.com/questions/4471800/if-z-in-mathbb-c-setminus0-infty-why-textdist-z-0-infty-delta).
Comment: 4 up votes in 45 minutes, for as weak a question as this? And an almost identical question on a different account opened within 2 days of this one?
Comment: It's shorthand for $\text{dist}(\{z\},[0,\infty))$
Comment: @dxiv f $z \in \mathbb{C} \setminus[0,\infty))$ why $\text{dist}(z,[0,\infty)) > 0$?
Comment: $d(z, \mathbb{R}^+) = \inf_{t \in \mathbb{R}^+} |z - t| = \begin{cases} |\text{Im}(z)| &, \text{Re}(z) \geq 0 \\
|z| &, \text{Re}(z) < 0
\end{cases}$
Answer: This distance (from a point to a set, defined as the shortest distance from $z$ to the positive real axis, as said by @Kaind) can be expressed in the following way.
Let us denote by $L$ the left open half space ($\Re(z)<0$) and by $\mathbb{R^+}$ the positive real axis:
$$d(z,\mathbb{R^+})=\begin{cases}|z|,& z \in L\\ |\Im(z)|,& z \notin L \end{cases}$$

The locus of points such that $d(z,\mathbb{R^+})=1.5$.
Comment: @André mash I am out at present. I will answer you soon.
Comment: For the Geogebra programming, I do it by expressing the function as a **polar function** in two steps 1) and 2):                                            1) Definition of the characteristic function of interval $(\pi/2,3 \pi/2)$ by $u(t)=\pi/2 <t<3*\pi/2)  $
   2) Definition of the Curve by $Curve(R*(u(t)+(1-u(t))/|\sin(t)|;t),t,0,2*\pi)$.
Comment: It should be absolute value of imaginary part of z.
Comment: @Kaind you are right. Fixed. Thanks.
Comment: @JeanMarie How do you do this in GeoGebra?
Comment: @JeanMarie How do you prove this algebraically? Formally.
Comment: @JeanMarie   thank you


Comparing two binomial survey answers

Question: I am trying to determine if results of a survey question for two different departments is significant. The question is "Were you fully satisfied by the service you received today?" Answer is Yes / No.
Department A: 52% of 141 customers were satisfied with their service
Department B: 67% of 233 customers were satisfied with their service
Is the difference statistically significant? (I am using excel and don't have access to the more fancy stats packages.)
Comment: This will have a binomial distribution if and only if the answers are independent.
Answer: Building upon Michael Chernick's comment, if they are independent, you can test this with a standard test comparing two proportions. In R:
<code>prop.test( c(73, 156), c(141, 233) )

    2-sample test for equality of proportions with continuity correction

data:  c(73, 156) out of c(141, 233)
X-squared = 7.8991, df = 1, p-value = 0.004946
alternative hypothesis: two.sided
95 percent confidence interval:
-0.25971681 -0.04387799
sample estimates:
prop 1    prop 2
0.5177305 0.6695279
</code>
The p-value is 0.004946

Comparing two binomial survey answers


ApexCharts How to update y-axis scales dynamically?

Question: I am using ApexCharts with the Vue wrapper. I can successfully change the min and max values by setting them with a function. this.options.yaxis[0].min = Number(4500); for example, when I log it out in the console, the value is what I set it to. However, it seems to have no effect on the chart itself, the scales still read defaults of the pushed series.
initGraph(data) {
  var tempNum = 0;
  var tempNum2 = tempNum;
  this.options.yaxis[0].max = Number(5000);
  this.options.yaxis[0].min = Number(4500);
  console.log(this.options.yaxis[0].min);
  console.log(this.options.yaxis[0].max);
  for (var series in data) {
    this.series.push(data[series]);
  }
}

My goal is to change the scales on the y-axis as new series are filtered into the series object.
Answer: You need to update the whole options config and not just a single property to allow the Vue watcher to catch the change.
this.options = {
  yaxis: {
    min: 4500,
    max: 5000
  }
}

Answer: Update option before update series and it works:
chart.updateOptions( {
  xaxis: {
    categories: ["Stackoverflow", "is", "great"]
  },
  yaxis: {
    min: 4500,
    max: 5000
  }
});


Antiderivative of $\lvert z \rvert^2$

Question: How does one determine (or show) that the complex function $f(z)=\lvert z \rvert^2$ does not have an antiderivative? (I'm assuming this because contour integrals along two different curves with the same end points yield different results).
Is there no antiderivative because $\lvert z \rvert^2 = zz^\star = -z^2+2z\Re \{z\}$, and $\Re\{z\}$ is non-integrable?
Answer: The simplest way is to know that every function that is once differentiable in an open set is also twice differentiable, so $f$ cannot have an antiderivatve unless it is differentiable.
But if $|z^2|$ is differentiable, then so is $\bar z  = \frac{|z|^2}z$, and that quite blatantly violates the Cauchy-Riemann equations everywhere!
Answer: $\lvert z \rvert^2$ has no antiderivative for the same reasons that $\lvert \overline{z} \rvert^2$ doesn't:
Prove $\overline{z}^2$ has no antiderivative w/ and w/o using path (in)dependence

Antiderivative of $\lvert z \rvert^2$


Calculate mean and standard deviation of the ratio of two dependent variables

Question: I have an instrument of which I would like to understand the uncertainty on the measurements taken, so that every time that I perform a single measurement, I can apply the error obtained and therefore compare it to other measurements. In order to estimate the uncertainty, I took 30 measurements one after another.
The variable that I am interested in getting out of this instrument is actually the ratio of two variables, A and B, measured by the instrument at the same moment, so that for each round of measurement, I will have a pair (A$_i$, B$_i$), with i = 1, ... 30. My final variable therefore will be $y = \frac{A}{B}$.
What some people in my lab are doing is to take these 30 measurements, calculate the mean and the standard deviation of the ratio as if the ratio were a direct measurement. That is:
$\bar{y} = \frac{1}{N} \sum \frac{A_i}{B_i}$ and $\sigma_y = \frac{1}{N - 1} \sum (y_i - \bar{y})^2$
My first thought, though, would have been to treat A and B as two separate measurements (as they are), dependent to each other (since coming from the same instrument), and to calculate the standard deviation using the error propagation formula:
$\bar{y} = \frac{\bar{A}}{\bar{B}}$ and $\sigma_y = \sqrt((\frac{\partial y}{\partial A})^2 \sigma_A^2 + (\frac{\partial y}{\partial B})^2 \sigma_B^2 + 2 \frac{\partial y}{\partial A} \frac{\partial y}{\partial B} \sigma_{AB})$
Now my question: What is the theoretical difference between the two approaches? When should one use the first (taken that it is the correct approach), and when to use the second?
Answer: $\bar{y} = \frac{\bar{A}}{\bar{B}}$ isn't true. Small example with $n = 2, A = (1, 3), B= (1, 2)$ then $\bar y = 1.25$ but $\frac{\bar{A}}{\bar{B}} = 4/3 = 1.33...$. For the general point consider $C = \frac{1}{B}$ and compare the formula for the Covariance of $A$ and $C$.
If you had strong priors about $A,B$ then maybe it would make sense to model them, but if you just are trying to estimate mean and $\sigma$ of $y$ from just your sample, then you aren't gaining anything by not directly looking at $y$.
Comment: Could you please support this statement with some reference? Because if I look at any book for uncertainty calculation (for example, https://uscibooks.aip.org/books/an-introduction-to-error-analysis-the-study-of-uncertainties-in-physical-measurements-third-edition/), then it is written that for any indirect measurement one should use the error propagation formula. That is where my confusion comes from.
Comment: Maybe I was a little fast on the draw after I saw the error in $\bar y$. I'm not quite an expert on error propagation. We yould test it with a simulation, but I'm not even sure waht you plug in for A,B when you only have a sample.


Using Alarm Manager to Start a Service

Question: I have some code I want to execute at 3:00am every day. I've read the Service Class Documentation and it seems I can use AlarmManager to fire an intent(Activity or Service, I think?), and then, in that intent create and post a message in the Android Notification area.
<code>Calendar threeAM = Calendar.getInstance();
threeAM.set(Calendar.HOUR_OF_DAY,2);
threeAM.set(Calendar.MINUTE,0);
threeAM.set(Calendar.SECOND,0);
threeAM.set(Calendar.MILLISECOND,0);
AlarmManager alarmManager =
         (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, myNotifier.class);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, threeAM.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, PendingIntent.getService(context, 1, i , 0));
Log.i("Service TEST", "Alarm set?" );
</code>
It runs through the code with no problems, but there is no indication that the alarm is set, and the activity doesn't start. I'm using an activity that I know works. I tried wrapping it in a try/catch, nothing in logcat...
Answer: I think you should register your activity to receive boot broadcast receivers so that your application starts on the moment the OS boot up complete. here is the link http://www.androidenea.com/2009/09/starting-android-service-after-boot.html
It will not help in terms of notification but yes it will solve your problem of activity not starting...
Answer: Your code will only work if you execute it before 3am. Otherwise, you will be setting an alarm in the past.
Comment: I've tried setting it to just a few minutes ahead when I was testing it. It seems the start time should launch the activity the first time, and then repeating on the interval argument, is that right? Is there a way to check what alarms are set?
Comment: @cinqoTimo: "It seems the start time should launch the activity the first time, and then repeating on the interval argument, is that right?" -- yes, though I have never used `AlarmManager` to start an activity. "Is there a way to check what alarms are set?" -- the alarms are buried in the `dumpsys` output somewhere. http://developer.android.com/guide/developing/tools/adb.html#shellcommands

Using Alarm Manager to Start a Service


Required MultipartFile parameter 'file' is not present

Question: I am using Spring Boot to test a upload functionality, and getting
'Required MultipartFile parameter 'file' is not present'
error. Following are the 1) JSP, 2) Controller 3) Config Class 4) embedded tomcat log.

JSP page
----------------------------------------------------------------------------
<!DOCTYPE html>

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Message: ${message}

List Of Objects

Upload New File to this Bucket

    <form action="uploadObject" method="post" enctype="multipart/form-data">

                File to upload
                <input type="file" name="file" />

                <input type="submit" name="submit" value="Add" />

    </form>

2. Controller:
@RequestMapping(value = "/uploadObject", method = RequestMethod.POST)
    @Override
    public String upload(@RequestParam("file") MultipartFile file,
            @RequestParam("bucketName") String bucketName,
            Map<String, Object> model) {

        LOG.info("Object name parameter is " + file.getOriginalFilename());
        LOG.info("Bucket name parameter is " + bucketName);
....
}

3) Config Class:
package com.phi.piranha.client.config;

import javax.servlet.MultipartConfigElement;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.MultiPartConfigFactory;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Configuration
@EnableAutoConfiguration
@ComponentScan("com.phi.piranha")
public class PiranhaStorageServiceClientApplication extends
        SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(
            final SpringApplicationBuilder application) {
        return application
                .sources(PiranhaStorageServiceClientApplication.class);
    }

    @SuppressWarnings("PMD.SignatureDeclareThrowsException")
    public static void main(final String[] args) throws Exception {
        SpringApplication.run(PiranhaStorageServiceClientApplication.class,
                args);
    }

    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultiPartConfigFactory factory = new MultiPartConfigFactory();
        factory.setMaxFileSize("1024KB");
        factory.setMaxRequestSize("1024KB");
        return factory.createMultipartConfig();
    }

    @Bean
    CommonsMultipartResolver multipartResolver(){
        return new CommonsMultipartResolver();
    }
}

4) Emedded Tomcat log:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC4)

2014-03-28 14:41:01.216  INFO 2852 --- [           main] c.PiranhaStorageServiceClientApplication : Starting PiranhaStorageServiceClientApplication on USDSFOSFC1NBOPY with PID 2852 (C:\a\workspace\sandbox\s3-poc-client\target\classes started by 310152252)
2014-03-28 14:41:01.220 DEBUG 2852 --- [           main] o.s.boot.SpringApplication               : Loading source class com.phi.piranha.client.config.PiranhaStorageServiceClientApplication
2014-03-28 14:41:01.270  INFO 2852 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6f434304: startup date [Fri Mar 28 14:41:01 PDT 2014]; root of context hierarchy
2014-03-28 14:41:01.273 DEBUG 2852 --- [           main] ationConfigEmbeddedWebApplicationContext : Bean factory for org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6f434304: org.springframework.beans.factory.support.DefaultListableBeanFactory@62b08658: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,piranhaStorageServiceClientApplication]; root of factory hierarchy
2014-03-28 14:41:01.897  INFO 2852 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'multipartResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=piranhaStorageServiceClientApplication; factoryMethodName=multipartResolver; initMethodName=null; destroyMethodName=(inferred); defined in class com.phi.piranha.client.config.PiranhaStorageServiceClientApplication] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration; factoryMethodName=multipartResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/MultipartAutoConfiguration.class]]
2014-03-28 14:41:02.188 DEBUG 2852 --- [           main] ationConfigEmbeddedWebApplicationContext : Using MessageSource [org.springframework.context.support.ResourceBundleMessageSource: basenames=[messages]]
2014-03-28 14:41:02.189 DEBUG 2852 --- [           main] ationConfigEmbeddedWebApplicationContext : Using ApplicationEventMulticaster [org.springframework.context.event.SimpleApplicationEventMulticaster@58a1c2bf]
2014-03-28 14:41:02.495 DEBUG 2852 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Code archive: C:\Users\310152252\.m2\repository\org\springframework\boot\spring-boot\1.0.0.RC4\spring-boot-1.0.0.RC4.jar
2014-03-28 14:41:02.495 DEBUG 2852 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Code archive: C:\Users\310152252\.m2\repository\org\springframework\boot\spring-boot\1.0.0.RC4\spring-boot-1.0.0.RC4.jar
2014-03-28 14:41:02.496 DEBUG 2852 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Document root: C:\a\workspace\sandbox\s3-poc-client\src\main\webapp
2014-03-28 14:41:02.546  INFO 2852 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 9090
2014-03-28 14:41:02.884  INFO 2852 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2014-03-28 14:41:02.885  INFO 2852 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52
2014-03-28 14:41:03.077  INFO 2852 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2014-03-28 14:41:03.077  INFO 2852 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1811 ms
2014-03-28 14:41:03.810  INFO 2852 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2014-03-28 14:41:03.813  INFO 2852 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2014-03-28 14:41:04.356  INFO 2852 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-03-28 14:41:04.483  INFO 2852 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-03-28 14:41:04.483  INFO 2852 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-03-28 14:41:04.744  INFO 2852 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2014-03-28 14:41:04.763 DEBUG 2852 --- [           main] ationConfigEmbeddedWebApplicationContext : Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@11a91abc]
2014-03-28 14:41:04.765 DEBUG 2852 --- [           main] utoConfigurationReportLoggingInitializer :

=========================
AUTO-CONFIGURATION REPORT
=========================

Positive matches:
-----------------

   MessageSourceAutoConfiguration
      - @ConditionalOnMissingBean (types: org.springframework.context.MessageSource; SearchStrategy: all) found no beans (OnBeanCondition)

   PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer
      - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) found no beans (OnBeanCondition)

   JmxAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.jmx.export.MBeanExporter (OnClassCondition)
      - SpEL expression on org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration: ${spring.jmx.enabled:true} (OnExpressionCondition)
      - @ConditionalOnMissingBean (types: org.springframework.jmx.export.MBeanExporter; SearchStrategy: all) found no beans (OnBeanCondition)

   DispatcherServletAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - @ConditionalOnClass classes found: org.springframework.web.servlet.DispatcherServlet (OnClassCondition)

   DispatcherServletAutoConfiguration.DispatcherServletConfiguration
      - no DispatcherServlet found (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)
      - @ConditionalOnClass classes found: javax.servlet.ServletRegistration (OnClassCondition)

   EmbeddedServletContainerAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)

   EmbeddedServletContainerAutoConfiguration.EmbeddedTomcat
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.apache.catalina.startup.Tomcat (OnClassCondition)
      - @ConditionalOnMissingBean (types: org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; SearchStrategy: current) found no beans (OnBeanCondition)

   HttpMessageConvertersAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.http.converter.HttpMessageConverter (OnClassCondition)

   HttpMessageConvertersAutoConfiguration#messageConverters
      - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.HttpMessageConverters; SearchStrategy: all) found no beans (OnBeanCondition)

   HttpMessageConvertersAutoConfiguration.ObjectMappers
      - @ConditionalOnClass classes found: com.fasterxml.jackson.databind.ObjectMapper (OnClassCondition)

   HttpMessageConvertersAutoConfiguration.ObjectMappers#jacksonObjectMapper
      - @ConditionalOnMissingBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found no beans (OnBeanCondition)

   HttpMessageConvertersAutoConfiguration.ObjectMappers#mappingJackson2HttpMessageConverter
      - @ConditionalOnMissingBean (types: org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; SearchStrategy: all) found no beans (OnBeanCondition)

   MultipartAutoConfiguration
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.multipart.support.StandardServletMultipartResolver (OnClassCondition)
      - @ConditionalOnBean (types: javax.servlet.MultipartConfigElement; SearchStrategy: all) found the following [multipartConfigElement] (OnBeanCondition)

   ServerPropertiesAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)

   ServerPropertiesAutoConfiguration#serverProperties
      - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.ServerProperties; SearchStrategy: current) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet,org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter (OnClassCondition)
      - @ConditionalOnMissingBean (types: org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration#hiddenHttpMethodFilter
      - @ConditionalOnMissingBean (types: org.springframework.web.filter.HiddenHttpMethodFilter; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#defaultViewResolver
      - @ConditionalOnMissingBean (types: org.springframework.web.servlet.view.InternalResourceViewResolver; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#requestContextListener
      - @ConditionalOnMissingBean (types: org.springframework.web.context.request.RequestContextListener; SearchStrategy: all) found no beans (OnBeanCondition)

Negative matches:
-----------------

   RabbitAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.amqp.rabbit.core.RabbitTemplate,com.rabbitmq.client.Channel (OnClassCondition)

   AopAutoConfiguration
      - required @ConditionalOnClass classes not found: org.aspectj.lang.annotation.Aspect,org.aspectj.lang.reflect.Advice (OnClassCondition)

   BatchAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.batch.core.launch.JobLauncher,org.springframework.jdbc.core.JdbcOperations (OnClassCondition)

   JpaRepositoriesAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.data.jpa.repository.JpaRepository (OnClassCondition)

   MongoRepositoriesAutoConfiguration
      - required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.repository.MongoRepository (OnClassCondition)

   MongoTemplateAutoConfiguration
      - required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.core.MongoTemplate (OnClassCondition)

   DataSourceAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)

   DataSourceTransactionManagerAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)

   JmsTemplateAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.jms.core.JmsTemplate,javax.jms.ConnectionFactory (OnClassCondition)

   DeviceResolverAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.mobile.device.DeviceResolverHandlerInterceptor,org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver (OnClassCondition)

   MongoAutoConfiguration
      - required @ConditionalOnClass classes not found: com.mongodb.Mongo (OnClassCondition)

   HibernateJpaAutoConfiguration
      - did not find HibernateEntityManager class (HibernateJpaAutoConfiguration.HibernateEntityManagerCondition)

   ReactorAutoConfiguration
      - required @ConditionalOnClass classes not found: reactor.spring.context.config.EnableReactor (OnClassCondition)

   RedisAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.data.redis.connection.lettuce.LettuceConnection,org.springframework.data.redis.core.RedisOperations,com.lambdaworks.redis.RedisClient (OnClassCondition)

   SecurityAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.security.authentication.AuthenticationManager (OnClassCondition)

   ThymeleafAutoConfiguration
      - required @ConditionalOnClass classes not found: org.thymeleaf.spring4.SpringTemplateEngine (OnClassCondition)

   EmbeddedServletContainerAutoConfiguration.EmbeddedJetty
      - required @ConditionalOnClass classes not found: org.eclipse.jetty.server.Server,org.eclipse.jetty.util.Loader (OnClassCondition)

   WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#beanNameViewResolver
      - @ConditionalOnBean (types: org.springframework.web.servlet.View; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#viewResolver
      - @ConditionalOnBean (types: org.springframework.web.servlet.View; SearchStrategy: all) found no beans (OnBeanCondition)

   WebSocketAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.web.socket.WebSocketHandler (OnClassCondition)

2014-03-28 14:41:04.821  INFO 2852 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port: 9090
2014-03-28 14:41:04.829  INFO 2852 --- [           main] c.PiranhaStorageServiceClientApplication : Started PiranhaStorageServiceClientApplication in 4.231 seconds (JVM running for 5.249)

Answer: I figured out that there is an issue with the MultipartAutoConfiguration within spring boot. I disabled it and added @Bean in the web config and it worked. Based on the exception I saw that the Jackson Mapper was trying to resolve the multipart content instead of the multipart resolver itself.
Here is the snippet.
@EnableAutoConfiguration(exclude={MultipartAutoConfiguration.class}

Add the following in your webconfig class
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
    logger.info("Loading the multipart resolver");
    CommonsMultipartResolver multipartResolver
            = new CommonsMultipartResolver();
    return multipartResolver;
}

Comment: After spending hours researching, this is the correct answer.
Comment: @ashoka please provide the pom.xml dependency for this
Comment: https://www.baeldung.com/spring-file-upload
For those spending hours and hours scratching your head. You need to add multipartResolver.
Answer: I think that was a bug in Spring Boot RC4. Did you try with RC5 or a snapshot?
Comment: 1.0.1.BUILD-SNAPSHOT seems to have the same issue the log is below.                                                               ApplicationContext@3fc056f8: startup date [Tue Apr 01 16:21:24 PDT 2014]; root of context hierarchy
2014-04-01 16:21:24.645  INFO 5692 --- [lication.main()] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'multipartResolver': replacing [Root bean: c
lass [null];
Comment: It works for me (eg the getting started guide). That log statement is normal I think.
Comment: Resolved, it works on the file upload to a @Controller.
Comment: still see issue with PUT to a @RestController, posted here http://stackoverflow.com/questions/22847775/spring-boot-request-method-put-not-supported  thanks for your help


Maintaining ViewData between RenderAction calls

Question: I'm rendering a common Log-In form using Html.RenderAction, on every page of my site.
If the user enters their details into the text-box and clicks 'Submit', it does a POST to a controller that handles the log in.
If they make a mistake, such as entering an invalid email address, it will populate the ModelState with an error message and then redirect back to whatever page they were on before.
The problem is, because RenderAction occurs as a separate request, I'm losing the ViewModel.
Even when I put it into TempData it gets lost, since TempData is flushed on each separate request.
Is there a way of preserving data between consecutive Html.RenderAction calls?
If not, any suggestions on how I might be able to hack this? (Should put the data in Session?)
Comment: Note: Looks like I'm not the only one with this issue:
http://forums.asp.net/t/1438013.aspx
Comment: Try this as well:

http://jonkruger.com/blog/2009/04/06/aspnet-mvc-pass-parameters-when-redirecting-from-one-action-to-another/
Answer: Here's what I've done for the time being. (This probably isn't the most ideal solution.)
I created a 'PreserveViewDataAttribute', which I put on any action for which I want to preserve the ViewData in the session.
In my BaseController, I overrode the 'Redirect' method with my own method, which does the following.

Gets a reference to the Action method that called it (a bit of reflection here)
Checks if this method has the 'PreserveViewDataAttribute' defined on it
If it does, copies the current ViewData to a Session variable. (The label of the variable is the same as the current action name, with '_ViewData' tacked onto the end.)
In either case, calls the base Redirect method.

Then I created a property in the BaseController called 'PreservedViewData', which returns the ViewData in session, relevant to the current action. (Or returns null if not found).
Thus, to preserve ViewData as long as I want, I need only decorate my action with  'PreserveViewDataAttribute', and then call 'PreservedViewData' whenever I need it.
Let me know if you want the source-code to this.
Answer: You might like this Post-Redirect-Get section's approach by Kazi Rashid.
http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#prg


catch errors of postgis st_clip, and fix "Could not get band from working raster"

Question: I have millions of polygons, and one larger table of raster (tiled).   I want to st_clip(raster, polygon), then apply st_summarystatsagg() on the clipped raster.  Code looks like below.
with pieces as (
select d.pid,
       st_clip(r.rast, d.geom) as rast
       from tbl_raster as r
       inner join tbl_poly as d
       on st_intersects(r.rast, d.geom)
)
insert into tbl_out(pid, val1, val2, val3)
select pid,
       (stats1).mean as v1,
       (stats2).mean as v2,
       (stats3).mean as v3
from (
     select p.pid,
            st_summarystatsagg(p.rast, 1, true) as stats1,
            st_summarystatsagg(p.rast, 2, true) as stats2,
            st_summarystatsagg(p.rast, 3, true) as stats3
     from pieces as p
     group by p.pid
);

The code works for small subset of polygons (thousands), but when I pass millions, it comes back with error
ERROR:  RASTER_clip: Could not get band from working raster
CONTEXT:  PL/pgSQL function st_clip(raster,integer[],geometry,double precision[],boolean) line 8 at RETURN

I want to get more diagnostic message of what polygon causes this trouble.  Is there any way to do try-catch block type of thing then I am going to dump some info from there. Or let it give some null value or something and make the query to complete, then I look at output for the problem.
Version of postgresql is 9.6.1, postgis is 2.3.1, gdal 2.1.2, and running this on Linux using psql -f.
Thanks!
EDIT:
Following @Eelke's suggestion, I used for loop in PL/pgSQL and identified where the problem is.
It seems that if polygon touches raster with no shared interior points, ST_Clip fails, if there are multiple band calculation requested.  As test code below shows, it seems to work as expected (by me) if I calculate union of raster that ST_Intersects with polygons.  But this turned out to be costly.  I am hoping to find alternative to ST_Intersects, which doesn't pick things up if no interior points are shared.  But I couldn't find a function to do this and couldn't figure out expression...  Is there such expression?
Below is an reproducible results I came up with :
--DROP SCHEMA IF EXISTS test_rast;
--CREATE SCHEMA test_rast;

SET search_path TO test_rast, public;

-- Create raster catalog of 3 bands
DROP TABLE IF EXISTS dummy_rast_3band;
CREATE TABLE dummy_rast_3band(rid int, rast raster);
INSERT INTO dummy_rast_3band(rid, rast)
VALUES
(1, ST_AddBand(
                ST_MakeEmptyRaster(240, 240, 82,   59.6, 6./3600., 6./3600., 0, 0, 4326),
                ARRAY[
                ROW(1, '8BUI'::text, 0, 255),
                ROW(2, '8BUI'::text, 0, 255),
                ROW(3, '8BUI'::text, 0, 255)
                ]::addbandarg[]
        )
),
(2, ST_AddBand(
                ST_MakeEmptyRaster(240, 240, 82.4, 59.6, 6./3600., 6./3600., 0, 0, 4326),
                ARRAY[
                ROW(1, '8BUI'::text, 0, 255),
                ROW(2, '8BUI'::text, 0, 255),
                ROW(3, '8BUI'::text, 0, 255)
                ]::addbandarg[]
        )
) ;

-- Almost identical raster catalogue, the only difference being there is only one  band
DROP TABLE IF EXISTS dummy_rast_1band;
CREATE TABLE dummy_rast_1band(rid int, rast raster);
INSERT INTO dummy_rast_1band(rid, rast)
VALUES
(1, ST_AddBand(
                ST_MakeEmptyRaster(240, 240, 82,   59.6, 6./3600., 6./3600., 0, 0, 4326),
                '8BUI'::text, 0, NULL
        )
),
(2, ST_AddBand(
                ST_MakeEmptyRaster(240, 240, 82.4, 59.6, 6./3600., 6./3600., 0, 0, 4326),
                '8BUI'::text, 0, NULL
        )
) ;

-- Prepare polygon which touches one raster
DROP TABLE IF EXISTS dummy_poly;
CREATE TABLE dummy_poly(pid int, geom geometry);
INSERT INTO dummy_poly(pid, geom)
VALUES
(1, ST_GeomFromText( 'MULTIPOLYGON(((82.4180000000001 59.8655000000001,82.4 59.8655000000001,82.4 59.8745000000001,82.4180000000001 59.8745000000001,82.4180000000001 59.8655000000001)))', 4326));

-- Four tests with ST_Clip()
-- This works, with 1-band raster
SELECT ST_Summary(ST_Clip(r.rast, d.geom))
FROM dummy_rast_1band AS r INNER JOIN dummy_poly AS d
ON ST_Intersects(r.rast, d.geom);

-- This fails with
--   RASTER_clip: Could not get band from working raster
--   CONTEXT:  PL/pgSQL function st_clip(raster,integer[],geometry,double precision[],boolean)
--             line 8 at RETURN
SELECT ST_Summary(ST_Clip(r.rast, d.geom))
FROM dummy_rast_3band AS r INNER JOIN dummy_poly AS d
ON ST_Intersects(r.rast, d.geom);

-- If ask for one band, that works
SELECT ST_Summary(ST_Clip(r.rast, 2, d.geom, true))
FROM dummy_rast_3band AS r INNER JOIN dummy_poly AS d
ON ST_Intersects(r.rast, d.geom);

-- If I union raster into bigger piece, it works
SELECT ST_Summary(ST_Clip(ST_Union(r.rast), d.geom))
FROM dummy_rast_3band AS r INNER JOIN dummy_poly AS d
ON ST_Intersects(r.rast, d.geom)
GROUP BY d.geom;

Comment: I think that if you would write a pgsql function that retrieves the data and processes it row by row you could catch the error and report on which row it occured.
Comment: Thank you for suggestion, that seems a good idea.
Answer: As I said in the EDIT above, I think the problem comes from unexpected behavior of ST_Clip when acting on particular condition: (1) raster has multiband and (2) polygon touches raster with no shared interior.  My workaround it to operate each band separately.  It appears to run slightly slower than the original, but it's not a catastrophe.
with pieces as (
select d.pid,
       st_clip(r.rast, 1, d.geom) as rast1
       st_clip(r.rast, 2, d.geom) as rast2
       st_clip(r.rast, 3, d.geom) as rast3
       from tbl_raster as r
       inner join tbl_poly as d
       on st_intersects(r.rast, d.geom)
)
insert into tbl_out(pid, val1, val2, val3)
select pid,
       (stats1).mean as v1,
       (stats2).mean as v2,
       (stats3).mean as v3
from (
     select p.pid,
            st_summarystatsagg(p.rast1, 1, true) as stats1,
            st_summarystatsagg(p.rast2, 1, true) as stats2,
            st_summarystatsagg(p.rast3, 1, true) as stats3
     from pieces as p
     group by p.pid
);


Getting Permission issue while running flutter app to real device

Question: I am getting permission issue while installing flutter app to real device

Logs

Exception: null. The flutter tool cannot access the file.
Please ensure that the SDK and/or project is installed in a location that has read/write permissions for the current user.

Flutter Doctor

<code>[✓] Flutter (Channel stable, 1.22.6, on Linux, locale en_IN)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
[✓] Android Studio (version 4.0)
[!] VS Code (version 1.52.1)
✗ Flutter extension not installed; install from
https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[!] Connected device
! No devices available

! Doctor found issues in 2 categories.
</code>
Comment: What device do you using?
Comment: samsung galaxy M30s
Answer: Change the permission of the flutter SDK folder and the permission of your project folder.


undefined reference to `gcry_check_version' , what's wrong?

Question: cmake ..
make
then failed to build.
the error message is as follows:
[ 96%] Building C object src/gui/curses/CMakeFiles/weechat-curses.dir/gui-curses-color.o
[ 97%] Building C object src/gui/curses/CMakeFiles/weechat-curses.dir/gui-curses-key.o
[ 97%] Building C object src/gui/curses/CMakeFiles/weechat-curses.dir/gui-curses-main.o
[ 98%] Building C object src/gui/curses/CMakeFiles/weechat-curses.dir/gui-curses-mouse.o
[ 99%] Building C object src/gui/curses/CMakeFiles/weechat-curses.dir/gui-curses-term.o
[100%] Building C object src/gui/curses/CMakeFiles/weechat-curses.dir/gui-curses-window.o
Linking C executable weechat-curses
../../core/libweechat_core.a(wee-network.o): In function `network_init':
wee-network.c:(.text+0x1c): undefined reference to `gcry_check_version'
wee-network.c:(.text+0x30): undefined reference to `gcry_control'
wee-network.c:(.text+0x44): undefined reference to `gcry_control'
collect2: ld returned 1 exit status
make[2]: *** [src/gui/curses/weechat-curses] Error 1
make[1]: *** [src/gui/curses/CMakeFiles/weechat-curses.dir/all] Error 2
make: *** [all] Error 2

my os is centos 5.3, which package i should in stall in order to build this software successfully?
Answer: Apparently you are trying to link an executable, missing libgcrypt library.
See http://www.gnu.org/software/libgcrypt/
Comment: in fact i have installed that lib:(
Comment: how to tell cmake where to find it?
Answer: I had the same issue and found this. Since I'm using Code Blocks I found:

Go to Settings> Compiler and Debugger
Linker Settings
Since the libraries are already installed --> Add the following Link Libraries:
/usr/local/lib/libgpg-error.so
/usr/local/lib/libgcrypt.so

This fixed the compiler errors. :)
Answer: On Ubuntu 15.04, with libgcrypt.h installed in /usr/include (by the repository package), I only had to change the compiler settings. This should work with Ubuntu 14.04/14.10, and probably w/ other Debians.
I'm on Code::Blocks, so my instructions are for that. See the documentation for more information.

Go to Settings -> Compiler... -> Global compiler settings
On the "Compiler settings" tab, click "Other options", and AT THE TOP of that, put 'libgcrypt-config --cflags\' (the ' should actually be a backtick, but SO has odd formatting...)
On the "Linker settings" tab, under "Other linker options:", AT THE TOP put 'libgcrypt-config --libs\' (again, with backticks instead of ').
Click OK and compile your project.


Multiple values in a row

Question: How do I get multiple values (from one field) in a row in the node template? I have a field where a user can select up to 3 values. I would like that to be displayed this way:

Industry: industry1, industry2, industry3

I don't want it displayed like this:

Industry: industry1
            industry2
            industry3

I am using Drupal 7.
Answer: If it's just adding the commas to an array, PHP has implode().
implode(', ', $fields).

I think iRex is asking how to get the values. In this case, I would use the following code.
$fields = array();
foreach ($node->field_name['und'] as $field) {
  $fields[] = $field['value'];
}

Comment: You are right Joe. I'm practically useless with PHP though, and I was looking for the correct syntax
Answer: You should be able to do this in a field template.
If your field is called tester, the template would be called field--field_tester.tpl.php, and it would have code similar to this (assuming the field is a text field):
<?php
  foreach($items as $values => $item) {
    print render($item['#markup']) . ", ";
    }
?>

Doing it in a field template lets you manipulate the field as requirements demand, without messing around with the rest of the node's output format.
Comment: Perhaps I should have mentioned that I'm using Drupal 7. I was trying to display multiple values from a (multiselect) field in a row. I tried using this in a node--mycontenttype.tpl - I hid, then displayed the unchanged multiple values, but came short when tring to rearrange them in a row...

 &item) {
 print render($item['product_image']); }?>
//returns a blank.  So does the following

 &item) {
 print render($content['product_image']); }?> // What am I missing?
Comment: As I suggested, rather than formatting the individual field in the node--mycontenttype.tpl.php template, you can leave the node alone and instead write a field template field--field_fieldname.tpl.php. That will format only the specific field and leave everything else alone.

See the code in my answer, above, for a way to output the field values as comma-separated items all on one line.
Comment: Got it! thanx! This did the tricK:-    $item) {
    print render($item) . ", ";
    }
?>
Answer: There is also a module for that: Field Delimiter

Field Delimiter provides an additional setting for field formatters, allowing multi-value fields to be displayed with a delimiter between the values.
Answer: Could you please post the html structure? We can do it in different way from css(content) to jquery (.after()/.before())
if it's a list you can use
$('ul.YOURCLASS li a:not(:last)').append(', ');

width the css:
li:after
{
content:", ";
}
li.last:after{
  content:none;
}

Comment:
Image

field_product_image[$node->language][0]['safe_value']; ?>

Multiple values in a row


Erro no download de PDF: unknown protocol: c

Question: Estou tentando fazer o download de um arquivo PDF, utilizando JSF..
Porém ao executar o método, a exception é lançada.
Meu Método:
public void download(String pathUrl) throws IOException {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();

        response.reset();   // Algum filtro pode ter configurado alguns cabeçalhos no buffer de antemão. Queremos livrar-se deles, senão ele pode colidir.
        response.setHeader("Content-Type", "application/pdf");  // Define apenas o tipo de conteúdo, Utilize se necessário ServletContext#getMimeType() para detecção automática com base em nome de arquivo.
        OutputStream responseOutputStream = response.getOutputStream();

        // Lê o conteúdo do PDF
        URL url = new URL(pathUrl);
        InputStream pdfInputStream = url.openStream();

        // Lê o conteúdo do PDF e grava para saída
        byte[] bytesBuffer = new byte[2048];
        int bytesRead;
        while ((bytesRead = pdfInputStream.read(bytesBuffer)) > 0) {
            responseOutputStream.write(bytesBuffer, 0, bytesRead);
        }
        responseOutputStream.flush();

        // Fecha os streams
        pdfInputStream.close();
        responseOutputStream.close();
        facesContext.responseComplete();
    }

A Exceção Lançada:

java.net.MalformedURLException: unknown protocol: c   at
  java.net.URL.(Unknown Source)   at java.net.URL.(Unknown
  Source)   at java.net.URL.(Unknown Source)  at
  br.com.cogerh.template.controller.RelatorioBean.download(RelatorioBean.java:137)
    at
  br.com.cogerh.template.controller.RelatorioBean.gerarCapa(RelatorioBean.java:74)
    at
  br.com.cogerh.template.controller.RelatorioBean.gerarRelatorio(RelatorioBean.java:62)
    at
  br.com.cogerh.template.controller.RelatorioBean.init(RelatorioBean.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)   at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:344)
    at
  org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:295)
    at
  org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:130)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:396)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1505)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:334)
    at br.com.cogerh.template.util.ViewScope.get(ViewScope.java:23)     at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:330)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at
  org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1117)
    at
  org.springframework.beans.factory.access.el.SpringBeanELResolver.getValue(SpringBeanELResolver.java:56)
    at
  com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at
  com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:72)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:161)    at
  org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
    at
  com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at
  javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at
  javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIOutput.getValue(UIOutput.java:174)   at
  javax.faces.component.UIInput.getValue(UIInput.java:291)  at
  com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
    at
  com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
    at
  com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
    at
  javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1864)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)    at
  javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:889)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1857)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1860)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1860)
    at
  com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:461)
    at
  com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
    at
  javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    at
  org.apache.myfaces.tomahawk.application.ResourceViewHandlerWrapper.renderView(ResourceViewHandlerWrapper.java:169)
    at
  com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)    at
  com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)   at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at
  org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at
  org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at
  org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at
  org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Answer: Consegui solucionar o problema da seguinte maneira:
Adicionei a String
file:///

Ao meu pathURL, Ficando assim o método:
public void download(String pathUrl) throws IOException {
    pathUrl = "file:///"+pathUrl;
    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();

    response.reset();   // Algum filtro pode ter configurado alguns cabeçalhos no buffer de antemão. Queremos livrar-se deles, senão ele pode colidir.
    response.setHeader("Content-Type", "application/pdf");  // Define apenas o tipo de conteúdo, Utilize se necessário ServletContext#getMimeType() para detecção automática com base em nome de arquivo.
    OutputStream responseOutputStream = response.getOutputStream();

    // Lê o conteúdo do PDF
    URL url = new URL(pathUrl);
    InputStream pdfInputStream = url.openStream();

    // Lê o conteúdo do PDF e grava para saída
    byte[] bytesBuffer = new byte[2048];
    int bytesRead;
    while ((bytesRead = pdfInputStream.read(bytesBuffer)) > 0) {
        responseOutputStream.write(bytesBuffer, 0, bytesRead);
    }
    responseOutputStream.flush();

    // Fecha os streams
    pdfInputStream.close();
    responseOutputStream.close();
    facesContext.responseComplete();
}


jQuery to change background on table row based on values of two cells within that row

Question: I have a tampermonkey script that highlights table rows when specific columns contain specific text.
For example the code below successfully highlights rows were column 1 contains 'M' and rows where column 3 contains 'P'.
$("td:nth-of-type(1):contains('M')").parent().css("background-color","#ccccff");
$("td:nth-of-type(3):contains('P')").parent().css("background-color","#ccccff");

How can I use an AND operator or an IF statement to highlight a row only if column 1 contains 'P' AND column 3 contains 'M'?
Answer: Grab all the
 elements and filter that down to the ones with the  elements matching your requirements.
Once you have that filtered collection, set the background colour.

const MATCH = [{
  col: 0,
  chr: "M"
}, {
  col: 2,
  chr: "P"
}]

$("tr").filter((_, tr) => {
  // get the  children
  const cells = $(tr).children("td")
  // Ensure each MATCH appears in each cell respectively
  return MATCH.every(({ col, chr }) => cells.eq(col).text().includes(chr))
}).css("background-color", "#ccf")

    No capital "m" here
    foo
    No capital "p" here

    Mo Money
    bar
    Mo Problems

    Pass the
    baz
    Mayo please

Comment: Thanks, I've got this is working, now I'm just trying to adapt to check column 1 for a value and column 3 for a value.
Comment: @mshiers I've updated my answer. You should [edit your question](https://stackoverflow.com/posts/71403079/edit) though so it makes sense
Comment: Yes, thank you, this is working great.  I can follow what it's doing but I never would have got that from scratch!  Lots of learning to do.  I've updated my question.