Wordpress and Static content

Question: Can I serve static (.html) content from the same directory as a wordpress install. Where the static content is to replace some of the existing content in wordpress. We only want to remain using wordpress for maybe 2 sections of our site. We have otherwise created static pages for everything else.
I am thinking we can do some htaccess magic to get done what is ultimately desired. Which is replacing example.com/index.php (the "home") with index.html for example, while leaving the rest of the blogcentric views open to using index.php
is this possible or am I wrong in assuming I can lay over wordpress in this fashion?
Comment: Yes you can have static HTML files. No alteration to code nor `htaccess` files
Comment: if I understood correctly you can just make a folder at root and serve html from there. you can then create a redirect if you need to make the landing page from that root folder.
Comment: I want to serve html files less the extension. In the same directory as wordpress root, so I can seamlessly serve wordpress content through wordpress using the same url schema, basically without having to create a "blog" subdirectory. to put wordpress in. The pages today, already exist in Wordpress, but. We are breaking certain sections out that are more static in nature into HTML outside of wordpress, to get rid of some of the wordpresss overhead on those pages.
Answer: Yes, very possible to serve static from the same directory. Easy way would to be to create a home (or name whatever you want to be used as url) directory within the root directory of the WP install. Now when you go to yoursite.com/home it will serve the index.html, but shouldn't include the filename.
EDIT: also if you edit your wp_options table in your database and set the home option to http://yoursite.com/home it should act as your homepage.
Hope this helps!

Wordpress and Static content


Region bounded by $y= x$, $x=0$ and $y=15$, rotated about the x-axis and y-axis

Question: I am wondering if there is a difference between the answers of these when getting the volume of solid of revolution:
Region bounded by $y = x$, $x = 0$ and $y = 15$, rotated about the $x-axis$
Region bounded by $y = x$, $x = 0$ and $y = 15$, rotated about the $y-axis$
I tried the first one which is rotated about the x-axis and I got $2250π$.
For the second one I am confused on how to solve, is it possible that I use any of disk, washer, or shell method?
Comment: When you rotate around y-axis, you get a cone with height $h = 15$ and radius $r = 15$ so the volume will be $1125 \pi$. When you rotate around x-axis, it is the cone of same volume cut out from a cylinder of height $h = 15$ and radius $15$. So you get $2250 \pi$.
Comment: What did you get? What is $2250\pi$? Is it volume?
Comment: @VIVID Sorry, I forgot to indicate it. Yes, volume :)
Comment: @VIVID  Thank you, can I use any of the methods, disk, washer, or shell?
Comment: Can you describe those methods? I agree with @MathLover and so does my answer. Try this!
Comment: @SwaytheDestroyer'STD' Whatever method you use will get the same answer. Although usually we just pick whichever one is the easiest to integrate. In this case, it looks like disc (i.e. washer, just the same name) method is the easiest.

Although the *really* easy one is to simply not use calculus.
Answer: No objects are not the same.

Your region is the following triangle:

Rotation around the $x$-axis:

Rotation around the $y$-axis:

However, you should be able to see the relation between their volumes.
Answer: Volume of the figure produced by rotation is equal to $V = 2 *S * π * r$
Where S is area of cross-section, r is distance of the center of mass from rotation axis.
For x it is 10, for y it is 5, see pic.
So we get for the first case $2 *1/2 * 15^2 * 10 = 2250 π$
In second case $2 *1/2 * 15^2 * 5 = 1125 π$
plot of the area


how to get a post or get variable

Question: I have an html form that depending on the checkbox my java-script change it from GET to POST.  This piece of code is currently working.
My question is I have a variable on the server side that I need to get. The html variable is sent either as POST or GET, but not sure how to retrieve that variable regardless or what method the html uses.  I know how to get the variable as either POST or GET manually, but Not sure how to go about accomplishing this automatically.  Any suggestions?
$myVariable = $_GET['htmlVariable'] or $myVariable = $_POST['htmlVariable']

