how to check no of times query executed?

Question: I am using Oracle 11gr2 Database. Is there a way to check how many times one particular query executed  and what is total run time of that execution for a current date or with in last 24 hrs? Its like history of sql run time. Please provide your suggestions.
Comment: Will the Query have bind variables?
Comment: I am look for a script that can be used for both type queries one with bind variables and one without.
Comment: Look at the V$sqlarea view.
Answer: <code>select sql_text, sql_fulltext, executions, elapsed_time/1000000 seconds
from gv$sql
order by executions desc;
</code>
This will only return queries that have not aged out of the shared pool, and only give you cumulative run times.  But if you're only interested in the most common queries, chances are they have been used recently and will not age out.
An AWR report, or one of the DBA_HIST_* tables, may also help.  If you have grid control you can very easily select a 24-hour period and generate a report that will display the top queries.

Update:
I don't think there's any way to get statistics for each individual execution.  The historical performance views work by sampling, they do not capture everything.  In practice, this is enough information for performance tuning.  If something doesn't happen often enough to get sampled it's not worth tuning.
AWR can be used to find the approximate number of executions per day:
<code>--Number of Executions today.
select
    --Executions at last snap.
    (
        select executions_total
        from dba_hist_sqlstat
        where snap_id =
            (
                --Latest snapshot.
                select max(snap_id) keep
                    (dense_rank last order by begin_interval_time) end_snap_id
                from dba_hist_snapshot
            )
            and sql_id = '5ms6rbzdnq16t'
    )
    -
    --Executions at beginning of day.
    (
        select executions_total
        from dba_hist_sqlstat
        where snap_id =
            (
                --Snapshot for beginning of the day.
                --Assumes there are hourly snapshots that start on time.
                select snap_id begin_snap_id
                from dba_hist_snapshot
                where trunc(begin_interval_time, 'hh') = trunc(sysdate)
            )
            and sql_id = '5ms6rbzdnq16t'
    ) executions_today
from dual;
</code>
Comment: I have SQLId for a query that I got from AWR report that generated from OEM and I actually wants to find how many times today that query executed and elapsed time for each execution?
Comment: From above Query  i got this error                                                  ERROR at line 4:
ORA-01427: single-row subquery returns more than one row
Comment: That might be because of my assumption about hourly snapshots.  Or maybe the same SQL_ID has multiple rows with different plan hash values?  You'll need to modify the query to fit your needs.


How to properly develop a machine learning model for a poker game?

Question: I've created an annotation for poker games, similar to chess games. After compiling information from thousands of games, I want to use this large data set for machine learning.
To simplify, let's focus on the last betting round of a Texas Hold'em game. The five cards in the table are visible, and the computer needs to take a decision (fold, check, bet or raise). Of course, each action is dependent on the circumstances of the game (e.g. you can only fold if someone has placed a bet).
So, the decision is somewhat between a classification (fold, check, bet) and a regression (bet \$1,000, bet \$1,500, bet \$2,125, etc). And the result should not be 'correct' or 'incorrect', but a payout over your decision. For instance, if you have bet \$1,500 and the others have folded, then you "win" \$1,500. But if someone has a better game than you, then you lost -1 * your bet, or minus \$1,500.
I need to reinforce that there is not a correct option. In poker, you need to maximize your returns in the long run. The exact same decision in an exact similar situation can have different outcomes if the opponent shows a pair of aces or a pair of threes in the last round -- and the computer can't know when to fold and when to bet in this situation, it needs to be consistent in the long run.
So, let's include some requisites:

The overall technique 'result' should be the sum of all the individual instance results;
It would be good to have conditional decisions, e.g. you check, the opponent raises, and then you need to decide again based on this action;
The main goal of this modeling is to implement different machine learning techniques, and use the data set to evaluate them.

