Using PlacePicker in a fragment

Question: I am trying to use the google placepicker from within a fragment that is part of my Android app. I cant seem to use the data being returned by the onActivityResult. I used a solution from (https://inthecheesefactory.com/blog/how-to-fix-nested-fragment-onactivityresult-issue/en) to get the results back within a fragment. However this solution doesnt allow me to change elements in my view based on input from my placePicker. The toast with the place info works but not changing the button because its outside the inflated view. I am using fragments because my app is a tabbed slider app with 2 fragment, creating location and viewing locations.
Please help and ask for clarification if necessary!
Here is the onCreateView in myFragment extends Fragment class:
<code>@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_make_minyan, container, false);

    //Map Place Activity
    final Button locationButton = (Button) rootView.findViewById(R.id.button_location);
    locationButton.setOnClickListener(new View.OnClickListener() {
        //int RESULT_OK;
        public void onClick(View v) {
            PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
            try {
                getActivity().startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            }
        }
    });
    //a bunch of other buttons and spinner etc that are working.

    return rootView;
}
</code>
And here is the onActivityResult code used from the solution linked above.
The commented out line is the line of code that wont work currently.
<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == Activity.RESULT_OK) {
            Place place = PlacePicker.getPlace(data, getActivity());
            //locationButton.setText(String.format("Place: %s", place.getName()));
            String toastMsg = String.format("Place: %s", place.getName());
            Toast.makeText(getContext(), toastMsg, Toast.LENGTH_LONG).show();
        }
    }
}
</code>
Answer: If you write getActivity().startActivityForResult(...), then the onActivityResult will be called in your Activity and not in your Fragment.
Try with just startActivityForResult(...)

Using PlacePicker in a fragment


How to compare two cluster solutions in graphs?

Question: I have two ways to cluster nodes in a given graph, and now I want to compare my two clusters so to measure how "similar" the resulting clusters are. I have found some measures of similarity (Rand index, Variation of information, etc), but none of them takes into account the structure of the graph.
So my question is if exist some measure that considers distances in the graph?
Comment: Can you paste in a simple example dataset / pair of cluster outputs?
Answer: Measures like Rand index are based on pairs of points.
A pair of points is essentially an edge.
These measures are based on the agreement on which object should be 'linked' and which should not be 'linked', so I would call of this family of measures "graph based". And for sure they will work on graph  clusterings.


Fast note progression - Terminology

Question: I have no idea how to call these.
basically, it is when you have fast long strings of note progressions, spanning multiple octaves. These would be my examples, as I don't know how to describe it:
The part from 1:32 -

from 0:32

Since I have no idea what the musical term for this type of musical formula is, I can't really look for a way to improve my playing.
Thank you in advance.
Comment: Could be glissando.
Answer: Based on your description, I too thought like Tim that you were referring to glissando but listening to the recording, I think these are simply arpeggios on the left hand while the right hand is simply repeating two notes.
The right hand shouldn't present much challenge here, so you just need to practice your arpeggios.
One way to practice them is to play by position: i.e. you play as many of the notes as you can at once and then you move your hand to play the next group of notes.  This will help you memorize where your fingers should go.  You will also need to strengthen your fingers as well, and work on the most difficult transition where the fingers move over your thumb by, for example, repeating that transition multiple times when you play the arpeggio.
There you have your crash course on playing arpeggios assuming this is indeed what you wanted to learn about :-)

Fast note progression - Terminology


Ag-Grid row data .map param.value

Question: I am using Ag-Grid React - and trying to map the params.value in the rowData using:
{
  headerName: "Assigned To",
  field: "assignedTo",
  colId: "assignedTo001",
  sortable: true,
  floatingFilter: true,
  filter: 'agTextColumnFilter',
  cellRendererFramework: function(params) {
    if(!params.data.assignedTo) {
      return ''
    }
    // return JSON.stringify(params.data.assignedTo)
    params.data.assignedTo.map((user) => {
      if(user) {
        return JSON.stringify(user)
      }else{
        return 'Not assigned'
      }
    })
  }
},

The commented out line above the .map // return JSON.stringify(params.data.assignedTo) works fine, but I need to map through the array to display the user.uid or user.name.
I started off trying to use the default params.value, that did't work so I switched to using the params.data.
The code above is not working, getting a Uncaught Error: cellRendererFramework(...): Nothing was returned from render. error.
What is the best way to return multiple values from an array in a row?
Comment: You aren't returning the result of `params.data.assignedTo.map((user) => { ... }`, which probably needs to be converted from an array to string.
Answer: Add return  statement before params.data.assignedTo.map((user) => {
Comment: oh damn, lol - Thanks! got lost in all of these return(s)

Ag-Grid row data .map param.value


What is wrong in this characterisation of open sets containing all rationals?

Question: I am having a problem understanding what's wrong with this:I know statement 1 is false and 2 is true but I can't find the mistake.
1)Any open set in $R$ is a countable union of disjoint open intervals. So if we take any open set containing all rationals its complement contains only irrational points. But because endpoint of one interval is the starting point of the next, we can associate the right endpoint of any interval(which is irrational) to each interval. Hence the number of irrational points in the complement is countable.
2)We can construct an open set in $R$ with measure less than $1$ containing all rationals. Hence its complement will have infinite measure and is uncountable.
Comment: Presumably by "measure less than $1$" you mean "finite measure," since $\mathbb{R}$ has measure $\infty$, not $1$ ...
Comment: I was talking about the open set containing all rationals to have measure less than 1
Answer: Actually, both (1) and (2) are correct! The error is when you say:

Hence the number of irrational points in the complement is countable.

This only works if you know that every irrational is the right endpoint of some interval in the collection. And this is not true.
For example, consider the set of open intervals $$\{(0, 3), (3, 3.1), (3.1, 3.14), (3.14, 3.141), ..., (3.142, 3.15), (3.15,3.2), (3.2, 4), (4, 5)\}.$$ It should be clear that these intervals "converge to $\pi$" - so $\pi$ isn't the right endpoint of any one of these intervals.
As counterintuitive as it may seem, in an open cover of the rationals with finite measure, most irrationals are not the endpoints of any of the intervals in the cover.
Comment: So I am missing out on some irrational points in the complement in a case such as this. I got it. Thanks, Yeah I meant what is wrong with my statement of the complement being countable. I know the characterisation of open sets was correct.


Calling MainApplication methods from BroadcastReceiver

Question: I have an Android Application with an Activity, a service and a Broadcast receiver. From the service I call a Broadcast Intent which works. The Broadcast Receiver receives the intent correctly.
But how can I access methods of the class MainApplication from my Class MyBroadcastReceiver ?
((MainApplication)getApplication()).myMethod(); gives the error-message "cannot resolve method"
//Call from the service-class
private void sendBroadcast() {
    Log.d(TAG, "Sending Broadcast Intent");
    Intent intent = new Intent();
    intent.setAction("com.package.name.MyBroadcastReceiver");
    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    sendBroadcast(intent);
}

//receiver class
public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //Doesn't work - "cannot resolve method"
        ((MainApplication)getApplication()).myMethod();
        //Doesn't work either
        ((MainApplication)context.getApplication()).myMethod();
        Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
    }
}

//Main Application Class
public class MainApplication extends Application{

    public void myMethod(){

    }

}

Best regards
Comment: See comment in code.. "cannot resolve method"
Answer: Cast the context to an Activity:
//receiver class
public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Activity activity = (Activity) context;
        ((MainApplication)activity.getApplication()).myMethod();
        Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
    }
}

Comment: Thank you! Very quick and easy solution.
Answer: The above usually happens if you haven't declared you MainApplication class in your AndroidManifest.xml.
Find the application tag in your AndroidManifest.xml file, and ensure it's name attribute points to your MainApplication - something like below.
<application
        android:name="com.you.package.MainApplication"

Comment: Thank you. On another occasion this was the right answer. But this time i have put the MainApplication in the AndroidManifest.xml file. The same call `((MainApplication)getApplication()).myMethod();` works, if I use it from another class, but unfortunately not when I try to call it from the `MyBroadcastReceiver`-class.
Answer: Create the BroadcastReceiver dynamically:
In your BroadcastReceiver class define class member:
YourMainActivity yourMain = null;

and method:
setMainActivityHandler(YourMainActivity main){
yourMain = main;
}

from your MainActivity do:
private YourBroadcastReceiverClassName yourBR = null;
yourBR = new YourBroadcastReceiverClassName();
    yourBR.setMainActivityHandler(this);
    IntentFilter callInterceptorIntentFilter = new           IntentFilter("android.intent.action.ANY_ACTION");
    registerReceiver(yourBR,  callInterceptorIntentFilter);

when yourBR.onReceive is fired you can call:
yourMain.methodOfMainActivity();


Confidence interval and type 1 error cumulation

Question: I have a sample of 15 subjects that did a test multiple times. Now I would like to see if the subjects differ in their mean performance. The usual approach would be a test for differences in means (e.g. t-test), but if I compare the subject with each other, I get a large type 1 error rate. Because of that, I thought about calculating a confidence interval for each subject and to see if they overlap.
What happens with the Type 1 Error here? Is there an alternative method to analyse the data?
Thanks for your patience and answers!
Comment: Looking at confidence intervals can be misleading. Sometimes two whiskers can overlap and difference still significant. Second, confidence interval and t-test are different products of the same process; if multiple testing is involved, threshold p is lowered, then the t-distribution constant that goes into the CI calculation should also be higher, making the CI wider. Aka the CI will not remain unchanged.
Comment: you mean that I should first correct the comparison-wise type 1 error and then use the corresponding t-value for the construction of the confidence interval?
Comment: Yes and no, I meant to indicate that i) the confidence interval method also suffers from inflated type I error as well, and ii) because of that, you may as well go for t-test, but with additional adjustment to the p-value. Look for "Post-hoc mean comparison" and you may find some useful way to address the inflated type I error issue.
Comment: How many observations total? You have 15 subjects, how many total test observations?
Comment: each one did the test 5-6 times, not many, I know. Bad design?
Answer: I would approach this as a repeated measures design, which can be done in a multilevel model framework which is robust to imbalance in the number of observations per subject.
Think about it this way:
$score_{it}=\beta_{i}+\mu_i+\epsilon_{it}$
or rewritten in a two-level framework:
$score_{it}=\beta_{i}+\epsilon_{it}$
$\beta_i=\gamma_i+\mu_i$
Where $\beta_i$ is the mean score for each subject across all their tests, $\mu_i$ is the random effect for the subject (i.e. the variability in score due to the subject), and $\epsilon_it$ is the random error for each individual test-subject unit (i.e. the within subject variability). This is flexible to put in additional level 1 or level 2 variables, like if you think subjects improve over time, you can add that in as well and it becomes a growth-curve model.
This doesn't suffer from multiple testing, and you can see how much variability is due to the subjects themselves, by the intra-class correlation coefficient (ICC):
$\sigma_{\mu}/(\sigma_{\mu}+\sigma_{\epsilon})$
Comment: Would the first $\beta_i$ actually be $\gamma_i$?
Comment: Correct; if collapse the two-level interpretation into the one-level, the beta and gamma are equivalent.


Python-It does not let me write to a text file

Question:    myfile.write(Car_Number_plate+str' went at',+ Speed_In_Miles_Per_Hour+'/n')

I am getting an syntax error on python, I am trying to write to a text file.
Comment: Does it work if you do each part as a separate write?
Comment: remove the comma and str'. your syntax is just pain wrong.
Answer: Yes, you would. Here is valid syntax for what you are trying:
with open("file.txt", "w") as myfile:
    myfile.write(Car_Number_plate + ' went at ' + Speed_In_Miles_Per_Hour + '/n')