Comment: What you're looking for is `$_REQUEST` https://www.php.net/manual/en/reserved.variables.request.php
Answer: 1) Use $_GET if you know that data is coming via URL parameter
if (isset($_GET['htmlVariable'] && $_GET['htmlVariable'] != '') {
  $htmlVariable = $_GET['htmlVariable'];
}

2) Use $_POST if you know that data is coming via HTTP POST method
if (isset($_POST['htmlVariable'] && $_POST['htmlVariable'] != '') {
    $htmlVariable = $_GET['htmlVariable'];
}

3) If you don't know use $_REQUEST
if (isset($_REQUEST['htmlVariable'] && $_REQUEST['htmlVariable'] != '') {
    $htmlVariable = $_GET['htmlVariable'];
}

Answer: It sounds like you're looking to check if one of the two methods is found. If it is, use that method, and if not, use the other method. To achieve this you can use isset(), and note that you'll also want to check that the string isn't empty:
if (isset($_GET['htmlVariable'] && $_GET['htmlVariable'] != '') {
  $myVariable = $_GET['htmlVariable'];
}
else if (isset($_POST['htmlVariable'] && $_POST['htmlVariable'] != '') {
  $myVariable = $_POST['htmlVariable'];
}
else {
  $myVariable = 'something else';
}

Also note that the order in which you check for the methods may make a difference, depending on your logic.
Comment: Why all that complexity, why don't you just use `$myVariable = $_GET['htmlVariable'] ?? $_POST['htmlVariable'] ?? 'something else';`
Comment: @Kerkouch Because that is valid only in PHP 7.0+. Not necessarily the case...
Answer: If you are building any page that may require either input type, instead of trying to determine what is being provided, just use $_REQUEST.
if (isset($_REQUEST['htmlVariable'] && $_REQUEST['htmlVariable'] != '') {
    $htmlVariable = $_REQUEST['htmlVariable'];

}
Comment: @Obsidian Age gave me the answer I was looking for, but incorrectly sets the $htmlVariable to $_GET in each example and I don't have enough points to comment on his answer to point that out. Kerkouch also give the correct answer but only as a comment.

how to get a post or get variable


404 page for UI-Router Extras and future states when a state is not found

Question: I'm new to Angular and as I'm usually building quite big applications I started creating a lazy loaded navigation. Things work pretty well, I'm able to lazy load modules and states using AngularUI Router, UI-Router Extras and ocLazyLoad.
Here is a simplified version of my code: http://plnkr.co/edit/BXyvzy?p=info.
My only problem is defining a 404 page with Futures States of UI-Router Extras. When I'm trying to request a state that doesn't exist or is not on any future state, the application silently redirects to "/". As far as I can see the code responsible for this in the source is:
function otherwiseFunc($state) {
    $log.debug("Unable to map " + $location.path());
    $location.url("/");
}];

This function is called as part of another function futureState_otherwise, which is declared as otherwise function for $urlRouterProvider.
$urlRouterProvider.otherwise(futureState_otherwise);

How can I handle correctly a state not found with UI-Router Extras and future states? Should I rewrite a new function for $urlRouterProvider.otherwise or is there any better way?
Thanks in advance!
Comment: This is a bug in UI-Router Extras, sorry about that.  I meant to go back and hook up the stock $urlRouterProvider.otherwise declaration, but never got around to it.  You can follow https://github.com/christopherthielen/ui-router-extras/issues/39 to be notified when I fix this, but that doesn't help you with your immediate problem.
Comment: Ok, thanks! I'll follow the Github issue and I'll update this question accordingly.
Answer: I created a pull-request on ui-router-extras Github page proposing a solution and it has been merged to the project. So this problem will be fixed with the new release.
https://github.com/christopherthielen/ui-router-extras/pull/77
Comment: This came up in the reviews, not sure if I should flag or upvote... But if this is the answer, good job!
Comment: Yes, this feature is now working in ui-router-extras 0.0.11 and above.


Prove $\lim_{n\to\infty}\int_0^1\sqrt{x^n+1}~dx=1$

Question: I was messing around on my calulator and I noticed that for large values of $n$, $\int_0^1\sqrt{x^n+1}~dx\to1$. I would like to prove this. So, this is my question:
Prove $$\lim_{n\to\infty}\int_0^1\sqrt{x^n+1}~dx=1$$
Geometrically this seems to make sense; for all values of $x$ in the interval $[0,1)$ it is obvious that as as $n$ increases then $x^n+1$ is very close to $1$, but I would like a formal proof.
Many thanks for your help.
Answer: Note that $\sqrt{1+x^n} \le \sqrt{1+x^n+x^{2n}/4}=1+x^n/2$ for $x \ge 0$; so
$$
1=\int_{0}^{1}dx\le \int_{0}^{1}\sqrt{1+x^n}\;dx \le \int_{0}^{1}\left(1+x^n/2\right)dx=x+\frac{x^{n+1}}{2(n+1)}\bigg\vert_{0}^{1}=1+\frac{1}{2(n+1)}.
$$
Since the endpoints of this interval $\rightarrow 1$ as $n\rightarrow \infty$, the value of the integral must also approach $1$ in this limit.
Comment: +1 Thank you for the very intuitive answer!
Comment: (+1) ... Note that Bernoulli's inequality instantly yields $\sqrt{1+x^n}\ge 1+\frac12 x^n$
Comment: Alternatively by Cauchy schwarz $$\int_0^1 \sqrt{1+x^n}\le \sqrt{\int_0^1 (1+x^n)\int_0^1 1^2}=\sqrt{1+\frac{1}{n+1}}$$ and then squeeze as you did
Answer: The point is we can permute intergral and limit (see below):
$$\lim_{n\to\infty}\int_0^1\sqrt{x^n+1}~dx=\int_0^1\lim_{n\to\infty}\sqrt{x^n+1}~dx = \int_0^1 1 dx = 1$$
Justification of the permutation limit - integral :
The dominated convergence theorem states that :
If $(f_n)$ are functions such that :

$f_n$ are piecewise continuous functions
$(f_n)$ simply converges to $f$ which is piecewise continuous
$\exists \varphi : I\mapsto \mathbb{R}^{+}$ piecewise continuous and integrable such that $\forall n\in \mathbb{N}, |f_n|\leqslant \varphi$

Then :
The $f_n$ and $f$ are integrable on $I$ and $$\int_I f_n \rightarrow \int_I f$$
Here you can use $\varphi :x\mapsto 2$, which is of course integrable.
Comment: @math You do need to apply the results you added, brutal as it may be, because your initial argument could be applied to similar situation where you can not interchange limit and integral.
Comment: Very interesting, I didn't know you could do that, thank you. Do you have anyything you could refer me to to find out more about what you answered; ie about permuting integral and limits?
Comment: Ok thank you since all those wonderful answers (even though i deserve them). I edited my answer.
Comment: it's still false?
Comment: @math it is ok now.
Comment: @math The statement you added is not wrong. Calling it dominated convergence theorem is a bit strange. This is a result valid in the much more general theory of Lebesgue integration.
Answer: Since this tools may be advanced for you (as you wrote in the comment) I just would like to give you a counterexample that rises the main problem here: it is not true that you can, in general, exchange limit and integral, that formally means: $$\lim _{n \rightarrow \infty} \int_{a}^{b} f_{n}(x) d x \neq \int_{a}^{b} \lim_{n \rightarrow \infty}f_n(x) d x$$
Just as an example try to compute the followings: $$\lim _{n \rightarrow \infty} \int_{-n}^{n} \frac{1}{2n} d x =1$$ and $$\int_{-n}^{n} \lim _{n \rightarrow \infty} \frac{1}{2n} d x =0$$ Clearly you get they are not equal.
In general, to have such limit theorems either you need uniform convergence of a sequence of functions if you are dealing with Riemann integrable functions, or you need more powerful tools like Lebesgue integral and the Lebesgue theory of integration.
What you are applying is what is known as the Lebesgue Dominated Convergence Theorem. All what you need is to consider the sequence of functions (with values in $[0,1]$) given by $$f_n(x)=\sqrt{x^n+1}$$ and noticing that we have the following pointwise convergence where $f(x)=0$: $$f_n(x) \rightarrow f(x) $$ and the following integrability condition $$|f_n| \le g \text{  for all  } n \in \mathbb{N}$$ where $g$ is an integrable function (in this case just pick $g$ equal the constant function 2 on $[0,1]$, that has clearly finite integral and dominates all the $|f_n|$). Then, since all this holds in your example, you can exchange limit ans integral and conclude the result.
You could also apply what is known as the Monotone Convergence Theorem (a bit modified) in this case for monotone decreasing sequences.
Comment: @EroSennin Adding that $g(x)=2$ is a good choice will complete the answer.
Comment: Woops, my bad! Thanks
Comment: It is there indeed :) Thanks anyways
Comment: This looks like an excellent answer, but unfortuantely it is too advanced for my current level of study. Your help is very appreciated though :)


Close html5 HTMLNotification when link is clicked

Question: I am using createHTMLNotification for a chrome extension.  The html for the notification includes a link in it.  What im trying to figure out is how to close the notification when the link is clicked.  My code is following
var notification = window.webkitNotifications.createHTMLNotification(
    "notification.html"
);
notification.show();

The code on the notification.html page fills in the data.  This page includes the jquery library.  When I try to do:
$('#title > a').click(function() {
    notification.cancel();
}

This of course does not work because notification is unknown on this html page.  I have also tried to do a notification.onshow during the first part of the code where i create the notification, but this as well produced no results.
Answer: Well I figured it out.  It was actually a pretty simple fix. All you have to do is in the click event for the href in the notification, add window.close().  This is because according to W3C specification it is a separate window so you can treat it as such
Answer: You can try following to set the focus to newly opened tab and close the notification on the way
notification.onclick = function(x) { window.focus(); this.cancel(); };
notification.show();


How to hear the numbers?

Question: There's this guy on youtube that I'd watch, he has a channel called 'Jazz Theory'. Anyway, one profound thing I heard him say is that you're not playing by ear until you can hear the numbers in anything you listen to.
And by numbers, what chord number is playing (I-VII), what melody number is playing (1-7). So as you're listening to music you constantly hear the different numbers being played. I think this is very useful.
So as an example, if I take the chords of the major scale. There's 3 major chords (I, IV, V) and 3 minor chords (ii, iii, vi) and one diminished. The diminished chord isn't used as much as the others. The root chord is easiest to hear as everything resolves to it. And it's relatively simple to hear if a chord is major or minor. However, sometimes it's hard to distinguish between the ii and iii, and the major chords IV and V. Although the V is easier as it sounds like it wants to resolve to the I.
I have a harp and sometimes I'll just randomly pick a chord or note without looking and try to figure out what number it is within my scale.
I'm still practicing this and I'm trying to think of ways to be better at this. But I was wondering, for those of your that can hear numbers. Do you have any tips or exercises on how you did it?
Comment: This is called "aural skills" or "ear training." If you attended a conservatory, you'd take classes dedicated to this skill for at least 2 years. There are many educational approaches, so this question is a little broad. But overall it's all about active listening. One of my colleagues learned this skill by forcing himself to transcribe an entire series of jazz standards by listening, playing on the keyboard, and writing it all down with pencil and staff paper. I learned it by composing a ton of songs in various styles.
Comment: Eventually, the number part fades, and one hears an interval, or a couple of chords, and plays them straight back. Rather like looking at music, recognising a G, then playing it. The middle part goes, and we see a note and play it without conciously thinking 'it's a G.' The idea is good, and works for a lot of people. As ever, lots of repetition.
Comment: I challenge the question's unspoken assumption: that "hearing the numbers" is a useful skill the OP needs to acquire. If you can understand chord sequences or tunes, or if you can even repeat tunes or series of chords you heard, then who needs proof that you know the numbers? Knowing the numbers requires additional cognitive load to "verbalise" something about the music you hear. You'd need this skill to communicate your ideas to others (e.g. when writing an answer to a Music.SE question) but I dispute the idea that you need to be able to do this while playing or listening to music.
Comment: Long before I went to a conservatory I tried to accompany songs by the I-IV-V cadence and also when teaching little children guitar my first goal aside of showing the chord patterns was that they "hear" when to change and also get a sense for the form of the songs.
Comment: the question may be related to this:
https://music.stackexchange.com/questions/90436/music-practice-for-by-ear-musicians/90452#90452
Answer: Relate the intervals and chord progressions to melody fragments and songs that you're familiar with, and let your brain's pattern recognition do the work. That worked best for me, and it seems to be the most common heuristic for ear training among the other people I've asked.
To use my own examples: Minor third is the Brahms lullaby, minor 2nd is the Jaws theme, down a fourth to the 5 below root is like a polka bassline, 3-2-1 is three blind mice, up a major seventh I cheat a bit and include the octave from the beginning of the "over the rainbow" melody, 1-3-5 I just hear the major chord triad, 1-4-5 is Blitzkrieg Bop, and so on. When you relate the interval distance to the melody you can already recognize in a split second, then you've got workable relative pitch.
For chord progressions, the general wikipedia article on "Chord progression" and the "See also" links at the bottom cover the common forms. From the root to the basics of dominant/subdominant with I-V and I-IV and I-IV-V, to all the common 4-chord ones like the Let It Be and Stand By Me variants (I-V-vi-IV / I-vi-IV-V) (these two wiki lists are some good unintentional comedy, and obligatory link to the classic "four chord song" routine from Axis of Awesome). And that's just two examples of the super common chord progressions, you also have the "Rhythm Changes" (I-vi-ii-V) from "I Got Rhythm" which covers most of the jazz songbook along with the ragtime and stomp, and several others if you go down the rabbit hole. Once you can identify the 1 chord within a progression from how it feels when it resolves, spotting the others is just intervals again with extra notes helping your pattern recognition for songs you know.
Warning: After you develop enough of these associations, you won't be able to turn it off -- you'll be subconsciously "hearing the numbers" when you hear music anywhere.
Comment: * songs that you're familiar with, and let your brain's pattern recognition do the work.* that's what I mean: These patterns are the schemes and the fisher mans net with wich we are "fishing" information in our universe.
Answer: Learning by doing:
Sing and play along. (Most important: listen to the bass.)

Many children songs use only the tonic and dominant: I-V. As you may know they begin and end at the tonic (home chord).

Progressively you can choose songs using also the subdominant. Here you can learn to differ between dominant and subdominant (e.g. Blues and Rock).

Next step  will be to identify the secondary dominants that arise in the semi finals and bridges.

There are some typical chord progressions like the subdominant cadence, the "fifties progression", the 1625 progression and its variations. By practicing these patterns you will recognize them when they are used in a piece.

Some tips:

Look for sheet music of songs you know and like under images, chords for piano, guitar, lyrics with chords. Transcribe the chords into the numbers. Play the chords by letters, by numbers, by heart, and

Play along to songs slowing down the tempo of youtube videos, search for the chords, (by trial and error), stop the video, notate the number, etc.

Listen to sonatinas and sonatas in C or G major. They have typical patterns (look up the sonata form: exposition..

Write your own arrangements in numbers using the patterns and play them. Invent your own melodies that fit to your patterns.

I've posted here some lists of songs using chords in a progressive form. You'll find them if you look up under chord progression, songs ...
(I'll try to find them and post the links).
Well, this is the last one containing some song titles:
Music practice for "by ear" musicians
Comment: +1 to listening the bass, in contemporary songs. Just loop through your favorite pop song albums like Nickelback or Eagles, and use good headphones or speakers. Try to recognize the bass notes and then play along.
Answer: I'm going to basically give the same advice I did in another question... thank you copy and paste.
Ear training took a while for me to get the hang of. What my Aural Skills professor taught me was a simple way to train for chord identification, though keep in mind, just like any skill it takes regular practice.
First, begin with tonicization. I highly recommend learning solfege for this. If you don't already know solfege or can't dictate melodies, work on that first. Instead of hearing the chords, learn to hear the melodies. The same skill involved for hearing chords is practiced with melodies, and I recommend learning that first bexause chords are far more advanced.
At the beginning of a piece I want to notate (or just hear the numbers, so to speak) chords for, I use the pattern Do-Mi-Sol-La-Sol-Fa-Re-Ti-Do for major keys.
When a chord is being played, try to match (singing or playing) the solfege pattern of chords to whatever chord is being played. The tonic, for example, is Do-Mi-Sol. Memorizing the solfege for each chord is incredibly beneficial, regardless of if you're a vocalist or harpist.
It is also imprtant to note that for Ear Training, most chords are played in inversions that lend to being played simply on a keyboard.
Here's a "chart" to help.
I: Do-Mi-Sol
ii: Re-Fa-La
iii: Mi-Sol-Ti
IV: Fa-La-Do
V: Sol-Ti-Re
vi: La-Do-Mi
vii°: Ti-Re-Fa
And that will bring us back to Do-Mi-Sol ;)
Eventually, you do this often enough that the solfege and numbers become synonymous and you don't need to run through the notes individually and will be able to hear the "numbers" pretty much immediately.
While certainly more complex than simply learning to recognize chords on their own, this method is far more comprehensive and prevents hiccups such as not being able to differentiate minor chords or the fourth and fifth.
If you need help for practice, my old Aural Skills professor publicly posts lessons and excercises on his YouTube channel. If you search Ear Training within it, you should find exercises which could be of use. His channel is simply "Dan Cutchen".
Good luck!

How to hear the numbers?


Why are quadratic forms that satisfy these conditions isotropic?

Question: I'd like to know why all quadratic forms satisfy the following:

1) If $F$ is an algebraically closed field, for example, the field of complex numbers, and $(V, q)$ is a quadratic space of dimension at least two, then it is isotropic.

And:

2) If $F$ is the field $Q_p$ of p-adic numbers and $(V, q)$ is a quadratic space of dimension at least five, then it is isotropic.

Any insight on these two is greatly appreciated.
Comment: recommend Cassels, inexpensive http://store.doverpublications.com/0486466701.html
Comment: You need to state clearly what is $(V,q)$ and what means isotropic. Possibly it reduces to *every positive definite matrix is diagonalizable over the algebraic closure*.
Comment: Isotropic means nontrivial kernel and $(V, q)$ is simply the quadratic form $q:V \rightarrow F$
Answer: On the first one, from Cassels. He  has characteristic not two. He does not say that all forms can be diagonalised over a field, he says that there is a normal basis. We use the polarization identity to get an inner product $\phi,$ a normal basis has $\phi(u_i, u_j) = 0$ when $i \neq j.$  Therefore the form applied to a vector becomes $\sum a_i x_i^2.$ Over an algebraically closed field, we can take all but the first two $x_i$ zero, then take $x_2 = 1,$ and solve for $x_1$ in $a_1 x_1^2 + a_2 = 0.$
The dimension 5 bit is a longer story. I recommend Cassels because he is focused on the rational numbers and the rational integers, he does isotropy for the $p$-adics in great and understandable detail. This includes tables for the Hilbert norm residue symbol, pages  43 and 44, with which the isotropy results are proved, pages 58-60 primarily. Your question is Lemma 2.7, page 60. The proof is pigeonhole on the $p$-adic squareclasses
Comment: @reuns yes, my $x_i = \langle x,u_i\rangle.$ Cassels does use the word diagonal later in the book.
Comment: So $\sum_i a_i \langle x,u_i\rangle^2$ the diagonalized form. And what is special over $\mathbf{Q}_p$ (and $\dim(V) \ge 5$) ?
Comment: @reuns, he shows that any ternary represents all but one p-adic squareclass. The remaining binary part (out of dimension 5), rather $-1$ times the binary section, represents half the squareclasses. Thus there is a nonzero element represented by both pieces. Hmmm, then he says he has already proved it for prime $p \neq 2$ in Lemma 1.7, Corollary, of Chapter 3, page 41. Good to know.
Comment: Tks, your [answer](https://math.stackexchange.com/questions/89138/isotropy-over-p-adic-numbers) and [this](https://en.wikipedia.org/wiki/Hasse%E2%80%93Minkowski_theorem) gives some clues


Azure Purview - Deleted folders in ADLS2

Question: We are scanning ADLS Gen 2 data lake successfully with Purview. However, if a folder is deleted in the lake and you re-scan, the scan does not remove the deleted folder. The deleted folder remains in Purview, but the last modified date (from the scan) remains as the previous scan date/time from when it was present. How can I purge these now invalid entries? Removing the previous scan does not work. Removing the entire source from Purview leaves the scan results behind in the register and a new scan does not clean them up. There is also no manual delete/purge option. The only option seems to be to remove the entire purview account from Azure, redeploy and reconfigure everything.
Am I missing a trick?
Answer: Reading to this https://learn.microsoft.com/en-us/azure/purview/concept-detect-deleted-assets this mostly seems like a expected behavior, did you try scanning more than twice post 5mins intervals.
To keep deleted files out of your catalog, it's important to run regular scans. The scan interval is important, because the catalog can't detect deleted assets until another scan is run. So, if you run scans once a month on a particular store, the catalog can't detect any deleted data assets in that store until you run the next scan a month later.
Comment: I scanned, deleted and scanned again. Like you say, maybe I need to run a couple of scans post delete but I would expect a scan that doesn't yield a match against a prior should result in a delete. Certainly the scan timestamps show that the two scans found different matches.


how to check in ajax form callback if form for failed validation

Question: I have a form and on and implemented a ajax submit callback which calls this function:
function popover_ajax_callback($form, &$form_state) {
    // watchdog("ajax_callback", "testing ajax callback", array(), WATCHDOG_ALERT);
    return '
' . $form_state['values']['first']['field_firstname'] . '
';
}

How do I check if the form failed or passed validation within this function?
Answer: function popover_ajax_callback($form, &$form_state) {
  $errors = form_get_errors();
  if( $errors ) {
    // error detected, do something
  } else {
    // everything is ok
  }
}

but your return value is not ok. You need to return an renderable array. You may want to try someting like this:
return array('#markup' => '
' . $form_state['values']['first']['field_firstname'] . '
');

Comment: actually my return value works. Is this just not following the standards then?
Comment: yeah, something like that :) but if it works, I think it's ok. it isn't such a big deal...
Comment: A year later but I now understand I should have used a [renderable array](http://drupal.org/node/930760) as return value ;)


Função PL/PGSQL Postgresql

Question: Tenho a seguinte função :
create function sppreenchecombomunicipio(p_uf text) returns TABLE(MUNICIPIO
text, COD_MUNICIPIO int)
AS $$
begin
return query select tb_municipio.municipio, tb_municipio.cod_municipio  from tb_municipio  where    UF = p_UF; end;
$$LANGUAGE plpgsql;

Ela esta funcionando, porem tenho lido na documentação oficial do postgresql que exitem outras formas de fazer esta funcção.
Qual seria a forma "correta" , ou esta forma que postei é a "correta"?
Exemplo da documentação que eu poderia adaptar para meu caso:
CREATE OR REPLACE FUNCTION get_all_foo() RETURNS SETOF foo
AS $BODY$
DECLARE
r foo%rowtype;
BEGIN
FOR r IN SELECT * FROM foo WHERE fooid > 0 LOOP
    -- can do some processing here
    RETURN NEXT r; -- return current row of SELECT
END LOOP;
RETURN;
END
$BODY$
LANGUAGE plpgsql;

Comment: Eu faço do mesmo jeito que você usa e funciona para mim. Eu uso para buscar os produtos, tenho uma tabela filha dos preços e organizo por índice.
Answer: A única observação é que não é necessário plpgsql, basta sql:
create function sppreenchecombomunicipio (p_uf text)
returns table (
    municipio text,
    cod_municipio int
) as $$
    select tb_municipio.municipio, tb_municipio.cod_municipio
    from tb_municipio
    where uf = p_uf;
$$ language sql;

Função PL/PGSQL Postgresql


Does domain of a first order language contain valuations? Quite confused about satisfiability?

Question: The domain of a first order structure contains all possible inputs to the functions of the first order structure. Does it also contain all possible outputs of the functions? (Answered in comments as yes)
Are valuations also elements of the domain? Are these two equivalent? I'm getting really confused about the notation for satisfiability.
enter image description here
Comment: Please, do not use images.
Comment: Yes; the "objects" belonging to the domain are the possible values for the variable. Thus, they are the possible "input values" for the functions. The function symbols of the language are interpreted as function on the domain whose output values are themselves objects of the domain
Comment: Consider the simple example of the language of *arithmetic* with $+$; it is interpreted as a binary function (sum) having a pair of numbers as input and a number as output $+ : \mathbb N \times \mathbb N \to \mathbb N$.
Comment: Thank you! Does the domain also contain possible valuations? I'm getting quite confused about the notation for valid when mappings are included.                                                   In other words:      M |=p[x|->d] (y)    and    M |=d (y)    are equivalent   if x==y?
Comment: Sorry, I've edited the main question to include a picture of what I mean, could you take a look?
Answer: Long comment
The "objects" belonging to the domain are the possible values for the variables. Thus, they are the possible "input values" for the functions.
The function symbols of the language are interpreted as function on the domain whose output values are themselves objects of the domain.
Consider the simple example of the language of arithmetic with $+$; it is interpreted as a binary function (sum) having a pair of numbers as input and a number as output $+ : \mathbb N \times \mathbb N \to \mathbb N$.
Valuations (aka: variable assignment functions) are function from language to domain of the interpretation that assign to each variable (and then to terms) an object of the domain. Thus, the "outputs" of valuations are objects of the domain.
Trying to mimic your symbols, the basic property of satisfaction that involves valuations is:

let $M$ a model, $A(x)$ a formula with free var $x$ and let $v$ a variable assignment such that $v(x)=d$ where $d$ is an element of the domain of $M$; we have that $M,v \vDash A(x) \text { iff } M \vDash A[x \leftarrow d]$.


Can invite module work for existing users?

Question: I'm using UR and invite module.  I'm trying to make it so you can "friend" "existing" users.  I don't know why Invite is only set for e-mail address invites for just non-users.  I want A FB style "friend" request.  Is there a way to fanangle this though these modules? Or, do I have to go in another direction with it?
Comment: Are you sure you're using [Invite](http://drupal.org/project/invite) in Drupal 7? It doesn't seem to have even a dev version out there for 7.
Comment: http://drupal.org/node/20967/release
Comment: Could you even accomplish something like this in 6?
Answer: The Invite module serves to invite those who are not yet existing users to become ones. That's why you cannot use it to invite existing users.
Anyway, when using UR, at existing user's public profile, there's a Become USERNAME's friend link which you can use to befriend an existing user. This is an equivalent of the Facebook Add Friend button.
With the UR's user_relationship_invites module enabled, you can give users the option of specifying a relationship when inviting new users, e.g. friend. Together with the Contact Importer this would be an equivalent of the Facebook Find friends page.


Como fazer para abrir um UserForm com o mesmo nome de um botão? Linguagem VBA

Question: Meu programa é formado por 20 botões e 20 UserForms. Eu queria simplificar o programa e fazer uma Sub Rotina única.
Cada vez que eu pressionar um botão, a Rotina VerificarBotaoPrecionado analisa o nome do botão e abre o UserForm com o mesmo nome do botão.
Botões: Foto1, Foto2, ..., Foto20
UserForms: Foto1, Foto2,... Foto20
Alguém poderia me ajudar?
Answer: Utilizando a função ShowAnyForm do Cpearson é possível realizar isto com um módulo de classe.
Um exemplo com a seguinte árvore de projeto VBA:

Formulário
Um exemplo com o seguinte Formulário:

Um formulário com dois botões com o nome do formulário que deve ser aberto.
E com o seguinte código:
Private collBtns As Collection
Private Sub UserForm_Initialize()
    'Créditos: www.andypope.info
    '          www.cpearson.com/excel/Events.aspx
    Dim cls_btn As Classe1
    Set collBtns = New Collection
    For Each ctrl In Me.Controls
        If TypeName(ctrl) = "CommandButton" Then
            Set cls_btn = New Classe1
            Set cls_btn.btn = ctrl
            collBtns.Add cls_btn, CStr(collBtns.Count + 1)
        End If
    Next ctrl
End Sub

Módulo de Classe
Este código é inserido no módulo de classe Classe1
    Public WithEvents btn As MSForms.CommandButton

Private Sub btn_Click()
    ShowAnyForm (btn.Name)
End Sub

Private Sub ShowAnyForm(FormName As String, Optional Modal As FormShowConstants = vbModal)
    'http://www.cpearson.com/Excel/showanyform.htm
    Dim Obj As Object
    For Each Obj In VBA.UserForms
        If StrComp(Obj.Name, FormName, vbTextCompare) = 0 Then
            Obj.Show Modal
            Exit Sub
        End If
    Next Obj
    With VBA.UserForms
        On Error Resume Next
        Err.Clear
        Set Obj = .Add(FormName)
        If Err.Number <> 0 Then
            MsgBox "Err: " & CStr(Err.Number) & "   " & Err.Description
            Exit Sub
        End If
        Obj.Show Modal
    End With
End Sub

Neste, o evento de cliques dos botões é declarado em btn_Click().
Que com o clique do botão, irá abrir o formulário de mesmo nome do Botão com a função ShowAnyForm.
As opções que você pode utilizar para mostrar o formulário são vbModal e vbModeless
Exemplo:
Private Sub btn_Click()
    ShowAnyForm btn.Name, vbModal
End Sub
Private Sub btn_Click()
    ShowAnyForm btn.Name, vbModeless
End Sub

Resultado
Comment: Adaptei no meu projeto e funcionou perfeitamente. Muito obrigado
Comment: Caro amigo, como faço para colar no texbox1 do userForm ativo o valor da célua A1 da planilha1?

"UserFormAtivo".textbox1.value = Sheets("plan1").range("a1").

Como faço para declarar a instrução que signifique "UserForm ativo"?


Help finding the right test

Question: I am running an experiment and now it is time to do some analysis, but I am having a hard time figuring out the right way to analyze my data. I have a number of questions, but first let me give you some context.
This is a behavioral experiment, where the setting is as follows:
i) There are 2 conditions, let's call them A and B.
ii) Each participant is randomly assigned to either A or B.
iii) Regardless of the condition, each participant goes through 8 trials.
iv) At each trial, we show a stimuli to the participant, and then record whether they exhibit a certain behavior. So we have a binary variable, call it Target_Behavior, which takes the value 1 is the participant exhibits this behavior, and 0 otherwise.
The first thing I want to study is whether there is a significant difference between the two conditions, regarding the frequency participants exhibit the target behavior. As you can see, for each participant we have 8 measurements, so it is a repeated measures setting, but I don't know how to choose the right test that takes this into account.
Furthermore, I don't know whether my data allows for any parametric assumptions, so I am only using non-parametric tests, which is detrimental to the power of my tests.
So far, I have been using a very simple (and probably wrong) solution. I am looking at each trial on its own. This way, for any trial we have only a single measurement for each participant, so, for example considering trial 1, I make a list containing the values of Target_Behavior for condition A, and the same thing for condition B. Finally, I do a chi-square test, comparing the two lists.
I am pretty sure this is suboptimal though, while it also poses an extra challenge. I am convinced there is a significant difference between conditions A and B, but the test I just described only gives significant results if there is a difference of about 30% in frequency between the two conditions. If they are at 20% it turns out to be not significant, however, this doesn't seem right to me, 20% is a huge discrepancy!
I have about 20 participants in each condition, if this is of any help.
I would really appreciate your help in figuring the right way to deal with this situation. I have been looking online for weeks, and still I haven't found a solution. I have some additional questions, but for now I think this is the most important one.
Thank you in advance!
Comment: It is my first PhD experiment, so I am getting a bit anxious over finding the right test. I guess that simply written, the question I would like you to help me with, boils down to: how can I test whether there is a difference between 2 conditions, if for each participant I have 8 measurements (i.e. trials), where each measurement is of the form "Success" (encoded as 1) or "Fail" (encoded as 0)?
Comment: For future reference, a far better time to be considering what analysis to do is when you are planning the experiment.  Since this is early in your research, maybe you shouldn't be testing at all, but *exploring* the data and mining them for testable, interesting hypotheses.  That's a fully legitimate exercise.
Comment: I totally agree with that, but in my domain it is time consuming to find suitable participants, so my supervisor insisted to first formulate our hypothesis and then perform the experiment to either confirm it or not. Perhaps if my next experiments involve easier to find groups, we are going to perform a kind of exploratory analysis. Currently I am trying to get the resources needed to be able to know what analysis to use under each possible setting. If you have any references or books on the topic, I would be happy to know.
Answer: Caveat: You don't state it explicitly but you imply that, for each participant, their trials are independent with the same probability of success. In this case, the number of successes is a binomial random variable with size = 8 and unknown probability p.
Update: In the comments you explain that the independence assumption holds but the success probability may change as participants become familiar with the experiment. In this case, the trials are binomial random variables with size = 1 and unknown probability pt. You can still use binomial regression after updating the model to include a fixed effect t for the sequence of trials.