Any suggestions of an existing technique which I should base my modeling?
Comment: I would start with some basic EV.  Get some reads on how often players will bluff and fold.  Check out Sklansky Theory of Poker.  ML with poker is very advanced.
Comment: This would appear to be a combination of two problems: modeling the utility of alternative game actions and probability models for those poker hands. The probability of poker hands and outcomes is well-covered already, but you'll need to make your own models for what the utility of game actions is. Some gamblers are risk takers, some are not, but it's not necessarily obvious which is better. What's optimal in this sense depends on specific goals. Moreover, I'm not sure that machine learning is particularly relevant here, so much as a utility model.
Comment: I think it would be wise to label the players and try to cluster them, i.e. are they risk takers or conservative. As @user777 explains, all the probabilities of poker hands are known. It is maybe better/safer to start of as a conservative player and try to figure out what kind of players you are against and try to add that into your model. There are also plenty of other features that you can add, such as [pot odds](https://en.wikipedia.org/wiki/Pot_odds) and other things.
Comment: Your modelling approach/assumptions appear to disregard betting and positioning information. It seems to focus almost exclusively to card equity. Yeah, this isn't going to be an straight-forward ride for you. Also just google "Poker Bots" and see the Wikipedia article on [Computer Poker Players](https://en.wikipedia.org/wiki/Computer_poker_players). You seem to (unintentionally) turn a blind eye to a lot of specialised poker literature. (+1  to @Paparazzi)
Answer: Generally, reinforcement learning is what you're looking for, though most reinforcement learning implementations focus on perfect information games (e.g. pong), not imperfect information games (e.g. poker).
A deep reinforcement learning algorithm has recently achieved super-human play in full-scale Limit Hold'em. Of the machine learning approaches to AI poker, this is state-of-the-art, though it is still ~5BB/100 hands worse than the best domain-specific expert AI (excluding the AI that effectively solved the game).
I suspect we'll see deep reinforcement learning approaches to no-limit start to be competitive with top domain-specific expert AI in the next 5 years.


Initialising a public module-level variable

Question: My VBA module has multiple subroutines. In most of them I calculate the last non-empty row so as to avoid loading unneeded cells.
Once the code checks which is the last non-empty cell of the second worksheet in the current workbook for the first time, the value of the variable stays constant throughout the changes done to the worksheet with the subroutines. So I am trying to declare and initialise it only once, instead of every time for each subroutine.
The declaration works:
Option Explicit

Public lastrow As Long

Public Sub CleanOrderNumbers()

 With Worksheets(2)

        Dim range As range

        lastrow = .Cells(Rows.Count, "A").End(xlUp).Row
        Set range = .range("A2:A" & lastrow)
        range.Replace What:="#", Replacement:="OrdNo"

 End With

End Sub

However I'd like to initialise the variable only once as well and avoid the repeating Cells(Rows.Count, "A").End(xlUp).Row.
I've tried using a function or a sub to take care of the initialisation.
Option Explicit

Public lastrow As Long

Public Function myrow()

lastrow = Worksheets(2).Cells(Rows.Count, "A").End(xlUp).Row
'alternatively as a constant?
'Const lastrow As Integer = Worksheets(2).Cells(Rows.Count, "A").End(xlUp).Row

End Function

Public Sub CleanOrderNumbers()

 With Worksheets(2)

        Dim range   As range

        Set range = .range("A2:A" & lastrow)
        range.Replace What:="#", Replacement:="OrdNo"

End With

End Sub

To no avail. Am I missing something in the syntax? Or is this supposed to be done in an entirely different way?
Answer: It doesn't look like you are calling myrow()?
Call myrow() or set the variable directly when the workbook opens by adding an event handler in the ThisWorkbook module:
Option Explicit

Private Sub Workbook_Open()
    lastrow = Worksheets(2).Cells(Rows.Count, "A").End(xlUp).Row
    'or
    myrow
End Sub

Answer: The definition as Const will not work in VBA as they cannot be initialized at runtime, a Const needs to be defined at compile time.
To avoid that the End-command is executed over and over again, you could simply check if the value is already set
If lastrow = 0 Then lastrow = Worksheets(2).Cells(Rows.Count, "A").End(xlUp).Row

Having lastrow defined as global would mean that this statement will be put everywhere in the code, so the idea to have a function instead is good. If I where you, I would name the function itself lastrow and rename the variable - now the rest of the code doesn't need to be changed at all.
Dim myLastRow as Long

Public Function lastrow()
    If myLastRow  = 0 Then
        myLastRow = Worksheets(2).Cells(Rows.Count, "A").End(xlUp).Row
    End If

    lastrow = myLastRow
End Function

Now that would still leave myLastRow as global variable. If you want to avoid that (and force the code to exclusively use the function), declare it as Static local variable.
Public Function lastrow()
    Static myLastRow as Long
    If myLastRow = 0 Then
        myLastRow = Worksheets(2).Cells(Rows.Count, "A").End(xlUp).Row
    End If
    lastrow = myLastRow
End Function


Firestore + React.js how to get documents from a collections by filtering from user?

Question: I have three fields for data, by default in the constructor they all setted to all. What ı want to do is making multiple queries on these fields like in mysql. For example: where field1 is apple, field2 is orange and ı do not touch the field 3.(Tumu means "All" by the way.) Here is my code:
class Kurumlar extends Component {
constructor(props) {
    super(props);
    this.state = {
        data: [],
        isLoading: true,
        page: 1,
        HizmetTuru: "Tumu",
        HizmetAlani: "Tumu",
        Ucretlendirme: "Tumu"
    };
}

handleChange = e => {
    this.setState({
        [e.target.name]: e.target.value
    }, console.log(this.state));
}

componentDidMount() {
    const db = firebase.firestore();
    let docs = db.collection("Paydaslar")

    console.log(this.state)

    //docs = db.collection("Paydaslar").where("HizmetTuru", "==", this.state.HizmetTuru);
    docs.get()
        .then(snapshot => {
            let data = [];
            snapshot.forEach(doc => {
                if (doc.data().isVisible) {
                    data.push(doc.data());
                }
            });

            this.setState({ data, isLoading: false });
        })
        .catch(err => {
            console.log("Error getting documents", err);
        });
}

componentDidUpdate(){
    const db = firebase.firestore();
    let docs = db.collection("Paydaslar")

   if(this.state.HizmetTuru != "Tumu"){docs=db.collection("Paydaslar").where("HizmetTuru", "==", this.state.HizmetTuru)}
   if(this.state.HizmetAlani != "Tumu"){docs=db.collection("Paydaslar").where("HizmetAlani", "==", this.state.HizmetAlani)}
  if(this.state.Ucretlendirme != "Tumu"){docs=db.collection("Paydaslar").where("Ucretlendirme", "==", this.state.Ucretlendirme)}

    docs.get()
        .then(snapshot => {
            let data = [];
            snapshot.forEach(doc => {
                if (doc.data().isVisible) {
                    data.push(doc.data());
                }
            });

            this.setState({ data, isLoading: false });
        })
        .catch(err => {
            console.log("Error getting documents", err);
        });
}

By this way if 1 field is setted to a value(different from all(Tumu in the code), other fields do not work.
Comment: Also another thing ı couldn't figure out how can ı select all in the where query in firestore?
Answer: If I understand correct you want to build a query with multiple possible conditions, depending on what the user selected.
In that case you can use the builder pattern:
const db = firebase.firestore();
let query = db.collection("Paydaslar").collection("Paydaslar")

if(this.state.HizmetTuru != "Tumu") {
  query = query.where("HizmetTuru", "==", this.state.HizmetTuru)
}
if(this.state.HizmetAlani != "Tumu") {
  query = query.where("HizmetAlani", "==", this.state.HizmetAlani)
}
if(this.state.Ucretlendirme != "Tumu"){
  query = query.where("Ucretlendirme", "==", this.state.Ucretlendirme)
}

docs.get()
  ...

Answer: I figured it out just in the if parts, do:
    if (this.state.HizmetTuru != "Tumu") { docs = docs.where("HizmetTuru", "==", this.state.HizmetTuru) }
    if (this.state.HizmetAlani != "Tumu") { docs = docs.where("HizmetAlani", "==", this.state.HizmetAlani) }
    if (this.state.Ucretlendirme != "Tumu") { docs = docs.where("Ucretlendirme", "==", this.state.Ucretlendirme) }


Bishop - Pattern Recognition & Machine Learning, Exercise 1.4

Question: I'm working on exercise 1.4 in Bishop's Pattern Recognition & Machine Learning book.
This exercise is about probability densities. I've two questions about this exercise.
First, I don't understand equation 1.27. He writes:
"Under a nonlinear change of variable , a probability density transforms differently from a simple function, due to the Jacobian Factor."
I never ever heard about the Jacobian factor. What is that factor?
"For instance, if we consider a change of variables $x = g(y)$, then a function $f(x)$ becomes $\tilde f(g(y))$. Now consider a probabilty density $p_x(x)$ that corresponds to a density $p_y(y)$ with respect to the new variable $y$, where the suffices denote the fact that $p_x(x)$ and $p_y(y)$ are different densities. Observations falling in range $(x, x + \delta x)$ will, for small values of $\delta x$, be transformed into the range $(y, \delta y)$ where $p_x(x)\delta x \simeq p_y(y)\delta y$, [...]"
What does the relation $\simeq$ mean in this context?
"[...] and hence
$$
\begin{align}
p_y(y) &= p_x(x) \left| \frac{\text{d}x}{\text{d}y}\right|\\
&= p_x(g(y))\left|g'(y)\right|."
\end{align}
$$
This is equation 1.27. I don't understand where this equation comes from. Why is there this absolute value?
"One consquence of this property is that the concept of the maximum of a probabilty density is dependent on the choice of variable."
And at this point the book refers to exercise 1.4:
"Consider a probability density $p_x(x)$ defined over a continous variable $x$, and suppose that we make a nonlinear change of variable using $x = g(y)$, so that the density transforms according (1.27). By differentiating (1.27), show that the location $\hat y$ of the maximum of the density in $y$ is not in general related to the location $\hat x$ of the maximum of the density over $x$ by the simple functional relation $\hat x = g(\hat y)$ as a consequence of the Jacobian factor. This shows that the maximum of a probability density (in contrast to a simple function) is dependent on the choice of variable. Verify that, in the case of a linear transformation the location of the maximum transforms in the same way as the variable itself."
I don't understand, what this exercise asks me to do... :/
Would be great, if someone could help me...
Answer: Equation 1.27 is called the change of variables theorem. I will try to explain it briefly here considering the same variables that the book mentions. $y \sim p_y$ and $x \sim p_x$ are the two random variables whose transformation is given by a function $g$,  i.e.
$$
\begin{equation}
x = g(y)
\end{equation}
$$
The question here is how does applying a transformation to $y$ affects the resultant density of $x \sim p_x$?
we know that probability densities integrate to 1.
$$
\begin{aligned}
\int p_y(y) dy =& \int p_x(x) dx = 1\\
p_y(y) =& p_x(x) |\frac{dx}{dy}|\\
p_y(y) =& p_x(g(y)) |\frac{dg(y)}{dy}|\\
p_y(y) =& p_x(g(y)) |g^{\prime}(y)|
\end{aligned}
$$
where the term $|g^{\prime}(y)|$ is called the Jacobian determinant of the function $g$ wrt $y$. || does not denote absolute value, but the determinant. More intuitively, this determinant is telling us about the infinestimal change in volume in $p_y(y)$ that your function $g$ causes. The video will give you a better idea about this.
Comment: In this case $|g'(y)|$ is the absolute value, since $y$ and $x$ are not vectors, they are scalar variables.
Answer: The reason for the term involving $|g(y)|$ originates from the change of variables from $x$ to $y$. When we change from $p_X(x)$ to $p_Y(y)$, we have to ensure that the integral over the probability distribution is still equal to one.
Supposing the change of variables is monotonically increasing, let $F_X(x)$ be the cumulative distribution function of $x$, then the cumulative distribution function
$$
F_Y(y)=P(Y\leq y)=P(X\leq g(y))=F_X(g(y))
$$
and the probability distribution function of Y is
$$
p_Y(y)={d\over dy}F_Y'(y)=p_X(g(y)){d g(y)\over dy}=p_X(g(y))\left|g'(y)\right|
$$
Since $g'(y)>0$ the absolute value is unnecessary, but in the case that the transformation is monotonically decreasing, we actually get $-g'(y)$ term, which again is $|g'(y)|$, so this absolute value sign covers both cases.
There is more information in statistics texts such as this.

I don't understand, what this exercise asks me to do...

What the exercise is asking you to do is to differentiate equation (1.27) with respect to $y$ to find the maximum value, where this derivative is equal to zero, and then show that this is not necessarily in the same place as the maximum value of $x$. It's a straightforward application of the product rule for differentiation.


how to use slidingmenu with sherlockActivity?

Question: I want to use SlidingMenu with SherlockActivity. I am not getting exactly how to use it.I am able to integrate both the library i.e.(SlidingMenu and SherlockActionBar).I tried it in the following manner.
public class MainActivity extends SherlockActivity {

private SlidingMenu slidemenu;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
            createSlidingMenu();
}

public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
    // TODO Auto-generated method stub
    menu.add("Search")
    .setIcon(android.R.drawable.ic_search_category_default)
    .setActionView(R.layout.collapsible_edittext)
    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS |  MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

    return true;
}

private void createSlidingMenu() {

    slidemenu = new SlidingMenu(this);
    slidemenu.setShadowDrawable(R.drawable.shadow);
    slidemenu.setShadowWidthRes(R.dimen.shadow_width);
    slidemenu.setFadeDegree(0.35f);
    slidemenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
            slidemenu.attachToActivity(this, SlidingMenu.SLIDING_WINDOW);
    slidemenu.setMenu(R.layout.sliding_view);
    slidemenu.setSlidingEnabled(true);
}
 }

I am able to show the menu with slide but that menu screen is occupying the whole screen not partial screen.And another issue is I want to show the menu with onclick of button on which is on the top-left corner of the screen.How I can achieve this.
Answer: I have used this library https://github.com/SimonVT/android-menudrawer/ check sample of that library and i have also used actionbarsherlock

code is below...
package com.example.slider;

import net.simonvt.menudrawer.MenuDrawer;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class MainActivity extends SherlockActivity {

    private static final String STATE_MENUDRAWER = "net.simonvt.menudrawer.samples.WindowSample.menuDrawer";
    private static final String STATE_ACTIVE_VIEW_ID = "net.simonvt.menudrawer.samples.WindowSample.activeViewId";

    private MenuDrawer mMenuDrawer;
    private TextView mContentTextView;

    private int mActiveViewId;

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

        setContentView(R.layout.activity_main);

        if (savedInstanceState != null) {
            mActiveViewId = savedInstanceState.getInt(STATE_ACTIVE_VIEW_ID);
        }

        mMenuDrawer = MenuDrawer.attach(this, MenuDrawer.MENU_DRAG_WINDOW);
        // mMenuDrawer.setContentView(R.layout.activity_windowsample);
        mMenuDrawer.setMenuView(R.layout.menu_scrollview);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getSupportMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onRestoreInstanceState(Bundle inState) {
        super.onRestoreInstanceState(inState);
        mMenuDrawer.restoreState(inState.getParcelable(STATE_MENUDRAWER));
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(STATE_MENUDRAWER, mMenuDrawer.saveState());
        outState.putInt(STATE_ACTIVE_VIEW_ID, mActiveViewId);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            mMenuDrawer.toggleMenu();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        final int drawerState = mMenuDrawer.getDrawerState();
        if (drawerState == MenuDrawer.STATE_OPEN
                || drawerState == MenuDrawer.STATE_OPENING) {
            mMenuDrawer.closeMenu();
            return;
        }

        super.onBackPressed();
    }

}

do not forgate set theme in android manifest file in your activity
<activity
            android:name="com.example.slider.MainActivity"
            android:theme="@style/Theme.Sherlock.Light"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Comment: @Dharwal Sodha i used the same library but I am not getting the instance of `MenuDrawer` class.Can you please tell me what may be the issue.
Comment: @Akshay he has used [android-menudrawer](https://github.com/SimonVT/android-menudrawer)
Answer: Finally I manage to achieve in the following manner.Changes I did in the Sliding menu library is SlidingActivity extends Activity so I changed it to SherlockActivity and then used in the following manner and it works great.
For doing this you need to add SherlockAction-Bar library in the SlidingMenu-library.
public class WhatsUpActivity extends SlidingActivity {

    private SlidingMenu slidingMenu;

    @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.whats_up);

    slidingMenu = getSlidingMenu();
    slidingMenu.setMode(SlidingMenu.LEFT);
    slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
    slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
    slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
    slidingMenu.setFadeDegree(0.35f);
    setBehindContentView(R.layout.menu_layout); //Menu view left side.

    setSlidingActionBarEnabled(true);
    }
}

hope this will be helpful for some one in future :)
Comment: @COLDICE wel come buddy :)


Traps and pitfalls in elementary algebraic manipulation

