Dynamic Background based on field url

Question: Lets say I have a music site that a user can add a youtube URL in a box and then the video will play.
Is it possible to have the background of that page change based on search parameters in the field.
So if a user puts in a Daft Punk video, could I have my site query a website with fan art and load the fan art as the background of that page?
EDIT:
To elaborate more.
Popular media players (PLEX and XBMC) will often "srape" websites for information about tvshows, movies, and artists. They pull the content (biography, rating, fanart, etc.) from the different sites (imdb etc.) and display them in the media player.
I want to extend this functionality to my site.
Now this is where it could get complicated.
My website has an emfield that allows users to paste the URL's of different videos from youtube, vimeo and others that will display one video then create a playlist of the pending videos in the list.
Fortunately the emfield can also pull the artist and song title of the video from youtube.
I want to use this information to then query a search on a website such as fanart.tv and pull an image or even corresponding artist information and display said information on my site as the corresponding song is playing.
In short:
1. URL is entered
2. Emfield displays video, artist, and song title
3. Somehow a search is performed on a website to locate that same artist and display fanart and other artist biography information
4. Listen and learn.
Comment: Can you please elaborate your question? If possible give some examples(field URL and Search parameters).
Comment: Updated my original post with more information.
Answer: You can do this but its probably more of a jquery problem than a Drupal one since you're changing the background of the page based on an asynchronous web call. Rough idea of how this would look:

attach an onsubmit handler to your form that would load the video from the url
add your logic to find the artist from this url (?) and then find the appropriate image
then modify the body background using this image, ex:
$('body').css('background-image', 'url(' + imageUrl + ')');

Dynamic Background based on field url


Countable sum of closed boundary sets

Question: I have to prove that for complete metric space and $f_n$ converge pointwisely to $f$
 $f^{-1}(a,b)\setminus Int(f^{-1} (a,b))  $ is countable sum of closed, boundary sets.
Here is my solution:
$f^{-1}  ((a,b))={x:a<f(x)<b}={x: ∃ n\in N  a+1/n  ≤f(x)≤b-1/n} =
{x: ∃ n∈N,∃ m∈M ∀_{(k>m)}  a+1/n  ≤f_k (x)≤b-1/n}=  $
$⋃_{(n,m)}⋂_{(k≥m)} f_k^{-1} ([a+1/n,b-1/n]) $ It is a countable sum of closed boundary sets.
But I am not sure if I can do it this way, if yes/no can you tell me why ?
Comment: yes, my mistake
Comment: $f_n$ converges pointwise to $f$, instead
Comment: $f^{-1}(a,b)$ is a subset, not an element
Comment: You should have said that $f_n$ are continuous.
Answer: I think you have the right idea, but the solution may be incomplete. I suppose that "closed boundary set" means "closed bounded set". But there is no reason for the set $f_k^{-1} ([a+1/n,b-1/n])$ to be bounded.
For better readability, I would separate the proof into three steps:
Step 1: $f^{-1}(a,b)$ is a countable union of closed sets. This is what you already did: $$f^{-1}(a,b) = \bigcup_{m,n}\bigcap_{k\ge m}f_k^{-1} ([a+1/n,b-1/n])$$  Step 2: $f^{-1}(a,b)$ is a countable union of closed bounded sets. This follows by fixing a point $x$  in the domain of $f$ and taking intersections with closed balls $\overline{B}(x,r)$ over $r=1,2,3,\dots$
$$f^{-1}(a,b) = \bigcup_{m,n,r}\left(\overline B(x,r)\cap \bigcap_{k\ge m}f_k^{-1} ([a+1/n,b-1/n])\right)$$ Step 3: $f^{-1}(a,b)\setminus \operatorname{Int}f^{-1}(a,b) $ is a countable union of closed bounded sets. For this, take the intersection with the complement of $\operatorname{Int}f^{-1}(a,b) $:
$$\bigcup_{m,n,r}\left((\overline B(x,r)\setminus \operatorname{Int}f^{-1}(a,b))\cap \bigcap_{k\ge m}f_k^{-1} ([a+1/n,b-1/n])\right)$$

Countable sum of closed boundary sets


Probability of Opening a Combination Lock

Question: A combination padlock has three rotating disks each with numbers 1 through 9. You forgot your code but remember that the sum of the three numbers is 8. In an attempt to open the lock, you begin entering all codes whose sum is 8. What is the probability that you will open the lock on the fourth try?
I am getting 1/21 but would like to confirm this answer. Thank you!
Comment: That's right. Just out of curiosity, did you use stars and bars to determine the $21$?
Comment: Hi Bob. Yes, I used 7C2 to obtain 21 ways to have a code adding up to 8. Then, 20P3/21P3 * 1/18 = 1/21, assuming we eliminate used codes.
Answer: There are $6+5+4+3+2+1=21$ possible codes whose sum is $8$.
If the question is asking that you open it on exactly the fourth try, then you need three failures and one success.
$$\frac{20}{21} \cdot \frac{19}{20} \cdot \frac{18}{19} \cdot \frac{1}{18}=\frac{1}{21}.$$
Comment: Thanks! Is 6+5+4+3+2+1 number obtained as (1,1,6), (1,2,5), (1,3,4),... (1,6,1) then (2,1,5), (2,2,4)...(2,5,1) etc?
Comment: @user240383 Yes.  If the first disk is `1` there are 6 ways the remaining two sum to seven.  If the first disk is `2` there are 5 ways the remaining disks sum to six.  If the first disk is... and so forth.  It's a clear pattern.
Comment: @user240383 Yes, Graham Kemp explained my thought process. However, I think your stars and bars approach is much nicer.
Answer: We have: $x+y+z = 8, x,y,z \geq 1 \Rightarrow x'=x-1,y'=y-1,z'=z-1 \Rightarrow x'+1+y'+1+z'+1 = 8 \Rightarrow x'+y'+z' = 5, x',y',z' \geq 0$. There are $\binom{5+3-1}{3-1} = \binom{7}{2} = 21$ ways of turning the disks. And the probability of not getting it right is $\dfrac{20}{21}$ for each time. Thus to get the $4$ th right, we have the probability being: $\left(\dfrac{20}{21}\right)^3\cdot \dfrac{1}{21}$
Comment: Why would you not exclude a combination, that you have already tried?
Comment: I assume you don't remember (save) what you tried each time.
Comment: @NotALoner `you begin entering all codes whose sum is 8` That sounds like OP is trying to say you remember previous tries.
Comment: Theoretically, I don't think one is allowed to exclude what one already unsuccessfully tried. But I could be wrong...
Comment: Assuming you take steps to avoid trying the same pattern more than once (such as simply trying them in sequence `116`, `125`, `134`,...`611`), then the probability that you open the lock **on** the fourth try is indeed $1/21$.


SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

Question: This is a PERN app. I don't remember ever getting this error, and I haven't found any records when doing a Google search.
I don't see anything wrong in the index.html file:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

    <title>React App</title>

    You need to enable JavaScript to run this app.

Where could it come from? I get it as soon as I start the app.
Comment: HTML is indeed invalid JSON. Somewhere you have code that expects JSON and gets HTML back. Check where that is, what the result is which will also probably give you a clue what's wrong. E.g., you might be getting an HTML page with an error.
Comment: It looks like you are trying to parse an HTML document as if it is JSON. That's not going to work, because HTML is not JSON... Without further information about your app, it's impossible to tell why it's trying to do this.
Comment: Did you figure this out - I'm struggling to solve the same problem
Answer: I'm just a beginner, but it happens when you are passing the wrong URL to the fetch function. Suppose that your db.json file is running on port 8000 and you are passing port 3000. That's why.
useFetch("http://localhost:3000/blogs/" + id);

Instead, try the following. It might help. :)
useFetch("http://localhost:8000/blogs/" + id);

Comment: You're right bro. It's fetch url problem
Comment: How can a JSON file run on a (TCP) port?
Comment: I second this. It happened to me as well when my client and server were running on 2 different ports and the client making the API call at it's own port (instead of server port). Solution was to set up COORS on the server and then add correct port while calling the API from the client (either by specifying the complete URL like in the answer above) or use proxying in client side.
Answer: I had this same error when I installed: npm gh-pages.
My solution was to delete the Homepage link in package.json file and it worked.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: I had the same problem.
If you are using a Node.js server, install this:
npm install body-parser
And add these lines in your server-side code:
const bodyParser = require("body-parser"); router.use(bodyParser.json());
Comment: Im sorry for answering on. but ur answer isnt clear because i have installed the `body-parser` package and added the following lines but the router isnt defined
Comment: if you are using app ( `const app = express(); `) then you can simply use `app.use(bodyParser.json()); ` in your code, router is an extra package i have installed for easier routing between urls.
Answer: I was trying to fetch data from the backend into my React application, without mentioning the proper path of the URL in the loader function of the react-router library. Hence this issue occurred and once I defined the correct path, it worked just fine.
const response = await fetch("http://localhost:8080/events");

I forgot to mention "events" in the URL.
Answer: Try this header and accept while fetching the URL and the problem should be resolved:
const response = await fetch(url, {
  headers:{
    accept: 'application/json',
    'User-agent': 'learning app',
  }
});

Comment: @Aaron Thanks I forgot to add the headers, and solved it!
Answer: I'm new at this, but I found if I added a proxy to my package.json file (client side, not server side) it worked!
It looks like this in package.json (placed above my dependencies):
"proxy": "http://localhost:3001",

I believe it's because the client side can't read it, and the proxy tells it to pass it to the server side which can read it.
Comment: Re *"the proxy tells it to pass it to the server side"*: Is there a source to back that up?
Answer: Check if you are calling your API prefixed with the protocol, like 'https://apiurl...', not like 'api.something'.
Answer: I faced the same issue and my JSON path was incorrect. Initially, it was fetch('./movies.json') which was the incorrect path.
I fixed it, and now it is working fine:
  useEffect(() => {
      fetch('../movies.json')
      .then(res => res.json())
      .then(data => setMovies(data.posts))

    }, [])

Answer: I was also faced with the same issue with React.

While fetching the JSON, always use a try-catch block to identity the error
Check fetching from locally or server side. If it is a local JSON file, then make sure there is an absolute path and relative path (example: public/data/mock.json)
Check the JSON file is valid or not (should not have any error)
This is the error for me: It's always a good practice to double check the structure of your JSON data and ensure that you are using the correct keys in your code.
Answer: I encountered a similar issue with the React application. I was trying to access data from a locally hosted JSON file. After spending almost an hour I figured out that it was just a path issue. I tried using a relative path and it worked for me! I hope it helps.
Answer: From your code snippet, it looks like you're working in a React app.
The npm run build command is to create the production build, so it won't give you the level of error detail you want.
Run npm start first to run your development server, then you'll see much more detail in your error messages in your browser console, and you can debug from there.
Answer: I got the same error while deploying a React application on Vercel. It turns out I forgot to add environment variables to the project settings in Vercel.
Answer: I used GitHub's workspace with two projects and one project called the other project's handle, but I forgot to make the other project's port (3000) public.
Make it public, and it's OK.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: The error message specifically mentions "<!DOCTYPE", which is the start of a document type declaration in HTML. It suggests that you are trying to parse HTML content as JSON, which would cause the error since HTML and JSON have different syntax and structure.
I got the same error for the following code in React:
const response = await fetch("https://swapi.dev/api/film/");