We can compare conditions A and B with a binomial regression. We assume that:

Each participant goes through a fixed number of trials (not necessarily the same number of trials).
The success probability of each participant is a function of their group assignment + random noise.

Under this model, conditions A and B have effects α and β, and the average success probabilities are a function of this effect. [Mathematically, effect = logit(probability).]
Finally, we test if there is a difference between conditions A and B with a t-test on the difference in effects, β - α.
The following code illustrates how to do this analysis in R.
library("broomExtra")
library("lme4")

set.seed(1234)

n <- 20
trials <- 8

alpha <- 0.5
beta <- 2
sigma <- 0.1 # std. deviation of participant random effect

id <- seq(1, 2 * n)
condition <- rep(c("A", "B"), each = n)

# On average participants in group A have effect alpha
# and participants in group B have effect beta
effect <- ifelse(condition == "A", alpha, beta)
# Add random noise to each participant's effect.
effect <- effect + rnorm(2 * n, sd = sigma)

aggregate(effect, list(condition), mean)
#>   Group.1         x
#> 1       A 0.4749336
#> 2       B 1.9422930

# The success probability is the inverse logit of the participant's effect.
prob <- plogis(effect)

# Finally generate the outcome: number of success in a fixed number of trials.
successes <- rbinom(2 * n, size = trials, prob = prob)