Question: Given the equation $x=x+2$:
\begin{align}
x &=x+2 \\\\
x-x &=2 \\\\
0&=2
\end{align}
This impies there is no solution
Given the equation $x+1=0$:
\begin{align}
x + 1 &=0 \\\\
\frac{x+1}{x+1} &= \frac{0}{x+1}  \\\\
1&=0
\end{align}
Clearly, the conclusion that there is no solution is invalid.
Is there a set of algebraic manipulation dos and don'ts to avoid such errors?
Comment: There was nothing wrong with the manipulation in the first case.  The initial equation, $x=x+2$, was already impossible.  For the second, don't divide by $0$.
Comment: @DietrichBurde I'm not criticising you or anything, but I don't think a response using group theory is very helpful for the OP. The OP did specifically mention "elementary". But whatever, you've been here longer than me so you probably know better :)
Comment: @Ajay Yes, I know. This is meant as a perspective, not as a practical answer. I find it important to realise that an equation is not just an equation, but depends on in which domain (or field, or whatever) you consider the equation.
Comment: @Ajay The OP may not know what a field is, but that $2=0$ is possible, he/she may have heard already from computer science, or from odd plus odd is even. Why not point to it? What is the point not to do it? If the OP doesn't like it, he/she can simply ignore it. But perhaps the OP will be curious about it, why not? Then the OP can still search for a video.
Comment: The equation $x=x+2$ over a field is equivalent to $2=0$, which is true for all fields of characteristic two, e.g., in $\Bbb Z/2\Bbb Z$, but false otherwise.
Comment: @TymaGaidash Yes, this is what I meant. Our students learn this modular arithmetic much earlier than elliptic integrals of the second kind, for example. So I was surprised.
Comment: @DietrichBurde I understand where you're coming from, but what's the point? I seriously doubt the OP even knows what a field is. I think what would have been better was for you to add some more explanation. Maybe a link or video explaining what fields are and what characteristic 2 means with some accompanying explanation. That would definitely have helped the OP see your perspective.
Comment: @DietrichBurde Fair point.
Comment: @DietrichBurde How is there any finite solution to $x=x+2\iff 0=2\iff$false? It looks like this field is defined to be a solution to the equation when there seemingly cannot be one.
Comment: @TymaGaidash  What do you mean by "seemingly cannot be"? Of course $2=0$ is true in $\Bbb Z/2\Bbb Z$. Then $0$ corresponds to even numbers, and $1$ to odd numbers. Clear $2=1+1=0$, because "odd plus odd is even". Some people write $2\equiv 0\bmod 2$, but in the field $\Bbb Z/2\Bbb Z$ this means the equality $2=0$. You are doing so advanced integrals, so that you certainly know this first semester material.
Comment: @DietrichBurde By "seemingly cannot be true", it was assumed the set of real numbers solved $x=x+2$, so it was confusing how a field could solve the equation. However, after a search, $\Bbb Z/2\Bbb Z$ relates to [modular arithmetic](https://en.wikipedia.org/wiki/Modular_arithmetic) which does allow this behavior.
Answer: First case:
You write:

$x=x+2 \rightarrow  x-x=2$

Algebraically, you added $-x$ to both sides. The operation is correct. However, the starting point was not correct. I mean what does $x=x+2$ tell us? It says that there is a quantity equals itself plus 2. This statement is illogic. Hence, the problem is in applying the algebraic operation to an expression that is not logical. Such cases appear when proving some statements by supposing the opposite argument and proceed with algebraic operations to stop when such an illogic expression appears meaning that the assumption was false.
Second Case:
You write:

$x+1 = 0$
$\frac{x+1}{x+1} = \frac{0}{x+1} \rightarrow  1=0$

Division operation is undefined or illegal operation (well, maybe with one exception...see below) when you divide by explicit zero figure or an expression that is zero. This is the "defensive" approach to obtaining logical results that we were taught in school.  One way to see why this is so, when you consider the relationship between division and subtraction. For example, $\frac{6}{2}=3$ can be seen as the unique number of subtracting operations of $(6-2)$ until zero is reached. In case of division by zero, the number of operations is not unique it could be one, two, etc.
This restriction in division is adopted by all computer programming languages use (to my knowledge).
Violating this restriction could possibly lead to invalid expression, and performing operations on invalid expression leads to illogic results.
In cases, one may be interested in the value of the function $f(x)$ when the value very near, but not equal, zero. In such cases, we use the limit techniques.
You can read more about this here: Wiki-Division By Zero.
I am aware of one case (very famous) where division by zero expression looks-like it works. This is the case of the Remainder Theorem. When you have a polynomial like $p(x)=x^2-1$ and you know that $x+1$ is a factor bit not the last factor of p(x), you can write $p(x)=\frac{x^2-1}{x+1}=x-1$. This is a valid case! It is not easy to see why this is valid without some knowledge in Analysis. For more on this you may want to look at Introduction to Division by Zero Calculus.


Paypal validation error in create method

Question: 1)The problem is that $paypal->create($api) Returns such an error
 Exception: Got Http response code 400 when accessing
    https://api.sandbox.paypal.com/v1/payments/payment. string(271) "
    {"name":"VALIDATION_ERROR","details":
    [{"field":"transactions.amount","issue":"Currency should be a valid ISO
    currency code"}],"message":"Invalid request - see
    details","information_link":"https://developer.paypal.com/docs/api/
    payments/#errors","debug_id":"cea4b8e54646c"}"

2)this is my code
$paypal = new \PayPal\Rest\ApiContext(
    new \PayPal\Auth\OAuthTokenCredential(
        'XXX',
        'YYY'
    )
);

$paypal->setConfig([
    'mode' => 'sandbox',
    'http.ConnectionTimeOut' => 30,
    'log.LogEnabled' => false,
    'log.fileName' => '',
    'log.LogLevel' => 'FINE',
    'validation.level' => 'log'
]);

$payer = new Payer();
$details = new Details();
$amount = new Amount();
$payment = new Payment();
$transaction = new Transaction();
$redirectUrls = new RedirectUrls();

//Payer
$payer->setPaymentMethod('paypal');

//Details
$details->setShipping('2.00')
    ->setTax('0.00')
    ->setSubtotal('20.00');

//Amount
$amount->setCurrency('USA')
    ->setTotal('20.00')
    ->setDetails($details);

//Transactions
$transaction->setAmount($amount)
    ->setDescription('Add balance');

$redirectUrls->setReturnUrl('http://thechaller.com/paypal/pay')
    ->setCancelUrl('http://thechaller.com/paypal/paypalCancel');

$payment->setIntent('sale')
    ->setPayer($payer)
    ->setRedirectUrls($redirectUrls)
    ->setTransactions([$transaction]);

try {
    $payment->create($paypal);
} catch (\PayPal\Exception\PayPalConnectionException $e) {
    echo "Exception: " . $e->getMessage() . PHP_EOL;
    var_dump($e->getData());
    exit(1);
} catch (Exception $e) {
    echo $e->getMessage();
    exit(1);
}

3) client id and secret take from here
This is screen shot
Comment: The first thing you are doing is resetting whatever key/secret you have, even if it's for a sandbox.
Comment: Yes, please do that. I have edited your post, but your credentials are still visible in the edit history. Please change them, as Scuzzy as already said.
Answer: You have $amount->setCurrency('USA'). It should be $amount->setCurrency('USD'). It's explained in the error message:

Currency should be a valid ISO currency code

the valid ISO currency code for USA is USD.
Comment: That's because your tax and subtotal adds up to 22, while the total is set to 20. Do you even read the error-messages you get?
Comment: Thanks for this answer I already fixed this error but the code does not work yet
Comment: Exception: Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment. string(319) "{"name":"VALIDATION_ERROR","details":[{"field":"transactions[0].amount","issue":"Transaction amount details (subtotal, tax, shipping) must add up to specified amount total"}],"message":"Invalid request - see details","information_link":"https://developer.paypal.com/docs/api/payments/#errors","debug_id":"15f5b6503f1d"}"
Comment: Thank you very much for the answer


Is it possible to use the Forena module in conjunction with the Flot module?

Question: I need to plot based on some data that will be fetched from an external (non-drupal) database. I have found the Forena module, but in the part I do not like about the graph utility it uses by default.
Is it possible to use the Flot module in conjunction with Forena?
The Forena module says: "Virtually any JavaScript library may be used with Forena to produce amazing displays".
How is it implemented?
Answer: I'm not aware of a way to use the Flot module in conjunction with the Forena (disclosure: I'm a co-maintainer) module.
About "Virtually any JavaScript library may be used with Forena ...": have a look at the feature request # 2364427, especially these comments in it:

Comment nr 7, which is about a module for using Forena data with the d3js library.
Comment nr 15, which is about a related sandbox project.
Comment nr 18, about the D3 strategy.

Another approach is to write your own "renderer", as a variation of the FrxSVGGraph renderer (which extends FrxRenderer), and which is how the current support for the PHP SVGGraph library is implemented.


Inequality with summation of cosine terms $\left|1 + 2\sum_{j=1}^k \cos (\frac{2\pi n}{q}j) \right| \leq 1 + 2\sum_{j=1}^k \cos (\frac{2\pi }{q}j)$

Question: I got stuck on the following problem:
Let $q\in \mathbb{N}$ be a fixed odd number and $k,n \in \{ 1,…,\frac{q-1}{2}\}$.
I want to show that
$$ \left|1 + 2\sum_{j=1}^k \cos (\frac{2\pi n}{q}j) \right| \leq 1 + 2\sum_{j=1}^k \cos (\frac{2\pi }{q}j).$$
By simple manipulations one can see that this is equivalent to
$$\left| \frac{\sin(\frac{2k+1}{q}\pi n)}{\sin(\frac{\pi}{q}n)} \right| \leq \frac{\sin(\frac{2k+1}{q}\pi )}{\sin(\frac{\pi}{q})}.$$
Any ideas?
Answer: Since
$$
\sum_{j=-k}^ke^{\frac{2\pi n i}{q}j}=\frac{\sin(\frac{2k+1}{q}\pi n)}{\sin(\frac{\pi}{q}n)}
$$
this enequality is equivalent to
$$
\left| \frac{\sin(\frac{2k+1}{q}\pi n)}{\sin(\frac{\pi}{q}n)} \right| \leq \frac{\sin(\frac{2k+1}{q}\pi )}{\sin(\frac{\pi}{q})},
$$
or
$$
\left| \frac{\sin(\frac{2k+1}{q}\pi n)}{\sin(\frac{2k+1}{q}\pi )} \right| \leq \frac{\sin(\frac{\pi}{q}n)}{\sin(\frac{\pi}{q})}.\tag{1}
$$
Also note that due to $k,n \in \{ 1,…,\frac{q-1}{2}\}$ one has $\sin(\frac{2k+1}{q}\pi )>0$,$\ \sin(\frac{\pi}{q}n)>0$,$\ \sin(\frac{\pi}{q})$.
Now consider two cases:
$\bf{1.}$$\ n=2m+1$. Then $(1)$ can be written as
$$
\left|\sum_{j=-m}^me^{\frac{2\pi(2k+1) i}{q}j}\right|\le \sum_{j=-m}^me^{\frac{2\pi i}{q}j}.\tag{2}
$$
The sum $\frac{1}{2m+1} \sum_{j=-m}^me^{\frac{2\pi i}{q}j}$ has a simple interpretation as the x-coordinate of the center of mass of $2m+1$ particles of equal mass placed on the unit circle in the positions $z_j=x_j+iy_j=e^{\frac{2\pi i}{q}j}$,$\ -m\le j\le m$ (due to the symmetry y-coordinate of the center of mass of this system is $0$). Observe that $\frac{m}{q}\le\frac{1}{q}\left(\frac{q-1}{4}-\frac{1}{2}\right)<\frac{1}{4}$, which means that all $x_j>0$, i.e. all $2m+1$ particles are on the right half plane(this fact will be used below).
In the following analysis we wil use the fact that center off mass of the particles $z_j=e^{\frac{2\pi i}{q}j}$,$\ -m\le j\le m$ will be farther away from the origin than center of mass of any other system (which has mirror symmetry with respect to x-axis) of $2m+1$ particles placed in different positions $z_j=e^{\frac{2\pi i}{q}j}$ of the unit circle.
(i) If $2k+1$$(k\neq 0)$ and $q$ are relatively prime, $(2)$ can be easily proved as follows. One can see that in this case all $z_j'=e^{\frac{2\pi(2k+1) i}{q}j}$, $\ -m\le j\le m$ will be different. So center of mass will be closer to the origin than in the case $k=0$, thus proving $(2)$ when $2k+1$$(k\neq 0)$ and $q$ are relatively prime.
(ii) If $2k+1$$(k\neq 0)$ and $q$ have a common factor $s\ge 3$, then for sufficiently small $k,m$ the coordinates $z_j'=e^{\frac{2\pi(2k+1) i}{q}j}$, $\ -m\le j\le m$ still can be different, and in this case one can apply the same argument as in (i).
However for sufficiently large $k,m$ there will be particles with the same $z_j'$. Let $0\le r< \frac{q}{s}$ be residue of $m$ $(\text{mod}\ \frac{q}{s})$. Since
$$
\sum_{j=0}^{q/s-1}e^{\frac{2\pi(2k+1) i}{q}j}=0
$$
there will be only $2r+1$ particles that contribute to the sum $\sum_{j=-m}^me^{\frac{2\pi(2k+1) i}{q}j}$. Therefore $(2)$ can be written as
$$
\left|\sum_{j=-r}^re^{\frac{2\pi(2k+1) i}{q}j}\right|\le \sum_{j=-m}^me^{\frac{2\pi i}{q}j}.\tag{3}
$$
This inequality can be proved by considering center of mass of $2m+1$ particles of equal mass:
$2r+1$ particles at different positions $e^{\frac{2\pi(2k+1) i}{q}j}$, $\ -r\le j\le r$ and the rest placed symmetrically at two points $z=\pm i$. Center of mass of this system will be always closer to the origin than $\frac{1}{2m+1} \sum_{j=-m}^me^{\frac{2\pi i}{q}j}$.
$\bf{2.}$$\ n=2m$. $(1)$ can be written as
$$
\left|\sum_{j=1}^me^{\frac{\pi(2k+1) i}{q}(2j-1)}+ c.c.\right|\le\sum_{j=1}^me^{\frac{\pi i}{q}(2j-1)}+ c.c.\tag{4}
$$
where c.c. means complex conjugate. The same analysis as above can be applied to prove this inequality.