There was a spelling mistake in the above URL. The correct URL is as follows:
const response = await fetch("https://swapi.dev/api/films/");

There was a s missing in the URL at the last. Please try to check if the URL is providing any data, in the JSON format wherever you trying to fetch it.
A simple solution would be to try and run the URL in the browser and see if it provides JSON data. If it doesn't provide any JSON data then that is not a correct URL for fetching JSON data.
Try some other URL.
Answer: When you get this error, make sure your Node.js server is running and fetching data from http://localhost:8000/dbname.


How to formally use Taylor expansions for $n$th derivatives and generating functions?

Question: When deriving Catalan numbers, the generating function takes on this form:
$$C(x) = \frac{1}{2} (1 - \sqrt{1-4x}) = \frac{1}{2} (1 - f(x))$$
where $f(x) = \sqrt{1-4x}$
How does one formally show what it evaluates to? I can do it somewhat "informally" like so:
$$f(x) = \sqrt{1-4x} = \sum_{n=0}^{\infty} \frac{f^{(n)}(0)}{n!} x^n$$
$$f(x) = \frac{f^{(0)}(0)}{0!} x^0 + \frac{f^{(1)}(0)}{1!} x^1 + \frac{f^{(2)}(0)}{2!} x^2 + \frac{f^{(3)}(0)}{3!} x^3 + \frac{f^{(4)}(0)}{4!} x^4 + ...$$
Now at this point I can literally start computing the successive derivatives of $f(x)$ and then plug in $0$ for each $x$ and look for patterns and "eyeball" a closed-form for it.
But is there a way at this point to formally show what the $n$th derivative is? Or is this more of an art than a science that changes depending on the function?
I could eyeball the $n$th derivative formula as well:
$f^{0}(x) = (1 - 4x)^{\frac{1}{2}}$
$f^{1}(x) = (\frac{1}{2})(-4)(1 - 4x)^{-\frac{1}{2}}$
$f^{2}(x) = (-\frac{1}{2})(\frac{1}{2})(-4)(-4)(1 - 4x)^{-\frac{3}{2}}$
$f^{3}(x) = (-\frac{3}{2})(-\frac{1}{2})(\frac{1}{2})(-4)(-4)(-4)(1 - 4x)^{-\frac{5}{2}}$
$f^{4}(x) = (-\frac{5}{2})(-\frac{3}{2})(-\frac{1}{2})(\frac{1}{2})(-4)(-4)(-4)(-4)(1 - 4x)^{-\frac{7}{2}}$
At this point I can eyeball the pattern and solve it manually. But again, what if I couldn't do that? Is there a more direct and methodical way to this?
Answer: May be, you could use the generalized binomial expansion $$(1+x)^a=\sum_{n=0}^\infty \binom{a}{n} x^n$$ which makes $$f(x)=\sqrt{1-4x}=\sum_{n=0}^\infty (-1)^n\binom{\frac 12}{n} (4x)^n=1+\sum_{n=1}^\infty (-1)^n\binom{\frac 12}{n} (4x)^n$$ and then $$C(x) = \frac{1}{2} (1 - \sqrt{1-4x})=\frac{1}{2}\sum_{n=1}^\infty (-1)^{n+1}\binom{\frac 12}{n} (4x)^n$$
Comment: How is the generalized binomial expansion going up to infinity? I thought that expansion only makes sense from $n=0$ up to $a$ in this case. Or is it technically $0$ for $n>a$ but it doesn't hurt to list the infinity for the sake of making it more consistent with how generating functions are handled?
Comment: Also how does $\binom{\frac{1}{2}}{n}$ work? A fraction in a binomial coefficient? Fractional factorials?
Comment: Take care : here, we consider that $a$ is not an integer. Have a look at https://en.wikipedia.org/wiki/Taylor_series (search for *Binomial series*).
Comment: I see the equation but I still don't understand how that works. Why is it going up to infinity when the typical formula stops at the exponent on the lefthand side, integer or not? Why doesn't it stop at the floor (or ceiling) of $a$, etc?
Comment: @MarkusScheuer I'm trying but I am not confident that I am doing this correctly or seeing what I am supposed to be seeing.
Comment: But the earlier equation says $(1+x)^a=\sum_{n=0}^\infty \binom{a}{n} x^n$, which means $(1+x)^{-1}=\sum_{n=0}^\infty \binom{-1}{n} x^n$. Just to clarify are you using $\binom{-1}{n} = (-1)^n \binom{-1+n-1}{n} = (-1)^n\binom{n}{n} = (-1)^n$?
Comment: Even so I don't know what I am supposed to be looking at


How can I use an n-dimension all-ones square matrix J to represent its power.

Question: J is a matrix described above, and I want to obtain $${ J }^{ 2 }, { J }^{ 3 },...,{ J }^{ n }$$I got some insights from the answer: What are the eigenvalues of matrix that have all elements equal 1? However, I still cannot figure out how to do it, although the characteristic equation is $${ \lambda  }^{ n }=n{ \lambda  }^{ n-1 }$$ and with the help of Cayley-Hamilton Theorem, I can get $${ J }^{ n }=nJ^{ n-1 }$$ But confused I cannot iterate J as: $${ J }^{ n }=n{ J }^{ n-1 }=n(n-1){ J }^{ n-2 }=...=n!{ J }^{  }$$Anyone can explain this?
Comment: You're right up until the point $J^{n-1} = (n-1)J^{n-2}$. The equation you deduced from Cayley--Hamilton only holds for the power $n$ and you can not simply replace $n$ by $n-1$. In fact, $J^m = nJ^{m-1}$ for all $m > 1$.
Answer: $J^2 = n J,$ so $J^3 = n^2 J,$ in general $J^k = n^{k-1} J.$
Answer: If $\def\tr{\operatorname{tr}}A$ is any rank$~1$ matrix of size $n\times n$ (for instance your all-entries-$1$ matrix$~J$), then its characteristic polynomial is $X^{n-1}(X-\tr A)$, where the factor $X^{n-1}$ is deduced from the $n-1$-dimensional eigenspace for eigenvalue $0$, and the final factor is there to make the sum of the roots (with multiplicity) of the characteristic polynomial equal to the trace of $A$, as it should be. But since the factor $X^{n-1}$ came from an actual eigenspace (as opposed to a generalised eigenspace), one only gets a single factor $X$ in the minimal polynomial. So  if $n>1$ the minimal polynomial of any $n\times n$ matrix of rank$~1$ is $X(X-\tr A)$. (Check that even in case $\tr A=0$, the minimal polynomial is $X(X-\tr A)=X^2$ rather than $X$.)
In case of your matrix $J$, the trace is$~n$, so the minimal polynomial is $X(X-n)=X^2-nX$; you matrix satifies $J^2=nJ$. From this it follows easily that $J^{k+1}=n^kJ$ for all $k\in\mathbf N$.
Comment: The explanation is detailed and concise. I think I should go to review minimal polynomial and some other concepts. Thank you.


How do you play this Chinese tab?

Question: Here's the tab: https://stevenlaw.files.wordpress.com/2018/01/e68891e5a49ae5969ce6ada1e4bda0e4bda0e69c83e79fa5e98193.pdf
And here the first two staves of that tab:

I specifically need help with few legends that I don't understand. Such as:

How do you play the note with a slash? The first one which is open 1st string then 1st fret 1st string whereas the 0 appears to be smaller? I tried doing a hammer on and it works perfectly but what is the right way to play that?
How do you play 3‿3 and 0⁀0, I believe that symbols signifies pull offs and hammer on on most tabs but how will I do that in this case where the notes are the same?

Sorry for the dumb questions and if I can't specify terms correctly. I'm still just starting out. Thank you
Answer: The smaller note with a slash is called a Grace note. It is to be played quickly to lead into the next longer note.
The 3‿3 and 0⁀0 are ties, which mean you play the note once but let it ring for the combined duration.
In tablature, Hammer-ons are usually indicated with H and Pull-offs by P, although the link between the notes does look the same.
Answer: These are from proper musical notation and aren't specific to Chinese tab. Looking at the musical notes themselves always helps me work out what I'm meant to be doing with my playing - even if my sight-reading of normal sheet music isn't as up-to-scratch as my tab reading!
A tie between two different notes is a way of denoting legato, which can be played on guitar with hammer-ons and pull-offs. Legato is basically just trying to play a string of musical notes as fluidly as possible, as if there is no defined break between notes (as opposed to picking every note individually). A tie between two of the same note, however, denotes that the note should be held on for the duration of the notes. For example, two of the same quarter note with a tie between denotes that you should hold on the note for the same duration as a half-note.
The small note with a slash through it is telling you to play that very quickly before the main note. It is a type of ornamentation or embellishment called a grace note. Specifically, a small note with a slash through it shouldn't take up any space of the main note, whereas a small note without a slash through it should take up a small part of the duration of the main note. In other words - with a slash through the small note, the main note should fall on the beat and the slash note should be played early, but without the slash through the small note, the small note should be played on the beat. I believe that is a point of contention though...
Comment: I'm not sure it's helpful to say a tie is a type of legato? I mean, it does literally mean "tied together", but legato doesn't forbid re-articulation. You should never re-articulate tied notes. Legato is a type of expressive technique, whilst ties are a fundamental part of notation.
Comment: That's fair, I misread what you wrote. The correct term in that case is slur, yes.
Comment: When saying "A tie between two different notes", I was referring to the ⁀/‿ notation, but I suppose that is true... I guess they're not technically *ties* in that scenario. Would it would be referred to as a slur when talking about legato? I'm a little rusty with my technical definitions as I've not studied music theory formally in a number of years!

How do you play this Chinese tab?


Example of automorphism $\sigma$ and $\alpha \in O_K$ such that $\alpha$ and $\sigma(\alpha)$ are not associates?