To make it better, you probably meant to type \n for a line break, not /n and you probably want to make sure those variables are strings or don't use + to combine them. You should also make it more PEP8 friendly. So:
car_number_plate = "ABC123"
speed_in_miles_per_hour = 33

with open("file.txt", "w") as myfile:
    myfile.write("{0} went at {1} mph \n".format(car_number_plate, speed_in_miles_per_hour))

Comment: this is  an error i m getting
Traceback (most recent call last):
  File "C:\Users\PShah\Documents\School\GCSE\TASK2a.py", line 38, in
    myfile.write(Car_Number_plate + ' went at ' + Speed_In_Miles_Per_Hour + '/n')
TypeError: Can't convert 'float' object to str implicitly
>>>
Comment: Yup, because it wasn't converted to string and you used `+` on it, see my edit.
Comment: Thank you so much you even made it so it comes on separate lines in the text file thanks a lot.


R data.table: how to go from tibble to data.table to tibble back?

Question: I use mainly tables in the tibble fromat from tidyverse, but for some steps, I use the data.table package. I want to see what is the best way of converting a data.table back to tibble?
I understand that data.table has some clever function setDT and setDF function, that convert from data.frame to data.table (and vice-versa) by reference, i.e. without making a copy.
But what if I wanted to convert back to tibble? Am I copying the data using as_tibble on the data.frame resulting from setDT()? Is there a clever way to use this, maybe using the setattr() from data.table?
library(data.table)
library(tidyverse)

iris_tib <- as_tibble(iris)

## some data.table operation
setDT(iris_tib)
setkey(iris_tib, Species)
iris_tib[, Sepal.Length.Mean := mean(Sepal.Length), by = Species]

## How to convert back to tibble efficiently?
setDF(iris_tib)
iris_tib_back <-  as_tibble(iris_tib)

## it looks like we were able to update by reference? Only rownames were (shallow) copied?
changes(iris_tib, iris_tib_back)

Comment: Your "some data.table operation" is very straightforward in the tidyverse right? Hadley has an interface to data.table that retains dplyr syntax if that's your preference: https://github.com/hadley/dtplyr Re your main question, maybe this answers it? (I have not tested.) https://github.com/Rdatatable/data.table/issues/1877#issuecomment-253864899
Comment: Ok, cool :) You can self-answer it (I won't answer since I don't have tibble installed and don't know how to confirm that the setattr trick achieves the desired result)
Comment: two great refs, thanks! The first is interesting and the second is... I think pretty much the answer I was looking for indeed! :-)
Comment: The issue is that I don't know myself that well how to ascertain result is correct haha, not sure to understand fully what `as_tibble()` does with the row.names. But I guess if I don't care too much about rownames, that should be fine
Answer: As @Frank mentioned, this was discussed in a post here. One possibility is to use the setattr() function, which set attributes by reference. Precisely:
setattr(x, "class", c("tbl", "tbl_df", "data.frame"))

And if there's a doubt about the original class:
old_class <- class(iris_tib)
setDT(iris_tib)
.... # bunch of data.table operatios
setDF(iris_tib)
setattr(iris_tib, "class", old_class)

This seems to do the necessary job converting back to a tibble.


Is mode a measure of central tendency?