AngularJS .openModel() reurns error not a function

Question: I have a project which combines AngularJS and Materialize CSS which opens a model with id #modal-some-form using AngularJS $('#model-some-form').openModel();.
Now I have another project with similar code, same JQuery, AngularJS and Materialize versions, but when trying to open the model I get:

Error: $(...).openModel is not a function

The code for the model is:

Andika bango jipya

                Ujumbe wa bango unahusu nini?

                    <select class="browser-default">
                      <option value="" disabled selected>Chagua</option>
                      <option value="1">Option 1</option>
                      <option value="2">Option 2</option>
                      <option value="3">Option 3</option>
                    </select>

                    mode_edit
                    <textarea id="ujumbe" class="materialize-textarea"></textarea>
                    Ujumbe wa bango

                    add Tuma
                    close Ghairi

And the code for my Angular script is:
var myApp = angular.module('myApp',[]);

myApp.controller('myController', function($scope, $http){

    $scope.openBangoForm = function(){
        $("#modal-bango-form").openModel();
    }

    $scope.closeBangoForm = function(){
        $('#modal-bango-form').closeModel();
    }

});

Neither closeModel() nor openModel(), but on the other project it runs well.
Please assist.
Regards
Comment: You are doing it wrong, you should not use jQuery methods in controller. Also it shoukd probably be openMod**a**l.
Comment: You do realize a fairy dies every-time you use jQuery in a controller? How are you calling those two methods? Has the DOM rendered and those elements with the id present when they run? Don't forget angular dynamically renders things. You should put those jQuery calls in a directive. Thats where they belong, its also why directives provide you with a jQuery/jqlite object.
Comment: check out my answer here http://stackoverflow.com/questions/40083395/materializecss-modal-error-openmodal-is-not-a-function/40937195#40937195
Answer: I came to realize before @dfsq replied to my question that i was misspelled the modal with model.
Fixing the line $('#modal-bango-form').openModel(); with $('#modal-bango-form').openModal(); fixed the problem.
It's dumb, but took me a day to figure out, duh!...
Hope will help someone there....


Is it possible to hide one div and show another div after scrolling 50% or more?

Question: i have one section inside 2 DIV's where the div's name 1st div and 2nd div . By Default 2nd div will be hidden, after scrolling 50% or more 1st div will be hidden and 2nd div will be displayed. How do i do that?
I used:
var heightDivid = $(window).height() / 2;
$(window).on('scroll', function(e){
    $('.sections-class').each(function(){
        if(this.getBoundingClientRect().top <= heightDivid ){
             $(this).removeClass('heightDivids') ;
        }
        else{
             $(this).addClass('heightDivids') ;
        }
    })
})

Comment: create a fiddle of your scenario and will be able to help you
Comment: Please show existing code. This site is not intended for us to make your project for you. There are many javascript ways to do this, but without something to elaborate on we are basically just writing all of your code.
Answer: Perhaps you can alter something along these lines to do what you're attempting to do.
Utilize jQuery's scrollTop to identify where you want the change to occur.
Set a limit for when you want to hide the one div and show the two div.
$(window).scroll(function() {
    var height = $(window).scrollTop();
    if(height  >  10) {
        $('.two').show();
        $('.one').hide();
    }
});

Example: http://jsfiddle.net/xv2m4qn6/
If you want the effect to reverse simply add a second conditional:
Example: http://jsfiddle.net/xv2m4qn6/1/
Answer: At Last I did :) and it's work for me .... Thank you all for your help :)
 var shadowEdgePoint = $(window).height() / 2;
    $(window).on('scroll', function(e){
        $('.section-class').each(function(){
            if(this.getBoundingClientRect().top <= shadowEdgePoint){
                         $('.two').show();
                        $('.one').hide();
            }
                else{
                        $('.two').hide();
                        $('.one').show();
                    }
        })
    });


Show that $(\sin x/x)^n\geq(\sin x_1\sin x_2...\sin x_n)/(x_1 x_2 ...x_n)$.

Question:
Suppose $0<x_i<\pi$ for $i=1,2,...n$ and $x=(x_1+x_2+...+x_n)/n.$
Show that $(\sin x/x)^n\geq(\sin x_1\sin x_2...\sin x_n)/(x_1 x_2 ...x_n)$.

By Jensen inequality, I showed that
$L.H.S\geq(\sin x_1+\sin x_2+...+\sin x_n)/(x_1+x_2+ ...+x_n)$.
But I don't know what to do then. Please help, Thanks.
Comment: One could rather use the fact that $u:x\mapsto\log(\sin(x)/x)$ is concave by checking that $u''(x)$ has the sign of $\sin^2(x)-x^2\leqslant0$, and apply Jensen to *that*.
Comment: Did you use jensen's on log(sin())?
Comment: @GautamShenoy you can post this as hint-like answer
Answer: First note that since $x\ge\sin(x)\ge0$ on $[0,\pi]$,
$$
\begin{align}
\frac{\mathrm{d}^2}{\mathrm{d}x^2}\Big(\log(\sin(x))-\log(x)\Big)
&=\frac1{x^2}-\csc^2(x)\\[6pt]
&\le0
\end{align}
$$
Therefore,
$$
f(x)=\log\left(\frac{\sin(x)}{x}\right)
$$
is concave. Jensen's inequality says that
$$
f\left(\overline{x_i}\right)\ge\overline{f(x_i)}
$$
which is $\frac1n$ times the log of the given inequality.
Answer: Hint: Apply Jensen's on log(sin(x)/x).
Comment: But a<b and c<d can't imply a-b<c-d...
Comment: @GautamShenoy: I should say it does.
Comment: But log and log(sin) are both concave hence the convexity/concavity of their difference does not follow.
Comment: You're right. I flipped the inequality incorrectly. Fortunately the edit I've made suffices. As you suggested.


ADFS 2.0 single sign out fails after multiple signin and signout

Question: Hi I am facing following issue for single sign out in ADFS 2.0.
I am using ADFS 2.0 as RSTS
Another ADFS 2.0 is registered as claim provider and is configured for Forms authentication.
I have 4 relying parties (RPs) hosted on another IIS server m/c.
I am opening all the 4 RPs in IE after authenticating against Claim Provider. Sign-out works perfectly fine for the first time. But if I sign-in again and click on sign-out ,any one of the RP application remains signed-in after refresh.I could also see the Auth cookie remaining there after sign-out is processed by the ADFS/LS site.
Note: single sign-out work correctly for multiple sign-in and sign-out if the count of RP apps is restricted up to 3.
Am I missing any settings in RSTS?
How R-STS remembers all the RPs for which it's creating the signout cleanup request (wa=wsignoutcleanup1.0)?
If it's a known issue in ADFS2.0, is it resolved in higher version of ADFS (3.0) any guess?
Thanks in advance.
Answer: I found the work around and mentioned the details here , but still following questions need some light
1)why that R-STS's adfs/ls site does snot sign-out one or more RP app(s) for multiple sign-in , sign-out. Is it like R-STS's adfs/ls site is randomly loosing one or more RP url in this case?
2)How R-STS's adfs/ls site is maintaining the RPs url and why single sign out does not work in case of multiple sign-in , sign-out without closing the browser?
3) Is this a known bug and is it fixed in higher version of ADFS say 3.0? or any thing I am missing in handling the single sign out?


Transfer money between users?

Question: Is there a way with Drupal to transfer money between users? Im making a skill sharing website, so users can buy and sell their skills. Thanks
Comment: No, you need to make use of 3rd party payment gateways like PayPal.
Answer: I think the Ubercart funds module that is the best answer for your question; the module still has a development snapshot only, though.
This will make you able to transfer funds through your drupal sites to different users.

Ubercart Funds implements a Site Funds Management System using Ubercart, It integrates features like Deposit Funds, Withdraw Funds, Transfer Funds..etc, which makes implementing most features of a Money site like Paypal or Skrill possible and easy using Drupal.
Comment: There is a Commerce Userpoints module that allows buy stuff with points or buy points (patch in the issue queue), but getting cash out again is not something that is currently available for Userpoints as far as I'm aware of. I actually don't know of a module that would allow something like this in general, not sure how this would work. PayPal e.g. seems to have some sort of API for this, so users would have to provide their paypal account, see http://stackoverflow.com/questions/4191887/how-to-send-money-to-paypal-using-php
Comment: As I understand that would allow users to buy points and then exchange points, but I still need to allow users to 'cash out' and exchange those points for real money. Does this have to be done manually? Thanks
Answer: Was just looking into this myself and came across Commerce Funds.

Commerce Funds implements a Site Funds Management System using Drupal Commerce, It integrates features like Deposit Funds, Withdraw Funds, Transfer Funds..etc, which makes implementing most features of a Money site like Paypal or Skrill possible and easy using Drupal.

Transfer money between users?


403 forbidden error when loading images in test server