Question: I am trying to solve an exercise from last year's exam:
Let $p$ be a prime number, let $ζ$ be a primitive $p$-th root of unity, and let $K = \mathbb{Q}(ζ)$.
I am looking for an example for a prime $p$ and $\alpha \in O_K$ and a Galois automorphism $\sigma$ such that $\alpha$ and $\sigma(\alpha)$ are not associates.
I am fairly new to number theory so what I have so far is quite basic: I think $O_K = \mathbb{Z}[\zeta]$ and am guessing the $\alpha$ we are interested in will be $\alpha = \zeta$? But don't know where to go from here. I think in general the Galois automorphism for the extension of rationals by a $p$-th root of unity fixes $1$ and sends each $\zeta \rightarrow \zeta^k$ for $1≤k≤p-1$?
Comment: What do you mean by "$\alpha$ and $\sigma(\alpha)$ are not associates"? Your thought that $O_K = \mathbb Z[\zeta]$ and the description of the Galois automorphisms are correct.
Comment: @Marktmeister the definition of associates I have is: elements $f$ and $g$ are associate if $f=g\mu$ for some invertible element $\mu \in O^{\times}_{K}$
Comment: Ah, of course. Thank you!
Answer: Suppose that $p = 3$. Then $[K:\mathbb Q] = 2$ and so there is exactly one pair of complex conjugate embeddings of $K$ into $\mathbb C$. By Dirichlet's Unit Theorem, the rank of $O_K^\times = \mathbb Z[\zeta]^\times$ is $0$. Hence $O_K^\times$ is torsion and coincides with the group of roots of unity in $K$. It follows that
$$O_K^\times = \{\pm 1,\; \pm \zeta,\; \pm\zeta^2 \}.$$
Now, let $\alpha := -1+ 2\zeta$ and $\sigma$ be such that $\sigma(\zeta) = \zeta^2$. Then $\sigma(\alpha) = -1+2\zeta^2 = -3 - 2\zeta$, where we used  $1 + \zeta + \zeta^2 = 0$. Now we calculate that
$$\sigma(\alpha) \neq \pm \alpha,$$
$$\zeta \cdot \sigma(\alpha) = -3\zeta-2\zeta^2 = 2-\zeta \neq \pm \alpha,$$
$$\zeta^2 \cdot \sigma(\alpha) = -3\zeta^2 - 2 = 1+3\zeta \neq \pm \alpha.$$
Hence our choice of $p$, $\sigma$ and $\alpha$ satisfies what we want.
Answer: You couldn't expect $\alpha$ to be $\zeta$.
As you pointed out, $\zeta$ will be sent to some $\zeta^{k}$ and they are both invertible in $\mathcal{O}_{K}$, thus associate !


Update dependency property when child property has been updated

Question: I have a class inheriting canvas with the following dependency property
public class StorageCanvas : Canvas
{
 public readonly static DependencyProperty StorageProperty = DependencyProperty.Register(
  "Storage",
  typeof(Polygon),
  typeof(StorageCanvas));

 public Polygon Storage
 {
  get { return (Polygon) GetValue(StorageProperty); }
  set { SetValue(StorageProperty, value); }
 }
}