Question: I am just starting out with my stat basics and that's where I came across measures of central tendency. In one of the books measure of central tendency is defined as a measure which yield information regarding the central or the middle part of a group of data. As we all know mean, median and mode are measures of central tendency. What I am not clear with is how is mode used to yield information regarding the the central part of a group of data. What if the the group of data has numbers which are occurring most other than in the central part? I am a bit confused here. Thanks for anyone's help in advance
Comment: @MichaelChernick - It depends on what you regard as central tendency and how central you want your measure to be.  For a unimodal distribution (sensibly defined), the difference between the mean and mode is never more than  $\sqrt{3} \sigma$, so it is not intrinsically bad
Comment: It wouldn't be a good measure of central tendency if you have a multimodal distribution or a distribution that is unimodal but highly skewed. The median is a good measure & the mean can be too. But the mean can be misleading for highly skewed or skewed & heavy-tailed. The mean, median & mode are all good measures for symmetric unimodal distributions that are not heavy-tailed. The Cauchy for example is symmetric & unimodal where the median & mode are the same but the mean does not exist. For Gaussian distributions the mean, mode & median are identical & good measures of central tendency.
Comment: I think of central tendency means that the measure defines a point at or near the middle of the distribution. So the median is always a good measure. If the mean is not finite as is the case with the Cauchy it isn't appropriate to talk about it as a measure of central tendency. There are other examples where the mean & mode can be very different from the median which makes them inappropriate in those cases. When the distribution is multimodal you have a problem in defining "the" mode & you can have a bimodal distribution where neither mode is close to the middle.
Comment: Gugaa Srikanth and @MichaelR.Chernick [Relevant](https://stats.stackexchange.com/questions/96371/should-the-mean-be-used-when-data-are-skewed). Michael, I suspect you are confusing "does the mean behave like the median" for "does the mean measure central tendency". "Central tendency" is poorly defined, and the median's "boundary between upper and lower 50% of distribution" is just *one* way to define it, not The Right way.
Comment: I always thought of the mode as the 'central tendency' for categorical data, & where this was perhaps somewhat metaphorical.
Comment: The mode *can* be a measure of central tendency, but [there are distributions](https://stats.stackexchange.com/a/541799/111259) for which the mode is anything but a measure of central tendency.
Answer: The notion that the mode constitutes a measure of "central tendency" is contextual at best, and hinges on the assumption that we are dealing with a distribution with a non-monotonic unimodal density.  There are many distributions where the mode is in the tails of the distribution, or even at the extreme edge of its support.  For example, the exponential distribution has its mode at zero, which is the extreme left edge of the support; not even close to a measure of central tendency.  More generally, one can construct a distribution with any mean and mode one wishes, so it is entirely possible to construct a distribution with a mode that is absurdly far away from the "centre" of the distribution, as measured by the mean.
My view is that your misgivings here are correct --- you should not consider the mode to be a measure of central tendency unless you have strong a priori reasons to believe you are dealing with a non-monotonic unimodal distribution with a "hump" somewhere near the middle of the distribution.  (And obviously judging this presupposes that one already has an a priori view of what constitutes the "middle".)  It is best just to ignore this aspect of your textbook.
Answer: Bickel & Lehmann (1975) suggest three criteria that a measure of location $\mu$ ought to meet to be worthy of the characterization, & it seems to me they might as well have talked of central tendency. The criteria are these:

$\mu(X) \geq \mu(Y)$ when $X$ is stochastically larger than $Y$, i.e.
when $\Pr(X > k) \geq \Pr(Y > k)$ for any $k$ & $\Pr(X > k) > \Pr(Y >
   k)$ for at least some $k$

$\mu(aX+b) = a \mu(X) + b$ for $a>0$

$\mu(-X) = -\mu(X)$

(The 2nd & 3rd together ensure that $\mu$ identifies the centre of symmetry of a symmetric distribution.)
It's already clear from @Ben's answer that the mode sometimes only barely meets the first criterion (perhaps oddly, B. & L. don't mention the mode): the scale family of exponential distributions is totally ordered, yet each distribution has the same mode.† Worse still, it can fail to meet it: let $X$ have a triangular distribution on [0,10] with mode 1, & $Y$ a triangular distribution on [0,4] with mode 2; then $X$ is stochastically larger than $Y$ despite having a lesser mode.

The median (obviously) & the mean (see https://math.stackexchange.com/q/3116135/59351) meet all three criteria, by the way. All the same, the mode seems fairly well entrenched as a measure of "central tendency", whatever exactly that's supposed to be. Perhaps it'd be sensible to follow B. & L. in requiring measures of location to meet all three criteria & then requiring measures of central tendency to meet only the 2nd & 3rd. On the other hand, the geometric, harmonic, &c., means perhaps have a claim to be measures of central tendency in their own right, though not of location; so there's a case for saying measures of central tendency need only meet the 1st criterion. At any rate just making such distinctions is the interesting & useful part.

†  In light of this example it's tempting to propose an additional criterion along the lines of 1.(a) $\mu(X) > \mu(Y)$ when $\Pr(X > k) > \Pr(Y > k)$ for any $k$ such that $0<\Pr(X>k)<1$ or $0<\Pr(Y>k)<1$.

Bickel & Lehmann (1975), "Descriptive statistics for non-parametric models. II. Location", Ann. Statist., 3, 5, pp. 1045–69
(I discuss other papers in this series dealing with dispersion & spread here, & must again thank Nick Cox for bringing them to my attention.)
Answer: Sometimes the mode is useful as a measure of the 'center' of a distribution.
In a right-skewed distribution the mode is often smaller than the median, which is in turn smaller than the mean.
For example, consider a gamma distribution, specifically
$\mathsf{Gamma(\text{shape}=\alpha = 5,\,\text{rate}=\theta=2)},$ which has mode $\frac{\alpha-1}{\theta} = 2,$ median $2.335454,$ and mean
$\frac{\alpha}{\theta} = 2.5).$ There are convenient formulas in terms
of the shape and scale parameters for the mode and mean, but in most cases the median must be computed by numerical integration.
qgamma(.5, 5, 2)
[1] 2.335454

If you have a moderately large sample from a population known to be gamma, but
with unknown parameters, then the parameters can be estimated by the
method of moments or by the method of maximum likelihood, from which
the mean and median can be estimated. (See the Wikipedia link above.)
For a very large sample the population mean is well estimated by the sample mean, and the population median is well estimated by the sample median. The mode can be very roughly estimated by looking at the
highest bar in a histogram, or more precisely estimated by finding
a kernel density estimator of the sample.
Suppose we have a sample of size $n = 10,000$ from $\mathsf{Gamma}(5,2).$
Then the sample mean 2,506 and median 2.324 are reasonably good estimates of the population mean and median, as shown below.
set.seed(1111)
x = rgamma(10^4, 5, 2)
summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
 0.1407  1.6806  2.3244  2.5057  3.1290  9.2822

Below is a histogram of these 10,000 observations along with a plot of
the population density curve [solid black] and the a kernel density estimate (KDE) [dotted red].
hist(x, prob=T, col="skyblue2", main="GAMMA(5,2)")
curve(dgamma(x, 5, 2), add=T, lwd=2)
plot(density(x), col="red", lwd=2, lty="dotted")

The highest histogram bar is centered at about 2.25, and there are
formulas for trying to refine this to get a slightly better estimate of the
population mode (one of them here). (A slightly different choice of histogram bins might
improve this estimate.)
The density estimator is made up of about 512 x-points and 512 y-points.
The maximum of the KDE, which can be taken as the sample mode 2.082, can be found using $-notation in R as shown below. (I have used the default version of the KDE in R.)
kde = density(x)
kde$x[kde$y == max(kde$y)]
[1] 2.081567

Is mode a measure of central tendency?


Intuition behind a retraction from the cylinder onto the mapping cylinder.

Question: Please excuse me for including pictures, but I thought it was easier than trying to redraw them here.
I am right now reading Strøm's book Modern Classical Homotopy Theory. I have encountered a problem, 5.21b) which concerns cofibrations (see the pictures). One should show that a morphism $i: A \rightarrow X$ is a cofibration iff there is a function $\phi:X \rightarrow I$ such that $A = \phi^{-1}(0)$ is a strong neighborhood deformation retract of $U = \phi^{-1}([0,1))$. In part a) I have no problem, but with b) i.e showing that if we have such a deformation retract, then $A \rightarrow X$ is a bigger problem. One wants to produce a retraction of $X \times I$ onto the mapping cylinder $A \times I \cup X$. They call $T$ the mapping cylinder in the text. Strom gives a picture trying to show how to define it, but I can't understand it properly. First of all:
How should I think intuitively (or non-intuitively, or at least some idea) on how this retraction should be constructed? The picture probably gives it, but I don't see it now.
How is the map defined?
Answer: The function $r:X\times I\to X\times\{0\}\cup A\times I$ is defined as follows:$$r(x,t)=\begin{cases}
(x,\ 0), &\text{ if }\phi(x)=1\\
(H(x,2(1-\phi(x))t),\ 0), &\text{ if }1/2\le\phi(x)<1\\
(H(x,t/(2\phi(x))),\ 0), &\text{ if }0<\phi(x)\le1/2,\ t\le2\phi(x)\\
(H(x,1),\ t-2\phi(x)), &\text{ if }0\le\phi(x)\le1/2,\ t\ge2\phi(x)
\end{cases}$$
It is easy to prove that all these partial functions are well-defined continuous maps and that they coincide where the domains intersect. Also, $r$ is the identity on $A\times I\cup X\times\{0\}$. Now, these partial functions could easily be glued to a single continuous map if the domains were all closed. Since they are not, we have to extend each function to the closure of its domain continuously.
To do this for the third function, let us denote $B=\{(x,t)\mid 0<\phi(x)\le1/2,\ t\le2\phi(x)\}$ which is the domain of that function. Its closure, as apparent from the picture, is $B\sqcup(\partial A\times\{0\}).$ The only way that we can extend the third map to this closure is by defining
$$f(x,t)=\begin{cases}
(H(x,t/(2\phi(x))),\ 0), &\text{ if }(x,t)\in B\\
(H(x,1),0)=(x,0), &\text{ if }(x,t)\in\partial A\times\{0\}
\end{cases}$$
Let us show that $f$ is continuous. This is clear for a point in $B$ as $B$ is open in $\overline B$. So take $a\in\partial A$. A typical neighborhood of $f(a,0)=(a,0)$ has the form $V\times[0,\epsilon)$, where $V$ is open and $\epsilon>0$. We can now apply the following lemma

Lemma: Let $X$ be a space, $A\subset X$, and $H:X\times I\to X$ a homotopy such that $H(a,t)=a$ for $a\in A.$ If $V$ is open, then there is an open $W\subseteq V$ such that $V\cap A\subseteq W$ and for every $w\in W$ the path $H(w,t)$ is contained in $V$.

Taking $X=U$ in the lemma, we obtain an open $W\ni a$ such that $f(w,t)\in V\times\{0\}$ for all $(w,t)\in W\times I$. This shows the continuity at $(a,0)$. We have thus extended the third function to a map with closed domain, in a way that is compatible with the other functions.
I am struggling with extending the second function. Funnily, I had actually just asked an own question dealing with that extension.
Comment: Great answer! This gives the definition of the function and that it is well-defined. But how should one , if one didn't have the picture actually come up with such a function? It is not obvious at all to me without the picture. It seems like "magic".
Comment: I got it from Strøm's paper [*Note on Cofibrations*](http://www.mscand.dk/article.php?id=1782). I think when defining such a function, the picture comes first and is then turned into a formula.


use computed Field in QWeb in kanban view odoo8

Question: I have a computed filed in my model :
initiatives_count = fields.Integer(compute=count_init)

when I am trying to use this filed in the QWeb kanban view like this:

it gives me that error:

Uncaught Error: QWeb2 - template['kanban-box']: Runtime Error:
  TypeError: Cannot read property 'value' of undefined

so any one have any idea where it goes wrong ????
Comment: it says coun instead of count?
Comment: sorry I have edited my code but I have the same error
Comment: Have you restarted the odoo service and refreshed the module again?
Comment: yes when I Use `record.field.value` for another it work fine
Comment: Maybe it is because its a function field. Try to add in the .py the parameter "store=True":

fields.Integer(compute=count_init, store=True)
Answer: I have find where I have go wrong that error because I did not define the fields that I will use in the view before using it like this:
<record model="ir.ui.view" id="amad_kanban_view_perspective">
    <field name="name">perspective Kabana</field>
    <field name="model">perspective</field>
    <field name="priority">10</field>
    <field name="arch" type="xml">
        <kanban>
            <field name="name"/>
            <field name="initiatives_count"/>
            <field name="initiatives"/>
            <templates>
                <t t-name="kanban-box">
                </t>
            </templates>
        </kanban>
    </field>
</record>


how to upgrade CentOS 5.11 to 6.x

Question: I have tried executing yum update command but it only took me from 5.11 to 6.x.  I need the server to be running CentOS 6.x for nagiosxi.
<code>[root@nagiosxi network-scripts]# uname -a
Linux nagiosxi.inl.gov 2.6.18-371.8.1.el5 #1 SMP Thu Apr 24 18:23:07 EDT 2014 i686 i686 i386 GNU/Linux
</code>
Comment: Have you looked at the CentOS/RedHat documentation?
Comment: Yes i have, it wasn't really clear as to how to do it
Comment: Which documentation specifically? It likely wasn't clear because that's generally not how they recommend doing things. Though there are (and have been) semi-official ways of doing it since CentOS 6 I believe.
Comment: Because you are upgrading to a major version, the safest way is to run preupgrade. Here's what centos has to offer http://wiki.centos.org/TipsAndTricks/CentOSUpgradeTool
Answer: As you probably know, CentOS is based on RedHat so the same rules apply for both.
In place upgrades between 4, 5, and 6 are not supported by RedHat (and thus CentOS).  The only supported upgrade path is from 6 to 7. The expectation is that an upgrade path will continue in future releases.
With that said, there is a way to upgrade from 5 to 6 but it is not supported by RedHat so be careful with how you use it.
The link is: In place upgrade

how to upgrade CentOS 5.11 to 6.x


Drupal 6 Search Redirect

Question: I would like to modify the search box to point to a custom search function.
So far, I have modified template.php to detect when the search box is being
called from a specific module and I reset some variables.
<code>function my_theme_preprocess_search_block_form(&$vars, $hook) {
    $uri = request_uri();
    if (preg_match("/\/my_module/", $uri)) {
        unset($vars["form"]["search_block_form"]["#title"]);
        $vars["form"]["search_block_form"]["#title"] = t("SOME SEARCH MESSAGE");
        $vars["form"]["search_block_form"]["#value"] = t("SOME SEARCH TERM");
    }
}
</code>
That works fine. But now what I want to do is have that form submit to some module of my own creation. Oddly, this isn't as obvious. Do I need to modify something in modules/search/ ? If so, what?
Comment: are you not using core search at all at this point? If so, why not just create a custom block with your search form in there and disable core search for performance gain. That way you don't even need to work with the form itself..
Comment: No, I only want to modify core search for this one module. This one module essentially proxies content from another system so in order for search to be meaningful I need to also proxy searches.
Answer: The way to alter the action handler for the search form is to add a submit handler, as outlined here: https://stackoverflow.com/questions/6444769/altering-search-form-action-not-working-for-custom-search-module-drupal-6. You can call your function in the submit handler or redirect to it from the submit handler.
<code>/**
* Implementation of hook_form_alter()
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'search_block_form') {
    $form['#submit'][] = 'mymodule_form_submit';
  }
}

/**
 * Process a block search form submission.
 */
function mymodule_form_submit($form, &$form_state) {
  // The search form relies on control of the redirect destination for its
  // functionality, so we override any static destination set in the request,
  // for example by drupal_access_denied() or drupal_not_found()
  // (see http://drupal.org/node/292565).
  if (isset($_GET['destination'])) {
    unset($_GET['destination']);
  }

  // Check to see if the form was submitted empty.
  // If it is empty, display an error message.
  // (This method is used instead of setting #required to TRUE for this field
  // because that results in a confusing error message.  It would say a plain
  // "field is required" because the search keywords field has no title.
  // The error message would also complain about a missing #title field.)
  if ($form_state['values']['search_block_form'] == '') {
    form_set_error('keys', t('Please enter some keywords.'));
  }

  $form_id = $form['form_id']['#value'];
  $form_state['redirect'] = 'search/mymodule/'. trim($form_state['values'][$form_id]);
  }
</code>
Comment: Great! This is what I needed. An important thing to note, though, is that `unset($form['#submit']);` is necessary before `$form['#submit'][] = 'mymodule_form_submit';` in `mymodule_form_alter`.

Drupal 6 Search Redirect


Add a second IP to SPF record, from an external SMTP server

Question: I would like to add the IP of an external SMTP server to an existing SPF record, which is looks like this:
<code>"v=spf1 a mx ip4:188.8.131.52 a:frey.mailpool.1.netmask.hu a:frey.mailpool.2.netmask.hu a:frey.mailpool.3.netmask.hu ~all"
</code>
Isn't will it mess up the parts with the "a:frey....." syntaxes, while the current and the new IP belongs to different servers? This would be the most simple way, but it looks too easy:
<code>"v=spf1 a mx ip4:188.8.131.52 ip4:220.127.116.11 a:frey.mailpool.1.netmask.hu a:frey.mailpool.2.netmask.hu a:frey.mailpool.3.netmask.hu ~all"
</code>
Thank you
Comment: it is not clear what you are asking. Can you clarify?
Comment: Is there an actual issue here? No, there's nothing wrong with `ip4` and `a` parts coexisting in an SPF record. http://www.kitterman.com/spf/validate.html parses your proposed record just fine.
Answer: The record, without evaluating for correct IP addresses and URLs, is valid. The only limit I am aware of for SPF is exceeding the maximum string length of a DNS TXT record, which is 255 characters.
RFC 4408 does give some additional guidelines:

3.1.4.  Record Size
The published SPF record for a given domain name SHOULD remain
  small enough that the results of a query for it will fit within 512
  octets. This will keep even older DNS implementations from falling
  over to TCP. Since the answer size is dependent on many things
  outside the scope of this document, it is only possible to give
  this guideline: If the combined length of the DNS name and the text
  of all the records of a given type (TXT or SPF) is under 450
  characters, then DNS answers should fit in UDP packets. Note that
  when computing the sizes for queries of the TXT format, one must
  take into account any other TXT records published at the domain
  name.  Records that are too long to fit in a single UDP packet MAY
  be silently ignored by SPF clients.

You may also want to read through the SPF Record Syntax and to better understand available mechanisms and what they do.


Prove that the numbers of the form $a+b\sqrt{2}$, where $a$ and $b$ are rational numbers, form a subfield of $\mathbb{C}$.

Question: I'm having trouble proving that a multiplicative inverse exists in the following problem:
Prove that the numbers of the form $a+b\sqrt{2}$, where $a$ and $b$ are rational numbers, form a subfield of $\mathbb{C}$.
Answer: Hint: What happens if you multiply $(a + b \sqrt{2})$ by $(a - b \sqrt{2})$?
Comment: i.e. use that to rationalize the denominator. Note that it cannot be $0\,$ (else $\,\sqrt2\in\Bbb Q)\ \ $
Comment: $(a+b\sqrt{2})(a-b\sqrt{2})=a^2-2b^2$. Sorry if I'm slow, but how does that help? What is the next step?
Comment: Note $a^2 - 2b^2$ is a non-zero rational number. So if you have $a + b \sqrt{2}$ then $(a-b \sqrt{2})/(a^2 - 2b^2)$ is the multiplicative inverse and it is contained in your field. So all you have to show is that your field is closed under multiplication and you will be done.


How to make subquery fast

Question: for an author overview we are looking for a query which will show all the authors including their best book. The problem with this query is that it lacks speed. There are only about 1500 authors and the query do generate the overview is currently taking 20 seconds.
The main problem seems te be generating the average rating of all the books per person.
By selecting the following query, it is still rather fast
select
    person.id as pers_id,
    person.firstname,
    person.suffix,
person.lastname,
    thriller.title,
    year(thriller.orig_pubdate) as year,
    thriller.id as thrill_id,
    count(user_rating.id) as nr,
    AVG(user_rating.rating) as avgrating
from
    thriller
inner join
    thriller_form
    on thriller_form.thriller_id = thriller.id
inner join
    thriller_person
    on thriller_person.thriller_id = thriller.id
    and thriller_person.person_type_id = 1
inner join
    person
    on person.id = thriller_person.person_id
left outer join
    user_rating
    on user_rating.thriller_id = thriller.id
    and user_rating.rating_type_id = 1
where thriller.id in
    (select top 1 B.id from thriller as B
    inner join thriller_person as C on B.id=C.thriller_id
    and person.id=C.person_id)
group by
    person.firstname,
    person.suffix,
    person.lastname,
    thriller.title,
    year(thriller.orig_pubdate),
    thriller.id,
    person.id
order by
    person.lastname

However, if we make the subquery a little more complex by selecting the book with the average rating it takes a full 20 seconds to generate a resultset.
The query would then be as follows:
select
    person.id as pers_id,
    person.firstname,
    person.suffix,
    person.lastname,
    thriller.title,
    year(thriller.orig_pubdate) as year,
    thriller.id as thrill_id,
    count(user_rating.id) as nr,
    AVG(user_rating.rating) as avgrating
from
    thriller
inner join
    thriller_form
    on thriller_form.thriller_id = thriller.id
inner join
    thriller_person
    on thriller_person.thriller_id = thriller.id
    and thriller_person.person_type_id = 1
inner join
    person
    on person.id = thriller_person.person_id
left outer join
    user_rating
    on user_rating.thriller_id = thriller.id
    and user_rating.rating_type_id = 1
where thriller.id in
    (select top 1 B.id from thriller as B
    inner join thriller_person as C on B.id=C.thriller_id
    and person.id=C.person_id
    inner join user_rating as D on B.id=D.thriller_id
    group by B.id
    order by AVG(D.rating))
group by
    person.firstname,
    person.suffix,
    person.lastname,
    thriller.title,
    year(thriller.orig_pubdate),
    thriller.id,
    person.id
    order by
    person.lastname

Anyone got a good suggestion to speed up this query?
Answer: Calculating an average requires a table scan since you've got to sum the values and then divide by the number of (relevant) rows. This in turn means that you're doing a lot of rescanning; that's slow. Can you calculate the averages once and store them? That would let your query use those pre-computed values. (Yes, it denormalizes the data, but denormalizing for performance is often necessary; there's a trade-off between performance and minimal data.)
It might be appropriate to use a temporary table as the store of the averages.
Comment: We were already talking about that, but we were hoping someone would know a solution that wouldn't have to do this.
Comment: @Frederik: I understand, but if you need the info, you *need* it. Mitigation is easiest approach really.

How to make subquery fast


Typescript property value should be a value of another property

Question: Suppose I have a type or interface Progress:
interface Progress {
  steps: string[],
  active: string
}

const p: Progress = { steps: ['foo', 'bar', 'baz'], active: 'bob' }; // Error, 'bob' not in steps

is there any way to state that the value of active should be one of the values in steps?
Another, admittedly contrived example:
interface Twins {
  p1: string,
  p2: string
}

const t: Twins = { p1: 'bob', p2: 'alice' }; // Error 'alice' is not the same as p1

where the value of p1 and p2 should be the same?
Answer: One way to achieve this would be using generics.
What we want to say is that Progress has a dynamic type which is based on some type T and then we can use T to add our validation.
interface Progress<T> {
  steps: T[],
  active: T
}

const p: Progress<'foo' | 'bar' | 'baz'> = { steps: ['foo', 'bar', 'baz'], active: 'bob' }; //Error

const q: Progress<'foo' | 'bar' | 'baz'> = { steps: ['foo', 'bar', 'baz'], active: 'bar' }; //No error

Playground
The above has a repetition of the foo, bar, baz. You can extract it out as a constant and avoid it.
You can use const assertion to create a read-only constant which you can use as a value and to generate a type out of it.
type Progress<T extends readonly string[]> = {
  steps: T,
  active: T[number]
};

const steps = ['foo', 'bar', 'baz'] as const;

const p: Progress<typeof steps> = { steps, active: 'bob' }; // Error
const q: Progress<typeof steps> = { steps, active: 'bar' }; // No error.

Playground
Comment: I don't think this is possible. It works with methods. So you can change your approach and start with a createProgress method.But with objects this is the extent to which typescript can help you
Comment: Interesting! Is there any way that typescript would be able to infer the generic parameter of Progress?
Comment: I actually needed it for a React component, which are functions (these days). So this works perfectly.


Orthogonal surfaces to a vector field

Question:
Consider the vector field $\mathbf F(x,y,z)=(y-x,x-y-xz,xy-z)$.

Find the equations of the characteristic curves of $\mathbf F$ and discuss the existence of orthogonal surfaces to $\mathbf F$.
Find the family of curves of part 1 restricted to the plane $z=0$.

Regarding the first part, the characteristic curves satisfy
$$\frac{dx}{y-x}=\frac{dy}{x-y-xz}=\frac{dz}{xy-z}$$
or
$$\begin{align}
(x-y-xz)dx&=(y-x)dy\\
(xy-z)dx&=(y-x)dx\\
(x-y-xz)dz&=(xy-z)dy
\end{align}$$
and, if I am not mistaken, the existence of such surfaces is guaranteed locally since $\mathbf F$ is continuous.
However, I am not sure what I am supposed to do in part 2. Any help would be appreciated.
Answer: If a characteristic curve $p(t)=(x(t),y(t),0)$ stays inside the $z=0$ plane, then $\textbf{F}(x(t),y(t),0)$ should have its $z$ component stay $0$, so $$x(t)y(t)=0$$, and
$$-(x-y)dy=(x-y)dx$$
Then solve these.

Orthogonal surfaces to a vector field


Project new point into MDS space

Question: I am trying to project a new point A(x, y, z) into a predefined MDS space in R. This is what I have so far:
set.seed(1)
x <- matrix(rnorm(3*10), ncol = 3)
DM <- dist(x)
MDS <- cmdscale(DM)

# New data point to be projected
A <- c(1, 2, 3)

I am not including A directly into x then fitting the MDS because it would affect the space coordinates. Is there a practical solution?

EDIT
I believe I found a solution by estimating the betas to predict the MDS axis:
x1 <- cbind(1, x) # add intercept
B <- solve(t(x1) %*% x1) %*% t(x1) %*% MDS # Betas

> MDS
             [,1]        [,2]
 [1,] -1.80789362  0.06801597
 [2,] -0.64418055 -0.21163109
 [3,]  0.04694820 -1.27040928
 [4,]  3.39617277 -0.21657115
 [5,] -0.96981358  0.46269025
 [6,] -0.24716695 -0.79861234
 [7,]  0.33620625  0.02618564
 [8,]  0.62473570  1.35544267
 [9,]  0.01895042  0.80023822
[10,] -0.75395865 -0.21534889

> x1 %*% B # same as MDS
             [,1]        [,2]
 [1,] -1.80789362  0.06801597
 [2,] -0.64418055 -0.21163109
 [3,]  0.04694820 -1.27040928
 [4,]  3.39617277 -0.21657115
 [5,] -0.96981358  0.46269025
 [6,] -0.24716695 -0.79861234
 [7,]  0.33620625  0.02618564
 [8,]  0.62473570  1.35544267
 [9,]  0.01895042  0.80023822
[10,] -0.75395865 -0.21534889

A <- c(1, 2, 3)
A <- c(1, A) # add intercept

> A %*% B # coordinates of A in the MDS plane
          [,1]      [,2]
[1,] -2.759456 0.5927178

Is my procedure correct?
Comment: @amoeba The idea is simply to plot A into the new MDS space in order to further improve the meaning of the plane drawn from the MDS. Don't know if this answers your question?
Comment: I was just wondering if you have a specific application in mind, and if so, what that application is.
Comment: @amoeba In practice `x` represent some scores from participants, and `A` represent a "perfect score".
Comment: @amoeba I edited my original post
Comment: You use `cmdscale` which is just PCA and not really MDS. "Classical multidimensional scaling (MDS) of a data matrix. Also known as principal coordinates analysis (Gower, 1966)." https://www.rdocumentation.org/packages/stats/versions/3.5.1/topics/cmdscale. If that's what you want, then projecting a new point is trivial (as per your Edit).
Answer: If you're using Euclidean distances, then classical MDS is equivalent to PCA, which readily defines a mapping into the low dimensional space, as amoeba mentioned. There should be various threads on this site describing how to do this. Otherwise, De Silva and Tenenbaum (2004) describe how to perform this mapping for classical MDS with arbitrary distances (note that it won't work for non-classical variants of MDS, e.g. non-metric MDS, variants that minimize the stress criterion, etc.). They call this procedure "distance-based triangulation". Although not originally formulated as such, it turns out to work by using the Nyström approximation, which is a way to approximate the eigenvalues/eigenvectors of a large matrix using a smaller submatrix (see Platt 2005).
Suppose we have $n$ training points. The squared distance between points $i$ and $j$ is stored in the $(i,j)$th entry of matrix $\Delta_n$. We use these distances with classical MDS to compute a $k$-dimensional embedding. Let each column of $k \times n$ matrix $L_k$ contain the low-dimensional embedding coordinates of a training point. Let $L_k^\#$ denote the transpose of the pseudoinverse of $L_k$. Instead of starting from scratch, this can be computed using components that were originally used to compute $L_k$ (see the paper for details). Let $\vec{\delta}_i$ denote the $i$th column of $\Delta_n$ (containing the squared distances from point $i$ to all other points), and let $\vec{\delta}_\mu = \frac{1}{n} \sum_{i=1}^n \vec{\delta}_i$ denote the mean of the columns.
Now, suppose we want to map a new point $a$ into the low dimensional space. Compute vector $\vec{\delta}_a$, containing the squared distance from $a$ to every training point. The low dimensional emedding coordinates of $a$ are then given by:
$$\vec{x}_a = -\frac{1}{2} L_k^\# (\vec{\delta}_a - \vec{\delta}_\mu)$$
References:

De Silva and Tenenbaum (2004). Sparse multidimensional scaling using landmark points.
Platt (2005). FastMap, MetricMap, and Landmark MDS are all Nystrom Algorithms.
Comment: +1 Interesting. But I suggest you mention that if one uses "real" (what's the term?) MDS as opposed to "classical" MDS, then a mapping is not possible at all. By "real" I mean what Wikipedia calls [metric MDS with "stress" loss function](https://en.wikipedia.org/wiki/Multidimensional_scaling#Metric_multidimensional_scaling_(mMDS)); this is what I think by default when somebody says "MDS".
Comment: @amoeba true, this wouldn't work for non-classical MDS (the real stuff :). I'll edit to emphasize that
Comment: Has anyone tested the accuracy of this in some capacity?
Comment: For pairwise distances computed using the earth mover's distance, I get reasonable (95%) correspondence between the true distances and a PCA embedding to 3 dimensions. However, if I use this out-of-sample MDS approach, the parity plot is a large blob.
Comment: ~4000 training points and ~700 validation points
Answer: As per amoeba's comment, another practical solution in R would be to use the stats::prcomp() and its associated predict() method if using the Euclidean distance for your MDS:
set.seed(1)
x <- matrix(rnorm(3*10), ncol = 3)

# New data point to be projected
A <- c(1, 2, 3)

> predict(prcomp(x, rank. = 2), matrix(A, nrow = 1))
           PC1        PC2
[1,] -2.759456 -0.5927178

Project new point into MDS space


Syntax Error I can't figure out on Apache2

Question: I was attempting to change the conf of my files in order to achieve port forwarding, however all of a sudden I get the following error when attempting to restart:
AH00526: Syntax error on line 30 of /etc/apache2/sites-enabled/000-default.conf:
RewriteCond: bad flag delimiters

I'm new to Apach2 so I'd appreciate if someone could provide input on what could be going wrong. I can't figure out what exactly the syntax error is.
This is how my files look:
00-defualt file
le-ssl file
EDIT:
These are the lines:
RewriteEngine on
RewriteCond %{SERVER NAME}=19thstreet.co
RewriteRule ^ https://%{SERVER NAME}%{REQUEST URI} [END,NE,R=permanent]

Answer: I figured it out. It was the underscore in Request_URL:
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

Comment: Also the correct lines would be
    RewriteEngine On
    RewriteCond %{SERVER_NAME} 19thstreet.co
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]


Can't uninstall default search module because the Commerce Base module is required

Question: I want to use Search API + Solr on my Drupal (& Drupal commerce) site.
The tutorials recommend to uninstall the core Search module.
However, I can't:
the UI at page /admin/modules has Search module checked and grayed out and trying drush pmu search results in the following output:
In ModuleInstaller.php line 432:

The following reasons prevent the modules from being uninstalled: The Commerce Base module is required

I am using Drupal 9.4.5, with all modules up-to-date. I installed it with the commerce_base installation profile as suggested at https://docs.drupalcommerce.org/commerce2/developer-guide/install-update/installation.
I didn't try it on a fresh install, but even if it works there, I would prefer to be able to modify my site as needed rather than starting from scratch -- any ideas how to start debugging this?
Answer: I think what you are asking is not possible commerce_base requires the core search module. I mean that you are not encountering a bug but rather a consequence of using that install profile.
Comment: As a side note, [Replace core search with Search API](https://github.com/drupalcommerce/commerce_base/issues/4) is a *Commerce Base* issue opened in 2017. Since then, there have not been any progress.
Comment: Thanks!
So, if I edited the commerce_base.info.yml file (say replacing search with search_api), I would be able to uninstall the module I suppose. Is it a terrible idea -- or will search_api work as a replacement?
Comment: If the *Search* module is effectively used by one of the modules installed by the *Commerce Base* profile, it won't work, since the *Search API* module doesn't implement the same classes/functions/methods implemented by the *Search* module. Even a view that uses a plugin that takes data from the *Search* module won't work.
Comment: It could also be the *Commerce Base* profile copied its dependencies from the *Standard* profile, and included the *Search* module even if that module isn't necessary. To verify this is the case, you should create a test site and check what happens when the profile dependencies are changed as you described in your comment.
Answer: The Search API module isn't a drop-in replacement for the Search module. This means that modules that expect the Search module to be installed won't work if you replace the Search module with the Search API module.
It could also be the Commerce Base profile copied its dependencies from the Standard profile and included the Search module, even if that module isn't necessary, or the Commerce Base profile dependencies haven't been updated and the Search module is now not required. In these cases, uninstalling the Search module and replacing it with the Search API module won't cause any issue on the site.
You can verify this is the case by creating a test site where the Composer Base dependencies are changed to exclude the Search module and include the Search API module and checking everything works as expected, including other Commerce modules you are using on your site.
(It could be there are Commerce modules that require the Search module but don't add it as their dependency, thinking the Search module is already a dependency for the Commerce Core module or any other Commerce module they need.)
On the issue queue for the Commerce Base profile, there is Replace core search with Search API, which is stalled since July 24, 2017 (the day that issue has been created).


How to choose the Normalization method for a co-occurence matrix?

Question: I have a co-occurrence matrix about hashtags usage (The value in the cell means the number of times two hashtags appear together in a single tweet), it is transformed from a 2-mode matrix. Now I want to use Ucinet to normalize this matrix because I have 4 matrices like this in different periods. Indeed, I want to compare the usage of hashtags at different times, so I should normalize all 4 matrices to decrease dimensional effects.
But I find that ucinet offers different methods for that: z-scores, marginal, Euclidean and so on. Which is the best? I don't know how to choose and I also find there is some difference between outcomes by different methods. Thanks for your help!
Comment: @utobi Sure, this is one of my co-occurence matrix(partly).
 https://i.stack.imgur.com/eyoff.png    The value in the cell means the number of times tag A and tag B appear together in the tweet( I have hundreds of thousands of tweets, and each tweet is analyzed as a co-occurrence unit
Comment: Just to make sure I understood correctly, (1) you have four $n \times n$ frequency tables. (2) you want to be able to compare these tables. Is that right? $n$ is the number of hashtags.
Comment: @utobi Hi, thank u for your reply! yes, I have 4 tables, but each one does not contain the same hashtags. The first one contains 100X100, the second for 120X120, the third 130X130, last 145X145. Some of them are repetitive and some of them are specific. I want to normalize these matrices and just compare  10 hashtags specifically.
Comment: For the tables to be comparable you have to wash out the sample size effect. To do this you simply divide each cell by the grand total. In this way, the resulting cells will be numbers between 0 and 1 and are thus comparable across different tables, i.e. tables from different time points, or experimental conditions, etc.
Comment: @utobi Thank you! It is so clear. And in ucinet there are 3 method of normalization: (1) Euclidean - Forces the Euclidean norm,  to be one; (2) Maximum - Forces the maximum of the elements to be 100; (3) Z-Score - Forces the mean of the elements to be zero and the standard deviation to be 1.  By row, column, matrix or row and column.  If standard deviation is initially zero then elements of matrix are treated as missing.    Is it OK for me to use either one? or only the "Maximum"
Comment: Unfortunately, I'm not familiar with `ucinet`, but maybe I am missing something from your problem. Could you share and describe one of these tables in your post?  It is not clear to me if you have a table for each tweet or if you pull the tables across many tweets. If you consider a table for a single tweet, I guess the tables would be very sparse.
Answer: Since the co-occurrence table is a quadratic and symmetric matrix around the main diagonal, it doesn't make any difference if you read it by rows or by columns. The main diagonal seems to be zero everywhere, which makes sense since it's unlikely that one repeats the same hashtag within the same tweet.
My suggestion is to normalize row-wise (or column-wise), that is, to divide each row by its total. In this way, the $i$th row of the table would represent the relative frequency distribution of co-occurrences for the hashtag $i$. You can now compare this frequency distribution with other frequency distributions from other tables or for other tags.
In my opinion, it doesn't make sense to compute quantiles or moment-based summaries on these distributions (so z-score is not meaningful either) since the variable in question is qualitative, i.g. having modalities "#1 vs #1", ..., "#1 vs #n".
You can instead use use the mode (i.e. the co-occurence with highest relative frequency) as a measure of location. As a measure of "variability" or entropy you may use the Shannon entropy.
If we denote by $p_{j|i}$ be the relative frequency of the co-occurence "#i vs #j", for $j = 1,\ldots,k$, the Shannon entropy is
$$
H = \sum_{j=1}^k p_{i|j}\log p_{j|i},
$$
with $p_{j|i}\log p_{j|i} = 0$ if $p_{j|i}=0$. $H$ assumes value zero, i.e. its minimum, when the distribution is uniform. Furthermore, it can be shown that $H\leq \log k$, thus if you use $H$ to compare frequency distributions with different $k$'s, it's better to use its normalized version
$$
H_n = \frac{H}{\log(k)}.
$$
Comment: It is so clear! Thank you for your help and time, I will try to use the Shannon entropy method, thanks again!


Python crashes on returning an C++ map value

Question: i am writing a Test to keep Data in a C++ map. I am using the Python C-Api.
Adding int values and getting the length of the map is no problem.
But when i get a value from the map and want to return it to Python than the Interpreter crashes.
This is my Code:
    //some includes
    int VerboseLog = 99;
    typedef map<const char*, int> SessionKeeper;
    static SessionKeeper openSessions;

    static PyObject* getSession(PyObject* self, PyObject* args) {
        cout << "get" << endl;
        const char *key;

        if (!PyArg_ParseTuple(args, "z*", &key)) {
            PyErr_SetString(PyExc_Exception, "UUID konnte nicht ausgelesen werden");
            PyErr_PrintEx(1);
            return NULL;
        }

        int r = openSessions.at(key);
        return Py_BuildValue("i", r);
    }

    static PyObject *addSession(PyObject* self, PyObject* args) {
        cout << "Hello" << endl;
        const char  *key;
        int toAppend;

        if (!PyArg_ParseTuple(args, "si", &key, &toAppend)) {
            PyErr_SetString(PyExc_Exception, "Ein Parameter konnte nicht ausgelesen werden");
            PyErr_PrintEx(1);
            return NULL;
        }

        openSessions[key] = toAppend;
        cout << openSessions.size() << endl;
        cout << openSessions[key] << endl;
        Py_RETURN_NONE;
    }

    static PyObject* length(PyObject *self){
        cout << "length: ";
        int i = openSessions.size();
        return Py_BuildValue("i",i);
    }

    static PyMethodDef SessionKeeper_methods[] = {
        /*Note the third entry (METH_VARARGS). This is a flag telling the interpreter the calling convention
        to be used for the C function. It should normally always be METH_VARARGS or METH_VARARGS | METH_KEYWORDS;
        a value of 0 means that an obsolete variant of PyArg_ParseTuple() is used.*/
        { "length", (PyCFunction)length, METH_VARARGS, "return length of a Session" },
        { "addSession", (PyCFunction)addSession, METH_VARARGS, "add a Session." },
        { "getSession", (PyCFunction)getSession, METH_VARARGS, "get a Session" },
        { NULL }
    };

    static PyModuleDef sessionKeeperMod = {
        PyModuleDef_HEAD_INIT,
        u8"SessionKeeper",
        NULL,
        -1,
        SessionKeeper_methods
    };

    static PyModuleDef CpluplusModules_ModDef = {
        PyModuleDef_HEAD_INIT,
        u8"CPlusPlusMouldes",
        u8"Enthält alle Erweietrungen",
        -1,
        NULL, NULL, NULL, NULL, NULL
    };

    PyMODINIT_FUNC PyInit_CPlusPlusModules(void) {
            PyObject* m, *sessionMod;

            if (PyType_Ready(&TAModulType) < 0)
                return NULL;

            if (PyType_Ready(&DatabaseReader_Type) < 0)
                return NULL;

            if (!(sessionMod = PyModule_Create(&sessionKeeperMod))) {
                cout << "fail" << endl;
                return NULL;
            }

            m = PyModule_Create(&CpluplusModules_ModDef);
            if (m == NULL)
                return NULL;

            Py_INCREF(&TAModulType);
            Py_INCREF(&DatabaseReader_Type);

            PyModule_AddObject(m, "TAModul", (PyObject *)&TAModulType);
            PyModule_AddObject(m, "DBReader", (PyObject *)&DatabaseReader_Type);
            PyModule_AddObject(m, "SessionKeeper", sessionMod);

            return m;
    }

The other Modules (DBReader and TAModule) workes fine. The goal will be to safe PythonObjects (containing DbReader Objects and TAModul Objects) in the map.
But bacck to my question why do the getSession crashes the Interpreter on return? And why do the length function works fine.
Answer: map<const char*,...> will match based on the address of the string rather than the contents. Therefore it's pretty likely that at will fail and throw an C++ out_of_range exception.
You should start by wrapping the line
int r = openSessions.at(key);

with a try {} catch block, to stop the out_of_range exception propagating through the Python interpreter (which isn't C++ so can't handle it).
You should then change the map to match the key on the string contents. The easiest way would be to use map<std::string,int>.
Comment: thanks that was a part of the problem, i also had to use "s" instate of "z* in the parsing function


Use Ecto in a mix task

Question: In a Phoenix Framework application I have a model Product with the field name. I want to create a mix task which lists all product names.
In Ruby on Rails this would be the code to solve the problem:
namespace :list do
  desc "List all products"
  task products: :environment do
    Product.all.each do |product|
      puts product.name
    end
  end
end

In Phoenix I can't even get the list of all products from the database. Here is the task code:
lib/mix/tasks/list.product.ex
defmodule Mix.Tasks.List.Product do
  use Mix.Task
  import Mix.Ecto
  alias App.Repo
  alias App.Product

  def run(_args) do
    products = Repo.all(Product)
  end
end

When I run this task I get this error message:
** (UndefinedFunctionError) function Ecto.Queryable.__using__/1
is undefined or private

What do I have to do to fetch all products from the database in this mix task?
Comment: Shouldn't it be `App.Product` instead of `Product`?
Comment: Possible duplicate of [How to get data from Ecto in a custom mix task](http://stackoverflow.com/questions/38225406/how-to-get-data-from-ecto-in-a-custom-mix-task)
Comment: I updated the code.
Answer: Add ensure_started(Repo, []) at the top of your run method. You may also want to import Ecto.Query for some query forms.
defmodule Mix.Tasks.List.Product do
  use Mix.Task
  import Mix.Ecto
  import Ecto.Query
  alias App.Repo
  alias App.Product

  def run(_args) do
    ensure_started(Repo, [])
    products = Repo.all(Product)
  end
end

Comment: It does not work in Phoenix 1.4 "undefined function ensure_started/2"
Comment: @hipertracker use this. `Mix.Task.run("app.start", [])`
Answer: The hard way:
defmodule Mix.Tasks.MyTask do
  use Mix.Task
  import Ecto.Query
  alias MyApp.Repo

  @start_apps [
    :postgrex,
    :ecto,
    :ecto_sql
  ]

  @repos Application.get_env(:my_app, :ecto_repos, [])

  def run(args) do
    start_services()

    # Run Ecto...

    stop_services()
  end

  defp start_services do
    Enum.each(@start_apps, &Application.ensure_all_started/1)
    Enum.each(@repos, & &1.start_link(pool_size: 2))
  end

  defp stop_services do
    :init.stop()
  end
end

or the easy way ;)
defmodule Mix.Tasks.MyTask do
  use Mix.Task
  import Ecto.Query
  alias MyApp.Repo

  def run(args) do
    Mix.Task.run("app.start")
    # Run Ecto...
  end
end

https://gist.github.com/hipertracker/a2ae2c7adf1fdd78b45712abeade7fe3
https://github.com/bitwalker/distillery/blob/master/docs/guides/running_migrations.md

Use Ecto in a mix task


Square roots and cube roots equation

Question: Solve over real $a$
$$\sqrt{3a-4}+\sqrt[3]{5-3a}=1.$$
If $p=3a-4$,
$$\sqrt{p}+\sqrt[3]{1-p}=1.$$
If $q=5-3a$,
$$\sqrt{1-q}+\sqrt[3]{q}=1.$$
Seems useful, but not sure how to proceed.
Answer: Let $x:=\sqrt{p}$ so $0=1-x^2-(1-x)^3=x(1-x)(3-x)$ and$$x\in\{0,\,1,\,3\}\implies p=x^2\in\{0,\,1,\,9\}\implies a\in\left\{\tfrac43,\,\tfrac53,\,\tfrac{13}{3}\right\},$$all of which work.
Comment: @NoChance $$1-\left(\sqrt{3a-4}\right)^2-\overbrace{\left(\sqrt[3]{5-3a}\right)^3}^{\left(1-\sqrt{3a-4}\right)^3}=0$$
Comment: Could you please elaborate at how the roots were removed? It looks very clever. Thanks.
Comment: @PeterForeman, this helps thanks.
Answer: Using your first substitution:
$$\begin{align*}
\sqrt p+\sqrt[3]{1-p}&=1\\[1ex]
\sqrt[3]{1-p}&=1-\sqrt p\\[1ex]
1-p&=(1-\sqrt p)^3\\[1ex]
1-p&=1-3\sqrt p+3p-|p|\sqrt p\\[1ex]
\end{align*}$$
If $p=3a-4\ge0$ (and this is the only case if you're looking for real-valued solutions, since $\sqrt p$ would be defined only for $p\ge0$), or $a\ge\frac43$, then $|p|=p$:
$$\begin{align*}
1-p&=1-3\sqrt p+3p-p\sqrt p\\[1ex]
1-p&=1+3p-(3+p)\sqrt p\\[1ex]
4p&=(3+p)\sqrt p\\[1ex]
\frac{4p}{3+p}&=\sqrt p\\[1ex]
\frac{16p^2}{(3+p)^2}&=p\\[1ex]
16p^2&=p(3+p)^2\\[1ex]
16p^2&=p^3+6p^2+9p\\[1ex]
p(p-1)(p-9)&=0
\end{align*}$$
Then either $p=0$, $p=1$, or $p=9$, which means either $a=\frac43$, $a=\frac53$, or $a=\frac{13}3$.
Answer: It is indeed useful. Write
$$
\sqrt[3]{1-p}=1-\sqrt{p}
$$
and cube:
$$
1-p=1-3\sqrt{p}+3p-p\sqrt{p}
$$
Writing $r=\sqrt{p}$ you get
$$
r^3-4r^2+3r=0
$$
and the rest should be easy. Just beware that the solutions are subject to $r\ge0$ and $p\ge0$ (in this case there's no problem, however).
Answer: One strategy is to get rid of the cube root first. Two reasons: first, it is the most complicated part of the problem; second, if you are working in the real numbers you can always take a cube root, but square roots require some care.
So write $x^3=5-3a$ to get $\sqrt {1-x^3}=1-x$
(It is obvious from this that $x=1$ is a solution). Now square this, conscious that squaring is likely to produce solutions which belong to the negative square root as well as the positive square root. $$1-x^3=(1-x)^2$$
One solution is $x=1$, and otherwise divide by $(1-x)$ to obtain $1+x+x^2=1-x$ or $x^2+2x=0$
Then work backwards and check that the solutions work for the original equation (and not the one with the negative square root).
That seems to work more smoothly than the other methods which have been suggested.

Square roots and cube roots equation


return data even if they are errors

Question: I have a stored procedure, in which return a table containing date,presence,total working hour if present...
Total Working Hour is calculated in a separate function that return a decimal value, But sometimes employees have a mistakes in data, like a duplicate punches or punch (out or in) for twice,
if any of the above scenario exist the function returned an error, and therefore The SP return error...
My request is when any error is occurred, i want to return 0 or -1 or whatever instead of the error, to forces the SP to return data even if they are errors..
The Error generating every time is :
SQL Server Subquery returned more than 1 value.
This is not permitted when the subquery follows =, !=, <, <= , >, >=

So I want in every time when this error occurred, to return a value instead of it,
the SP Code is:
ALTER PROCEDURE [dbo].[SM_GetAttendance]
(
    @StartDate date ,
    @EndDate date ,
    @EmployeeID NVARCHAR(6)
)
AS
BEGIN

    SET NOCOUNT ON;
DECLARE dte_Cursor CURSOR FOR
WITH T(date)
AS
(
SELECT @StartDate
UNION ALL
SELECT DateAdd(day,1,T.date) FROM T WHERE T.date < @EndDate
)
SELECT date FROM T OPTION (MAXRECURSION 32767);

    DECLARE @date NVARCHAR(20);
    CREATE TABLE #datetable(date DATETIME,Status NVARCHAR(50),nbOfWorkingHour DECIMAL(36,2))

--SELECT date FROM T
set @date = ''
OPEN dte_Cursor
FETCH NEXT FROM dte_Cursor INTO @date

WHILE @@FETCH_STATUS = 0
BEGIN
insert #datetable

SELECT
        cast((select distinct Convert(Nvarchar(12),date,102) from Attendance where date = @date
                            and employeeid =@EmployeeID ) as nvarchar(30))
                        date

,CASE WHEN  EXISTS (select 1 from Attendance
                        where employeeid=@EmployeeID and date = @date)
                then 'Present'
                else 'absent'
                        end Status

,dbo.GetWorkingHourPerDay(@date,@EmployeeID) as numberOFWorkingHour
FETCH NEXT FROM dte_Cursor INTO @date
END

CLOSE dte_Cursor;
DEALLOCATE dte_Cursor;
end

And The Part of the Function Code that get the error is:
SET @From = (SELECT Time from @Tbl where date = @Date AND (EmployeeID=@employeeID OR ISNULL( @employeeID, '') = '') and funckey = 'EMPIN')

set @to = (CASE WHEN EXISTS(SELECT Times from @Tbl where dates = @Date AND (EmployeeID=@employeeID OR ISNULL( @employeeID, '') = '') and funckey = 'EMPOUT' )
then (SELECT Time from @Tbl where date = @Date AND (EmployeeID=@employeeID OR ISNULL( @employeeID, '') = '') and funckey = 'EMPOUT' )
else (SELECT Top 1 Time from @Tbl where date = dateadd(day,1,@Date) AND (EmployeeID=@employeeID OR ISNULL( @employeeID, '') = '') and funckey = 'EMPOUT')
end)

return ROUND(CAST(DATEDIFF(@From,@to) AS decimal)/ 60,2)

the following piece of code that get the error :
(CASE WHEN EXISTS(SELECT Times from @Tbl where dates = @Date AND (EmployeeID=@employeeID OR ISNULL( @employeeID, '') = '') and funckey = 'EMPOUT' )

IN this example the employee have two out punches like the below :
EMPID       Date            Time            Status
123         2015-10-22      06:54:42 AM     OUT
123         2015-10-22      04:35:02 PM     OUT

So how to how to handle this state?
Answer: You can just change
(CASE WHEN EXISTS(SELECT Times from @Tbl where dates = @Date AND (EmployeeID=@employeeID OR ISNULL( @employeeID, '') = '') and funckey = 'EMPOUT' )

To this
(CASE WHEN EXISTS(SELECT top 1 Times from @Tbl where dates = @Date AND (EmployeeID=@employeeID OR ISNULL( @employeeID, '') = '') and funckey = 'EMPOUT' )

return data even if they are errors


Colocar um botão de desligar serviço na notificação de um App Android

Question: Na minha aplicação tenho um Service rodando em background, o qual coloca uma notificação na Status Bar do usuário, gostaria de adicionar um botão para desligar o serviço, como o Waze app de mapas faz.
Answer: Crie um BroadcastReceiver com o código necessário para parar o serviço.
Ao criar a notificação use o método addAction() do Notification.Builder passando um PendigIntent que lance esse BroadcastReceiver.
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

Notification n  = new Notification.Builder(this)
    ...
    ...
    ...
    .setAutoCancel(true)
    .addAction(R.drawable.icon, "Parar serviço", pIntent).build();

NotificationManager notificationManager =
  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

notificationManager.notify(0, n);

Outra forma seria o PendigIntent ser contruido de forma a lançar o serviço passando um 'Extra' que indicasse que o serviço deve ser parado.
O método onStartCommand() do serviço verifica esse 'Extra' e chama stopSelf().
O PendigIntent a usar no addAction() seria assim:
Intent intent = new Intent(this, oSeuServico.class);
Intent.putExtra("Parar","Sim");
PendingIntent pIntent = PendingIntent.getService(this, 0, intent, 0);

Comment: Certo, e o ícone de desligar na notificação como posso fazer?
Comment: Editei a pergunta com uma outra forma de fazer. O ícone é um *drawable*. No código que postei é `R.drawable.icon`, o primeiro parâmetro de `addAction`.
Comment: Entendi, muito obrigado! Já estou implementando aqui, acredito que vai dar certo :)
Comment: Outra coisa, tem hora que o action mostra, tem hora que não, quando tem muitas notificações, tem como determinar para sempre mostrar o action?
Comment: O que é que não mostra? O ícone de desligar ou a notificação toda?
Comment: Exato, coloquei a prioridade como máxima da notificação agora aparece.
Comment: Consegui implementar até a parte do BroadCastReceiver, agora eu gostaria de fechar toda aplicação, no broadcast..Algo como finish(); para fechar todo app.
Comment: Se o BroadcastReceiver for uma *inner* classe da sua *activity* você tem acesso ao método `finish()`. No entanto não faz muito sentido usar *notifications* para "parar" o serviço se a sua *activity* tem de se manter em execução enquanto o serviço estiver em funcionamento.


How to share Image from imageSwitcher in android

Question: How do I code to share current image that is in view (in the imageSwitcher) from gallery. I have an app that have multiple images in a gallery which after selected is then loaded into an imageSwitcher. So now I want to Share the image currently being viewed and sent using the Share Intent bringing up share Options window.
This is my code:
TextView drawableId;TextView stringCopy;
<code>    int imgs[] =
            {
                    R.drawable.pg1,
                    R.drawable.pg2,

            };
    String imgs1[] =
        {
                "R.drawable.pg1",
                "R.drawable.pg2",
        };
    int imgs2[] =
            {
                    R.drawable.infinity_96_58uvb_pg1,
                    R.drawable.infinity_96_58uvb_pg2,

            };

    ImageSwitcher imgSwitcher, imageSwitcher2;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    drawableId = (TextView) findViewById(R.id.textView);
    stringCopy = (TextView) findViewById(R.id.textView2);

    imgSwitcher = (ImageSwitcher) findViewById(imageSwitcher1);
    imgSwitcher.setFactory(this);

    final Gallery gallery = (Gallery) findViewById(R.id.gallery1);
    gallery.setAdapter(new MainActivity.ImageAdapter(this));

    gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View v, int position,
                                long id) {
            imgSwitcher.setImageResource(imgs2[position]);
            drawableId.setText(imgs1[position]+"");
            Toast.makeText(MainActivity.this, imgSwitcher + "", Toast.LENGTH_LONG).show();
            imgSwitcher.setVisibility(View.VISIBLE);
        }
    });
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            postPicture();
        }

        public boolean postPicture() {
            String a = drawableId.getText().toString();
            stringCopy.setText(a);

            Bitmap b = BitmapFactory.decodeFile(a);
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/*");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
            try {
                f.createNewFile();
                FileOutputStream fo = new FileOutputStream(f);
                fo.write(bytes.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();
            }
            share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
            startActivity(Intent.createChooser(share, "Share image File"));

            Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_LONG).show();
            return true;
        }

       });

    }
</code>
And here is my Error:
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: R.drawable.pg1: open failed: ENOENT (No such file or directory)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.mt_br.floatingactionbutton, PID: 13647
                  java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
                      at com.example.mt_br.floatingactionbutton.MainActivity$2.postPicture(MainActivity.java:112)
                      at com.example.mt_br.floatingactionbutton.MainActivity$2.onClick(MainActivity.java:101)
Answer: I substituted this:
<code>     public boolean postPicture() {

            int Position = gallery.getSelectedItemPosition();
            Bitmap b = BitmapFactory.decodeResource(getResources(), imgs2[Position]);
</code>


Can I modify Geode's default logging behavior?

Question: Geode's out-of-the-box logging behavior does not include the "name" of the logger on each line (usually the name of the class invoking the Log4j Logger). I want to add this field to the default logger configuration, the one that logs to <member-name>/<member-name>.log.
Using the instructions from the documentation, I was able to successfully configure an additional logger using the configuration below -- it writes to a separate file from the default (logs/app.log in this case), but the default configuration also still logs as normal to the default file.
My expectation would be that providing my own log4j2.xml would override the default configuration, not supplement it. Is there anything I can do to override the behavior of that default logger?
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="FATAL" shutdownHook="disable" packages="org.apache.geode.internal.logging.log4j">
    <Properties>
        <Property name="geode-pattern">[%level{lowerCase=true} %date{yyyy/MM/dd HH:mm:ss.SSS z} <%thread> tid=%tid] - %c - %message%n%throwable%n</Property>
        <Property name="geode-default">true</Property>
    </Properties>
    <Appenders>
        <File name="MyFile" fileName="logs/app.log">
            <PatternLayout pattern="${geode-pattern}"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="MyFile"/>
        </Root>
    </Loggers>
</Configuration>

Answer: I don't see anything wrong with your configuration, actually I just tried it locally and the members only log to the configured file instead of the default:
$> gfsh start locator --name=locator1 --J=-Dlog4j.configurationFile=$CURRENT_DIRECTORY/log4j-custom.xml
$> gfsh -e "connect" -e "start server --name=server1 --J=-Dlog4j.configurationFile=$CURRENT_DIRECTORY/log4j-custom.xml"

$> gfsh -e "connect" -e "shutdown --include-locators=true"

$> tree -L 3
.
├── gfsh-0_0.log
├── locator1
│   ├── ConfigDiskDir_locator1
│   │   ├── BACKUPcluster_config.if
│   │   ├── BACKUPcluster_config_1.crf
│   │   ├── BACKUPcluster_config_1.drf
│   │   └── DRLK_IFcluster_config.lk
│   ├── GemFire_user
│   │   └── services
│   ├── locator10334view.dat
│   ├── locator10334views.log
│   ├── logs
│   │   └── app.log
│   └── vf.gf.locator.pid
├── log4j-custom.xml
└── server1
    ├── logs
    │   └── app.log
    └── vf.gf.server.pid

I've tried with the latest release, GemFire 9.9.1, maybe you're using an older version?, can you try with the latest one?.
Comment: Yes that's exactly my issue, thanks Juan. My organization has been stuck on Geode 1.6.0 (Gemfire 9.5) for a few years now . Everything works perfectly when I run my case in 1.11.0... I think it's time to push for an upgrade. Thanks for your time, your answers are always great!


Multiplication and sum of Riemann integrable functions

Question: Consider, that $g(x)$ and $f(x)$ two Riemann integrable functions. There is $s(x) = g(x)*f(x)$. Will $s(x)$ be also Riemann integrable? The same question about sum $t(x) = g(x)+f(x)$. It seems to me, that neither $s(x)$ nor $t(x)$ are Riemann integrable, but is there some information about this?
Comment: You're asking a question that is answered in any Riemann integral book or online course. Also, your intuition is not correct.
Answer: The sum of two Riemann integrable functions is Riemann integrable if you consider the definition of Riemann integrable. Try to prove that $L(g + f, P) = L(g, P) + L(f, P)$ and $U(g + f, P) = U(g, P) + U(f, P)$ for any partition $P$.
$s(x)$ is in fact Riemann integrable as well. Proving it is a little more tricky. It can be seen easily by using Lebesgue Criterion (Riemann integrable functions are those that are continuous almost everywhere).


MySQL counting question

Question: How do I find out which user entered the most articles and then count how many articles that user entered using PHP & MySQL.
Here is my MySQL tables.
CREATE TABLE users_articles (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
title TEXT NOT NULL,
acontent LONGTEXT NOT NULL,
PRIMARY KEY (id)
);

CREATE TABLE users (
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(255) DEFAULT NULL,
pass CHAR(40) NOT NULL,
PRIMARY KEY (user_id)
);

Answer: select count(*) as coun, user_id  from users_articles group by user_id order by coun desc LIMIT 1
Comment: "take the top row" == "LIMIT 1"
Answer: SELECT user_id, COUNT(id) AS articles
FROM users_articles
GROUP BY user_id
ORDER BY articles DESC
LIMIT 1;

MySQL counting question


UIImageView Resize and Rotate issue using Erica Sadun example - prepopulate location

Question: I am using the example by Erica Sadun for how to resize and rotate a UIImageView: https://github.com/erica/iphone-3.0-cookbook-/tree/master/C08-Gestures/14-Resize%20And%20Rotate
It is a wonderful example and exactly what I am wanting, but it falls short in one area. I cannot figure out how to pre-populate the transform property of the UIImageView so that I can save the state of the image and load it back into a view later, with the same position, scale and rotation.
Currently every time I add the UIImageView subclass it starts in the top left corner of the screen, but for the life of me, I cannot figure out how to pre-populate the transform property so it doesn't so that.
When the image is created, we do:
originalSize = self.bounds.size;
originalTransform = CGAffineTransformIdentity;
touchBeginPoints = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);// could this be the issue?

The subclass contains a lot of code, so I am not sure it should be reposted in its entirety.
Anyone used this before and could help?
Answer: CGAffineTransformIdentity is a blank transform and won't do anything.
You need to set its transform to the transform you created.
Comment: Ha, you are right. I know it seems obvious, but I think I was digging a little too deep to find the problem. This fixed it, thank you!
Comment: No problem sometimes it takes a extra pair of eyes :)


How to avoid Image size shrink when aligning

Question: New to this framework i know i'm not good at aligning part of UI yet.
My aligning problem is my image get shrink the more padding it has so if possible can you go easy and point out my mistake here? i am practicing align my item to top left corner.
<code>    struct MasterLabMerge: View {
    var body: some View {

    ZStack {

        Color.gray.ignoresSafeArea()
        Image(systemName: "note")
            .frame(width: 300, height: 300)
            .padding(.leading, -300)
            .padding(.top, -500)
      }
    }

}
</code>
Comment: Using hardcoded values is generally considered bad practice with SwiftUI, try viewing this view on a small device such as an iPhone SE or an iPod touch. Use percentages with GeometryReader instead
Comment: thank and bless you lorem and asperi
Comment: my next course is geometryreader
Answer: You need to add <code>.resizable()</code> to enable an image to grow in size.
Also, you can align your item to the top left in better ways.
Option 1 (I personally think this is the best):
<code> ZStack {
   Color.gray.ignoresSafeArea()
   VStack {
     HStack {
         Image(systemName: "note")
             .resizable()
             .frame(width: 100, height: 100)
             .padding(.leading)
         Spacer()
     }
     Spacer()
   }
 }
</code>
Option 2:
<code> ZStack {
    Color.gray.ignoresSafeArea()
    }
    .toolbar {
        ToolbarItem(placement: .navigationBarLeading) {
            Image(systemName: "note")
                .resizable()
                .frame(width: 100, height: 100)
                .padding(.top)
        }
    }
</code>


Finding the limit of $\frac{\sqrt{1+x^2}}{x^2}$

Question: I am kind of confused when it comes to finding this limit:
$\displaystyle\lim_{x\rightarrow\infty}\frac{\sqrt{1+x^2}}{x^2}$
I did
$\dfrac{\dfrac{1}{2}\dfrac{1}{\sqrt{\arctan(x)}}}{2x}$
then I am kind of stuck I know I can multiply the complex fraction and get
$\dfrac{1}{4x \arctan(x)}$
but it does not make sense.
Comment: Note that the derivative of the numerator is $$
\left( {\sqrt {1 + x^2 } } \right)^\prime   = \frac{x}{{\sqrt {1 + x^2 } }}$$ and not $$\frac{1}{2}\frac{1}{{\sqrt {\arctan x} }}$$.
Answer: Alternatively, note that $$\sqrt{1+x^2}=\sqrt{x^2\left(1+\frac1{x^2}\right)}=\sqrt{x^2}\cdot\sqrt{1+\frac1{x^2}}=|x|\cdot\sqrt{1+\frac1{x^2}},$$ so that $$\frac{\sqrt{1+x^2}}{x^2}=\frac{x\cdot\sqrt{1+\frac1{x^2}}}{x^2}=\frac{\sqrt{1+\frac1{x^2}}}x$$ for $x>0$.
Added: Yet another, simpler way, pointed out by egreg in the comments, is to note that $x^2=\sqrt{x^4},$ so that $$\frac{\sqrt{1+x^2}}{x^2}=\sqrt{\frac{1+x^2}{x^4}}=\sqrt{\frac1{x^4}+\frac1{x^2}}$$ for $x\ne 0$.
Comment: Wouldn't writing the function as $\sqrt{\dfrac{1}{x^4}+\dfrac{1}{x^2}}$ be simpler?
Comment: Hard-working considering my lazy estimates :D +1 for that
Comment: I see so the limit is zero because the bottom part of the fraction increases much faster than the top... when approach infinity
Comment: @Fernando: Basically, yes. In fact, though, the top tends toward $1$ as $x\to\infty.$
Comment: @AlexR: Nothing wrong with using the Squeeze Theorem. +1 to you, too.
Comment: @egreg: It certainly would. Good point!
Answer: Let $x>1$ so $2x^2 > 1 + x^2$
$$\frac{\sqrt{1+x^2}}{x^2} < \frac{\sqrt{2x^2}}{x^2} = \sqrt 2 \frac{|x|}{|x|^2} = \frac{\sqrt 2}{|x|}$$
From here the limit should be clear, since $$\frac{\sqrt{1+x^2}}{x^2} \geq 0 \qquad \forall\ x\in \mathbb R$$
Answer: For x is large $\Longrightarrow$ $\sqrt{1+x^2} \sim \sqrt{x^2}  =|x|$.
Hence, $\frac{\sqrt{1+x^2}}{x^2} \sim \frac{|x|}{x^2}=\frac{|x|}{|x|^2}=\frac{1}{|x|}$.
Therefore:
$$\lim_{x \to \infty} \frac{\sqrt{1+x^2}}{x^2} = \lim_{x\to\infty}\frac{1}{|x|}=0$$
Comment: Was going to write the same. Intuitive but correct ;-)
Answer: For $x>0$ we have: $\lim_{x\to\infty}\frac{\sqrt{1+x^2}}{x^2}=\lim_{x\to\infty}\frac{\sqrt{x^2\left(1+\frac{1}{x^2}\right)}}{x^2}=\lim_{x\to\infty}\frac{\sqrt{x^2}\cdot\sqrt{1+\frac{1}{x^2}}}{x^2}=\lim_{x\to\infty}\frac{x}{x^2}=\lim_{x\to\infty}\frac{1}{x}=0$
Answer: x=tant then the limit becomes sect*cot²t where t now approaches pi/2 from the left.
Simplifying gives a cost in the num and a sin²t in the denom. Plugging in the t gives 0
Comment: And why would you want to do that? Seems a little overkill.
Comment: Well, the methods above aren't particularly short either. It's just a different way to calculate a limit without using the traditional L'Hospital's rule. I just wanted to show that trig sometimes can be very usefull in evaluating limits, not just integrals
Answer: HINT:$$\frac{\sqrt{1+x^2}}{x^2}=\frac{\sqrt{1+x^2}:x}{x^2:x}=\frac{\sqrt{1/x^2+1}}{x}$$
Answer: Here is another approach (especially for you too Alex). Draw  right triangle with 1 as the opposite of angle t and x^2 as the adjacent. Now the hypotenuse can be found with Pythaogras and is ofcourse the radical term in the limit. As x goes to infinity, sint goes to zero, and as a result, t goes to zero. Now you got limits, geometry and trig all in one!


Como configurar o componente JUnit do Demoiselle 2.4.2 para injetar dependências EJB

Question: Tenho uma aplicação Demoiselle 2.4.2/JSF/Hibernate que apresenta vários casos de teste em pleno funcionamento. Os BCs operados por estes casos de teste sofrem diversas injeções de dependência sem problema algum. Agora precisei da injeção de um cliente EJB, como mostrado no código abaixo:
@BusinessController
public class MeuBC implements Serializable {
    private static final long serialVersionUID = 1L;

    @Inject
    private SecurityServices securityServices;
    @Inject
    private TipoVinculoBC tipoVinculoBC;

    @EJB(lookup=Constantes.EXTERNAL_SERVICE_JNDI)
    private ExternalService EXTERNALService; // <=== Preciso desta injeção!!!

    // Restante da classe
}

No exemplo, temos TipoVinculoBC sendo injetado sem problema. No entanto, durante os testes apenas (funciona na execução da aplicação) ExternalService não é injetado, permanecendo com o valor null durante a execução, resultando em erro.
Ressalto que não se trata de teste de integração, ExternalService não está em teste, é apenas um serviço do qual o código de MeuBC depende (como qualquer outra API), logo é um teste unitário de MeuBC.
O que está faltando para que o DemoiselleRunner ou outro participante possa viabilizar a injeção do cliente de ExternalService?
Answer: Alex, o CDI, que é quem faz a injeção de depedências @Inject, inclusive no teste unitário, não dá suporte a anotações específicas do EJB.
A sugestão é você criar um Producer que obtém seu objeto do contexto do EJB para poder utilizar @Inject nas classes que precisam dessa dependência.
Note que isto não é uma limitação do DemoiselleRunner, mas do CDI em si.


If $f \colon \mathbb{R}^m \to \mathbb{R}^n$ is continuous and $\mathcal{H}^d(f(E))\leq L^d \mathcal{H}^d(E)$, is $f$ Lipschitz?

Question: Let $f \colon \mathbb{R}^m \to \mathbb{R}^n$ be continuous and such that for every $E\subset \mathbb{R}^m$ we have
$$
\mathcal{H}^d(f(E))\leq L^d \mathcal{H}^d(E),
$$
where $\mathcal{H}^d$ denotes the $d$-dimensional Hausdorff measure, with $d=\min\{m,n\}$.

Is $f$ $L$-Lipschitz?

I have an answer to the question unless $n=1$ and $m>1$. See below for details.

Case 1: $m=1$
For $f \colon \mathbb{R} \to \mathbb{R}^n$, we first note that $\mathcal{H}^1(E) \geq \operatorname{diam}(E)$, so we have
$$
|f(x)-f(y)| \leq \operatorname{diam}(f([x,y])) \leq \mathcal{H}^1(f([x,y])) \leq L\mathcal{H}^1([x,y]) = L |x-y|.
$$
Hence the answer in this case is positive.
Case 2: $m,n>1$
We can define $f \colon \mathbb {R}^m \to \mathbb{R}^n$ by $f(x_1,\dots,x_n)=(x_1,x_1^2, 0,\dots,0)$. Then $\mathcal{H}^d(f(E))=0$ (recall $d=\min\{m,n\}$) for every $E \subset \mathbb{R}^m$, so the inequality is trivially satisfied. However, the function is not Lipschitz (because $x^2$ is not).
Hence the answer in this case is negative.
Case 3: $m>1$, $n=1$
For this case, I have no proof nor counterexample.
Answer: Since $f$ is assumed globally defined and continuous, the remaining case $n = 1$ can be handled very similarly to the case $m = 1$:
For $x,y \in \mathbb{R}^m$, let $E_{x,y} := \{ (1-t)\cdot x + t\cdot y : t \in [0,1]\}$ denote the straight line segment between $x$ and $y$. Then $\mathcal{H}^1(E_{x,y}) = \lVert x-y\rVert$, and $f(E_{x,y})$ is a connected subset of $\mathbb{R}$ containing $f(x)$ and $f(y)$. Then
$$\lvert f(x) - f(y)\rvert \leqslant \operatorname{diam} \bigl(f(E_{x,y})\bigr) = \mathcal{H}^1\bigl(f(E_{x,y})\bigr) \leqslant L\cdot \mathcal{H}^1(E_{x,y}) =L\cdot \lVert x-y\rVert,$$
showing that $f$ is Lipschitz-continuous with Lipschitz constant $L$. Here the equality
$$\operatorname{diam} \bigl(f(E_{x,y})\bigr) = \mathcal{H}^1\bigl(f(E_{x,y})\bigr)$$
holds since $f(E_{x,y})$ is a connected subset of $\mathbb{R}$, i.e. an interval.
Note: in your case 1, the inequality $\mathcal{H}^1(E) \geqslant \operatorname{diam}(E)$ does not hold for arbitrary subsets of $\mathbb{R}^k$, it is guaranteed only for connected subsets. However, you use it only for path-connected sets, so the argument is correct.
Comment: Thanks, that was much easier than I expected, I don't know how I didn't see it. Also, thanks for your note.


JasperReport - JavaBean Data Sources from official documentation

Question: JavaBean from official documentation:
http://jasperforge.org/uploads/publish/jasperreportswebsite/trunk/sample.reference/datasource/index.html#javabeandatasources
"For instance, to retrieve the value of a report field named address, the program will try to call through reflection a method called getAddress() on the current JavaBean object. "
From my experience, I'm almost certain that it is not on the current object, but on all JavaBean objects (of a given type) that are passed as a collection or a list.
When I try to print an atribute of a specific instance of a bean, it prints all the values of all instances of that bean. Anyone knows how to pass this?
Answer: How are you printing your attribute? If it is by putting a textField into a detail band, then that behaviour is correct. This is because the detail band is repeated once for every record in the dataset. If you are using a bean datasource this means that accessing the field address from the detail band will call getAddress() for every bean in the collection.
If you don't want an element to be repeated, move it to a different band. Or if you want to print the value only for a specific bean, add a printWhenExpression to your element.
Comment: First of all, thank you for your reply. I actually want to pass the values for a specific bean and curiously I was thinking about printWhenExpression but it didn't sound me as a "clear" solution. Do I have to consider another bean attribute that relates a child bean with is parent bean? or there is a cleaner way to use printWhenExpression? A more complete explanation of my problem goes here: http://jasperforge.org/plugins/espforum/view.php?group_id=102&forumid=103&topicid=92360#92360. Thanks again.


Pairing function that is linear in one of its arguments

Question: I'm looking for a pairing function ($f: \mathbb{N}^2 \rightarrow \mathbb{N})$ which is linear in one of its arguments. That is to say it takes $(x,y)$ to some function $ax+b$ where $a$ and $b$ are determined by $y$. Any ideas?
Comment: Number theory tag?
Comment: You need to explain your requirements on your "pairing function"? Are $x$ and $y$ natural numbers, integers or what? Is the function just required to be 1-1 or is it required to be 1-1 and onto?
Answer: The mapping
$$\pi : \mathbb{N}_{\geq 0}^2 \longrightarrow \mathbb{N}_{\geq 0} ~~~;~~~ (x,y) \longmapsto 2^{y+1}x + (2^y -1)$$
will do the job.
Written differently, we have
$$
\pi(x,y) = 2^y (2x + 1) -1
$$
which makes it easier to see that $\pi$ has an inverse: For a given number $n \in \mathbb{N}_{\geq 0}$ you count the number of times you can divide $(n+1)$ by two, which gives you $y$. After these divisions you are left with an odd number, which can be written as $2m+1$, telling you that $x = m$. Formally:
$$
y= \max\Big\{~ k \in \mathbb{N}_{\geq 0} ~~\Big\vert~~ \frac{n+1}{2^k} \in \mathbb{N} ~\Big\} ~~~,~~~
x = \frac{1}{2} \Big(\frac{n+1}{2^y} - 1 \Big)
$$