Question: Am working with drupal7.When images are loading below error is showing in my test site console:
GET sites/default/files/styles/slideshow_full/public/plans/30989/main-image/contemporary_house_plan_westbrook_30-065_front.jpg?itok=TkUdCJQ5 403 (Forbidden)

When I paste the above URL in browser it is showing that "You are not authorised to access this page" error.
I checked all the permissions and all has 777.
But the same functionality  is working with my local site.Can anyone give me a suggestion to solve this issue?
Answer: This is a typical result of an incorrect url path.
That folder may/may not exist on the test server, but because it's outside of your user's folders, you 'don't have permission to access' it.
For example: Typical user's folders for cPanel are /home/USER/ with the site root at /home/USER/public_html. But, typical for a local machine is /var/www/....
So when you call sites/default/... from a local machine, it is possible that it's actually looking at /var/www/sites/default/.... When doing that on the test server, the path would be outside your user's folder and therefor no access permission.
It could be as simple as a missing ../ on your relative paths.
So you could try 1. adding ../ to the start of your paths and see if that takes it to the correct location.
or 2. Try explicitly setting the base url in your settings file $base_url = 'http://foobar.com'; to force a starting point for relative paths.


lmer: standardized regression coefficients

Question: I  have analyzed some data (the exact nature of which, I assume, is irrelevant for this question) using linear mixed effects models with the lmer() function from lme4.
There has been at least one question about standardized regression coefficients previously, in which, obviously, there has been the recommendation to use the scale() function in order to obtain standardized predictors and outcome variables before entering these into a model.
Furthermore, in a comment on an answer, @crash posted a link to an email by Ben Bolker, in which the latter provided a function, applying lm.beta() to "lmer-land".
The function, as provided there, looks like this:
lm.beta.lmer <- function(mod) {
   b <- fixef(mod)[-1]
   sd.x <- apply(mod at X[,-1],2,sd)
   sd.y <- sd(mod at y)
   b*sd.x/sd.y
}