Let's start with a simpler model that assumes participants in each group have exactly the same probability of success. This is not true in the simulation and it's also not a reasonable assumption in general.
model1 <- glm(
  cbind(successes, trials - successes) ~ condition,
  family = binomial(link = "logit")
)
tidy(model1, conf.int = TRUE, conf.level = 0.95)
#> # A tibble: 2 × 7
#>   term        estimate std.error statistic     p.value conf.low conf.high
#>   <chr>          <dbl>     <dbl>     <dbl>       <dbl>    <dbl>     <dbl>
#> 1 (Intercept)    0.674     0.167      4.03 0.0000548      0.352      1.01
#> 2 conditionB     1.67      0.326      5.12 0.000000299    1.06       2.34

It's more appropriate — and in the simulation definitely correct — that participants effects are not fixed but random, with mean equal to the condition effect.
model2 <- glmer(
  cbind(successes, trials - successes) ~ condition + (1 | id),
  family = binomial(link = "logit")
)
tidy(model2, conf.int = TRUE, conf.level = 0.95)
#> # A tibble: 3 × 9
#>   effect   group term   estimate std.error statistic  p.value conf.low conf.high
#>   <chr>    <chr> <chr>     <dbl>     <dbl>     <dbl>    <dbl>    <dbl>     <dbl>
#> 1 fixed    <NA>  (Inte…    0.704     0.200      3.51  4.42e-4    0.311      1.10
#> 2 fixed    <NA>  condi…    1.72      0.367      4.69  2.67e-6    1.00       2.44
#> 3 ran_pars id    sd__(…    0.440    NA         NA    NA         NA         NA

In the summary table, conditionB estimates the effect difference β - α between conditions A and B. Since this is a simulation, we know that the true difference is β - α = 2 - 0.5 = 1.5. Its estimate from the data is conditionB = 1.72 with a 95% confidence interval [1.00, 2.44]. The t-statistic for the null hypothesis that there is no difference between the conditions is 4.69 and the corresponding p-value is 2.7e-6. So there is strong evidence to reject the null, which of course doesn't hold in the simulation.
The effects α and β are logits (log odds) of the success  probabilities; the difference  β - α is the log odds ratio. It's easy to convert effects to probabilities with the inverse logit transformation.
# Pr{success in group A}, Pr{success in group B}, Pr{success in B} - Pr{success in A}
c(plogis(alpha), plogis(beta), plogis(beta) - plogis(alpha))
#> [1] 0.6224593 0.8807971 0.2583377
# estimate of Pr{success in B} - Pr{success in A}
plogis(1.72 + 0.704) - plogis(0.704)
#> [1] 0.2495652