Can I somehow make the dependency property "update" when the Storage polygon Points has been altered/updated, instead of requiring the polygon to be replaced with a new instance?
Comment: What do you mean by update? Redraw? Reevaluate? Relayout? Who is changing the Storage. It wouldn't be wise to just blindly update everytime a property changes. But you can trigger that for yourself with the Invalidate methods, like InvalidateVisual. Also you can change the meta data of properties to automaticaly call the Invalidate functions if they are changed, which would not work for your Storage, because it works by calling the setter.
Comment: I think, you can use dependency property `Callbacks` and `Validation`. See [msdn](http://msdn.microsoft.com/en-us/library/ms745795.aspx) for more information.
Comment: @dowhilefor I want to redraw the polygon on the Canvas whenever the polygons `Points` changes.
Answer: Well Polygon.Points is a PointCollection, so you could just subscribe to the Changed event of it and then call InvalidateVisual() as suggested by @dowhilefor
public class StorageCanvas : Canvas {
  public static readonly DependencyProperty StorageProperty = DependencyProperty.Register(
    "Storage",
    typeof(Polygon),
    typeof(StorageCanvas),
    new FrameworkPropertyMetadata(null, PropertyChangedCallback));

  public Polygon Storage {
    get {
      return (Polygon)GetValue(StorageProperty);
    }
    set {
      SetValue(StorageProperty, value);
    }
  }

  private static void PropertyChangedCallback(
    DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args) {
    var currentStorageCanvas = dependencyObject as StorageCanvas;
    if (currentStorageCanvas == null)
      return;
    var oldPolygon = args.OldValue as Polygon;
    if (oldPolygon != null)
      oldPolygon.Points.Changed -= currentStorageCanvas.PointsOnChanged;
    var newPolygon = args.NewValue as Polygon;
    if (newPolygon == null)
      return;
    newPolygon.Points.Changed += currentStorageCanvas.PointsOnChanged;

    // Just adding the following to test if updates are fine.
    currentStorageCanvas.Children.Clear();
    currentStorageCanvas.Children.Add(newPolygon);
  }

  private void PointsOnChanged(object sender, EventArgs eventArgs) {
    InvalidateVisual();
  }
}

So now if any individual Point in Storage changed, without actually recreating the entire object, InvalidateVisual() will be fired.
The concept is just about subscribing to the Changed event of PointsCollection. Whether it's the right thing to do for you is a question you need to address yourself based on your requirements and logic.
Comment: `InvalidateVisual()` is very-heavy weight way to trigger re-draw. If the size of the control is not changing, use `AffectsRender` or during `OnRender()` add a `DrawingGroup` to the `DrawingContext`, then anytime you want you can `DrawingGroup.Open()` and change the visual.
Answer: Register the dependency property with Affects render meta data option.
http://msdn.microsoft.com/en-us/library/system.windows.frameworkpropertymetadata.affectsrender.aspx


Relationship between Factorial and Binomial coefficients

Question: Over at this link, there is a claim that $(2n)! = n!n! {{2n} \choose {n}}$ - see Tom Boardman's answer, the second one down.
I'm wondering why this is the case and if anyone can provide a proof. Is this a special case of a more general relation, and does anyone have any good references for manipulating binomial coefficients and factorials?
Answer: For integers $a\ge b\ge 0$, we have ${a\choose b}=\frac{a!}{b!(a-b)!}$ (see wiki).  Take the special case $a=2b$ and you get ${2b\choose b}=\frac{(2b)!}{b!b!}$, then cross-multiply.
Comment: That's perfect, I made a typo in my original question - glad you understood what I was after!


Is including the main effect of the covariate enough?

Question: Is simply including a covariate in a model (ANCOVA) enough for variance in the DV due to it to be factored away? Or do the higher order interactions of the covariate with the other factors of the model have to be modelled as well?
In some software (e.g. Statistica), you have to specifically ask what factorial effects you want to have tested, and it seems to make a huge difference in the results whether you just ask for the main effect of the covariate or also ask for its crossings with all other categorical IVs.
I suppose it's up to the researcher/situation if you would then decompose any of those computed interactions (it would presumably depend on whether you consider the covariate to be 'of interest' or not), but the question is, which specific interactions do you "ask for" in the first place? Is there a trade-off between how informative an effect would be if included in the model VS the cost it would then have on inference power?
Also, does the covariate (continuous) factor have the same 'status' among the other (categorical) factors, i.e. is it somehow less important to include covariate-related interactions than it is to include categorical-factor-related interactions? Or does the selection of the requested interactions simply depend on hypotheses rather than being a simple answer such as "all possible interactions should be requested"?
Thanks a lot for any help!
Answer: It's an assumption made in regression that there are no interactions between covariates and predictors, so you should test for them, and if they are statistically significant (or if they actually make a difference) you should interpret those interactions.
It's a bit of a tricky issue because, as you say, there's a tradeoff. If you have two covariates, you have an interaction of covariates as well. And you should include things like quadratic effects of covariates, and quadratic interactions, and so on. Heteroscedasticity can also be a sign that you have omitted covariate interactions (perhaps covariates that you didn't even measure). Once you have a lot of covariates, you're then at risk of overfitting by including things like interaction effects. If I'm worried about this, I like to use something like boosted regression.
Comment: Thanks! But assuming I have a simple ANCOVA with 2 factors A and B (let's say A is between-subjects and B is within) and one co-variate C, then, after adding the full factorial for A and B (i.e., main effect of A and of B, and A*B), and the main effect of C, would I then also add A*C, B*C and A*B*C? Or would that depend on whether that interaction is of interest?
Comment: You assume that those interactions do not have an effect when you interpret the effects. (I wouldn't call it a 'simple' ancova when you have a repeated measures factor.)
Comment: Sorry, still not clear. So I should assume that all interactions involving the covariate (A*C, B*C and A*B*C) won't be significant - but does that mean I add them to (request them of) the model and then ignore whether they're significant or not, or do I simply not define them in my ANCOVA?
Comment: Add them, see if they're significant, if they're not, take them out.


Use YUI 2's Rich Text Editor for Inline Editing

Question: I am using inline editing in YUI 2's DataTable. I would like to use the Rich Text Editor for this, but it is not among the built-in options. Does anyone know of code that does this or how one might go about integrating it?
Answer: The rich text editor just requires a textarea with an Id, so make your own custom implementation of a yui datatable column editor, and define the appropriate text area within it.


I am having trouble with the logic in my code in android studio

Question: This code is supposed to serve on purpose, to verify that an email address that has been added to the database of "profiles" has not been entered before. After the user enters the relevant data, and attempts to verify the data as a legitimate entry, the email address is checked against other entries in the database (because emails are usually the most unique part of a set of entries other than the nickname)and if the email is unique to the database, the entry is accepted and a new column should be created in the database(which it is). The problem is that the email is always accepted as unique.
This code shows how the entries are weeded out to make sure they fit the convention of sign up sheets
public void registerAccount(View view) {
    LoginEntries entries = new LoginEntries(
            newEmailAddressInput.getText().toString(),
            newPasswordInput.getText().toString(),
            newFirstNameInput.getText().toString(),
            newLastNameInput.getText().toString(),
            newNickname.getText().toString(),fullPhoneNumber);
    String isTempEmail = newEmailAddressInput.getText().toString();

    String isTempPass = newPasswordInput.getText().toString();
    String confirmPasswordHolder = confirmNewPasswordInput.getText().toString();

    if (TextUtils.isEmpty(isTempEmail) && TextUtils.isEmpty(isTempPass)) {
        Toast.makeText(this, "Enter Email and Password", Toast.LENGTH_LONG).show();
        newEmailAddressInput.setText("");
        newPasswordInput.setText("");
        confirmNewPasswordInput.setText("");
    } else if (TextUtils.isEmpty(isTempEmail) && !TextUtils.isEmpty(isTempPass)) {
        Toast.makeText(this, "Enter Email", Toast.LENGTH_LONG).show();
        newEmailAddressInput.setText("");
        newPasswordInput.setText("");
        confirmNewPasswordInput.setText("");
    } else if (!TextUtils.isEmpty(isTempEmail) && TextUtils.isEmpty(isTempPass)) {
        Toast.makeText(this, "Enter Password", Toast.LENGTH_LONG).show();
        newEmailAddressInput.setText("");
        newPasswordInput.setText("");
        confirmNewPasswordInput.setText("");
    } /*Temporary while app is offline, when app will be operational, different prompt will search web to verify email address*/
    else if (!isTempEmail.endsWith("@gmail.com") && !isTempEmail.endsWith("@yahoo.com") && !isTempEmail.endsWith("@aol.com") && !isTempEmail.endsWith("@hotmail.com")) {
        Toast.makeText(this, "Not a valid email address, trying again", Toast.LENGTH_LONG).show();
        newEmailAddressInput.setText("");
        newPasswordInput.setText("");
        confirmNewPasswordInput.setText("");
    } else if (!dbHandler.signUpEmailCheck(isTempEmail)) {
        Toast.makeText(this, "Email used, please try again", Toast.LENGTH_LONG).show();
        newEmailAddressInput.setText("");
        newPasswordInput.setText("");
        confirmNewPasswordInput.setText("");
    } else if (!confirmPasswordHolder.equals(isTempPass)) {
        Toast.makeText(this, "Passwords don't match!", Toast.LENGTH_LONG).show();
        newPasswordInput.setText("");
        confirmNewPasswordInput.setText("");
        areaCodeInput.setText("");
        firstThreeDigitsInput.setText("");
        finalFourDigitsInput.setText("");
    } else{
        Toast.makeText(this, "Saved!", Toast.LENGTH_LONG).show();
        dbHandler.addEntry(entries);// adds entries to database
        printDatabase();
       }
}

this code, which is in the above method is the issue at hand. When the email is handed over to this code, it calls the method below from the database handler class.
else if (!dbHandler.signUpEmailCheck(isTempEmail)) {
            Toast.makeText(this, "Email used, please try again", Toast.LENGTH_LONG).show();
            newEmailAddressInput.setText("");
            newPasswordInput.setText("");
            confirmNewPasswordInput.setText("");

This method takes the email entry and uses it to call any and all other entries with the same name (as i understand it to work, i could be wrong which is why I am writing this question)
if the getColumnCount() function is anything but zero, the method returns true which shows makes the if statement false, which dictates the user to use another email. This never happens. I've tried with different positions of the true, false returns, but none of the combinations lead to the right conclusion.
   public boolean signUpEmailCheck(String emailEntry){
    //checks if a new email entry already exists in the database

    Integer holder;
    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_EMAILADDRESS  + "=\"" + emailEntry + "\"";
    Cursor c = db.rawQuery(query,null);
    holder = c.getColumnCount();
    if (holder > 0) {
        db.close();
        c.close();
        return true;
    } else {
        db.close();
        c.close();
        return false;
    }
}

This is the method that is called to enter the data into the database
public void addEntry(LoginEntries entry){
    ContentValues values = new ContentValues();

    values.put(COLUMN_EMAILADDRESS,entry.get_emailAddress());
    values.put(COLUMN_PASSWORD,entry.get_password());
    values.put(COLUMN_FIRSTNAME,entry.get_firstName());
    values.put(COLUMN_LASTNAME,entry.get_lastName());
    values.put(COLUMN_PHONENUMBER,entry.get_phoneNumber());
    values.put(COLUMN_NICKNAME,entry.get_nickname());
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_LOGINENTRIES, null, values);
    db.close();
}

Answer: Try to rewrite your query like this, also make sure emailEntry is not null.
 String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_EMAILADDRESS  + "=?";
 Cursor c = db.rawQuery(query, new String[] { emailEntry });

Also just check if the cursor is empty with the following methods:
if(!c.moveToFirst() || c.getCount() == 0){
    ...
    return true; // cursor is empty, the email doesn't exist
}else{
    return false; // cursor is not empty, the email exists
}

Comment: Thank you. I can finally move on to the other 50 bugs haha.
one question, how does  !c.moveToFirst() come in to play?
Comment: `moveToFirst()` will return false if the cursor is empty. Please accept my answer if it helped you to solve the issue.
Comment: Thank you for the help. I just did.


function with equal upper and lower sums

Question: Which function f on [0,1] has equal lower and upper sum for each partition? I guess constant functions are the only such functions. Give me some hint to prove it. Thanks in advance.
Answer: Suppose firstly  that $f(0) \ne f(1)$ and WLG $f(0) \lt f(1)$ then for the simple partition $[0, 1]$ the upper and lower sums differ (upper is $\ge f(1)$, and lower $\le f(0)$), and so by contradiction, $f(0) = f(1) = $(say) $C$.
Now, suppose $0 < x  < 1$ and that $f(x) \ne C$ WLG assume that $f(x) \gt C$. Then consider the partition $[0, x]; [x, 1]$. Upper sum is $ \ge f(x)$, while lower sum is $ \le C$, so again they differ and by contradiction,  $f(x) = C$ for all $x \in (0, 1)$
Putting the two together, $f(x) = C$ for all $x \in [0, 1]$
Answer: Suppose f is not constant. Then WLG we can assume that f (a) less than f (b) for different a and b.
For the partition  P :a,b  the upper and lower sums are different.
So no such a & b exist. Hence f is constant.


Protect SVN content?

Question: I installed SVN on a Windows 2008 server, everything works like it should, except that everybody knowing the structure and the server IP can check stuff out. How do I protect the SVN content? I am using TortoiseSVN as client. Do I use the authz file for that?
Thanks!
Comment: Are you using svnserve (the svn:// protocol) or are you hosting it over a web server? Apache or IIS? There are authentication mechanisms for both.
Comment: As a general rule: password-protecting networks resources is done server-side, not client-side ;-)
Answer: authz is for apache-hosted subversion. You need to create a users file in your repository's conf directory with user = password pairs and then reference it from your svnserve.conf file. From the online book:

Create a users file and realm
For now, the [general] section of svnserve.conf has all the variables you need. Begin by > changing the values of those variables: choose a name for a file that will contain your > usernames and passwords and choose an authentication realm:
[general]
password-db = userfile
realm = example realm

The realm is a name that you define. It tells clients which sort of "authentication namespace" they're connecting to; the Subversion client displays it in the authentication prompt and uses it as a key (along with the server's hostname and port) for caching credentials on disk (see the section called "Caching credentials"). The password-db variable points to a separate file that contains a list of usernames and passwords, using the same familiar format. For example:
[users]
harry = foopassword
sally = barpassword

Comment: Did that and it still lets me check out without asking for a password. What is the users name that tries to check out or read? I referenced the user file from the conf file (password-db = passwd).
Comment: Hmm - worked for me last time I tried it. Can I check you're restarting svnserve to make sure it picks up the configuration changes, and not specifying some other configuration file on the command line?

Protect SVN content?


What's the name for the effect size of a log linear regression model?

Question: I'm using a log linear regression to model a log transformed continuous positive variable, eg a quantity $Y$ that cannot be negative.
eg:
$$ log(Y) = \beta_0Const + \beta X$$
The coefficients of my predictors, after exponentiation should indicate proportional changes in the quantity $Y$ isn't it?
How do I call this effect in scientific publication? I read that for poisson regression it is used the term "Incidence Rate Ratio". But I guess this is correct only in the case $Y$ is a count variable, which is not my case.
Thanks
Answer: If the $X$ values are also on the same log scale, the regression coefficients are what economists call "elasticities". That's the fractional change in $Y$ per fractional change in $X$. If $X$ is not log transformed, this Wikipedia page uses the term "semi-elasticity" for the fractional change in $Y$ per unit change in $X$. (First I've heard of that term.)
If I were putting together a table of results, I might nevertheless just call your regression coefficients "slopes" or "coefficients" and specify the units (fractional change in $Y$ per unit change or per fractional change in $X$) in a table footnote. A name more directly related to what $Y$ and $X$ represent might be more useful to your readers rather than a generic (and potentially unfamiliar) term like "semi-elasticity."


What is the largest winning margin, in seconds, in an F1 race?

Question: In an F1 race, when the leader dominates a particular track, the gap between the winner and 2nd place can be really long in terms of seconds. What is the largest gap, in seconds, between the winner and the runner-up in an F1 race? Was there ever a race where the 2nd-placed driver was lapped by the winner?
Answer:
What is the largest gap, in seconds, between the winner and the runner-up in an F1 race?

That would be the 1958 Portuguese Grand Prix, held at the 7.4 km-long Circuito de Boavista. Stirling Moss beat championship rival Mike Hawthorn by 5 minutes, 12.75 seconds. Incidentally, this was also the race at which Hawthorn was initially disqualified until Moss protested on his behalf, a gesture which ultimately allowed Hawthorn to beat Moss to the title that year (and prevented Moss' record winning margin from being even larger).

Was there ever a race where the 2nd-placed driver was lapped by the winner?

Yes. There have, in fact, been two races where the 2nd-place driver was lapped twice by the winner. The first was the 1969 Spanish Grand Prix, with Jackie Stewart finishing two laps ahead of Bruce McLaren in 2nd. The second was the 1995 Australian Grand Prix, where Damon Hill was the only frontrunner not to suffer technical issues; Olivier Panis in 2nd suffered an oil leak in the closing stages that allowed Hill to lap him for a second time.


SQL Server: interpreting 'y' as BIT value

Question: In C, when you compared true/false value to 1/0, it worked very well.
I would want the similar possibility with SQL Server - when I have a bit column, I would like to compare myBitField = 'y' / myBitField = 'n'
Is there anything I can do about that? Maybe change some SQL interpreter settings or something?
Example of what I would like to do:
select * from
(
   select CAST(1 AS BIT) as result
) as main
where main.result = 'y'

Currently, it throws an error, and I would like it to return 1/true/'y', whatever, but I would like it to be able to make that comparison.
Comment: Not sure I understand corectly but in SQL if you declare myBitField as bit it will be 0 for false and 1 for true.
Comment: @CiucaS: Yes, and I would like to compare this bit field to 'y'/'n'.
Comment: In T-SQL, the `bit` datatype has two possible values - 0 being false, 1 being true - and it can be NULL. Nothing else. No settings available to change this. You'll have to get used to 0 and 1.
Answer: I suppose you want to do it for some yes/no thing. But this is generally a wrong concept, your application which is accessing the SQL Server should interpret y as a 1 and n as a 0 and afterwards set the correct parameters for the query. You should not (actually I'm temped to write "must not") do this in SQL Server, that's what you have a business logic for.
Comment: Yeah, I am aware of that, but I am currently in the process of migrating my company's old erp system into a new one, and am considering my options regarding char(1)/bit issue. ;)
Comment: Ok, I can understand the interest for a legacy system in order to change it only once, but I'll keep my answer standing in case someone with a terrible application design will find this question  ;)
Answer: As others have said, BIT and CHAR / VARCHAR are entirely different datatypes. But if you want to cast them during the select, you can use CASE expression like so:
-- Reading string as BIT
SELECT CAST(CASE RESULT WHEN 'Y' THEN 1 WHEN 'N' THEN 0 ELSE NULL END AS BIT) RESULT

-- Reading BIT as string
SELECT CAST(CASE RESULT WHEN 1 THEN 'Y' WHEN 0 THEN 'N' ELSE NULL END AS CHAR(1)) RESULT

And that's about as far as your options go here, far as I can understand. :)


Select All in DataGrid from button

Question: I have a little problem about selecting all rows from a DataGrid.
The question is that the CommandButton is in a UserControl which refers to the MainViewModel and the grid is in a UserControl which refers to another ViewModel. The first thought was to make a static method and call it from the mvm, but the datagrid is not static and can't be called. How can i do?
Edit:
I actually solved the problem by rferencing a static instance of the grid from the code behind.
In the pushbutton viewmodel i recalled the select all method inside the command execution
<code> if (_CommandBtnSelectAll == null)
 {
    // creo una nuova istanza del comando
    _CommandBtnSelectAll = new USCommands(
       item =>
       {
             ViewControlCodeBehind.grid.SelectAll();
       }
 }
</code>
In the ViewControl Code Behind i just had to set a static instance of a new DataGrid and assign it the actual datagrid.
<code>public static DataGrid grid;

public ControlBody() // It's the UserControl initialization
{
   this.grid = DataGridControl; // DataGridControl is the name of the actual control
}
</code>
Comment: Marco: please add relevant code to your post so we can see how your xaml is structured. There's a very right chance that you can simply exploit the inherited DataContext of usercontrol & pass it into command as a CommandParameter that can then set a property on ViewModel (For example `foreach(var item in viewModel.Items) item.IsSelected = true;` This will then get automatically picked up by DataGrid (assuming ViewModel.Items was bound to DataGrid & IsSelected was bound to ItemContainer.IsSelected) You can do a search on SO for IsSelected binding if you need more info on how to bind it.
Answer: You could send a message or an event from the view model and subscribe to and handle this event in the view using a messenger or an event aggregator. Please refer to this blog post for more information about this.
The other option would be to inject the view model with an interface that the view implements as suggested here.

Select All in DataGrid from button


Print array of imagefield fields for node type

Question: I need to get an array of imagefields for a specific node type or even just all imagefields or all fields for a node type.
Answer: You can get a list of all fields for a particular content type using the content_types() function:
$type = content_types($type_name);

if (isset($type['fields'])) {
  $fields = $type['fields'];
}

From there you can just loop through and see what type of field each is, and act on it accordingly.
Comment: This is helpful but imagefields are specified as filefields, is there a way to differentiate between the two?
Comment: There might be a better way but you could look at the `widget` for each field; if it's an `imagefield_widget` you can be pretty certain it's an image field type


How does URLConnection in java reuses the connection from the pool

Question: Can any one help me with a sample code of how the URLConnection reuses the connection?
URLConnection con = new URL("http://www.someurl.com").openConnection();

I am using the above code to make a URLConnection. For the first time, the URLConnection will open a new connection to the specified URL. But after that it will reuse the existing connection from the pool. Is there any to prove this (I mean through println()) ?
Actually is there any way to retrieve connection reused status from the pool?
Comment: You might be able to "wire sniff" to confirm that it's actually re-using connections.  Or check the connection at the server (assuming it uses http keep-alives, that's the only case when it reuses connections I'd imagine...) See also https://stackoverflow.com/q/3304006/32453
Answer: From the java.net.URL javadoc:

Returns a URLConnection object that represents a connection to the
  remote object referred to by the URL.
A new connection is opened every time by calling the openConnection
  method of the protocol handler for this URL.
If for the URL's protocol (such as HTTP or JAR), there exists a
  public, specialized URLConnection subclass belonging to one of the
  following packages or one of their subpackages: java.lang, java.io,
  java.util, java.net, the connection returned will be of that subclass.
  For example, for HTTP an HttpURLConnection will be returned, and for
  JAR a JarURLConnection will be returned.

So for a http protocol url it will return a HttpURLConnection
From the java.net.HttpURLConnection javadoc:

Each HttpURLConnection instance is used to make a single request but the
  underlying network connection to the HTTP server may be transparently shared by other instances

So the underlining tcp connection might be pooled
Comment: Okay. Agreed. But is it possible to prove it? It would be very much helpful if you provide a sample code to prove the tcp connection being pooled and reused.
Comment: @Dilip B S It isn't possible to prove it from code, that's how completely it's engineered to be hidden under the hood. You would have to sniff the network.
Comment: hmmm:) But it seems just conceptual. So perhaps there could be a way to prove it... We rely on the java doc. If the requirement is to prove it, then we have to.
Comment: hmm having to prove that a programming language base library does what is says is a little strange. Is it more related to having to profile a certain method for network traffic?
Comment: :-)   But my requirement is that... Anyway thanks for the response


SelectControl doesn't work in OpenLayers using IE8

Question: I'm trying to display an alert message when a user clicks on one of the vectors is in the vector layer. This works fine in all browser, except IE8.
    map = new OpenLayers.Map(id, {
        theme: null
    });

    vectorLayer = new OpenLayers.Layer.Vector("Vector Layer");

    map.addLayer(vectorLayer);
    selectControl = new OpenLayers.Control.SelectFeature(vectorLayer);

    vectorLayer.events.on({
        'featureselected': onPopupFeatureSelect,
        'featureunselected': onPopupFeatureUnselect
    });

    map.addControl(selectControl);
    selectControl.activate();

    // ...

    function onPopupFeatureSelect(feature) {
        alert("OK");
    } // <-- Exceptions are thrown here

Whenever the onPopupFeatureSelect function is finished (at {) the IE8 debugger somehow falls into the JQuery code and throws exceptions there.
Am I using the select feature correctly?
Update: The crash occurs when I click anywhere in the map. It is not related to the popup feature.
Answer: JQuery in combination with VML was causing this problem. I updated to version 1.7.1 and everything is working fine.
More information here: http://bugs.jquery.com/ticket/7071


How can I run multiple tests in a valid and random fashion?

Question: I hope this is the correct place to ask this question. I'm currently doing research where I'm comparing two groups on their EEG frequency spectra. I wasn't too sure how to approach this.
Data:
I have the power values (dB) of multiple frequencies per subject, ranging from 0.6 to 30, in steps of 0.2, thus 148 data points.

Problem:
In general, I would like to know where my two groups (red and black) differ on the power spectrum. I could run a t-test on every 148 bins, but I will surely run into several problems like multiple comparisons.
Question:
Which statistical test would be most appropriate here? Specific types of non-parametric tests? Is there some form of random testing that would be fitting here? Bootstrapping? How would that work? And would you in addition have any tips on how to implement this test (e.g. in R), even though that is out of the scope of this forum.
Comment: one option would be to use a regression model and identify the coefficient differences, so you need to find a sutable model for your power spectrum.
Answer: I've came up with a solution myself, so maybe this helps someone in the future. A valid way to deal with this kind of data can be permutation testing (see here).
To quote from the article:

The nonparametric statistical test is performed in the following way:
(1) Collect the trials of the two experimental conditions in a single
  set.
(2) Randomly draw as many trials from this combined data set as there
  were trials in condition 1 and place those trials into subset 1. Place
  the remaining trials in subset 2. The result of this procedure is
  called a random partition.
(3) Calculate the test statistic on this random partition.
(4) Repeat steps 2 and 3 a large number of times and construct a
  histogram of the test statistics.
(5) From the test statistic that was actually observed and the
  histogram in step 4, calculate the proportion of random partitions
  that resulted in a larger test statistic than the observed one. This
  proportion is called the p-value.
(6) If the p-value is smaller than the critical alpha-level
  (typically, 0.05), then conclude that the data in the two experimental
  conditions are significantly different.

Based on a tutorial on youtube by Jonne Sälevä (2015), I created the following code, up to step 5 from above:
<code>## Loop over all the columns of interest
for(i in range of columns){

  ## Split the data
  group1_data <- perm_data[perm_data$Group == "group1",]
  group2_data <- perm_data[perm_data$Group == "group2",]

  ## Make separate lists of group and dependent variable data
  combined_groups <- c(group1_data$Group, group2_data$Group)
  combined_x      <- c(group1_data$x, group2_data$x)

  ## Number of simulations
  nsims <- 10000

  ## The observed difference in means
  diff_obs <- mean(group1_data$x) - mean(group2_data$x)
  ## Initialize a variable to store the differences
  diffs <- rep(NA, nsims)

  ## Permutation for loop
  for(k in 1:nsims){
    shuffled_labels <- sample(combined_groups, replace = FALSE)
    diffs[k] <- mean(combined_x[shuffled_labels == 1]) - mean(combined_x[shuffled_labels == 2])
   }

  ## p-value = (number of more extreme differences than diff_obs/nsims)
  length(diffs[abs(diffs)>= abs(diff_obs)])/nsims
  perm_pvalue[index] <- mean(abs(diffs) > abs(diff_obs))

}
</code>
Comment: I agree that the optimal strategy here is a permutation test, especially since the power spectrum data is unlikely to be normally distributed (although a log transform of your data may get you closer).

However there are two serious issues with above suggestion. The first is that you have a lot of dependencies in your data that you should taken into account when determining the significance (e.g. if neighbouring frequencies show the same pattern, this should strengthen your belief). The other is that the difference in means alone is unlikely to be a good indicator of difference.
Comment: See https://www.ncbi.nlm.nih.gov/pubmed/?term=pernet+2015+tfce


Can you upgrade sqlite3 version on your android?

Question: I'm writing an app which uses the Foreign Key Constraints which support was only just brought in for on version 2.2, and my phone is 2.1  Is there any way to upgrade the version of sqlite3 on the htc desire or any other android phone when your application installs?
Answer: short answer, no.
Longer answer.
Yes, but you would have to have root because the sqlite binary is in /system/xbin. you would need root access to be able to overwrite that file. you would not be able to upgrade any other device unless they too had root, and a recovery image that supported update.zips that can be signed using the "test keys". then you would have to manually distribute the update zip file, that the user would have to reboot in to recovery mode, flash the update.zip to apply your "patch".
Comment: nasty!  Thanks for the answer.  Looks like I'll have to manage the database without Foreign_Keys then 8-(
Comment: don't forget to mark the answer accepted if you are satisfied with the answer. it's hard to get answers in the future if you don't ever mark them.
Answer: As Ryan pointed out, you can change the binary if you have root access, but there is also another possibility: you can add the compiled SQLite native files to your app and access them via JNI. Here is an example project using SQLite with the Spatialite extension: https://github.com/mrenouf/android-spatialite


How to get Last ID of created data from related model?

Question: I can't fetch last id of created data from related model.
I tried to use $alacarte->id but it doesnt get the right ID of the model.
$order = array(
            'os_id' => $orderSlip->id,
            'group_id' => $menu['group_id'],
            'size' => $menu['size'],
        );

$alacarte = $this->menu->find($menu['id']);

$alacarte->orders()->create($order)->save();

return $alacarte->id;

I expect the output of the last created order to be the ID of Model\Order, but the actual output is the ID of the Model\Menu.
Answer: [Solved]
I just removed save() after creation.
$menu = $alacarte->orders()->create($order)->save()
changed to
$menu = $alacarte->orders()->create($order)
return $menu->id


Unable to get the right type in cellForItemAtIndexPath in my UICollectionView

Question: In my UICollectionView, in its cellForItemAtIndexPath method, I am trying to typecast the cell to my custom cell of type MyCollectionViewCell. But the object is still resolved as just a UICollectionViewCell. What could be the issue? I have associated the cell with my custom class that inherits from UICollectionViewCell in my storyboard. Please see the images below.
Answer: In the viewDidLoad method, replacing
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

with
[self.collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

fixed the issue.
Commenting that entire line also seemed to work.
Comment: It is also working without the line of code because the storyboard automatically registers your custom cell to your collectionView using the identifier you provide in the inspector. You only need to register your cell manually when you are not using storyboards.


C# - Efficient way of searching and replacing strings from a file

Question: I have a text file where I wish to search if a set of lines exists and update/overwrite them or if the set of lines does not exists, add them.
Here is the text file.
#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# Use name-based virtual hosting.
#
##NameVirtualHost *:80

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
##<VirtualHost *:80>
    ##ServerAdmin email@example.com
    ##DocumentRoot "C:/xampp/htdocs/dummy-host.localhost"
    ##ServerName dummy-host.localhost
    ##ServerAlias www.dummy-host.localhost
    ##ErrorLog "logs/dummy-host.localhost-error.log"
    ##CustomLog "logs/dummy-host.localhost-access.log" combined
##</VirtualHost>

##<VirtualHost *:80>
    ##ServerAdmin firstname.lastname@example.com
    ##DocumentRoot "C:/xampp/htdocs/dummy-host2.localhost"
    ##ServerName dummy-host2.localhost
    ##ServerAlias www.dummy-host2.localhost
    ##ErrorLog "logs/dummy-host2.localhost-error.log"
    ##CustomLog "logs/dummy-host2.localhost-access.log" combined
##</VirtualHost>

<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    DocumentRoot "C:/xampp/htdocs/dummy-host2.localhost"
    ServerName dummy-host2.localhost
    ServerAlias www.dummy-host2.localhost
    #ErrorLog "logs/dummy-host2.localhost-error.log"
    CustomLog "logs/dummy-host2.localhost-access.log" combined
</VirtualHost>

Here is the skeleton code. I first open the text file, and read it to the end so that I can use the Regex class. (I chose this because the code looks cleaner and concise rather than doing it the C way - looping). But it isn't that simple because I need to check first a set of lines.
    StreamReader reader = new StreamReader(path);
    string content = reader.ReadToEnd();
    reader.Close();

    // Replace the strings using Regex replace method
    StreamWriter writer = new StreamWriter(path);
    writer.Write(content);
    writer.Close();

Given a port number, I appended it to this pattern
string virtualHost = "<VirtualHost *:" + cls_globalvariables.portNumber + ">";

And I used
Match match = Regex.Match(content, virtualHost);

to find the index of the search pattern. I also had to find the index of its closing tag  and replace them with an updated version of those lines. I have no problems of searching the ending line but I do have a problem of distinguishing the commented from uncommented lines.
Regex.Match returns the first occurrence of the search pattern which is the commented line. What I wanted to do was to search patterns without comments but how do I do that? I began thinking in C schemes such as looping character by character backwards and forwards starting from the match.Index until I detect a delimiter of "\r\n". Is there an efficient C# way to solve this?
Comment: Just skip over the lines with comments before calling `ReadToEnd()` by calling `ReadLine()` and checking if the line starts with `#`.
Answer: You can either do it the way Jesse suggests, or if you want to stick to Regex, just put ^ at the start of your regex and set RegexOptions.Multiline.

Multiline mode. Changes the meaning of ^ and $ so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string. For more information, see the "Multiline Mode" section in the Regular Expression Options topic.


Views keeps crashing when I change setting

Question: I have created a Latest News view which I'm displaying in my sidebar as a block. When I then go back to change anything such as the Title of the View or the number of items that can be displayed, it crashes. can anyone help? I have attached a screen print which shows the error.
Answer: It is jquery version issue. Views is not crashing, It is returning json response which  Drupal is not handling properly due to jquery version issue. If you are using jquery_update module. Change the jquery version to 1.5 or older. If not; use this module. Latest jquery_update module allow you to set different jquery version for administrator pages and actual site nodes. Set the jquery version 1.5 or older for administrator pages and higher for actual site nodes if needed.
Comment: amazing, you are right, i had jquery set to v1.8 in the modules configuration, i changed to 1.7 and the problem has gone. I really appreciate such a quick response, thank you ! :)
Comment: it will be a pleasure.


Parametric infinite series convergence

Question: I've been going trough some exercises regarding Cauchy's root test and D'Alembert's ratio test for infinite series. Let me just say that I am aware that they are equivalent, due to Stolz–Cesàro theorem. I had some parametric series on hand, and since you can't never go too much in detail with analysis of entities with parameters (at least I had regrets every time I didn't do it), I first started by first applying basic convergence test, that is, series $\sum{a_n}$ diverges if $\lim_{n\to+\infty}a_n \ne 0$. Then I would apply appropriate test, root or ratio test, depending on the series. It struck me that for each and every one case the series converged for the whole interval in which it could actually converge. That is, if the convergence test said the series diverges whenever a parameter, say $p$, is in the interval $I$, then the series was convergent exactly at the whole interval $I$ when one of the two other tests was applied.
I am wondering is why is this happening. Was I not firm with my analysis? In all examples the parameter $p$ was given as a positive real number, so is it possible that for the negative numbers of $p$ those series do still diverge somewhere within $I$? I will state some of the practice problems that were more interesting, and the solutions I've got for them. I hope that someone could tell me If what I have noticed was somewhat of a fact, or does it just come down to the fact that $p$ was always positive. Can I at least always expect that for positive $p$ both convergence and root/ratio test give the same results? If not, what are some counterexamples?
Example 1:
$$\sum_{n=1}^{+\infty}(\frac{p\cdot n}{n+1})^n,\ p \in (0,+\infty)$$
Series converges for $p \in (-1,1)$. For this case I did actually took $p \in \mathbb{R}$, because it was not as hard to go through all the cases as for the other ones. Here I used the root test. Also $\lim_{n\to+\infty}a_n = \frac{1}{e}\lim_{n\to+\infty}p^n$ and $\lim_{n\to+\infty}\sqrt[n]{a_n}=p$.
Example 2:
$$\sum_{n=1}^{+\infty}\frac{n^2}{(p+\frac{1}n)^n}, p\in(0,+\infty)$$
Series converges for $p \in (1,+\infty)$. Also
$\lim_{n\to+\infty}a_n = \frac{1}{\sqrt[p]{e}}\lim_{n\to+\infty}(\frac{1}{p})^n$ and $\lim_{n\to+\infty}\sqrt[n]{a_n}=\frac{1}p$.
Example 3:
$$\sum_{n=1}^{+\infty}\frac{1}{p^n+1}, p \in (0,+\infty)$$
Series converges for $p\in(1,+\infty)$. Here I couldn't really systematically simplify the limits in question so I went on intuition, though with same conclusions as before:
$$\lim_{n\to+\infty}a_n = \left \{
  \begin{aligned}
    &0, && p > 1 \\
    &\frac{1}2, && p = 1\\
    &1, && p < 1
  \end{aligned} \right. ,$$
which yields that the series diverges for $p \le 1$, and $$\lim_{n\to+\infty}\sqrt[n]{a_n} = \left \{
  \begin{aligned}
    &\frac{1}p, && p > 1 \\
    &1, && p \le 1\\
  \end{aligned} \right. ,$$ which yields that series converges only for $p>1$.
Example 4:
The last one, I promise
$$\sum_{n=1}^{+\infty}(n+p)\left (\frac{p+1}{p^2+1} \right )^n, p \in (-1,+\infty)$$
Here limits are:
$$\lim_{n\to+\infty}a_n = \left \{
  \begin{aligned}
    &0, && \frac{p^2+1}{p+1} > 1
    &+\infty, \frac{p^2+1}{p+1} \le 1
  \end{aligned} \right. ,$$
so the series diverges for $p \in ((-\infty,-1)\cup[0,1]) \cap (-1,+\infty) = [0,1]$, and
$$L = \lim_{n\to+\infty}\sqrt[n]{a_n} = \frac{p+1}{p^2+1}.$$ Since series converges for $L < 1$, we get $p\in(-\infty,0)\cup(1,+\infty)$. Since it is given that $p>-1$, finally series converges for $p \in(-1,0)\cup(1,+\infty)$.
Comment: I thinks you have stumbled upon something called as [radius of convergence](https://en.wikipedia.org/wiki/Radius_of_convergence)
Comment: Well I do not think so, as that has to do with the series of functions fn(x), while my question only has series with positive, nonincreasing terms @Tutankhamun
Comment: Look at Example 1 it can be seen as power series , that is a function of p, $\sum (\frac{n}{n+1})^n \cdot p^n$ restricted to a positive domain. Also the corollary of root test is [cauchy hadamard theorem](https://en.wikipedia.org/wiki/Cauchy%E2%80%93Hadamard_theorem#:~:text=In%20mathematics%2C%20the%20Cauchy%E2%80%93Hadamard,unknown%20until%20Hadamard%20rediscovered%20it.)
Comment: Alright, I see that it can be.  The thing is, functional series were not introduced in the material that I am using at the point when those exercises are presented. Though I can see that this can be related to the radius of convergence, when I think about it. But that still does not answer the questions presented in my OP. Can you maybe address those in an answer? @Tutankhamun
Answer: Let $a_n = \frac 1{p + n}$, for $p > 0$. Then $\lim_{n\to \infty} a_n = 0$, making $\sum_n a_n$ potentially convergent for all $p$.
But of course, a comparison to the harmonic series shows that instead it diverges for all $p$.
Comment: That is such a simple example! And yet I failed to think of it. Thank you very much! It seems like I was indeed just lucky with the example problems!
Comment: You weren't all that lucky in your examples. The vast majority of algebraic formulas for $a_n(p)$ are going to lead to exactly the same condition holding: they will converge for all $p$ where $\lim_n a_n(p) = 0$, except possibly at the boundary. To come up with a counter-example, first you need to find a divergent series on the edge of convergence, so $a_n \to 0$. Then you need to involve $p$ in a way that moves along that edge instead of across it. My example is surely the easiest solution where the involvement of $p$ is not completely trivial (such as $a_n = \frac pn$ would be).
Comment: I see. I must say that this is a very helpful insight! Thank you very much again!

Parametric infinite series convergence


How to perform redirect after login with the Modal Forms module?

Question: I have some pages in my website with links using the Modal forms (with ctools) module to login. I want to redirect users after logging in using these modals to the same page that have the link to this modal form
Any idea how do this?
Comment: Answers from [this question](http://drupal.stackexchange.com/q/19110/16495) does not work for you? How do they fail?
Answer: The page callback of the login URL provided by the Modal Forms module is modal_forms_login.
/*
 * A modal user login callback.
 */
function modal_forms_login($js = NULL) {
  // Fall back if $js is not set.
  if (!$js) {
    return drupal_get_form('user_login');
  }

  ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    // 'title' => t('Log in'),
    'ajax' => TRUE,
  );

  $output = ctools_modal_form_wrapper('user_login', $form_state);
  if (!empty($form_state['executed'])) {
    // We'll just overwrite the form output if it was successful.
    $output = array();
    ctools_add_js('ajax-responder');
    $output[] = ctools_modal_command_dismiss(t('Login success'));
    if (isset($_GET['destination'])) {
      $output[] = ctools_ajax_command_redirect($_GET['destination']);
    }
    elseif(module_exists('login_destination')) {
      $destination = login_destination_get_destination('login');
      $output[] = ctools_ajax_command_redirect($destination['path']);
    }
    else {
      $output[] = ctools_ajax_command_reload();
    }
  }
  print ajax_render($output);
}

At a quick glance, you can tell that you can either set your destination in the query string of your login link, like so:
drupal_add_library('system', 'drupal.ajax');
$login_link = l('Login', 'modal_forms/nojs/login', array(
  'query' => array('destination' => 'redirect-here'),
  'html' => TRUE,
  'attributes' => array(
    'class' => array('ctools-use-modal'),
  )
));

Or, install and configure the Login Destination module
Answer: I had the same issue and this is my solution:
1) create a module mymodule
2) override menu item using hook_menu
function mymodule_menu(){
    $items['modal_forms/%ctools_js/login'] = array(
        'title' => 'Log in',
        'page callback' => 'mymodule_modal_forms_login', // your custom callback function
        'page arguments' => array(1),
        'access callback' => TRUE,
        'file' => 'mymodule.module', // file with the mymodule_modal_forms_login function
        'type' => MENU_CALLBACK,
    );
    return $items;
}

3) copy and paste from model_forms.page.inc on your mymodule.module file and change the name y the body of the function
function vdf_modal_forms_login($js = NULL) {
global $user;

// Fall back if $js is not set.
if (!$js) {
    return drupal_get_form('user_login');
}

ctools_include('modal');
ctools_include('ajax');
$form_state = array(
    // 'title' => t('Log in'),
    'ajax' => TRUE,
);

$output = ctools_modal_form_wrapper('user_login', $form_state);
if (!empty($form_state['executed'])) {
    // We'll just overwrite the form output if it was successful.
    $output = array();
    ctools_add_js('ajax-responder');
    $output[] = ctools_modal_command_dismiss(t('Login success'));

    if (in_array("custom_role_1", $user->roles)) {
        $output[] = ctools_ajax_command_redirect("custom_page_1");
    } elseif (in_array("custom_role_2", $user->roles)){
        $output[] = ctools_ajax_command_redirect("custom_page_2");
    }else {
        $output[] = ctools_ajax_command_redirect("custom_page_3");
    }
}
print ajax_render($output);
}


Efficient data structure with two keys

Question: I have an Android app in which I use a HashMap to store container objects. During the course of the App, the datastructure is accessed continuously.
However, about half the time, the reference used in not the Key in the map but another variable from the object so I end up looping over the structure again and again.
Is there an efficient way to have a datastructure indexed on two keys in Java ?
Answer: Why not two maps with different keys, but that both refer to the same values?
Comment: @SaadFarooq: Yes, exactly.  Objects in Java are always accessed via references.
Comment: Hmm... could you elaborate on how that works conceptually ?? Wouldn't that result in two copies of the Objects or does Java just store references and put the Objects somewhere in memory ?
Comment: OK. So when I write, I write to both Maps.... say map1.put(key1, value) and map2.put(key2, value)...
Comment: @SaadFarooq: ...that's totally fine, and there's still only one copy of `value`.
Answer: Manage two maps, where two sets of keys map to the same underlying set of objects. Wrap them in a class that has methods similar to a normal map, but internally searches on both keys, and synchronizes additions and deletions.
This is efficient because manipulations are (in the worst case) linearly proportionate to managing a single map.
Answer: You could use one map with both keys:
Map<Object, Person> personMap = new HashMap<Object, Person>()

Person person = ...
personMap.put(person.getName(), person)
personMap.put(person.getSSN(), person)

Then you can retrieve by the key. This of course assumes that there are no collisions in your key usage. If your two keys are different class types, then this is safe to do. If your keys are the same type (example String), then you may not want to use the two maps solution.
Follow-up: This approach does suffer from losing type safety, but it only impacts put(K, V) and putAll(Map<? extends K, ? extends V>), as get(Object) and containsKey(Object) always accepts Object.
So with this limitation I'd wrap this single map or go with the two map solution (also wrapped).
Comment: I'm going to say it: this ruins a lot of the nice advantages of type safety.
Answer: I'd create a key object that combines the two variables.
Comment: Yeah... after reading the other answers I was thinking along the same lines.... but both my keys are not necessarily present at the same time... the second key is obtained after a web service call. With the other solutions I can do a get and then put with the other key.
Comment: but I think this might work with overriding the equals method so that the Key object matches on any of the two variables
Comment: but wouldn't a Get with one (half) key, remove and then put with the the full key work. Its only one operation more than the other solution (the remove)
Comment: Keys must be immutable.  That's true in Python; true in Java.

Efficient data structure with two keys


Armazenar valores de entrada em Java

Question: Preciso armazenar valores com mais de uma entrada. Se um programa solicita 10 entradas, eu devo armazenar em 10 variáveis? No caso as entradas são do tipo Int.
Comment: Essa é uma dúvida para programadores muito iniciantes. A resposta vai depender muito do objetivo de armazenar as 10 entradas.
Comment: Utilize um Array, ou outra estrutura de dado.
Comment: Obrigado pela ajuda, o problema estava nas estruturas de controle e não no armazenamento de variáveis.
Comment: @D.rosario A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos, terá assim que aceitar a resposta).
Answer: Sim, deve, mas entenda o que é uma variável.
A dúvida não fala sobre que valores serão entrados, mas é provável que estas variáveis sejam do tipo int, já que para exercícios assim costuma pedir apenas valores numéricos inteiros.
Porém o mais provável é que espera-se que use um array. Uma variável do tipo array é aquela que armazena outras variáveis em sequência. Então teremos 11 variáveis, 1 para o array e 10 para os inteiros.
Em linguagens tipadas, como o Java, todas variáveis possuem tipos em tudo. Então tem um array de inteiros.
Quando estamos usando um array estamos falando de acessar um valor que depende de variações: uma é o array e outra é o dado em si. Então para acessar um array basta usar o nome da variável, mas para acessar o valor é necessário usar o nome da variável do array e o índice que indica qual variável dele será usada.
Então vamos criar o array do tipo int com 10 posições.
int[] array = new int[10];

Agora para acessar a primeira variável dele usamos:
array[0]

Para a segunda:
array[1]

Até a última:
array[9]

Isso é como acessar array0, array1, array9, mas se usasse os nomes assim o índice não poderia variar e isso deixa a aplicação pouco flexível. Com o índice é possível usar uma variável nele, assim:
array[i]

Coloquei no GitHub para referência futura.
Que posição está pegando? Aquela que a variável i indicar, varia, e esta é a beleza da computação. Assim você pode manipular 10 variáveis em até uma linha fazendo um laço de repetição.
Não está acostumando com array, laço (loop), essas coisas? Tem bastante informação aqui no site que pode te ajudar, dá uma pesquisada.

Armazenar valores de entrada em Java


Problem based on Projective and Injective Module

Question: Show that the following are equivalent for a ring:
(1) any $R$-module is projective.
(2) any $R$-module is injective
This is problem in Dummit Foote book, problem number 6, page 403. I was trying by using equivalent definition of projective and injective module but nothing
 find effective.Any help/hint in this regards would be highly appreciated. Thanks in advance!
Answer: A module $M$ is projective iff every short exact sequence
$$0\to A\to B\to M\to0$$
splits. So all modules are projective iff every short exact sequence
splits. So what about injectivity instead of projectivity
?
Comment: A module $M$ is injective iff every short exact sequence
$$0\to M\to A\to B\to0$$
splits.


A standard name for a formula to "Maximize true positives while minimize false positives"

Question: I am using an evaluation metric to reward the true positives and penalize the false positive ones retrieved by a function $f(\cdot)$.
Indeed, it can be represented as follows:
$\frac{\texttt{|TP|} - \texttt{|FP|}}{|\texttt{instances}|}$, where $\texttt{|TP|}$ and $\texttt{|FP|}$ are the number of true positives and false positives, respectively.
The goal is simple: selecting a function that maximizes $\texttt{TP}$ while minimizes $\texttt{FP}$.
I need to find a standard name for this formula to motivate its advantages for my work.
I am familiar with "sensitivity", "specificity", "F-measure", "recall", and "precision". However, none of them computes what I'm evaluating here.
Answer: I do not think this metric has an "official" name. For instance, it does not appear on the very comprehensive Wikipedia page on sensitivity and specificity, which also discusses many other related metrics.

I am a bit doubtful whether your proposed measure is really very useful. Suppose you have a completely random distribution of instances, with >50% positives and <50% negatives. Then you can maximize your criterion $f$ by classifying everything as "positive" - regardless of whether there are 51% true positives, or 60%, or 99.99%. Similarly, if there are <50% positives and >50% negatives, then you will maximize your function by classifying everything as "negative", again regardless of the actual prevalences. This incentive structure does not look very helpful to. (And of course, the same argument holds if these prevalences are conditional on predictors.)
This is very much related to the problems of straight-up accuracy as an evaluation measure, where the exact same problem comes up. I would recommend that you take a look at Why is accuracy not the best measure for assessing classification models? and think about how this applies to your measure.
Comment: Thanks :). Following your example, assume 100 instances of people to be classified as male/female. Assume 60 men and 40 women. If f returns all 100 people as men, the objective value is 60-40=20% but if f only returns men as men, it is 60%. If f returns nothing it is 0 but not maximized yet. Thus, the objective is maximized if it returns as more actual men and fewest possible women. The goal is to find all and only positive ones. The reason I don't want to use f-measure is that this function gives me some properties to optimize (it can decomposed into positive/negative components easily)
Comment: Yes, of course if you have a model that predicts classes perfectly, then you are good. But typically there is no perfect model, i.e., we have a predictive distribution of 60/40 *conditional on all predictors*. Your proposed measure would in this situation reward predicting "man" for *all* cases. The same for 51/49, and 99.99/0.01. I maintain that this makes no sense. ...
Comment: ... And also, that your measure cannot differentiate between these three cases. So it won't even tell us that there is something here that we may need to look more deeply into. For this, you need proper [tag:scoring-rule]s or similar measures that work on *predictive distributions*.


evaluating logistic regression's performance

Question: I am working on the scoring model and I aim to predict the probability of default. I have, say m, different candidate Logistic Regression models $M_{1}, \dots, M_{m}$ and I would like to choose the best one for prediction of the probability. Assume, that the data set is moderately large.
My approach is the following:
1) Randomly split the data set into Train and Validation Sets, say in proportion 80/20 without replacement.
2) Train each Logistic Regression model $M_{1}, \dots, M_{m}$ using Train Set and compute Areas Under ROC $AUC_{1}, \dots, AUC_{m}$.
3) Re-split the data again and compute the new $AUC_{1}, \dots, AUC_{m}$.(This is, basically, Monte-Carlo Cross Validation.)
Then, I am thinking to make boxplots for $AUC_{1}, \dots, AUC_{m}$ and choose the model $M_{i}$ which performs "better" according to the boxplots.
Is this correct way? Can I perform the same evaluation, but with Gini index? In my opinion it would make sense, but I haven't seen it in the literature. Also, intuitively I am not satisfied with just one split of the date, because every time we split it we get quite different result.
Comment: You could use a scoring rule such as the [Brier Score](https://stackoverflow.com/questions/25149023/how-to-find-the-brier-score-of-a-logistic-regression-model-in-r)
Comment: No, you would use the Brier Score (a proper scoring rule) in place of AUC-ROC (a semi-proper scoring rule). See [here](https://stats.stackexchange.com/questions/339919/what-does-it-mean-that-auc-is-a-semi-proper-scoring-rule) for more detail
Comment: @Robert Long, does the approach that I proposed make sense? Should I compute Brier Score  on Validation Set only?
Comment: @Robert Long Sorry, I am confused. Don't we compute AUC-ROC based on the Validation set?
Comment: How many observations do you have? Data splitting is only advisable when $n$ is very large, see also https://stats.stackexchange.com/questions/66457/how-to-do-external-validation-of-regression-models
Answer: One major issue with the ROCAUC is that it does not change upon applying monotonic transformations to the predictions. Thus, ROCAUC does not evaluate how accurate the predicted probabilities are (and your goal is to get accurate ones), just how well the two categories have their predictions separated.
Thus, as the comments describe, ROCAUC probably is not the performance metric you want to assess.
However, there are two common performance metrics that do get after the probabilities: Brier score and log loss ("crossentropy loss" in some circles). Both of these are examples of the strictly proper scoring rules that are discussed here.
$$
\text{Brier Score} = \overset{N}{\underset{i=1}{\sum}}\left(
y_i-\hat y_i
\right)^2\\
\text{Log Loss} = -\dfrac{1}{N}\overset{N}{\underset{i=1}{\sum}}\left(
y_i\log(\hat y_i) + (1-y_i)\log(1 - \hat y_i)
\right)
$$
A reasonable criticism of both the Brier score and log loss is that they are difficult to interpret. To that, I respond:

You are just comparing models, where all that matters is the relative performance instead of any absolute sense of performance.

Without a context, it is quite difficult to decide what qualifies as good performance.

Both the Brier score and log loss can be transformed to give values that are analogous to the $R^2$ of linear regression fame. These are the Efron and McFadden pseudo $R^2$ values, respectively, discussed by UCLA. I also give the equations below.

$$
R^2_{\text{Efron}} = 1-\left(\dfrac{
\overset{N}{\underset{i=1}{\sum}}\left(
y_i-\hat y_i
\right)^2
}{
\overset{N}{\underset{i=1}{\sum}}\left(
y_i-\bar y
\right)^2
}\right)\\
R^2_{\text{McFadden}} = 1-\left(\dfrac{
\overset{N}{\underset{i=1}{\sum}}\left(
y_i\log(\hat y_i) + (1-y_i)\log(1 - \hat y_i)
\right)
}{
\overset{N}{\underset{i=1}{\sum}}\left(
y_i\log(\bar y) + (1-y_i)\log(1 - \bar y)
\right)
}\right)
$$
Above, the $y_i$ are the true categories, coded as either $0$ or $1$; the $\hat y_i$ are the predicted probabilities of category $1$; and $\bar y$ is the unconditional probability of membership in category $1$ (so just the proportion of $1$s out of all instances).
Finally, I recommend a read of Benavoli et al. (JMLR 2017) for comparing models on multiple sets of out-of-sample comparisons.$^{\dagger}$ While the article makes a case for using Bayesian methods, it also discusses classical approaches.
REFERENCE
Benavoli, Alessio, et al. "Time for a change: a tutorial for comparing multiple classifiers through Bayesian analysis." The Journal of Machine Learning Research 18.1 (2017): 2653-2688.
$^{\dagger}$As one of the comments remarks, there are legitimate reasons not to like out-of-sample predictions unless the sample size is quite large.


Why paths of length return 0 using Pytorch?

Question: This function return error which is same as below while the paths is correct. Am I misunderstanding how paths works? (This snippet is from github-repo)
paths = paths[::skip_frame]

ValueError: slice step cannot be zero

Here is the main function:
 def make_gif(paths, gif_path, max_frame=50, prefix=""):
      import imagei

paths.sort()
skip_frame = len(paths) // max_frame

paths = paths[::skip_frame]

images = [imageio.imread(path) for path in paths]
max_h, max_w, max_c = np.max(
        np.array([image.shape for image in images]), 0)

Here is how function called:
parser = argparse.ArgumentParser()
parser.add_argument("--model_name", type=str)
parser.add_argument("--max_frame", type=int, default=50)
parser.add_argument("--output", type=str, default="sampe.gif")
parser.add_argument("--title", type=str, default="")

if __name__ == "__main__":
    args = parser.parse_args()

    paths = glob(f"./logs/{args.model_name}/networks/*.png")

    make_gif(paths, args.output,
            max_frame=args.max_frame,
            prefix=f"{args.title}\n" if args.title else "")

Comment: What is the `len` of `paths`, and what is the value of `max_frame`? You're using integer division, so any answer `0 < n < 1` will be rounded down to 0.
Answer: You get this error because your skip_frame is zero. Make sure it's value is at least one.


Introduction to Conditional random fields

Question: I came across the application of a conditional random field (CRF) to the output from a convolutional neural network (CNN) for image segmentation.  The additional CRF step seems to be a common technique for image segmentation and as a post-processing step in CNNs for segmentation.
I began looking into how they work which lead me to a course on probabilistic graphical models by Daphne Koller on Coursera.
I found this course to be useful, but very general.
My question is: what is a good text or course to study the construction and training of CRFs, preferably one that starts with a gentle introduction assuming no prior background?
Answer: andrew maccallum has an excellent article on CRFs - https://people.cs.umass.edu/~mccallum/papers/crf-tutorial.pdf
There has to be a few assumptions on prior background like probability and general math.


React Native Typescript Formik typings of handleSubmit in onPress

Question: I just started a project on React Native with Typescript and came along Formik in order to build form in my application.
I did the great formik tutorial guide and saw the use of formik with RN section in JS.
However, when I tried to translate this example into typescript, then I got the following typing error on the Button's onPress attribute:
No overload matches this call.
  Overload 1 of 2, '(props: Readonly<ButtonProps>): Button', gave the following error.
    Type '(e?: FormEvent<HTMLFormElement>) => void' is not assignable to type '(ev: NativeSyntheticEvent<NativeTouchEvent>) => void'.
      Types of parameters 'e' and 'ev' are incompatible.
        Type 'NativeSyntheticEvent<NativeTouchEvent>' is not assignable to type 'FormEvent<HTMLFormElement>'.
          Types of property 'nativeEvent' are incompatible.
            Type 'NativeTouchEvent' is missing the following properties from type 'Event': bubbles, cancelBubble, cancelable, composed, and 17 more.
  Overload 2 of 2, '(props: ButtonProps, context?: any): Button', gave the following error.
    Type '(e?: FormEvent<HTMLFormElement>) => void' is not assignable to type '(ev: NativeSyntheticEvent<NativeTouchEvent>) => void'.ts(2769)
index.d.ts(6926, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps> & Readonly<{ children?: ReactNode; }>'
index.d.ts(6926, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAt...

From what I understand, the handleSubmit function (e?: FormEvent<HTMLFormElement>) => void, accepts an event from a form submission (onSubmit attribute of a form element). Since there is no Form equivalent in RN, it complains receiving the (ev: NativeSyntheticEvent<NativeTouchEvent>) => void from the RN Button's onPress attribute.
In order to get rid of the error and keep going, I used this following workaround which I'm not satisfied with :
 <Button
              title="Do it !"
              color={colors.red}
              onPress={
                (handleSubmit as unknown) as (
                  ev: NativeSyntheticEvent<NativeTouchEvent>
                ) => void
              }
/>

I'd like to know how should I solve this typing error properly.
CodeSandbox: App.tsx:32
Thank you for your help.
Answer: You can describe your type like: (event: GestureResponderEvent) => void;
Code sample
Answer: You can try this
<Button
onPress={e => handleSubmit(e as unknown as FormEvent<HTMLFormElement>)}
title="Submit"/>

Answer: I usually do this:
<Pressable onPress={(e:any) => formik.handleSubmit(e)}>


Why do incoming batsmen always mark the off-stump line?

Question: In cricket, I have often seen that incoming batsmen come in and mark the off-stump line with assistance from the non-striker. This is done by holding the bat in line with the stump till aligned, then scratching a line in the pitch with their shoes. It makes sense when done by openers, but I have often seen batsmen coming in at number 7 or 8 and performing this ritual before facing the first ball on that end of the pitch.
Why do incoming batsmen mark their line even if they come in lower down the order? Shouldn't the line marked by the previous batsmen be enough?
Answer: The batsman isn't necessarily marking off-stump - they're marking their own individual preferred position. Some players will "take guard" on leg stump, others further across towards off stump.
Two other obvious issues:

The stumps are reversed for left and right handers. If you're a left hander coming in after a right hander, you're going to want a different guard.
Different players may take guard at different distances from the stumps so they'll need their mark in different places.


Diophantine equation $a^3 + b^3 + c^3 = 2$

Question: I have a pretty difficult math question that I have no idea even how to begin. Here it goes:

Find the nonzero integers $a$, $b$, $c$ such that $a^3 + b^3 + c^3 = 2$?

I would assume that at least one of the integers would be negative. Also, I got as far as $(a+b+c)^3 = 2^3$ but I'm not sure what good this will do.
(So, not to cower in shame I made a mistake above seeing as how  $(a+b+c)^3 \ne 2^3$. I admit I failed there. But how to work this equation?)
Comment: There are infinitely many non-zero solutions.
$$(1+6x^3)^3 + (1-6x^3)^3 + (-6x^2)^3 = 2$$ The key is start from a known solution $(a,b,c) = (1,1,0)$ of the equation and play with it.
Comment: How did you get to $(a+b+c)^3$?!
Comment: How did you get $(a+b+c)^3=8$?
Comment: Daw man, you're right. Sleep deprivation is causing my basic algebra skills to lack! Now, I'm even further behind that I 'believed' I was...
Comment: Source?${}{}{}$
Answer: In $1908$, A.S. Werebrusov found the following parametrization of $x$, $y$, and $z$ for the sum of three cubes $x^3+y^3+z^3$ equal to $2$:
$$
(1 + 6t^3)^3 + (1 − 6t^3)^3 + (−6t^2)^3 = 2.
$$
A further references here is L.J. Mordell, On Sums of Three Cubes, Journal of the London Mathematical Society $17$ (1942), 139–144. There are several discussions about the sum of three integer cubes, see here and the references given therein.


Shiny's tabsetPanel not displaying plots in multiple tabs

Question: I am trying to use multiple tabPanel controls within the tabsetPanel in Shiny. Lets say I start with only one tab using the following code:
mainPanel(
    tabsetPanel(
    tabPanel("Plot",plotOutput("distPlot"))
    )

The code runs fine and displays the plot in the tab.
But the moment I introduce another tab just to test the tabs out, both the tabs stop displaying any plots at all. I am using the following code:
mainPanel(
    tabsetPanel(
    tabPanel("Plot",plotOutput("distPlot")),
    tabPanel("Plot",plotOutput("distPlot"))
    )

Please note that I am trying to display the same plot in both tabs just to test if the tabs work. All I get are two blank tabs (if I use only one tab, the plot displays properly).
Would someone please be able to help me figure this out?
Answer: You assign "distPlot" to plotOutput's parameter outputId. "ID" indicates that this value has to be unique over the entire shiny app. You can assign the same plot to two different plotOutputs though:
runApp( list(

  server = function(input, output) {
    df <- data.frame( x = rnorm(10), y = rnorm(10) )
    output$distPlot1 <- renderPlot({ plot( df, x ~ y ) })
    output$distPlot2 <- renderPlot({ plot( df, x ~ y ) })
  },

  ui = fluidPage( mainPanel(
    tabsetPanel(
      tabPanel( "Plot", plotOutput("distPlot1") ),
      tabPanel( "Plot", plotOutput("distPlot2") )
    )
  ))
))

Comment: That makes complete sense. Worked perfectly. Thanks for your answer.
Answer: we can also write the above code in a single line as
tabsetPanel(
  tabPanel( "Plot", plotOutput("distPlot1"),plotOutput("distPlot2") )
)