Yet, the "mod at X" and "mod at y" parts are hyperlinked and appear not to resemble executable R code. Specifically, when trying to define this function, R outputs
Error: unexpected symbol in:
"b <- fixef(mod)[-1]
sd.x <- apply(mod at"

so apparently R does not like the spaces.
I am interested in how I would need to change the code of lm.beta.lmer() in order to successfully apply this to my lmer models, but my nooby R skills forbid me to do so.
If anyone provided a useful answer to this, I would deeply appreciate this.
Cheers, bunsen
EDIT
Thanks @Wolfgang, I was not aware of this. However, having changed the abovementioned code accordingly, i.e. writing mod@X and mod@y, I get the following output when applying the function to a model:
>lm.beta.lmer(mod)
Error in apply(mod@X[, -1], 2, sd) :
no slot of name "X" for this object of class "lmerMod"

Apparently, the code fails to access the Field X in slot pp of the lmerMod object (of which the first column is labelled "(Intercept)", so I assume it is the one that should be deleted). Since I get this error, I do not know, whether the Field y of slot resp of this object will be accessed, but I guess not.
I have attempted various ways of changing the code in order to make it access the X and y fields of the respective slots, but failed. Which part am I doing incorrectly, or rather (since I do not tell the ways I've tried): which is a possible way to access these fields?
I have noticed, that most likely I will be faster using the scale() function, but I am eager to learn a solution to my question.
Thanks again!
Comment: The `mod at X` parts are supposed to be `mod@X`. Mailing lists often replace "@" with " at " to make it more difficult for spammers to farm e-mail addresses.
Comment: Thanks @Wolfgang. However, there are problems that follow and I have edited my question accordingly.
Answer: You can get at X and y using the getME() function. So, this should work:
lm.beta.lmer <- function(mod) {
   b <- fixef(mod)[-1]
   sd.x <- apply(getME(mod,"X")[,-1],2,sd)
   sd.y <- sd(getME(mod,"y"))
   b*sd.x/sd.y
}

Comment: Minor fix for cases when there there's only a single predictor (in which case this throws an error as the dim of getME(mod,"X")[,-1] = NULL) would be to coerce getME(mod,"X")[,-1] into something with dimensions ~ e.g., (although I'm sure there's a more efficient version and this may cause later problems!):

lm.beta.lmer <- function(mod) {
   b <- fixef(mod)[-1];
   sd.x <- apply(matrix(getME(mod,"X")[,-1]),2,sd);
   sd.y <- sd(getME(mod,"y"));
   b*sd.x/sd.y;
}


Are absolutely continuous functions analytic?

Question: I am asking for a proof that any absolutely continuous function with absolutely continuous derivatives is analytic, once I am studying a function with the first property and 'd like to obtain the second one.
I know that exist smooth functions that are not analytical, but and if the derivatives are absolutely continuous?
If I am wrong, a counterexample is really welcome.
Thank you.
Comment: Just integrate my example then.
Comment: An absolutely continuous function might not be differentiable. For example $|x|$.
Comment: @ArcticChar oh, sorry, I mean with absolutely continuous derivative. Thank you
Comment: @ArcticChar, so, if I understand well, $x|x|/2$ has abs. cont. first derivative $|x|$... but $x|x|/2$ is not analytical..? Sorry, I could not understand very well. Maybe you 'd like to post your counterexample as answer if you have time. But anyway thank you so much!
Answer: You are asking whether any absolutely continuous function, all of whose derivatives exist and are absolutely continuous, is analytic.  This is false.  Counterexample: any smooth, nonanalytic function.
Indeed, any smooth function on an interval $(a,b)$ is absolutely continuous (on any closed subinterval $[c,d]$ of $(a,b)$), and all its derivatives exist and are also absolutely continuous.
This is because if $f: [c,d] \rightarrow \mathbb R$ is continuous and differentiable on $(c,d)$, with continuous derivative, then $f$ is already absolutely continuous.
Answer: A famous counterexamples can be obtained by studying the function
$$f(x)=\begin{cases} e^{-\frac{1}{x}} & \text{ when }x>0, \\ 0 &\text{ when }x\leq 0.\end{cases}$$
This function happens to be $\mathcal{C}^\infty(\mathbb{R})$ (this requires some work but nothing beyond calculus)
Then, the function $\phi (x)=f(1-x)f(x+1)$ is also in $\mathcal{C}^\infty(\mathbb{R})$, is nonnegative and vanishes outside $(-1,1)$. Hence, $\phi$ along with all its derivatives, is absolutely continuous. This function however is not analytic!
This kind of functions (some variations of them rather) are called smooth mollifiers. This is also a related Wikipedia article.
Answer: Posting the comment above as answer, as requested.
The function
$$g(x) = \frac{1}{2} x|x|$$
is differentiable everywhere, with
$$g'(x) = |x|$$
absolutely continuous. However, $g$ is not analytic: if $g$ is analytic, then $g'$ is differentiable. So this $g$ is a counterexample.
An absolutely continuous function (which might not be differentiable) in general is far from analytic. Even when a function is infinitely differentiable, it might not be analytic as the other answer shows.


Cholesky decomposition in python, recursive

Question: I am trying to make a recursive program to compute the Cholesky factorization, but the output is not in lower triangular form. How can I change this to compute it correctly?
def cholesky(A):

    n = np.shape(A)[0]
    A[0,0] = math.sqrt(abs(A[0,0]))

    if n == 1:
        return A
    else:
        A[1:,0] /= A[0,0]
        A[1:,1:] -= np.dot(A[1:,0], (A[1:,0]).T)
        cholesky(A[1:,1:])

Comment: take a look at `numpy.linalg.cholesky`
Answer: I'm sure there's a prettier way (in particular, numpy.linalg.cholesky), but this looks like it does ok on reasonable test data.  I follow the notation from the wikipedia article, and use their example as the test data.
import numpy as np

def cholesky_reduce(A):
    pivot = A[0, 0]
    b = np.mat(A[1:, 0])
    B = A[1:, 1:]
    return B - (b.T * b) / pivot

def L(A):
    n = A.shape[0]
    if n == 1:
        return np.sqrt(A)
    b = np.mat(A[1:, 0])
    pivot = np.sqrt(A[0, 0])
    return np.bmat([
        [np.mat(pivot), np.zeros((1, n - 1))],
        [b.T / pivot, L(cholesky_reduce(A))]
    ])

def __main():
    A = np.array([[4, 12, -16], [12, 37, -43], [-16, -43, 98]])
    print(L(A))

if __name__ == '__main__':
    __main()


jquery load function not working

Question: function newPage(pagenum)
{
  /* load page default from server - pass product name */
  $('#data').html("
Loading.....
").load(
    '/college/college_change.php',
    { product:'college',
      city:"<?php echo $city ?>",
      university:"<?php echo $university ?>",
      programmes:"<?php $programmes ?>",
      type:"<?php echo $type ?>",
      entrance_exams:"<?php echo $entrance_exams ?>",
      pagenum:pagenum
    });
}

you can just check the code / page at
http://abc.com/tempcollege
I am using this load function, it works well in most browsers, but in IE it does not load the data.
Answer: Are you certain it isn't loading? Could be that it is, but you have a layout glitch in IE that causes your data to not show. This is sometimes the case when an AJAX request seems to work in standards-compliant browsers, but not IE.
Try adding a callback to your load() with a simple alert() of the data returned. See if IE shows the data. If so, then it is some sort of layout issue.
$('#data').html("
Loading.....
")
          .load('/college/college_change.php',
                 {   product:'college',
                     city:"<?php echo $city ?>",
                     university:"<?php echo $university ?>",
                     programmes:"<?php $programmes ?>",type:"<?php echo $type ?>",
                     entrance_exams:"<?php echo $entrance_exams ?>",
                     pagenum:pagenum
                 },
                 function(data) { alert(data) }  // Verify data received (or not)
               );

EDIT:
Be sure you wrap your jQuery code such that it runs after the DOM is loaded.
Either:
$( function() {
    // my jQuery code
});

Or:
$(document).ready( function() {
    // my jQuery code
});

They are effectively the same.
Comment: @patrick - i had done that. it does not alert anything in IE.
Comment: @pradeep - Do you get any errors in IE's developer tools? Any chance that you actually have a trailing comma after `pagenum` in your code?
Comment: @pradeep - So you get an `alert()`, but it is blank? Or you get no `alert()` popup at all?
Comment: @pradeep - So this is fixed now, right? You selected an answer, so I assume so.
Comment: @patrick - nope dude , still not working. it does not alert anything in IE
Comment: @pradeep - If it's not fixed, you shouldn't select an answer. You clicked the checkmark next to the answer **gnarf** gave. Click it again, and I'll have another look.
Comment: @pradeep - I don't imagine that the `.html()` call has anything to do with it. But perhaps you could try it without that just to eliminate it as a potential problem.
Comment: @patrick - okie i did that. i will try solutions . you can check the live page at link i have given and see if you can find some errors
Comment: @patrick - hey i was wrong . i think i was looking at cache earlier. when i alert(data). its getting the page. but not getting displayed in the div.
Comment: @pradeep - Works for me in IE, but first I get `Object Expected submenu.js Line 2 Character 1` error. Make sure `submenu.js` is loaded **after** jQuery loads. Also, turn on debugging in IE's developer tools. You'll see the error.
Comment: @pradeep - Just got your other comment. So it is likely a display issue.
Comment: @patrick - does the page load in ur IE??if so whts ur IE version. i am using IE 6.0 .
Comment: @pradeep - Your script appears in the middle of the page. It appears as though you are running the script **before** the `#data` element has been loaded. Place the script at the **bottom** of the page, or (preferably) wrap it in `$(function(){ // my code })`. I'll update my answer.
Comment: @patrick - hey if u see my code .. its as per u say
Comment: @patrick - i did put newPage(0); at end of page .. but did not work.
Comment: @pradeep - I see. The debugger cut off the end of the script, so I had to copy/paste it into my editor. I'll have another look.
Comment: @pradeep - Can you eliminate some of the HTML that is loaded? When you had an alert, I think I saw a script in there. Maybe there's an issue with that? Everything else looks good right now.
Comment: @pradeep - Also, I see that above the `#data` element, you have an element with the ID `#response`, but then you are creating another element with ID `#response` in your HTML call `.html("Loading.....")`. You can not have 2 elements with the same ID. I think this especially causes trouble in IE.
Comment: @patrick - i removed the extra div also. but no success found :(..any other idea ?
Comment: @pradeep - Have you tried without this? --> `.html("Loading.....")` I don't know why that would make a difference, but who knows. Also, it is so much easier to debug if you organize your scripts into a separate file, rather than embedding them in the middle of your HTML.
Comment: @patrick - i tries a simple code like $.post('/college/college_change_temp.php',{product:'college',city:"",university:"",
programmes:"",type:"",
entrance_exams:"",pagenum:pagenum},
function(data)
{
$('#data').html(data);
}
); also then also did not work..
Comment: @patrick - hey i tried to print just hello from back end and it printed it. but while printing whole data .its failing.  any thing i should specifically check in php/css?
Comment: @pradeep - You were definitely getting the data you requested since the `alert()` was popping up with the expected HTML. There must be some sort of markup error in the data. IE can be fickle. Try to simplify the HTML being returned, and narrow down the issue that way.
Answer: First, you forgot to echo the $programmes.
Second, when I use php to set variables in JavaScript I always declare the variables before I use them.
var theCity = '<?php echo $city; ?>';

$([...]).load('/college/college_change.php/', {city: theCity},
function(r) {
    alert('done loading');
});

And are you sure you did the linking right to the php-script? It's easy to mess up with the slash in the beginning of the path string.
I hope this will be to any help.
Comment: the same path works for FF. does its meaning different in IE?. okie i will correct the echo mistake and check

jquery load function not working


Why do I get a startup error of R, when I try to start Rstudio?

Question: New information:
I have installed a previous version of r-studio (rstudio-1.3.1093-amd64.deb) as was implied in the link that @MViking sent me, and know I am getting a more informative error.
Firstly, at the terminal I get the following message:
<code>"Uncaught TypeError: Cannot read property 'notifyRCrashed' of undefined"
</code>
Then, the popup window of rstudio appears as shown below:
Comment: Maybe this answer will help with your error message "The R session process exited with code 127"  https://stackoverflow.com/questions/63448572/install-rstudio-on-ubuntu-20-4-error-code-exited-status-127
Comment: What happens when you start `R` in a normal terminal window?
Comment: @DirkEddelbuettel When I start R in the terminal I get the normal R workspace interface
Answer: Problem solved by installing the default R and rstudio version!


Por que não consigo pegar os dados da form?

Question: algo muuuuito estranho ta acontecendo, primeira vez que isso acontece.
Tenho um formulário de cadastro. quando clico em salvar, no console aparece 'undefined' e alinha... Impossível ser 'undefined' pois existem dados preenchidos!!! Vejam abaixo:
HTML
<form name="formAddress" ng-controller="InicialCtrl">
    Nome do estabelecimento
    <input class="form-control" type="text" name="name" mg-model="estabele.nome">

    CEP
    <input class="form-control" type="text" name="cep" mg-model="estabele.cep">

    Endereço
    <input class="form-control" type="text" name="address" mg-model="estabele.and" >

    Cidade
    <input class="form-control" type="text" name="city" mg-model="estabele.cidade" >

    UF
    <input class="form-control" type="text" name="uf" mg-model="estabele.uf" >

    Contato
    <input class="form-control" type="text" name="phone" mg-model="estabele.telefone">

    <button class="btn btn-block btn-primary btnRegister" ng-click="cadastro(estabele)">Cadastrar</button>
</form>

controller:
app.controller("InicialCtrl", ['$scope', '$http', '$window', '$location', '$rootScope', function ($scope, $http, $window, $location, $rootScope) {

$scope.cadastro = function(estabele){
    console.log(estabele);
}

}]);

Answer: Porque você esta usando mg-model invés de ng-model.
Comment: Compartilho desses deslizes hahahaha
Comment: É mesmo velho... Valeu... Acho que de tanto escrever essas diretivas, a gente escreve tão rápido que não se dá conta quando escrevemos errado e depois nos matamos para encontrar o problema achando que está tudo certo e não olhamos as coisas mais óbvias kkkkk
Abraçõo.


How do you prevent twig variable from last instance of template overriding those that go before it?

Question: I am creating a module that will allow editors to display nodes as "cards" using the summary from the node for the card text and a field (field_hero) as a background image to the card, the user can then click-thru to the actual content from the card.  The editor can also define, via the layout builder the colour behind the text for the card and also where the text appears (top, left, right, bottom).
If I add several of these cards to a page using the layout builder, all of the cards use the values for position and colour from the last instance placed on the page.
My code block plugin code is:
<code>  public function build() {
if ($entity_id = $this->configuration['entity']) {
  if (($entity = $this->entityStorage->load($entity_id)) && $entity->access('view')) {
    $render_controller = \Drupal::entityTypeManager()->getViewBuilder($entity->getEntityTypeId());
    $view_mode = isset($this->configuration['view_mode']) ? $this->configuration['view_mode'] : 'default';

    if (isset($this->configuration['card_colour'])) {
      $entity->card_colour = $this->configuration['card_colour'];
    }
    if (isset($this->configuration['card_layout'])) {
      $entity->card_layout = $this->configuration['card_layout'];
    }

    return $render_controller->view($entity, $view_mode);
  }
}

return [];
</code>
}
And my twig template is (ignore the empty url() in the style attribute):
<code>{%
    set classes = [
        'node-card',
        'card-' ~ node.card_layout|clean_class,
        node.card_colour|clean_class,
        'clearfix'
    ]
%}
<article{{ attributes.addClass(classes) }}>
    <div{{ content_attributes.addClass('bg-img', 'clearfix') }} style="background-image: url()">
        <div class="summary">
            {{ content.body }}
        </div>
    </div>
</article>
</code>
Answer: $render_controller->view() invokes hook_ENTITY_TYPE_view() and this would be a better place to add custom values to the entity view.
Although probably not good practice you could get your approach working by cloning the entity before modifying the field values:
<code>$entity = clone $entity;
</code>
In any case you need to adjust caching so that you store for each variant a different cache item in the render cache. For example by adding cache keys to the build array before returning it:
<code>$build = $render_controller->view($entity, $view_mode);
if (isset($entity->foo)) {
  $build['#cache']['keys'][] = $entity->foo;
}
return $build;
</code>
Comment: Thanks for the answer. The clone method doesn't seem to change anything.  I am at a loss to see how I can use the hook method as the values I need to add to the node are held in the layout builder block configuration, which would not be accessible in the hook_ENTITY_TYPE_view.
Comment: The clone method shows no results because there might be a second problem with the render cache, see the edit.
Comment: Thanks 4k4 - I had already started down the path of the cache keys, I'm wrestling with cache contexts now! At least I now know where I'm going.


How to give class name to no results behavior in views

Question: I added price column first to view > hide it. I added special price column to view > in no results behavior i added price field token as below:
[field_price]

How to give a css class name to the 'no results behavior text'?
Thanks,
D
Answer: Can you add a class to the no results token? Like
[token].
Dunno if it works that way. Try that.


Music notation with valid use of B## and E##

Question: Can anyone show me a piece of repertoire that validly uses B## and E## notes?
I've had people tell me that of course they exist, but have never been able to give me an example; or they try to build a theoretical example using something like the key of A# major, rather than the much more simple Bb major.
This is just to prove to myself that a double-accidental is always a white note on the piano. :)
Comment: Why do you need a piece of music to validate double sharps? An augmented 5th above A# is E##, for example in an **A#+7** chord. Also, double sharps (which are not necessarily accidentals) are not always white keys. B## is enharmonic to C#, and E## is enharmonic to F#, neither of which are white keys.
Comment: It's the practicality of coming across them in sheet music - I stumbled over a lot of double sharps in a piece until I realised they were always the next white note up, then they were no problem. There are examples here of E## and Cbb which would seem to be quite rare, and then B## and Fbb would be rarer still. So the 'always a white note' thing might be a good enough heuristic.
Comment: A good heuristic for what purpose?  It would be far less confusing just to recognize that a double sharp is just two half steps higher, whether the note is black or white.
Answer: Here is Scriabin's study op. 42, no. 5, bar 18, which includes an E-double-sharp...
Answer: I don't know about pieces using B## or E##, but I can give an example of a piece of piano music using Cbb: Godowsky's paraphrase on Strauss's "Die Fledermaus". In the section below,

there is a Cbb in the left hand in the third bar, which is a double-accidental and which is a black note on the piano (enharmonic to Bb).
Answer: F♯♯maj13♯11 consists of the notes F♯♯-A♯♯-C♯♯-E♯♯-G♯♯-B♯♯-D♯♯
Enharmonic to Gmaj13♯11.
Used in C♯♯ major as a IV chord.
How to theoretically use this absolute mess of a chord: If you started a piece in D♯ minor, then modulated to E♯ minor, then to E♯ major, then went to C♯♯ minor, then to C♯♯ major, you could theoretically use this chord as the IV. Basically, thorugh a bunch of modulations, it's possible to get there. Or you could be smart and just write augmented chords in sharp keys.


Restrict access for a specific forum to a specific user role

Question: I am using Drupal 8 and the core Forum module.
I have several forums on a site.
I wish to restrict access for some of the forums based on the role of the user.
eg:
<code>Forum A: 'Moderator' and 'Role A' can access ('Role B cannot access')
Forum B: 'Moderator' and 'Role B' can access ('Role A cannot access')
</code>
I cannot seem to find a way to do this and am having trouble finding a straight answer about how to do it online.
Answer: Taxonomy Access Control Lite is a good module to achieve this.

This node_access module governs access to nodes based on the taxonomy
  terms applied to the nodes. A simple scheme based on taxonomy, roles
  and users controls which content is visible.
As the name implies, this module shares some functionality with an
  earlier module called Taxonomy Access Control (TAC). If you are
  shopping around for an access control module to use, consider that one
  as well. See this module's README.txt for an explanation of "why yet
  another access control module".

I have implemented one of my site for same purpose.
You can also go for
Content Access and ACL modules.

This module allows you to manage permissions for content types by
  role and author. It allows you to specifiy custom view, edit and
  delete permissions for each content type. Optionally you can enable
  per content access settings, so you can customize the access for each
  content node.

One more Option Using Group module.

The Group module allows you to create arbitrary collections of your
  content and users on your site and grant access control permissions on
  those collections
Out of the box, Drupal only allows a person to view, create or edit
  the different content types you create. However, you might want to be
  able to let them view or edit all content types, but only in a
  specific section of the site.


Switching from table to graph give wrong data

Question: I'm using the Drupal Commerce Report module as a base for my stats. I have a table which give me data about my sales per month.

I'd like to use graph instead of table, to make it easier to compare. For some reason, the coma is gone, so all my sales reports are wrong

I tried to alter data in a pre_render, in a preprocess (by checking the format, test with a dot instead of a coma) but still having the wrong result
Answer: This was caused because the value where rewritted in the view (thousand separator, number after coma...). Reverted to initial configuration solved the problem.


Where can be found all MenuProps attributes of a Select in Material UI

Question: Having the next Material UI Select, I've found that one can modify its behavior and appearence.
import React from "react";
import MenuItem from "@material-ui/core/MenuItem";
import Select from "@material-ui/core/Select";

class SimpleSelect extends React.Component {
  state = {
    age: 10
  };

  handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  render() {
    return (
      <Select
        value={this.state.age}
        onChange={this.handleChange}
        inputProps={{
          name: "age",
          id: "age-simple"
        }}
      >
        <MenuItem value="">
          None
        </MenuItem>
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
      </Select>
    );
  }
}

export default SimpleSelect;

This is the above one with MenuProps added, also a sandbox where I'm playing with it.
import React from "react";
import MenuItem from "@material-ui/core/MenuItem";
import Select from "@material-ui/core/Select";

class SimpleSelect extends React.Component {
  state = {
    age: 10
  };

  handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  render() {
    return (
      <Select
        value={this.state.age}
        onChange={this.handleChange}
        inputProps={{
          name: "age",
          id: "age-simple"
        }}
        MenuProps={{
          anchorOrigin: {
            vertical: "bottom",
            horizontal: "left"
          },
          transformOrigin: {
            vertical: "top",
            horizontal: "left"
          },
          getContentAnchorEl: null
        }}
      >
        <MenuItem value="">
          None
        </MenuItem>
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
      </Select>
    );
  }
}

export default SimpleSelect;

My question is: where can I find all the possible attributes (like anchorOrigin, transformOrigin, etc) available for it?
I want to make the dropdown wider and also to add checkboxes for each dropdown item but I don't know what MenuProps attributes to access.
Answer: The starting point for finding this is the Select API documentation: https://material-ui.com/api/select/. Within the Props section you will find MenuProps:

MenuProps     object      Props applied to the Menu element.

In the above, the word "Menu" links to the Menu API documentation. You may look at that and say "but where is anchorOrigin and transformOrigin?"
At the end of the Menu Props API documentation, you will find the following:

Any other props supplied will be provided to the root element (Popover).

In the above, the word "Popover" then links to the Popover API documentation (where you will find anchorOrigin and transformOrigin).
At the end of the Popover Props API documentation, you will find the following:

Any other props supplied will be provided to the root element (Modal).

Similarly, in the above, the word "Modal" links to the Modal API documentation. So the full props available on Menu are the combination of all the props documented for Menu, Popover, and Modal. There is some work in progress to improve the documentation to provide more direct access to all the applicable props: https://github.com/mui-org/material-ui/issues/18288.


Is it possible to determine the constituents of a matrix product, given the result?

Question: Suppose we have a set $M$ of two or more matrices such that every matrix product $X$ composed of matrices drawn with replacement from $M$ is unique.
Is there a set $M$ for which we can determine the constituents (including order) of the matrix product, given the result matrix X?
Edit: I'm specifically interested in the case where the product consists of an arbitrary number of matrices drawn with replacement from $M$, e.g. $M = \{A, B, C\}$ and $X = ABABBBACBAABC$.
Comment: If every matrix in $M$ is invertible, and the products considered are products of just two matrices, the way to determine the constituents, including order, answer is trivial.  Simply left multiply by each of the elements of $M$ and then compare the result to every element of $M$; then if that does not find the product, do the same starting with right multiplying by the inverse of each element of $M$.  The same goes for products of any finite number of matrices.  Did you mean the problem to allow for infinite products? because then it gets a lot tougher.
Comment: Yes, I'm specifically interested in the tougher case; not infinite products necessarily but arbitrary finite products.
Answer: If every matrix product drawn from the set is unique, then take $\{A, B, C, \cdots \}$ to be matrices such that the logs of the determinants $\log |A|, \log |B|, \cdots \}$ are linearly independent over the rationals.  Then given the product $X$, the number of powers of each of the members of $M$ is determined by taking the determinant of $X$ and expressing its log as a sum of the log determinants of the members of $M$.  Since that is a finite number of factors, it only remains to try all the permutations of that finite collection $A^a, B^b, \cdots\}$.
But to get "universal uniqueness"  $M$ must be chosen such that no two of the permutations yield the same product.  Because of the Jacobi identity (the sum of all three cyclic permutations of the three matrix commutator form is zero) it seems likely that that can never be the case for all products of the matrices.
The Jacoby identity is
$$
[A,[B,C]] + [B,[C,A]] + [C,[A,B]] = 0
$$
where $[X,Y] \equiv XY - YX$.


Open flutter screen from Native Method call

Question: In flutter app I have impalement one native screen using platform channel. After that I want to back in flutter and open new flutter screen but I can't open the screen.
I follow below step:
1)From flutter I call Native screen by method Channel.
2)After that from native I call flutter by method channel, but in this process I get the data from native but another screen is not open.
I have implement like this:
  Future<dynamic> searchCallHandler(MethodCall call) async {
    switch (call.method) {
      case 'openSearch':
        print('call callMe : arguments = ${call.arguments}');

        navigatorKey.currentState.push(
          MaterialPageRoute(builder: (context) => SearchLocation()),
        );
        return Future.value('called from platform!');
      default:
        print('Unknowm method ${call.method}');
        throw MissingPluginException();
        break;
    }
  }