Comment: Thank you very much for your help. You are right, I didn't say anything about the independence of the trials, but the thing is that it is a bit complicated. Although there is no direct dependence between trials, as participants get familiar with the stimuli, they are expected to exhibit the targeted behavior more. Trials themselves are independent, but it is a latent variable of "familiarity" that could (or maybe should) influence their behavior. I hope I explain it clearly enough, does it make any sense to you? Do you maybe have a suggestion for this case or at least some references to study?
Comment: Binomial regression can incorporate a possible "learning with time" effect. For example consider the model *Yij = condition + time + (1 | id)* where *Yij* be the *j*th trial of the *i*th participant. This model has fixed condition effect, fixed time effect and a random participant effect. You can also let *time* interact with *condition*.
Comment: The model I proposed first is equivalent to *Yij = condition + (1|id)*. So you can see how you can add complexity within the same framework of binomial regression. Even add a non-linear time effect using splines. However, I'd suggest you start simple and add complexity step by step only if the complex model fits the experimental data better.
Comment: You cannot imagine how helpful your answers have been! I have a couple of somehow silly question though; i) the variable "time" you include in the model is the number of trial, right? ii) How should I interpret the final coefficient? For example, in your initial example, what the value of 1.72 means? The question I really want to answer is if there is any significant difference across conditions. After that I would also like to study the interaction of condition and trial, as you suggested. In general, do you have any references about experimental designs and appropriate statistical analysis?
Comment: Perhaps *time* wasn't the best choice of term. Yes, I mean *order* / *number* of trial. Chronological *time* could make sense in a situation where we expect participants practice between trials to improve their change of success. But your description of *familiarity* suggests *order* of trials makes more sense. And I've updated the answer to explain the relevant statistic.
Comment: About experimental design, I found this CV [thread](https://stats.stackexchange.com/q/1815/237901). But instead I'd suggest to ask the advice of your PhD advisor or even better the professors & other grad students in your program. This way you'll find recommended textbooks in your area of study. [Aside note: Commenters don't get notified of your replies unless you tug them with @username.]
Comment: Thank you very much for everything :) So if I got it right, I should format my file as: _User id_, _Number of Trial_, _Condition_, _Success_, and then fit a model that predicts _Success_, using fixed _Number of Trial_ and _Condition_ effects, as well as a random _User id_ effect. This would also mean that for each participant I would have repeated values in _User id_ and _Condition_ columns. Should I specify anything as a factor though? I am not really sure, but if I am to study differences among trials, shouldn't I convert them to factors? Is it fine to use _User id_ as an integer?
Comment: Unfortunately, my advisor is not really an expert on statistical analysis, while my peers are also mostly familiar with standard tests like chi-square. Getting in touch with a professor from a more technical department is an option, I am just a bit hesitant, because I feel like my questions are going to be boring and make me seem clueless, which I am, but so far I have been trying to deal with this fact on my own by looking for online resources.
Comment: I suggest the following coding: Success is 0 or 1, ID is a unique integer or a factor, Condition is "A" or "B", number of trial is an integer. I wouldn't make #trial a factor because then the sequential ordering is lost. So trial #1 is (potentially) as different from trial #2 as it is from trial #8. Your hypothesis is that participants get better with each trial. Without having seen any data I'd be interested in three hypothesis about the #trial effect: no #trial effect, linear effect, smooth nonlinear effect. In this order.
Comment: Start simple, esp. since you are also learning about stats. Work on the #trial effect vs linear effect comparison. You can ask for more feedback on CV (in a new question); there are model checks that you can/should do to confirm that a particular model makes sense for your data. The stakes are high because you spent time & effort on your experiment, so you shouldn't worry about asking for help so that you can draw conclusions from the data.
Comment: On the topic of (text)books about statistics, here is a very opinionated & biased list: [The Art of Statistics](https://www.amazon.com/Art-Statistics-How-Learn-Data/dp/1541675703/), [R tutorials](https://ww2.coastal.edu/kingw/statistics/R-tutorials/index.html), [Mixed Models](https://m-clark.github.io/mixed-models-with-R/). A mixed model has both fixed effects (eg. condition) and random effects (eg. participant).
Comment: Thank you for the suggestions and all your help. I will probably start a new thread as soon as I advance my analysis a bit.

Help finding the right test


Does piecewise differentiable curve mean $C^1$-curve in this context?

Question: Munkres - Topology p.405

Lemma 66.3
Let $\gamma$ be a piecewise differentiable loop in the complex plane; let $a$ be a point not in the image of $f$. Then, $Wnd(\gamma,a)=\frac{1}{2\pi i} \int_\gamma \frac{1}{z-a} dz$.
Theorem 66.4 (Ahlfors version)
Let $C$ be a simple closed piecewise differentiable curve in the complex plane. Let $G$ be the interior of $C$. If $f$ is analytic on an open set $\Omega$ containing $G$ and $C$, then for each point $a$ in $G$, $F(a)=±\frac{1}{2\pi i} \int_C \frac{F(z)}{z-a} dz$

Munkres wrote that this version of Cauchy integral formula is in Ahlfors's text, but Ahlfors, in his text, defines a "piecewise differentiable curve" as a piecewise $C^1$ curve.
Nevertheless, does this theorem hold for a loop which is piecewise differentiable but not piecewise $C^1$?
Answer: The theorem is even true for rectifiable curves (but this takes quite some effort; even defining what the integral is takes some work).
In most situations, the exact formulation doesn't matter all that much. Recifiable, piecewise differentiable curves can be approximated well enough with piecewise $C^1$-curves for example.
You want to exclude some pathological examples though: a closed loop which is piecewise differentiable doesn't have to be rectifiable. A piece of the curve could be the parts of the graph $y=x^2 \sin (1/x^4)$ (or similar) and it's not clear how to define curve integrals along such beasts.
Comment: Is there a text or a page proving this for rectifiable curves? I can define Riemann-Stieltjes integral along bounded variation, and I'll try to prove this for non-differentiable rectifiable curves, but I need a reference so that I can check when I get stuck proving it.
Comment: @Rubertos The most general treatment I have seen in print is in Tutschke, Vasudeva: [An Introduction to Complex Analysis: Classical and Modern Approaches](https://books.google.se/books?id=puXBwu7ztkwC&pg=PR6&lpg=PR6&dq=tutschke+vasudeva&source=bl&ots=Jmsi5OqIhP&sig=VE9H5vuJDxmZkVv2pXCqrT9E3Yg&hl=sv&sa=X&ved=0CD8Q6AEwBGoVChMIodT9-fv4xwIVSd0sCh23bQ43#v=onepage&q=tutschke%20vasudeva&f=false) The "introduction" in the title is a little misleading, since it's a good idea to have seen measure theory and functional analysis before trying to read it. (Section 4.6.3 seems relevant for your question.)


Unity3D using OnTriggerStay

Question: I'm using the event OnTriggerStay2D to destroy an object, the reason i'm using this instead of OnTriggerEnter2D is because i'm dragging the object using the touchscreen, and i want to destroy it after it is released, the problem i have is that OntriggerStay2D is not always called, so sometimes the object is not destroyed after it is released and it has to be moved again to work, i've read the docummentation from Unity

OnTriggerStay is called almost all the frames for every Collider other that is touching the trigger.

public void OnTriggerStay2D(Collider2D other)
{
        if (gameObject.tag == other.tag) {

            Destroy (other.gameObject);

    }
}

I would like to know if there's any way to call OntriggerStay2D everytime i release the object.
Thanks.
Edit
Dragging code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

    public class Drag : MonoBehaviour {

        private bool draggingItem = false;
        private GameObject draggedObject;
        private Vector2 touchOffset;

        void Update ()
        {
            if (HasInput)
            {
                DragOrPickUp();
            }
            else
            {
                if (draggingItem)
                    DropItem();
            }
        }

        Vector2 CurrentTouchPosition
        {
            get
            {
                Vector2 inputPos;
                inputPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                return inputPos;
            }
        }

        private void DragOrPickUp()
        {

            var inputPosition = CurrentTouchPosition;

            if (draggingItem)
            {

                draggedObject.transform.position = inputPosition + touchOffset;

            }
            else
            {

                RaycastHit2D[] touches = Physics2D.RaycastAll(inputPosition, inputPosition, 0.5f);
                if (touches.Length > 0)
                {
                    var hit = touches[0];
                    if (hit.transform != null && hit.rigidbody != null)
                    {
                        draggingItem = true;
                        draggedObject = hit.transform.gameObject;
                        touchOffset = (Vector2)hit.transform.position - inputPosition;
                    }
                }
            }
        }

        private bool HasInput
        {
            get
            {

                return Input.GetMouseButton(0);
            }
        }

        public void DropItem()
        {
            draggingItem = false;

        }

    }

Comment: What does `OnTriggerStay2D` have to do with dragging object?
Comment: I'm dragging the object to collide to another one, but i don't want to destroy it when they collide, i want to destroy it when i release it if they are still touching.
Comment: That makes sense now. Please add your drag code too. That will help give you an answer.
Comment: I edited the question, i added the dragging code.
Comment: You could just perform a RayCast, after you released the object. So you dont have to use the OnColliderStay Method.
Answer: Avoid using OnTriggerStay2D for this. You can use a boolean variable that you set to true and false in the OnTriggerEnter2D and OnTriggerExit2D function.
bool isTouching = false;

void OnTriggerEnter2D(Collider2D collision)
{
    Debug.Log("Entered");
    if (collision.gameObject.CompareTag("YourOtherObject"))
    {
        isTouching = true;
    }
}

void OnTriggerExit2D(Collider2D collision)
{
    Debug.Log("Exited");
    if (collision.gameObject.CompareTag("YourOtherObject"))
    {
        isTouching = false;
    }
}

You can now check the isTouching variable when the object is released.
if(isTouching){
....
}

Note that I suggest you abandon your current code that uses Raycast and Input.GetMouseButton(0); since you are using this on mobile devices too. You should be using Unity's new EventSystem for this since it is made to be mobile friendly too.
Since you are using 2D collider, see #7 from this answer.
Here is a complete example of how to drag a Sprite with the new EventSystem. Combine that with the answer above and you get a much more better solution.
Comment: Thanks, Just by removing the OnTriggerStay2D and using the boolean as you said works perfectly, but i'm looking into your recommendation to improve it, but thank you very much, your solution really works.
Comment: Nice. Glad I was able to help and you definitely use that EventSystem I mentioned.

Unity3D using OnTriggerStay


Visualizing 10 random test examples, the predicted labels, and the actual label from MNIST data set

Question: I am trying to visualize 10 randome test examples, the predicted lables and the actual labels for MNIST data set. but I am getting this error

TypeError: Invalid shape (28, 28, 1) for image data

Can anyone please help me fixing the error? Is it the right approach to visualize test examples, the predicated labels and the actual labels?
<code>%tensorflow_version 1.x
import tensorflow as tf
from matplotlib import pyplot
import matplotlib.pyplot as plt
import random
print(tf.__version__)
    mnist = tf.keras.datasets.mnist
    (training_images, training_labels), (test_images, test_labels) = mnist.load_data()
    training_images = training_images.reshape(60000, 28, 28, 1)
    training_images = training_images / 255.0

    #visualizing 10 random test examples
    for i in range(10):
      pyplot.subplot(330 + 1 + i)
      pyplot.imshow(test_images[i], cmap=pyplot.get_cmap('gray'))
      pyplot.show()

    test_images = test_images.reshape(10000, 28, 28, 1)
    test_images = test_images/255.0
    model = tf.keras.models.Sequential([
      tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Flatten(),
      tf.keras.layers.Dense(128, activation='relu'),
      tf.keras.layers.Dense(10, activation='softmax')
    ])
    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    model.fit(training_images, training_labels, epochs=10)
    test_loss, test_acc = model.evaluate(test_images, test_labels)
    print(test_acc)
</code>
Answer: You simply need to remove the last axis such that your images are of size (28, 28) instead of (28,28,1). Pyplot expects either RGB images with 3 dimensions or black and white images with only 2.
Answer: Try:
<code>pyplot.imshow(np.squeeze(test_images[i]), cmap=pyplot.get_cmap('gray'))
</code>


JRebel: ERROR javax.servlet.ServletException: java.lang.VerifyError: Bad return type

Question: idea 2017.1,tomcat9.0.0.M20,jrebel7.0.8. Run with jrebel for "Tomcat 9.0.0.M20"
HTTP Status [500] – [Internal Server Error]
Type Exception Report
Message java.lang.VerifyError: Bad return type
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: java.lang.VerifyError: Bad return type
Exception Details:
  Location:
    org/apache/jasper/compiler/JspUtil.getInputStream(Ljava/lang/String;Lorg/apache/tomcat/Jar;Lorg/apache/jasper/JspCompilationContext;)Ljava/io/BufferedInputStream; @35: areturn
  Reason:
    Type 'java/io/InputStream' (current frame, stack[0]) is not assignable to 'java/io/BufferedInputStream' (from method signature)
  Current Frame:
    bci: @35
    flags: { }
    locals: { 'java/lang/String', 'org/apache/tomcat/Jar', 'org/apache/jasper/JspCompilationContext', 'java/io/InputStream' }
    stack: { 'java/io/InputStream' }
  Bytecode:
    0x0000000: 2b01 b803 a299 001f 2cb6 0368 b803 6e2b
    0x0000010: b903 7201 002a b603 754e 2d01 b803 a299
    0x0000020: 0005 2db0 014e 2bc6 001a 2a04 2ab6 0002
    0x0000030: b600 083a 042b 1904 b900 b802 004e a700
    0x0000040: 092c 2ab6 00b9 4e2d c700 17bb 00ba 5912
    0x0000050: bb2a b800 bcb7 00bd b803 a8c0 03aa bfbb
    0x0000060: 00be 592d 1104 00b7 00bf b0
  Stackmap Table:
    same_frame(@36)
    append_frame(@65,Null)
    full_frame(@71,{Object[#16],Object[#650],Object[#652],Object[#421]},{})
    same_frame(@95)
<code>org.apache.jasper.servlet.JspServlet.service(JspServlet.java:338)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:168)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1244)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1027)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
com.darlingtech.util.SessionFilter.doFilterInternal(SessionFilter.java:65)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:123)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:167)
org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
</code>
Comment: Confirmed bug in integration with tomcat 9.0.0.M18 and later. Will let you know when it's fixed.
Comment: Try the latest nightly: https://zeroturnaround.com/software/jrebel/download/nightly-build
It should work with tomcat versions up to 9.0.0.M20
Answer: Integration with Tomcat 9.0.0.M20 has been added in the 7.0.9 version of JRebel.