in above code get the arguments value but not go in the SearchLocation Screen of the flutter.
Comment: the same (( https://github.com/flutter/flutter/issues/75314
Answer: You need to understand how flutter works with native here and the activity stack.
In a flutter app, there is one main activity which extends the FlutterActivity. All your views and screens are drawn in this activity. So when you open your app there is just one activity (FlutterActivity) in the native android activity stack.
Now when you invoke a method to start a new Activity on the native, it spins a new Activity and the android native activity stack has 2 activities.
After that when you are calling:
navigatorKey.currentState.push(
  MaterialPageRoute(builder: (context) => SearchLocation()),
);

through the method channel, flutter is still navigating to the the new screen in its own activity (FlutterActivity) which is behind the current visible native activity.
So the solution is:
Call finish() before invoking the openSearch method from the native end.
This will destroy the current native activity and let the FlutterActivity come to foreground, and you can see the search screen in flutter.
Comment: Thanks. Finish activity is working but if I don't want to finish native activity because on back press I want to see that activity. Can achieve this by other solution?


Weird error message in Xcode 4.3 with LLDB

Question: I am currently writing an iOS app with Xcode 4.3.2. In most parts of my code, debugging with LLDB works just fine. However at some point I am getting a strange message while stepping through my code. When I hover over an iVar, it says

Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol OBJC_IVAR_$_MyFancyClass.iVar

instead of showing me the value. However, in the Variables View, I can see it just fine. Until I'm selecting Print Description of ... that is, because then, Xcode crashes...
When I use GDB, the hovering works but the type and values of the variable are wrong.
I recon that there is something wrong with my code which in turn causes the debuggers to fail. However, the code runs fine.  I'd love to provide some samplecode but the class is rather long and I can't pinpoint the exact location of my screwup. So has anybody encountered a similar behavior?
UPDATE: Actually, it seems as if this happens everywhere in my code, not just in some specific files. If it helps, while LLDB show the above message, GDB always shows an object of the Class that is owning the iVar, instead of the iVar itself.
It looks as if there is something wrong with the memory management. For example, if I say something like
[notificationCenter addObserver:self selector:@selector(foo) name:bar object:objA];

the selector is invoked even when I have
[notificationCenter postNotificationName:bar object:objB];

Comment: Your code may be long, but it doesn't seem like enough people have encountered this. Can u just show a summarized version of some code where this behavior occurs?
Comment: Well, since it happens absolutely everywhere in my Code, I really don't know what I could post...
Comment: I'm just guessing here so I'm not posting an answer, but what happens if you try using the debugger console and print the object out using "po"? Also, do you perhaps have any sort of special gdb configuration fie in place? Is this an included library that you're trying to debug? Are you building with debug information enabled? Double check your build settings (generate debug symbols, optimization level, debug information format).
Comment: Matej, you actually got it :) I already checked the settings but I did it again and noticed that "Deployment Postprocessing" was set to YES for Debug-Mode. Changing it to NO removes the warning and although I'm not quite sure if LLDB runs all smooth now (will have to check the settings more carefully), this definitely answers my question. It's a pity, that I just wasted a TSI on the matter :) So feel free to formulate a proper answer in order to collect your reward :)
Answer: The cause of this error are incorrect build settings, as indicated by the discussion in the question post comments. This can be fixed by setting "Deployment Postprocessing" back to NO for Debug-Mode (the default value).
Answer: Make sure MyFancyClass.m is added to your Target
Answer: Your selector that the nsnotification is being sent to needs to have one (and only one) argument, which is an NSNotification. So when you do this:
[notificationCenter addObserver:self selector:@selector(foo) name:bar object:objA];

-(void)foo
{

}

...you need to be doing this:
    [notificationCenter addObserver:self selector:@selector(foo:) name:bar object:objA];
-(void)foo:(NSNotification *)notification
{

}

Notice the colon in the selector for the notificationCenter, and the argument for foo.
Comment: Correct. However, that was just me, having a typo in my pseudo-code. Remember, the real problem are the weird debugger warnings :)
Comment: (NSNotification)notification
 should be
(NSNotification*)notification


Set of homomorphisms on a free abelian group is a free abelian group.