C++ RadixSort efficient ways

Question: I am trying to implement the Radix Sort algorithm in C++ trying to sort an int array.
As far as I see, there are two possible ways:

Sort by binary digits, e.g. get bit after bit using bitwise operators and sorting  them in 2 buckets (0 and 1).
Sort by decimal digits, which makes 10 buckets (0 to 9).

I don't see which of the two would be more efficient however. Sorting in only 2 buckets seems to be quite inefficient, but using decimal digits means the fast bitwise operators can't be used and instead I have to use the especially slow % and / operators.
So which one of these would be faster?
(PS: the code I'm developing will be used in a very time-critical section that's why I ask)
Answer: Generally one sorts into a power-of-2 number of buckets, so that one can reduce the number of passes AND benefit from bitwise operations.
Comment: So attempt 1 would make more sense? because I dont see how to increase the number of buckets to e.g. 4 or 8 if im using bitwise operators.
Comment: Or do you mean sorting e.g. by hex digits which would make 16 buckets?
Comment: Not by "hex digits" necessarily, but by a group of binary digits, yes.
Comment: [example base 256 radix sort](http://stackoverflow.com/questions/1271367/radix-sort-implemented-in-c/40457313#40457313)

C++ RadixSort efficient ways


Will the .lower function in an if statement interrupt the correct input?

Question: Python3 noob here. In the below code I expect if I enter "window" for the choice1 input then it would move on to the input prompt for choice2. But what I get instead is the else statement at the bottom, "You fell into a spike pit as you entered the house! Game Over." What am I doing wrong? Thanks
choice1 = input('You are in front of the house, which way do you want to enter? Type "front door" or "window" and hit Enter \n')
if choice1.lower == "window":
    choice2 = input('You snuck in through a window. You come to the foyer and can take the staircase upstairs or down to the basement. Type "basement" or "upstairs" and hit Enter to proceed \n')
    if choice2.lower == "upstairs":
        choice3 = input("You go upstairs and are in a hallway with 3 doors to enter: 1 red, 1 green, 1 blue. Which color door do you choose? \n")
        if choice3.lower == "red":
            print("The room is full of poisonous snakes! Game over.")
        elif choice3.lower == "green":
            print("You found the lost trick-or-treaters and lead them out of the haunted house to safety. You win!")
        elif choice3.lower == "blue":
            print("You ended up in a warewolf's room. It eats you! Game over.")
        else:
            print("This door doesn't exist... Game over.")
    else:
        print("You encountered a witch who cast a spell turning you into a rat! Game Over.")
else:
    print("You fell into a spike pit as you entered the house! Game Over.")```
</code>
Comment: It should be `lower()`.
Answer: I'm noticing you did [variable].lower, variable being a placeholder for whatever variable you used.
You are accessing the function object itself, not the actual function to run, if you want to run the function, you need to change everything to [variable].lower() -- like this:
<code>choice1 = input('You are in front of the house, which way do you want to enter? Type "front door" or "window" and hit Enter \n')
if choice1.lower() == "window":
    choice2 = input('You snuck in through a window. You come to the foyer and can take the staircase upstairs or down to the basement. Type "basement" or "upstairs" and hit Enter to proceed \n')
    if choice2.lower() == "upstairs":
        choice3 = input("You go upstairs and are in a hallway with 3 doors to enter: 1 red, 1 green, 1 blue. Which color door do you choose? \n")
        if choice3.lower() == "red":
            print("The room is full of poisonous snakes! Game over.")
        elif choice3.lower() == "green":
            print("You found the lost trick-or-treaters and lead them out of the haunted house to safety. You win!")
        elif choice3.lower() == "blue":
            print("You ended up in a warewolf's room. It eats you! Game over.")
        else:
            print("This door doesn't exist... Game over.")
    else:
        print("You encountered a witch who cast a spell turning you into a rat! Game Over.")
else:
    print("You fell into a spike pit as you entered the house! Game Over.")```

Answer: You need to add parenthesis to your .lower method. Like this - choice1.lower() Without them the method would not be called. And that is why you get the error because .lower will give out the memory location. So use Parenthesis for .lower()
Answer: lower is a method, so you need to use choice1.lower() instead of choice1.lower. choice1.lower will give you the method object instead of a string which you want.


Entidade não pode ser referenciado por várias instâncias

Question: Estou tentando salvar os dados nesse método aqui...
public ActionResult AtualizaInicioAtividade(Atividade atividadePre, Atividade atividadePrincipal)
    {
        try
        {
            using (CPMDatabaseEntities db = new CPMDatabaseEntities())
            {
                atividadePre.Ativo = atividadePre.Ativo;
                atividadePre.CodigoMilestone = atividadePre.CodigoMilestone;
                atividadePre.Descricao = atividadePre.Descricao;
                atividadePre.Inicio = atividadePrincipal.TerminoCedo.AddDays(1);
                atividadePre.InicioCedo = atividadePre.Inicio;
                atividadePre.TerminoCedo = atividadePre.TerminoCedo.AddDays(atividadePre.TempoRevisado);

                Tarde(atividadePre);

                db.Entry(atividadePre).State = EntityState.Modified;
                db.SaveChanges();

                return RedirectToAction("Dashboard");
            }
        }
        catch (Exception)
        {

            throw;
        }
    }
// metodo ainda em construcao
 public ActionResult Tarde(Atividade atividade)
    {
        try
        {
            using (CPMDatabaseEntities db = new CPMDatabaseEntities())
            {
                int QtdDependencia = db.Dependencia.Where(a => a.AtividadePrincipal == atividade.Codigo).Count();

                if (QtdDependencia == 0)
                {
                    atividade.TerminoTarde = atividade.InicioCedo.AddDays(atividade.TempoRevisado);
                    atividade.InicioTarde = atividade.TerminoTarde.AddDays(atividade.TempoRevisado * -1);
                }

                if (QtdDependencia == 1)
                {
                    atividade.InicioTarde = Convert.ToDateTime("10/10/2015");
                    atividade.TerminoTarde = Convert.ToDateTime("10/10/2015");
                }

                return View(atividade);
            }
        }
        catch (Exception)
        {

            throw;
        }

    }

Porém aparece esse erro aqui:
An exception of type 'System.InvalidOperationException' occurred in ISystemCritical.dll but was not handled in user code
Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
Comment: O que faz o método `Tarde`?
Comment: atualizei a pergunta.
Comment: já tentou chamar `db.Entry(atividade).State = EntityState.Detached;` antes do seu return no método Tarde?
Comment: Não funcionou...
Answer: Este erro está acontecendo pois você está utilizando dois DbContext para manipular uma mesma entidade.
Voce até podia utilizar o método Detach em versões mais antigas do Entity Framework e acredito que o método do @Bruno funcionaria, mas saiba que este método foi removido por um motivo:
Diferente dos métodos Attach, Add e Remove, o Deatach não operava nos relacionamentos da entidade, então você teria que se preocupar em chamar o Detach para cada uma das entidades relacionadas (entidades filhas) manualmente.
Mesmo que você insista em contornar o problema, você está deixando de aproveitar o que o Entity Framework traz de melhor.
A idéia geral, e que faz o Entity Framework tão poderoso, é que ele "observa" todas as entidades que você busca do Banco, e que você adiciona no contexto.
Assim, com um único SaveChanges(), ele, salva todas as entidades de uma única vez (de forma atômica), executando inserts, updates ou deletes, conforme a necessidade.
Isso quer dizer que o melhor a se fazer no seu caso é reescrever seu fluxo, evitando que dois contextos tenham que ser criados:
 public ActionResult AtualizaInicioAtividade(Atividade atividadePre, Atividade atividadePrincipal)
        {
            try
            {
                using (CPMDatabaseEntities db = new CPMDatabaseEntities())
                {
                    atividadePre.Ativo = atividadePre.Ativo;
                    atividadePre.CodigoMilestone = atividadePre.CodigoMilestone;
                    atividadePre.Descricao = atividadePre.Descricao;
                    atividadePre.Inicio = atividadePrincipal.TerminoCedo.AddDays(1);
                    atividadePre.InicioCedo = atividadePre.Inicio;
                    atividadePre.TerminoCedo = atividadePre.TerminoCedo.AddDays(atividadePre.TempoRevisado);

                    ConfiguraTarde(db, atividadePre);

                    db.Entry(atividadePre).State = EntityState.Modified;
                    db.SaveChanges();

                    return RedirectToAction("Dashboard");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

private void ConfiguraTarde(CPMDatabaseEntities db , Atividade atividade){
                    int QtdDependencia = db.Dependencia.Where(a => a.AtividadePrincipal == atividade.Codigo).Count();

                    if (QtdDependencia == 0)
                    {
                        atividade.TerminoTarde = atividade.InicioCedo.AddDays(atividade.TempoRevisado);
                        atividade.InicioTarde = atividade.TerminoTarde.AddDays(atividade.TempoRevisado * -1);
                    }

                    if (QtdDependencia == 1)
                    {
                        atividade.InicioTarde = Convert.ToDateTime("10/10/2015");
                        atividade.TerminoTarde = Convert.ToDateTime("10/10/2015");
                    }

}

    // metodo ainda em construcao
     public ActionResult Tarde(Atividade atividade)
        {
            try
            {
                using (CPMDatabaseEntities db = new CPMDatabaseEntities())
                {
                   ConfiguraTarde(db , atividade);

                    return View(atividade);
                }
            }
            catch (Exception)
            {

                throw;
            }

        }

Isto deve resolver no momento, mas lhe aconselho a ler este ótimo tutorial do msdn que mostra, por exemplo, que você não precisa usar o Using(DbContext) em cada action.


RoyalSlider overflow is visible IE 10

Question: I am creating a slideshow using Royal Slider but its misbehaving in IE10 ONLY.
I have created a fiddle to show the problem: http://jsfiddle.net/vwDFa/6/.
Hover over the slide, drag over to the next slide and come back to the first slide. As you come back the overflow is visible for a second(its hard to see it the first time). IE10 is the only browser that does this.
this pic shows what happens on my site in IE10 (overflow visible after the blue arrows):

Markup (sorry for the long code, i trimmed it as much as possible):

Stay Classy: Watch our one-on-one with Anchorman 2's Will Ferrell

Stay Classy: Watch our one-on-one with Anchorman 2's Will Ferrell

Stay Classy: Watch our one-on-one with Anchorman 2's Will Ferrell

Stay Classy: Watch our one-on-one with Anchorman 2's Will Ferrell

Ron Burgundy and the Channel 4 News team are back on the big screen in Anchorman 2: The Legends Continues. With the '70s behind them and the modern "Me" decade upon them, San Diego's top rated foursome kick off the 1980s trying their best to stay classy while grappling with the troubling new phenomenon of 24-hour news channels. Can Ron (Will Ferrell), weather man Brick (Steve Carell), man on the street Brian (Paul Rudd) and sports guy Champ (David Koechner) handle this new state of affairs or will the pressure have them breaking down in glass cases of emotion? Our bets are on the latter.Cineplex's own Jolanda Grillone sat down with Ferrell -- the man behind the Anchorman legend -- to talk on his successful partnership with Adam McKay, where their idea for this kind-of-a-big-deal sequel came from and just how we can stay classy under pressure. Watch the interview below now:

See Anchorman 2: The Legends Continues in theatres starting today.

Stay Classy: Watch our one-on-one with Anchorman 2's Will Ferrell

See Anchorman 2: The Legends Continues in theatres starting today.

Stay Classy: Watch our one-on-one with Anchorman 2's Will Ferrell

See Anchorman 2: The Legends Continues in theatres starting today.

CSS:
#main {
    float:left;
    position:relative;
    width:732px;
    height:158px;
    margin-top:10px;
}
.item {
    float:left;
    height:140px;
    width: 680px;
    overflow:hidden;
    position:relative;
}
.news-feed-item {
    overflow:hidden;
    float:left;
    position:relative;
    height:138px;
    width: 225px;
    border-top:1px solid #ccc;
    border-bottom:1px solid #ccc;
    border-right:1px solid #ccc;
    background-color:rgb(243, 243, 243);
}
.news-feed-item .news-data {
    float:left;
    width: 214px;
    padding-left:5px;
}
.news-data {
    font-family:"segoe-regular";
    float:left;
    padding-left:5px;
    color: black;
}
.title {
    font-family:"segoe_uisemibold";
    position:inherit;
    z-index: 200;
    color:#339dde;
    font-size:12px;
    line-height:14px;
    padding-bottom:3px;
    padding-top:5px;
    background-color:rgb(243, 243, 243);
    width: 212px;
}
.news-item .description {
    float:left;
    z-index:100;
    font-size:11px;
    line-height:16px;
}
.news-feed-item .description {
    font-size:11px;
    line-height:16px;
}
/* Slider styling*/
 #full-width-slider {
    width: 100%;
    height:140px;
    color: #000;
}
.fullWidth {
    margin: 0 auto 12px;
    overflow: visible !important;
}

JS:
function createSlider() {
    $('.royalSlider').royalSlider({
        arrowsNav: true,
        loop: false,
        keyboardNavEnabled: false,
        controlsInside: false,
        imageScaleMode: 'fill',
        arrowsNavAutoHide: true,
        autoScaleSlider: false,
        controlNavigation: 'bullets',
        thumbsFitInViewport: false,
        navigateByClick: true,
        sliderDrag: true,
        sliderTouch: true,
        startSlideId: 0,
        autoPlay: false,
        transitionType: 'move',
        globalCaption: true,
        visibleNearby: {
            enabled: true,
            center: false,
            centerArea: 0.91
        },
        /* size of all images */
        imgWidth: 227,
        imgHeight: 140
    });

    /* Show Navigation Arrows on load */
    $(".rsArrowRight, .rsArrowLeft").removeClass("rsHidden");

    setTimeout(function () {
        $(".rsArrowRight, .rsArrowLeft").addClass("rsHidden");
    }, 1500);
}

$(document).ready(function () {
    createSlider();
})

What I would like is to hide the overflow that happens, if you compare the behavior with IE8 or Chrome, you will see the difference. Is this an IE10 bug? Plugin bug?
EDIT I cannot reproduce the issue in Chrome using the emulator on a different computer. This might be a IE setting problem?
Answer: Change centerArea: 1 in the javascript, like this:
centerArea: 1

P.S. I think you also want .main instead of #main
Working fiddle:
http://jsfiddle.net/vwDFa/7/
The 'visible nearby' data makes things visible nearby (as in, the next frame), just like you were experiencing. You can actually remove the whole block if you don't want that.
visibleNearby: {
    enabled: true,
    center: false,
    centerArea: 0.91
},

More fiddle:
http://jsfiddle.net/vwDFa/8/
Comment: On my site 0.91 is correct for centre area otherwise it becomes off centre. And no I need the visible nearby to be on since I want to show the next slide. I think you misunderstood my question. Look at the image I posted. That Extra text after the arrows shouldn't happen. The next slide should only be visible inside it's container not outside of it.
Comment: Did you change #main to .main in the css?
Comment: That was a typo on my part. Doesn't solve the issue.
Comment: They you will need to put up a jsfiddle that demonstrates the problem. Your current jsfiddle seems to be doing what you want. (at least on my chrome browser)
Comment: OK will do once I get home.
Comment: Try putting overflow:hidden on the .main css as well. Worth a shot.
Comment: Once you drag back notice the right edge of the slide/window. You will see it flicker.
Comment: I don't see anything like that on chrome or ie.

RoyalSlider overflow is visible IE 10


Explanation of argument: inverse of a $p$-adic integer

Question: Let $a=a_0+a_1p+a_2p^2+\cdots$ be a $p$-adic integer with $0\le a_i<p$ and $a_0\neq 0$.
Then $a$ has multiplicative $p$-adic inverse $c_0+c_1p+c_2p^2+\cdots$ with $0\le c_i<p$, and is obtained as follows: the following arguments are from Algebra by Mac Lane and Birkhoff. I could not understand them, so can anybody explain it?

$a_0c_0\equiv 1\pmod p$ i.e. $a_0c_0-1=b_1p$.

$a_0c_1+a_1c_0+b_1\equiv 0\pmod{p}$ i.e. $a_0c_0+(a_0c_1+a_1c_0)p-1=p^2b_2$.

$\cdots$

$a_0c_k+a_1c_{k-1}+\cdots + a_kc_0+b_k\equiv 0\pmod{p}$ i.e. $a_0c_0 + (a_0c_1+a_1c_0)p+\cdots + (a_0c_k+\cdots + a_kc_0)p^k-1=p^{k+1}b_{k+1}$.

I got only first step: $a_0\neq 0\pmod p$ so it has inverse in $\mathbb{Z}/p$, so we get $c_0\in \{1,2,\ldots,p-1\}$ with $a_0c_0\equiv 1 \pmod{p}$, so $a_0c_0=1+b_1p$. Then $b_1$ is carry.
Next steps, unclear to me.
Comment: You can think of this process as analogous to the calculation of the reciprocal of a power series with a non-zero constant term. For example, if you are to determine the early coefficients $c_0,c_1,c_2,\ldots$ of the Taylor series of $1/\cos x$:
$$c_0+c_1x+c_2x^2+\dots=\frac1{\cos x}=\frac1{1-x^2/2+x^4/24+\cdots}$$
you would similar expand the product of the cosine series and $c_0+c_1x+\cdots$, and then equate coefficients of like powers to those of  the desired product $1=1+0\cdot x+0\cdot x^2+\cdots$.
Comment: Existence questions you can handle for example by thinking of the right hand side of
$$c_0a=1+p y_1+p^2y_2+\cdots$$
as simply $1+p\xi$. Then you can realize the reciprocal using the sum formula of a geometric series
$$\frac1{1+p\xi}=1-(p\xi)+(p\xi)^2-(p\xi)^3+\cdots.$$ That geometric series obviously converges $p$-adically etc...
Comment: The next step is an equation for $c_1$ because everything else is known. Can you solve for $c_1$?
Comment: It is perhaps instructive to see this as exactly the same process as long division of ordinary integers or polynomials: you're computing $1/a$, so write $1 = 1+0p+0p^2+\dots$, set up the usual division process, and at each step think "what do I need to multiply $a$ by to match the 'leading term' of the current step".
Comment: Compare this near-duplicate: https://math.stackexchange.com/q/4460082/96384
Answer: Expanding on the idea in the comments, to view this as ordinary division:
We are trying to compute $1/a$ with $a = a_0 + a_1 p + a_2 p^2 + \dots$.
Write $1 = 1 + 0 p + 0 p^2 + \dots$, and set up the long division
$$
\begin{array}{l r}
& \underline{~~\; \phantom{aaaaaaaaaaaaaaa}} \\
a_0 + a_1 p + a_2 p^2 + \dots & \big) ~ 1 + 0p + 0p^2 + \dots \\
&
\end{array}
$$
To execute the first step, we look for a number $c_0$ that makes $a_0 c_0 = 1$, except of course our digits work modulo $p$< so really we want $a_0 c_0 \equiv 1 \pmod{p}$, or as you say $a_0 c_0 - 1 = b_1 p$ for some integer $b_1$.
Hence the next step becomes:
$$
\begin{array}{l l}
& \underline{~~\; c_0 \phantom{aaaaaaaaaaaaa}} \\
a_0 + a_1 p + a_2 p^2 + \dots & \big) ~ 1 + 0p + 0p^2 + \dots \\
& ~~\; a_0 c_0 + a_1 c_0 p
\end{array}
$$
which given the above relation is the same as
$$
\begin{array}{l l}
& \underline{~~\; c_0 \phantom{aaaaaaaaaaaaa}} \\
a_0 + a_1 p + a_2 p^2 + \dots & \big) ~ 1 + 0p + 0p^2 + \dots \\
& \underline{~~\; 1 + (b_1 + a_1 c_0) p} \\
& ~~\;~~\; -(b_1 + a_1 c_0)p
\end{array}
$$
Thus our goal in the next step is to multiply $a = a_0 + a_1 p + a_2 p^2 + \dots$ by something so that the leading term matches $-(b_1 + a_1 c_0) p$.
It has to be a multiple of $p$ for the power of $p$ to match, so call it $c_1 p$:
$$
\begin{array}{l l}
& \underline{~~\; c_0 + c_1 p \phantom{aaaaaaaa}} \\
a_0 + a_1 p + a_2 p^2 + \dots & \big) ~ 1 + 0p + 0p^2 + \dots \\
& \underline{~~\; 1 + (b_1 + a_1 c_0) p} \\
& ~~\;~~\; -(b_1 + a_1 c_0)p  \\
& ~~\;~~\; a_0 c_1 p + a_1  c_1 p^2
\end{array}
$$
We want the leading terms to cancel when we subtract (that's the point of the division algorithm!) so here the goal has to be
$$
-(b_1 + a_1 c_0) \equiv a_0 c_1 \pmod{p},
$$
or in other words $a_0 c_1 + a_1 c_0 + b_1 \equiv 0 \pmod{p}$.
This explain the second bullet in their argument.
Continue from there! You might find it instructive to carry the process out with some concrete numbers and see that there's nothing mysterious going on here, it just looks a bit of a mess because of the many variables.


How to disable Service provider initialized SSO in Spring SAML?

Question: My product uses only Identity Provider initialized SSO and it works fine.
Requests to http://localhost:8080/saml/SSO are validated. For correct requests a session is created, for wrong ones I am getting status 401.
I have problem with incoming requests to other endpoints (ones that should be secured), like
http://localhost:8080/messages
When request has correct, authenticated session id  it works fine.
But for not authenticated requests, I am redirected to my Identity provider page, with URL
https:///sso/SSO?SAMLRequest=
How to disable that behavior? I want just to reject those requests with 'Authentication failed' response, without any interaction with Identity provider.
Answer: Simply remove the SAMLEntryPoint which is responsible for initialization of SP SSO. Spring Security will then use the default entry point which should behave as you expect. You will still be able to send SAML messages to /saml/SSO.
Edit:
Detailed steps are given below

Create bean implementing org.springframework.security.web.AuthenticationEntryPoint
Simplest imlementation is  <bean name="http403ForbiddenEntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"/>
Use that bean in <security:http entry-point-ref="http403ForbiddenEntryPoint">
Remove  <bean id="samlEntryPoint" class="org.springframework.security.saml.SAMLEntryPoint">
Comment: Thanks, it works perfecty! I edited your answer and added detailed steps.


Change file to correct URL in Yii framework

Question: Index path of my yii application is "site.com/www/index.php". How to write htaccess file to open my application by url: "site.com" ?
Answer: You should simply read this :
http://www.yiiframework.com/doc/guide/1.1/en/topics.url#hiding-x-23x
Comment: Where to put the file that given in the article? In the root directory? How I should set path to index.php?


Capturar dados input Iframe

Question: Bom, numa página tenho um iframe, nele é exibido parte do outro site meu, estão em servidores diferentes, o que preciso é acessar o input do iframe e enviar para uma variavel javascript de minha página, sendo que pelo Iframe não tem como enviar por Post ou GET. Pelo que já li, os browsers por questão de segurança não permitem isso, mas, vi algo relacionado a Post Messenger do HTML5, mas, não encontrei nada de documentação ou que explique como funciona.
Alguem já precisou e solucionou este problema?
Comment: A página que está dentro do iFrame está no mesmo domínio?
Comment: Não, estão em dominios e servidores diferentes
Comment: Então sugiro usares [JSONP](http://pt.stackoverflow.com/q/70267/129), caso ambas as páginas sejam tuas e tenhas aceso a uma linguagem de servidor.
Answer: Digamos que você tenha dois sites em dominios diferentes, onde o cliente acessar o dominio1.com e o mesmo possui um iFrame apontado para o dominio2.com.
Para o dominio dominio2.com enviar uma mensagem para o dominio1.com é necessario usar o método .postMessage()
var outraJanela = window.parent;
var data = { ... }; //objeto que será enviado;
var json = JSON.stringify(data);
outraJanela.postMessage(json, "http://dominio1.com");

note que especificamos o dominio que será o alvo, isto é para evitar que o seu dominio se comunique com dominios indesejados, como por exemplo dominio-falso.com.
agora em dominio1.com você precisa adicionar um listener para receber a mensagem enviada por dominio2.com
window.addEventListener("message", function (event) {
    if (event.origin === "http://dominio2.com") {
        var data = JSON.parse(event.data); // os dados enviados por dominio2
    }
});

Mais uma vez é necessario verificar quem enviou a mensagem, por isto verificamos ser a origem é a esperada, no caso dominio2.com.
caso você precise enviar uma mensagem de confimação para o dominio2.com, basta fazer o seguinte:
window.addEventListener("message", function (event) {
    if (event.origin === "http://dominio2.com") {
        var data = JSON.parse(event.data); // os dados enviados por dominio2
        event.source.postMessage("OK", event.origin);
    }
});

lembrando que será preciso adicionar window.addEventListener("message", ...) em dominio2.com para que ele possa receber a mensagem de confimação.

Capturar dados input Iframe


Odd Primes Problem Proof

Question: Given the odd prime numbers,
Prove that if $x$ and $y$ are adjacent odd primes in this list, then $x + y$ has $3$ prime factors. The factors need not be distinct.
Here is an example I have provided:
$3 + 5 = 8 = 2 \cdot 2 \cdot 2$. Therefore, $8$ has $3$ repeated factors of $2$.
Comment: By odd adjacent primes do you mean the neighbouring odd primes? .... Yeah actually I think you do, forget that I asked.
Answer: If $x$ and $y$ were consecutive odd primes then $x+y = 2z$ for some integer $z$. If $z$ was a prime that would make $z$ lie between $x$ and $y$ which is not possible since $x,y$ are consecutive primes. Hence, $z$ has atleast two prime factors (not necessarily distinct).
Comment: @Pp..  Yes.  and it's my own decision how I want to respond to that.
Comment: I think it would be much better not to answer questions at this level that show no effort.
Comment: @WillO isn't it a better idea to encourage the user asking the Q to show efforts first than discourage users from answering them ? :-)
Comment: Sciona:  I think that discouraging users from answering them is prerequisite to encouraging effort.
Comment: @Sciona:  Plus, this seems to be a particularly egregious case since the comment on Meelo's answer indicates that the OP hasn't stopped to think about this question for an instant.
Comment: @WillO That is what you think. Not every body thinks that asking for showing effort is not an stupid idea.
Comment: Yeah, the show-effort army is "that rational".
Comment: @WillO: Thanks, I misread adjacent as twin.
Comment: @WillO It is not your job. You are not anybody's daddy. It is their own decision the amount of effort each one want's to put on a problem.
Comment: @WillO Andre's comment 'Multiplicity 4.' is ambiguous. When we talk about multiplicity of a prime dividing $p$ dividing $n$, we are looking for the highest power of $p$ in prime factorization of $n$. He possibly meant number of prime factors is $4$.
Answer: $$11+13=24=2^3\cdot 3\,\,\,\,$$
Comment: @mathemagician:  You're asking how to prove that $3+1=4$ ?????
Comment: Multiplicity $4$.
Comment: @AndréNicolas How can I prove that?
Answer: Suppose $x<y$ are adjacent odd primes. Then $x+y = 2a$, $a\in\mathbb{Z}$.
$x<y \Rightarrow 2x<x+y<2y \Rightarrow 2x<2a<2z \Rightarrow x<a<y$
How $x$ and $y$ are adjacent primes, then $a$ is not prime. Suppose $a=b\cdot c$, with $b, c>1$.
So $x+y = 2\cdot b\cdot c$. Therefore $x+y$ has at least 3 prime factors

Odd Primes Problem Proof


Erro ao tentar exibir as informações de um objeto em um

Question: Estou desenvolvendo um sistema usando utilizando JSF, PrimeFaces, JPA, maven e PostgreSQL. Eu sou novo em JEE e estou tendo dificuldades com o uso do PrimeFaces, então vamos ao problema:
Eu tenho uma tela de listagem de clientes e nessa tela eu gostaria de poder visualizar, atualizar ou excluir um cliente cadastrado.
Para começar eu estou tentando exibir informação de um cliente selecionado, porém, ao selecionar o objeto na tela e clicar no botão para exibir o dialog, estou obtendo a seguinte exceção:

Cannot convert Cliente {"aqui fica as informações do objeto selecionado :) "} of type class model.entidade.Cliente to class javax.faces.model.ListDataModel

ManagedBean:
@ManagedBean
@SessionScoped
public class ControlerCliente implements Serializable {
    private static final long serialVersionUID = 1L;
    private Cliente cliente;
    private Endereco endereco;
    private ListDataModel<Cliente> selectClientes =null;

 public ControlerCliente() {
        this.endereco = new Endereco();
        this.cliente = new Cliente();
        }
    public List<Cliente> obterClientes() {
        return ClienteModel.getInstanceCliModel().findAllClientesModel();

    }

}

Tela de listagem:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <ui:composition template="./../templates/template.xhtml">

            <ui:define name="top">
                <ui:include src="/includes/menu.xhtml"/>
            </ui:define>

            <ui:define name="content">
                <h:form>

                        <f:facet name="header">
                            LISTA DE CLIENTES CADASTRADOS
                        </f:facet>

                            <h:outputLabel value="#{cliente.codigo}"/>

                            <h:outputText value="#{cliente.nome}"/>

                            <h:outputText value="#{cliente.cpf}"/>

                            <h:outputText value="#{cliente.dataAbertura}"/>

                            <h:outputText value="#{cliente.email}"/>

                            <h:outputText value="#{cliente.telefone}"/>

                            <h:outputText value="#{cliente.endereco.bairro}"/>

                            <h:outputText value="#{cliente.endereco.numero}"/>

                            <h:outputText value="#{cliente.endereco.cep}"/>

                        <f:facet name="footer">

                        </f:facet>

                </h:form>

                    <h:form>

                            <h:outputText value="CÓDIGO"/>

                            <h:outputText value="CPF"/>

                            <h:outputText value="EMAIL"/>

                            <h:outputText value="NOME"/>

                            <h:outputText value="DATA-CADASTRO"/>

                            <h:outputText value="RUA"/>

                            <h:outputText value="BAIRRO"/>

                            <h:outputText value="CIDADE"/>

                    </h:form>

            </ui:define>

        </ui:composition>

Answer: O datatable está com o parâmetro selectionMode="single", portanto você pode selecionar apenas um registro da tabela. O problema é que você está setando o registro selecionado em uma ListDataModel, em: selection="#{controlerCliente.selectClientes}". Tente mudar para selection="#{controlerCliente.cliente}".


Negate regular expression

Question: Suppose I have a simple regular expression describing a language like $(a+b)^* a?b (a+b)^*$ (a language in $\Sigma = \{a,b\}$ consisting of all words with substring $a?b$). I haven't found a general way to negate any regular expression, and it seems that no such way exists. There is similar question: A regular expression for the words that don't contain the sequence $ab$ over $\{a,b,c\}$, but the way described there quickly becomes very complicated when regular expression length increases. How to deal with this?
Comment: However @Hagen's meaning of `?` is the usual meaning for `?` in "regular expressions", and the "any character" meaning is only commonly used in simple patterns that have no repetition constructs and so are _not_ called "regular expressions".
Comment: Isn't $a?b=\{ab,b\}$? Then you want all words not containing $b$, i.e. $a^*$.
Comment: No, $a?b = a \{a,b\} b$ ($?$ is any symbol).
Comment: D'oh, if you've encountered DOS wildcards and PERL r.e. in real life, you are doomed to mix things sooner or later. :)
Comment: @HenningMakholm, I have some books about theory of formal languages, and the meaning of $?$ is "any character" in many of them. But in programming-related fields yes, it's as Hagen wrote.
Answer: Convert the regular expression to a finite automaton accepting $L$. Then interchange accepting and non-accepting states, which produces an automaton accepting $\Sigma^*\setminus L$. Finally, convert the automaton to a regular expression.
Comment: @chersanya: The regex-to-DFA is easy enough (and in most practical cases ends with a nice smallish automaton), but DFA-to-regex is very complicated and tends to produce huge resulting regexes. Unfortunately it's the best avaliable _general_ procedure for negating regexes.
Comment: It's not so easy to build a DFA for $a?b$, and for NFA it's not easy to build a regex...

Negate regular expression