Question: If $G$ is a free abelian group with rank $n$, I need to show that ${\rm Hom}(G,\mathbb{Z})$, set of all homomorphisms is also free abelian group of rank $n$,
My work:
Since $G$ is free abelian group then $G$ can be generated by the set $\{g_1,g_2, \cdots,g_n\}$. Let $f \in{\rm Hom}(G,\mathbb{Z})$, then $f(x)=\sum_{i=1}^n{c_if(g_i)}$, where $x=\sum_{i=1}^n{c_ig_i}$, but this gives a generator set of ${\rm Im}(f)$ and I need to get generators for ${\rm Hom}(G,\mathbb{Z})$, so for arbitrary $f$ we have the same set of generators which is in $\mathbb{Z}$.
Comment: Consider homomorphisms $\phi_{i}\in\operatorname{Hom}(G,\Bbb Z)$ for which $\phi_{i}(g_i)=1$ and $\phi_i(g_j)=0$ for $j\ne i$. (Such $\phi_i$ exist, are unique, etc.)
Comment: @HagenvonEitzen, that's it. Thank you very much!
Answer: The idea is the same used to get a basis for the dual space of a vector space $V$ of finite dimension.
Let us define the homomorphisms $g_i^*\colon G\to \mathbb{Z}$ such that $g_i^*(g_j):=\delta_{ij}$. Then given $f\in Hom(G,\mathbb{Z})$ you have that
$ f=\sum_{g_i}f(g_i)\cdot g_i^*$
Now suppose that $\sum_{g_i}a_ig_i^*=0$. Then $\left(\sum_{g_i}a_ig_i^*\right)(g_j)=a_j=0$ for each $j$. Hence $Hom(G,\mathbb{Z})$ is a free abelian group of rank $n$.


Not able to start app in Apache Tomcat

Question: Just to let you know, I'm not a programmer at all so I'm kind of lost in my problem. I'm trying to migrate an app from a Windows Server 2003 server on Apache Tomcat 4.1 and Java 1.4.2 (App is working fine on that server). I'm tried migrating it on a Windows Server 2008 R2 with any version of Apache Tomcat and Java compatible with W2KR2 but I'm always getting the same error when I try to start the app from the web interface:
<code> org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/GestClientsAS2]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3780)
    at org.apache.catalina.startup.HostConfig.reload(HostConfig.java:1307)
    at org.apache.catalina.startup.HostConfig.checkResources(HostConfig.java:1290)
    at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1474)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:280)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1141)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1365)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1369)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1345)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: javax/mail/internet/MimeBodyPart
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
    at java.lang.Class.getDeclaredMethods(Unknown Source)
    at org.apache.catalina.util.Introspection.getDeclaredMethods(Introspection.java:127)
    at org.apache.catalina.startup.WebAnnotationSet.loadMethodsAnnotation(WebAnnotationSet.java:275)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:138)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:65)
    at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:331)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:770)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:302)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5083)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
</code>
I believe there is a class missing? How would I fix this?
Thanks.
Comment: And now for a human readable comment: Possibly a library was (wrongfully) added to the old server that you did not copy to the new server. Do a search for *.jar on the old server and on the new server and compare the results. You are looking for a library related to 'javamail'.
Comment: Add the jar to tomcat/lib or define path-to-jar-file in the class path so that tomcat can refer to.
Comment: You are missing the `MimeBodyPart` class. You can find the JAR here: http://www.java2s.com/Code/Jar/j/Downloadjavamailmailapi14jar.htm
Comment: I'm guessing I have to put that jar file in the lib folder? Should I restart the server or something?
Answer: Since you told me you application was running in a java 1.4 version, and this class is only default in Java 5+ version (See documentation: http://docs.oracle.com/javaee/5/api/javax/mail/internet/MimeBodyPart.html), you will have to import it to your project.
Download it: http://www.java2s.com/Code/Jar/j/Downloadjavamailmailapi14jar.htm
Since it is a web application, put this jar file inside, WEB-INF/libs, so, the classloader will load it, restart the server.
if its not a web project you can right click on the library and go to "Build Path" -> "Add to Build Path".
Comment: Thanks, that fixed it. I'm getting a different error now but its security related so I should be able to fix that one
Comment: Ok, so, if you can, mark it as the correct answer, and if you need anything else, just create another topic and i can help you out :)

Not able to start app in Apache Tomcat


A question about Jordan Lemma and estimation Lemma

Question:
Let $|F(z)|\leq \frac{M}{R^k}$ for some positive numbers $M$ and $k$, where $z=Re^{i\theta}$. Prove that
$$\lim_{R\to\infty}\int_{|z|=R,\:\mathcal{R}(z)\geq0}e^{imz}F(z)\,dz=0$$
for any constant $m>0$.

The only thing I could think is using Jordan Lemma which I'm not sure how. Is it possible that the question be wrong? I appreciate any hint.
It's very similar to Proving a modified version of Jordan's lemma?. However here we have $e^{imz}$ instead of $e^{mz}$, which in this case, I couldn't prove it.
Comment: The integral should be over $\lvert z\rvert = R$, and $\operatorname{Im} z \geqslant 0$. Then it's just Jordan's lemma. Since $\lvert e^{imz}\rvert = e^{-m\operatorname{Im} z}$, the integrand becomes large on the lower half-plane, and usually there isn't cancellation making that part tend to $0$ as $R \to \infty$.
Comment: There have been, and in future will be, more embarrassing typos in tests and in textbooks.
Comment: This was something that I thought during my test, but I said it's impossible to have a such a type on the test. :(
Answer: I think that the following should be a counter example. I will build it in steps

The real function $\frac{ e^{-mx}}{x^2 + 1}$ is continuos and positive but not summable. So
$$
\int_{-\infty}^{+\infty} \frac{ e^{-mx} }{x^2 + 1} \; dx = +\infty
$$
The complex function $f(z) = \frac{1}{1 - z^2}$ has modulus smaller than $\frac{2}{|z|^2}$ for large enough $|z|$
Due to Residue theorem, since the function $\frac{e^{imz}}{1-z^2}$ has only one simple pole in the right half disk of radius R > 1, that is $1$ with residue $\frac{e^{im}}{2}$ , denoting with $\sigma_R$ the curve
$$
   \sigma_R : [-R,R] \quad
   \sigma_R(t) = it
$$
then
$$
\int_{|z|=R, \Re(z) > 0} e^{imz} f(z) \; dz - \int_{\sigma_R} e^{imz} f(z)\; dz = 2\pi i \frac{e^{im}}{2}
$$

$$
 \int_{|z|=R, \Re(z) > 0} e^{imz} f(z) \; dz =  \pi e^{im} + \int_{\sigma_R} e^{imz} f(z) \; dz = i \int_{-R}^R \frac{e^{-mt}}{1 + t^2} \; dt
$$
Point 1 and 3 togheter imply that the limit does not go to zero, while point 2 guarantee that all the hypothesis are satisfied
Comment: This is a very nice counterexample, thank you! I would still like to keep the question open to find out about alternative counterexamples and possible solutions.
Comment: The second part is only true for larger value of $|z|$, but the question hypothesis states it should be true for all $z=Re^{i\theta}$. But I think it's very close.
Answer: This time i will show a counter example that fully satisfy your hypothesis, but not the thesis. The main idea is the same of my previous answer. Please, correct me if wrong.
step 1 The real function $ \displaystyle f(x) = \frac{e^{-mx}}{x}$  is summable over $\mathbb{R^+}$ but not summable over $\mathbb{R^-}$, hence
$$
  \int_{-\infty}^{+\infty} \frac{e^{-mx}}{x} \; dx = - \infty
$$
step 2 the complex function $\displaystyle f(z) = \frac{1}{z}$ is such that $\displaystyle |f(R e^{i \theta})| = \frac{1}{R}$.
step 3 We define four curves for $R > 1$
$$
 \sigma_{1,R} : \left[ \frac{1}{R}, R  \right] \to \mathbb{C} \qquad \sigma_{1,R}(t) = it
\qquad
\qquad
 \sigma_{2,R} : \left[ -R, -\frac{1}{R} \right] \to \mathbb{C} \qquad \sigma_{2,R}(t) = it
$$
$$
 C_{1,R}: \left[ -\frac{\pi}{2}, \frac{\pi}{2} \right] \to \mathbb{C} \qquad C_{1,R}(t) = R e^{it}
\qquad \qquad
C_{2,R}: \left[ -\frac{\pi}{2}, \frac{\pi}{2} \right] \to \mathbb{C} \qquad C_{2,R}(t) = \frac{e^{it}}{R}
$$
To visualize it, the composition of this four path (noticing that $\sigma_{1,R}$ and $\sigma_{2,R}$ need to be reversed) is the boundary of a half donut
step 4 We now compute the integral of $\displaystyle \frac{e^{imz}}{z}$ over $\sigma_{1,R}, \sigma_{2,R}$ and $C_{2,R}$:
$$
  \int_{\sigma_{1,R}} \frac{e^{imz}}{z} \; dz = \int_{1/R}^R \frac{e^{-mt}}{t} dt
\qquad \qquad
  \int_{\sigma_{2,R}} \frac{e^{imz}}{z} \; dz = \int_{-R}^{-1/R} \frac{e^{-mt}}{t} dt
$$
Thus the limit
$$
  \lim_{R \to \infty} \int_{\sigma_{1,R}} \frac{e^{imz}}{z} \; dz + \int_{\sigma_{2,R}} \frac{e^{imz}}{z} \; dz = \int_{-\infty}^{\infty} \frac{e^{-mt}}{t} \; dt = \infty
$$
Where $\infty$ is the complex compactification infinity. The other integral instead, by the small circle lemma - (if you need clarification i can explicitly prove it) is such that
$$
\lim_{R \to \infty} \int_{C_{2,R}} \frac{e^{imz}}{z} \; dz = i \pi
$$
step 4
Noticing that the composition of the aforementioned paths describe the boundary of a domain $D$ not containing $0$, the function $\displaystyle \frac{e^{imz}}{z}$ is olomorphic in this domain and in particular the integral over $\partial D$ is zero by the cauchy's integral theorem. Hence
$$
  \lim_{R \to \infty} \int_{C_{1,R}} \frac{e^{imz}}{z} \; dz = \lim_{R \to \infty} \int_{\sigma_{1,R}} \frac{e^{imz}}{z} \; dz + \int_{\sigma_{2,R}} \frac{e^{imz}}{z} \; dz + \int_{C_{2,R}} \frac{e^{imz}}{z} \; dz
= \int_{-\infty}^{+\infty} \frac{e^{-mt}}{t} \; dt + i \pi = \infty
$$
In particular the LHS cannot be zero


The set $X=\{a+b\sqrt{2}\;;\;a,b\in\mathbb{Q}\}$

Question: Let $X=\{a+b\sqrt{2}\;;\;a,b\in\mathbb{Q}\}$, show that elements of $X$ is unique.
My attempt : I thought of considering the elements $a_{1},a_{2},b_{1},b_{2}\in\mathbb{Q}$ such that $a_{1}+b_{1}\sqrt{2}=a_{2}+b_{2}\sqrt{2}$, to show that $a_{1}=a_{2}$ and $b_{1}=b_{2}$. However, I am stuck here and I don't know how to continue.
Comment: Duplicate isn't it ?
Comment: can you please show us your attempt? Moreover this is a duplicate question
Comment: I apologize for my ignorance.
Comment: Just an annoying pedantic note, the elements of a set are always unique. What you are trying to show is that each element has a unique representation of the form shown.
Answer: We have $a_1-a_2=(b_2-b_1)\sqrt{2}$. If $b_1\ne b_2$ then this implies $\sqrt{2}=\frac{a_1-a_2}{b_2-b_1}\in\mathbb{Q}$, a contradiction. So we must have $b_1=b_2$. And this also implies $a_1=a_2$.
Comment: Thank you very much sir, I will accept your answer in a moment