Injection of rational torsion points over elliptic curve over integers in to $\Bbb F_p$-torsion points via finite flat group schemes

Question: Suppose $X$ is an elliptic curve over $\Bbb Q$ defined by a Weierstrass equation. We may consider this with integer coefficients and then reduce modulo $p$, and if $p$ is nice enough with respect to $X$ we get an elliptic curve which we'll call $X'$ over the field $\Bbb F_p$. Something I've heard/read a few times is that the $n$-torsion of $X(\Bbb Q)$ injects in to the $n$-torsion of $X'(\Bbb F_p)$ as long as $n$ is coprime to $p$.
I'm trying to understand why this is so. In my search, I've found Matt Emerton's answer to a very closely related question. It seems that there's a strategy which proceeds via some facts about finite flat group schemes, but he doesn't say much about it in the linked post (or maybe he does and I'm not getting it). Is there any way to show this claim about the injection of torsion just from knowing that the kernel is a finite flat group scheme? I have an ok background with schemes, but I have not yet spent much serious time with elliptic curves, so I would appreciate answers that focus more on the scheme-theoretic aspects.
Answer: Emerton's answer is, I think, on a less elementary level than that: it's addressing the case of what $p$-torsion becomes mod $p$. This case is rather simpler: the kernel of the $n$-torsion extends to a smooth finite scheme $G$ over $\mathbb{Z}_{(p)}$. By base changing to the ring of integers of a local field $K$ (with residue field $k$), we know that $G$ is finite smooth free of rank $m$ [in this case $m=n^2$] coprime to $p$ over $O_K$.
Let $C \subset G$ be a closed open subset and let $A=O(C)$ (free $O_K$-algebra of finite rank, with $A \otimes k$ reduced), we want to show that $A$, $A \otimes K$, and $A \otimes k$ have the same idempotents (which will imply the result – as I'll explain afterwards).
The bijection from the idempotents of $A$ to the idempotents of $A \otimes k$ is well-known (it's basically Hensel). The inclusion from the idempotents of $A$ to those of $A \otimes K$ is clearly well-defined and injective. But if $e \in A\otimes K$ is idempotent, then for some $a \in O_K$ (a power of the uniformizer, chosen to be minimal – suppose for the sake of contradiction that $a$ is noninvertible) $e'=ae \in A$ and $e'^2=ae'$. But this means that $e'^2$ vanishes in $A \otimes k$ so $e'$ was already divisible in $A$ by the uniformizer, so we could have chosen $a$ with a smaller valuation!
Why is this enough? Well, consider the residue disk $C$ of the unit point in the special fiber of $G$: $G$ is finite as a topological space, so it is the finite reunion of closures of points on the generic fiber, so $C$ is closed. But $G$ is finite as a topological space, so $C$ is constructible. Since $C$ is of course stable under generization, so $C$ is open.
So $C$ is a closed open subscheme of $G$ with its special fiber reduced to a point, so by the above its generic fiber must be connected. But $C$ is smooth over $O_K$ so its generic fiber is the spectrum of a finite reduced, connected $K$-algebra with a $K$-point (the unit), so it must be $K$, ie reduced to a point, so we are done.
Comment: Throughout this argument, I used the stronger assumption of smoothness rather than flatness, which follows rather elementarily from the theory of elliptic curves (at least for fiberwise smoothness). But I think that the sole "rank invertible in the ring" hypothesis is enough to derive fiberwise smoothness for any commutative flat group scheme over a nice enough ring.
Comment: Thanks, this solves my problem. I ended up coming up with a slightly different proof too: since we can show smoothness of the kernel by directly computing the geometric fibers and noting that they're unramified by Riemann-Hurwitz, the kernel must actually be regular when $(n,p)=1$. But that means all the local rings are domains, so irreducible components can't intersect, and since the torsion points in the generic fiber determine irreducible components of the kernel, we win.
Comment: @Hank Scorpio: I had been trying to find with the regularity but it didn't occur to me what it meant about irreducible components. That's a very good argument too!


Integral w.r.t. a cumulative density function

Question: I was reading a paper and couldn't understand the following transition. Could someone tell me where the term of $p^k (\frac{1}{2} − c′)$ comes from in the following transition?
Def: Cumulative function of interest
$$
F(x) =
\begin{cases}
    0 & \text{for } x < -c' \\
    p^k & \text{for } x \in [-c', 0) \\
    (p + (1 - p) x)^k & \text{for } x \in [0, 1] \\
    1, & \text{for } x > 1
\end{cases}
$$
Integral of interest
$$
\int^{\infty}_{-\infty} x d F(x) = p^k (\frac{1}{2} - c') + \int^{1}_{0} x d F(x) = \cdots
$$
My attempts
First, I expanded the integral based on the sections as follows;
$$
\int^{\infty}_{-\infty} x d F(x) = \int^{-c'}_{- \infty} x dF(x) + \int^{0}_{-c'} x dF(x) + \int^{1}_{0} x dF(x) + \int^{\infty}_{1} x dF(x)
$$
Then, i was not sure how to compute each term... could someone tell me how to compute the integral over a CDF?
Reference

Appendix B of this paper
https://math.stackexchange.com/questions/4605847/integral-over-a-cumulative-density-function
Comment: @whuber I think i was not clear about what to ask in the above post. Sorry!
Comment: Do you know what the notation $dF(x)$ indicates?  It's the derivative of the function $F$ with respect to $x$, handwaving over some details that aren't important here.  The first and last integrals should be clear... what is the derivative of a constant?  Then think carefully about what is happening with the transition between the first and second integral - follow @whuber's recommendation and plot the function - and that should help you with the second one.  Then on to the third one!
Comment: Well you still have the third term, the integral over $[0,1]$.
Comment: Oh, no, it just generates the $-p^kc'$ term.  Basically, there's a jump in $F$ at $-c$, which means there's a discrete mass at that point, that has probability $p^k$.  So its contribution to the expected value is just $-c * p^k$.
Comment: Perhaps graphing an instance of this family of functions would clarify the calculations.  Due to the four-part definition of $F,$ this result reflects four separate calculations: which one(s) are you wondering about?
Comment: @whuber thank you for your comment! Yeah, out of 4 sections, I'm wondering where $p^k (1/2−c′)$ comes from.
Comment: @jbowman thank you for your detailed suggestion! As you mentioned, 1st and 4th terms become 0 as the derivative of a constant in the CDF. Then, 2nd term will be $\int^{0}_{-c'} x p^k dx = [ \frac{1}{2} x^2 p^k ]^{0}_{-c'} = 0 - \frac{1}{2} c'^{2}p^k$....?
Comment: oh, so is it like $\int^{0}_{-c'} x dF(x) = \int^{0}_{-c'} x p^k$? then we get $[x p^k]^{0}_{-c'} = 0 - c' p^k$. But still I don't know where 1/2 comes from then....
Comment: @jbowman Sorry, I'm a bit confused. In the transition of interest ( $\int^{\infty}_{-\infty} x d F(x) = p^k(\frac{1}{2} - c') + \int^{1}_{0} x dF(x)$ ), the third term ( $ \int^{1}_{0} x dF(x)$ ) that we are discussing now still remains, right? So, I thought the second term ( $ \int^{0}_{-c'} x dF(x)$ ) will somehow generate the quantity of $p^k (1/2 - c')$
Comment: @jbowman Got it! And I'm really sorry for asking a lot.. but then do you know where $1/2 p^k$ comes from?? Summarising our discussion, wow we know that in the transition in `My Attempts` of the question, the first and final terms become 0 and the second term generates $-c' p^k$ and the third term remains the same.
Answer: Let us express the CDF in terms of the Heaviside function $H(\cdot )$, this function is defined by,
$$ H(a) = \left\{ \begin{array}{ccc} 1 & \text{ if } & a\geq 0 \\ 0 & \text{ if } & a < 0 \end{array}\right. $$
Note, $H$ itself is a CDF, in some sense it is the "simplest" CDF. Now, we will do something extremely controversial, we claim that the derivative of the Heaviside function is the delta function, i.e., $H' = \delta$. Where $\delta(\cdot)$ is defined as follows,
$$ \delta(a) = \left\{ \begin{array}{ccc} \infty & \text{ if } & a = 0 \\ 0 & \text{ if } & a\not = 0 \end{array}\right.$$
This is the delta "function", it has the additional property that, $\smallint_I (g\cdot \delta) = g(0)$ provided that $I$ is an interval that contains the singularity $0$ and $g$ is a continuous function at $0$. For instance, $\smallint_{(1,2)} (g\cdot \delta) = 0$ but $\smallint_{(-1,2)} (g\cdot \delta) = g(0)$. You can intuitively think of $\delta$ as a PDF, which integrates to $H$. Of course, no such function exists in the classical sense with such properties, but let us not be worried about that yet.
Now the function that you wish to integrate can be described by,
$$ F(x) =  p^k \bigg( H(x+c') - H(x) \bigg) + (p+(1-p)x)^k\bigg( H(x) - H(x-1) \bigg) + H(x-1)$$
Therefore, the "derivative" is equal to,
$$ F'(x) = \delta(x-1) + p^k \bigg( \delta(x+c') - \delta(x) \bigg) + k(1-p)(p+(1-p)x)^{k-1}\bigg( H(x) - H(x-1) \bigg) + (p+(1-p)x)^k\bigg( \delta(x) - \delta(x-1) \bigg)$$
Therefore, the calculation you are looking for is equal to,
$$ \int_{\mathbb{R}} x ~ d F(x) = \int_{\mathbb{R}} x F'(x) $$
Now substitute the above "derivative" and use the delta properties.
Comment: No, it's a different kind of derivative than the Riemann integral we all learned in Calc I, and the notation is different.  In most practical cases, writing loosely, it'll be easily translatable into the usual integral, as you have done in your comments answering parts 1, 2, and 4 of the original post, but it fixes up some problems with the Riemann integral from a mathematical point of view, enabling a lot of really elegant proofs etc.
Comment: @Rowing0914 Yes, if you want to, you can write $x F'(x) ~ dx$ at the very end, but here the $dx$ is purely symbolic and serves no purpose any more. But if it makes it easier for you to understand the calculation then it just means you treat the integral of $x F'(x)$ as a usual integration problem with delta functions in there.
Comment: Thank you for your answer! In the last equation, isn't there $dx$ at the end of the integral of LHS??


Show users a different page (depending on their role) after logging in

Question: In my site I have two different roles for users named recruiter and candidate. when they register their account they can choose their role (recruiter or candidate). And when they login my site I will check user is recruiter or candidate. after this check I will show them a different page (recruiter page and candidate page).
How to proceed with this?
Answer: Have a look at the Front Page module. Module description:

The Front Page module allows for customised home pages dependant on
  role. The pages can be of the following types:

Alias (only 2.x branch) - Allows for another Drupal path to be shown as the home page without redirecting the user.
Redirect - Allows you to redirect users to a local or remote URL.
Themed - Allows you to enter some static text that will be placed into the content area of a standard Drupal page.
Full - Allows for static content to be displayed to the screen as is. This method does not pass through Drupal's theming system.

One of the options should fit your need.
Comment: bro send me website links to more clears steps to proceed. Thanks Bro
Comment: There's a [README file](http://cgit.drupalcode.org/front/tree/README.txt) in the module.
Answer: You can write a simple module for assigning role
/**
 * Implements hook_form_BASE_ID_alter()
 */
function CUSTOM_MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Get the system roles.
  $roles = array_map('check_plain', user_roles(TRUE));

  $form['roles'] = array(
    '#type' => 'select',
    '#title' => t('Roles'),
    '#default_value' => array(),
    '#options' => $roles,
  );
}

/**
 * Implements hook_user_insert()
 */
function CUSTOM_MODULE_user_insert(&$edit, $account, $category) {
  // Save the role if it's set.
  if (isset($edit['roles'])) {
    // Push the roles to $account object so that user_save can get the role property.
    $account->roles[] = $edit['roles'];
  }
}

And after the user is logged in use Rules module to redirect to any of your page
Answer: These are both well used Drupal modules. Login destination does pretty much what you want, Login Toboggan doesn't quite do that but adds some nice signup features that you might want to use concurrently.
Login destination

The Login Destination module allows you to customize the destination
  that a user is redirected to after logging in, registering to the site
  (7.x), using a one-time login link or logging out (7.x). The
  destination can be an internal page or an external URL. It is possible
  to specify certain conditions like referring pages or user roles and
  make the destination depend upon them. You may use PHP snippets to
  provide custom conditions and destinations. It is also possible to
  keep users on the currently visited page after logging in or out.

or
Login toboggan

The LoginToboggan module offers several modifications of the Drupal
  login system in an external module by offering the following features
  and usability improvements:

Allow users to login using either their username OR their e-mail
  address.
Allow users to login immediately. Provide a login form on
Access Denied pages for non-logged-in (anonymous) users.
The module
  provides two login block options: One uses JavaScript to display the
  form within the block immediately upon clicking "log in". The other
  brings the user to a separate page, but returns the user to their
  original page upon login.
Customize the registration form with two
  e-mail fields to ensure accuracy.
Optionally redirect the user to a
  specific page when using the 'immediate login' feature.
Optionally
  redirect the user to a specific page upon validation of their e-mail
  address.
Optionally display a user message indicating a successful
  login.
Optionally combine both the login and registration form on one
  page.
Optionally have unvalidated users purged from the system at a
  pre-defined interval (please read the CAVEATS section of INSTALL.txt
  for important information on configuring this feature!).
Integrates
  with Rules module to do various tasks when a user validates via email
  validation process (see http://drupal.org/node/880904 for an example)
Comment: Hi cozmo. Please try to avoid link-only answers. Better is to include some information from the linked resource. (Links can go down over time). Thanks for contributing!
Comment: Sorry, new to this!
Answer: Here is the easiest way to do it without installing additional modules: create a module with this code and specify inside the code role names and destinations:
function MY_MODULE_user_login(&$edit, $account)
{

    if (user_has_role_by_role_name('role_one', $account)) {
        drupal_goto('role_one_goes_here'); // relative path
    } elseif (user_has_role_by_role_name('role_two', $account)) {
        drupal_goto('role_two_goes_here'); // relative path
    }
}

function user_has_role_by_role_name($role_name, $user)
{
    $role_object = user_role_load_by_name($role_name);
    if (user_has_role($role_object->rid, $user)) {
        return true;
    } else {
        return false;
    }
}

Answer: You can use the Rules module for this. Here is a rule (in Rules export format tht you can import in your own site using the Rules UI) that should be close to what you'd need (for a recruiter):
{ "rules_redirect_to_recruiter_content" : {
    "LABEL" : "Redirect recruiter to recruiter content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "recruiter\/content" } } ]
  }
}

This rule assumes that the recruiter role has role id = 4 (change to whatever role id that fits). And the path (in the Rules Action) to redirect to is assumed to be recruiter/content (change that path to fit your needs).
You could create a similar rule for "Candidate", starting from a clone from the Recruiter role. Or you could use the the Conditional Rules module to consolidate both rules in a single one.


Which scale(s) can I use?

Question: I've just come back from my jazz workshop and the lines I played over a G7 C7 G7 D7#9 Eb7#9 D7#9b13 G7 progression were ok, -ish. When asked, our teacher told me to try dorian scales, over mixolydian and altered chords. What is your angle on this?
Comment: All Blues? If so, it helps a lot to listen to the soloists on that recording.
Comment: You spotted it right away of course. I didn't know if it was alright to actually name the tune. You guys are so strict. But I suppose you have to. I agree with you: listen listen, listen...but I'm just an amateur and although I try to train my ear as best I can, I'd love to have some tips about that tune.  I have fun on swing progressions but blues progressions are a big deal for me. I'm European, you see.  I played bebop C all over the progression but wasn't really happy about it, obviously. I have good phrasing and a good sense of time but I want to improve.
Comment: @user45784, a full transcription of Coltrane's solo can be found [on page 60 of this document](http://jeffweissmusic.com/wp-content/uploads/2015/12/John-Coltrane-Artist-Transcriptions.pdf).
Comment: @jdjazz, Thanks. I think I'll try to figure out which scales he plays throughout and when. Miles Davis' solo is easier to follow on the guitar but Trane's is a hard nut to crack. I appreciate.
Answer: Common scales that "fit" the 7th chord include:

Myxolydian (b7)
Major pentatonic (1, 2, 3, 5, 6)
Bebop (b7, natural 7)
Lydian dominant (#4, b7)
Whole tone
Diminished (half, then whole steps)
Diminished whole tone (b2, b3, b4, b5, b6, b7 - most common on "#9b13" chords)

If you haven't seen this video from the "Jazz Tutorials" channel, I would strongly suggest it. The Lydian Dominant scale emerges from the teacher's "chord tones + whole step" philosophy.
Comment: You can find these (and more!) scales in Jamey Aebersold's *Scale Syllabus*: http://jazzbooks.com/mm5/download/FREE-scale-syllabus.pdf
Comment: Might be worth adding the relative Dorian for a sus sound. For example, over G7, play D dorian.
Comment: Indeed. The scale syllabus uses a separate notation (G7 sus 4, or D-/G), so maybe I'll just relegate this info to the comments!
Comment: Do you consider a change from G7 to G7sus4 to be in a different category from G7 → G7#11 or G7 → G7alt? Don't they all use separate notations?
Comment: I don't know of a consistent way to measure how different one chord symbol (or chord) is from the next, but "not having a 3rd" seems like a big enough distinction.
Comment: Every single option (G7sus, G7alt, G7#11) changes the harmony. But every single option (G7sus, G7alt, G7#11) also preserves the underlying dominant 7th harmony. The G7sus chord doesn't change the harmony--it's still a dominant 7th chord. Playing the major 3rd over a G7sus isn't uncommon by any means (the suspension-resolution makes a nice sound). Further to this point, you can sometimes find Keith Jarrett voicing sus chords with a major third on the top of the chord as part of an upper structure.
Comment: Given (a) how common a sus sound is over extended improvisation on a dom7 chord, (b) the use of sus chords & lines in the original recording of All Blues (particularly over the IV7 chord), (c) the nature of this question (asking about scales rather than chords), and (d) the mention of dorian in the original post, I think it's worth including. (I really like this post overall and I gave it a +1 when making the original comment.)
Answer: It's important to realize that not every scale that can theoretically be played over a dominant seventh chord is also a good choice in a specific musical context. In the case of the given progression the following scales are used in practice:

G7     G mixolydian
C7     C mixolydian
D7#9   D half-whole, D altered, D (minor) blues
Eb7#9  Eb half-whole, Eb altered, Eb (minor) blues

Note that there's not a lot of time to play scales over the D7#9 and the Eb7#9 chords, so what people usually do is play (incomplete) arpeggios. As I've mentioned in a comment, you can learn a lot by analyzing the solos played by the greats. As an example, try to play an Fm7 arpeggio over D7#9, and a Gbm7 arpeggio over Eb7#9. In this way you'll play the 7, b9, #9, and the #11 of the respective chord.
It's also helpful to analyze the melody, and use it in your improvisations. The first thing that one notices it that over D7#9 the perfect fifth (A) as well as the #5 (b13) are used. Over Eb7#9 it's also the perfect fifth, not an altered fifth, that is used. This would imply the half-whole scale rather than the altered scale over these two chords. Another suitable choice matching the note choice of the melody over these two chords is the (minor) blues scale, which will give you the 5, 7, and #9.
Comment: +1 Nice overview. Might be worth mentioning the ways one can stretch the song over the I7 and IV7 chords as that seems to be what the instructor was suggesting. @user45784, if you listen to Coltrane's solo on All Blues, you can hear the [whole tone scale](https://youtu.be/uRBgy43gCoQ?t=406) at 6:48, the [lydian dominant](https://youtu.be/uRBgy43gCoQ?t=446) scale at 7:30, [who knows](https://youtu.be/uRBgy43gCoQ?t=462) at 7:43, a [relative minor](https://youtu.be/uRBgy43gCoQ?t=465) lick at 7:46, and an [altered scale](https://youtu.be/uRBgy43gCoQ?t=471) at 7:51 and 7:55.
Comment: This is very interesting: you use arpeggios from the II chord of the melodic minor scale from which the alt. chord is derived, right? Yet the quality should be half-diminished... so you actually substitute the Fmb5 for Fm7.
Comment: @user45784: The ii chord of melodic minor is a minor 7 chord, not a half-diminished chord (the half-diminished would occur in harmonic and natural minor).
Comment: you're right. Got it mixed up because II chords in minor are generally half-diminished. It's a Xsusb9 chord. Thx
Answer: You're not really asking the right question! It's taking a narrow, inward-looking, mechanical approach to a wide topic - how to play good jazz.
It's often a good idea to find a song using the chord sequence and see what the original melody was.  That may well be the BEST thing to play over that sequence.  And I bet is isn't just scales.
Comment: Is this an answer? The question is "what scales can I use?" It seems like you're answering a different question, "how do I learn to improvise over these changes?"
Comment: @jdjazz - Right now, the question reads: _When asked, our teacher told me to try dorian scales, over mixolydian and altered chords. What is your angle on this?_  So IMO this is a perfectly valid answer: The angle is "Find a tune that uses those changes, hear the melody line and listen to what the soloists do with it." I upvoted this answer. I think it's a very good "angle".
Comment: He wants to play good jazz.  Let's not find reasons to stop us suggesting how.
Comment: @LaurencePayne, oftentimes in my learning a specific question will arise. To continue progressing, the most helpful thing is often a specific answer. Other general advice can be helpful, but the primary reason for asking a question to get an answer. I think you've left the question unanswered.
Comment: @Stinkfoot, the question is in the title: "which scale(s) can I use?" The asker offers three example scales. He asks what folks think about *the three example scales* in the context of a question *about scales*. I agree that "listen to the tune" is useful advice, but it's not an answer to this question which is very narrowly focused on scales. I don't think the usefulness supersedes the lack of answer to the actual question.
Comment: @jdjazz  - I agree here with Laurence Payne in his comment. I think you are splitting straws in your criticism, especially since the question is much more clearly explained in the body than the title, which is a very brief - and based on the follow-up, not an entirely accurate -
 encapsulation of the content. This isn't an patent application. :)
Comment: @Stinkfoot, the title could not be clearer: he plainly asks what scales can be used. The body could not be clearer: he suggests one possible answer to his own question, listing three scales. Then he asks what people think about the three proposed scales. There is no ambiguity. To assert that the asker is mistaken or wrong seems plainly false.
Comment: Ok guys! I didn't want to trigger Major (in which key? I  don't know) mayhem here. I'll go for a BB King box and call it a day ! ;))
Comment: Sometimes the best answer can be 'You're not really asking the right question!'.   When someone asks for a mechanical solution to an artistic question, they deserve guidance.
Comment: @LaurencePayne, I completely agree with you, and I think that's an excellent example of why the comment feature is so useful. I would upvote this if it were a comment. (I have found that a combination of knowledge about scales + listening to recordings to be the most helpful.)
Comment: Go on then!  I've added to my answer.

Which scale(s) can I use?


Wordpress - Posts per page not working for specific category-slug.php

Question: I have a specific category-slug.php page.
I want to display the first category "banner-ads" with only 1 post per page and then below that, display 3 posts per page from the category "featured."
I don't want to use:
**query_posts( 'posts_per_page=4' );**
I've tried the pre_get_posts function but can't seem to get it working.
Right now the number of posts per page that's displaying is the number I assigned in Settings->Reading
Here's my current code:
$args1 = array(
    'category_name' => 'banner-ads',
    'posts_per_page' => 1
    );

$the_query = new WP_Query( $args1 );

while ( $the_query->have_posts() ) :
    $the_query->the_post();
    ar2_render_posts( null, array ( 'type' => 'node' ), true );
endwhile;

wp_reset_postdata();

$args2 = array(
    'category_name' => 'featured',
    'posts_per_page' => 3
    );

$query2 = new WP_Query( $args2 );

while( $query2->have_posts() ):
    $query2->next_post();
    ar2_render_posts( null, array ( 'type' => 'traditional' ), true );
endwhile;

wp_reset_postdata();

Answer: You haven't made reset: wp_reset_postdata();
Useful about categories: http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
Here is mine for one of pages
First loop:
<?php
$postq1 = new WP_Query(
 array(
  'post_type' => array('post','yourcustom'),
  'posts_per_page' => 1,
  'category_name'=>'banner-ads')
 );
if($postq1->have_posts()):
    while ( $postq1->have_posts() ) :
        $postq1->the_post();?>
<article id="post-<?php the_ID();?>">....

<?php
    endwhile;
endif;
wp_reset_postdata();
?>

Second loop:
<?php
$postq2 = new WP_Query(
 array(
  'post_type' => array('post','yourcustom'),
  'posts_per_page' => 3,
  'category_name'=>'featured')
);
if($postq2->have_posts()):
    while ( $postq2->have_posts() ) :
        $postq2->the_post();?>
<article id="post-<?php the_ID();?>">....

<?php
    endwhile;
endif;
wp_reset_postdata();
?>

... rest of code with query_posts();
Comment: That didn't seem to work, it still showing whatever was set in the settings page.
Comment: what happens, when You put `wp_reset_postdata()` BEFORE each loop also (so it would be before and after, like double reset).

OR

there might be problem with `ar2_render_posts()`
Comment: I was able to control the amount for the first loop by adding this function:
Comment: add_filter('post_limits', 'my_post_limits');

function my_post_limits( $limit ) {
    if ( in_category('banner-ads') ) {
        return 'LIMIT 0, 1';
    }
    return $limit;
}

and then removing it after the loop

remove_filter('post_limits', 'my_post_limits');

Now to figure out why it doesnt work on the second loop
Answer: Okay so I finally figured it out. If you want to force it to take certain number of posts then add the filter with its function then at the end of the loop remove it. I realized for my second loop that the ar2_render_posts() function was conflicting with the code so I'm opting to redoing that function from scratch since its basically a layout function.
add_filter('post_limits', 'my_post_limits');

function my_post_limits( $limit ) {
    if ( in_category('banner-ads') ) {
        return 'LIMIT 0, 3';
    }
    return $limit;
}

    $args1 = array(
        'category_name' => 'banner-ads'
        );

    $the_query = new WP_Query( $args1 );

    while ( $the_query->have_posts() ) :
        $the_query->the_post();
        ar2_render_posts( null, array ( 'type' => 'node' ), true );
    endwhile;

    wp_reset_postdata();
    remove_filter('post_limits', 'my_post_limits');

Answer: it is pretty simple, just alter query_args in ar2_render_posts
ar2_render_posts( null, array (
     'query_args' => array ( 'posts_per_page' => 1 ),
), true );


Aurora Serveless - Data API no longer exists. What to do?

Question: I'm trying to create an Aurora Serverless database, using the Data API function in order to be able to access the query editor. Unfortunately, the UI was modified and I have been searching for the Data API enablement but could not find it. I followed this tutorial - 10:38 if helpful.

Could you please help me ? Maybe it's with another name but I don't know ?
Answer: You must be using Aurora Serverless v2. Only Aurora Serverless v1 supports Data API. So you have to use v1, or architect your application so that it does not require Data API.
Answer: Update 04/01/2024: AWS have released the Data API for Aurora Serverless v2... hooray! Apparently only for Postgresql at the moment, but MySQL to follow.  They claim to have kept the same API signatures, but I have not tried it personally yet.
https://aws.amazon.com/blogs/database/introducing-the-data-api-for-amazon-aurora-serverless-v2-and-amazon-aurora-provisioned-clusters/
===== original answer ===
There is a more detailed discussion of the "Data API for AWS Aurora Serverless v2" issue here: Does Aurora Serverless V2 have a Data API? , which should help you choose which way to go in your architecture.
If you are interested in having Data API for v2, please consider submitting a Support Request to AWS, as discussed here https://stackoverflow.com/a/72675703/13702327
Answer: AWS has officially launched data API for Aurora serverless v2
Digging through it you can see that there are some limitations. First, the data API is only available for Postgresql for now and only in certain regions.
Hopefully, this is only temporary and I think AWS will make the data API accessible to the different configurations (serverlessv2 and provisioned) in and all regions.


Descobrir string dentro de string sem biblioteca string.h?

Question: Minha função precisa verificar se uma string está contida em outra e falar onde ocorreu o primeiro local onde a letra ficou igual, mas está retornando sempre o tamanho da primeira string
O que tem de errado na minha implementação?
meu codigo:
void str_conteudo( char str1[], char str2[])
{
int i=0;
int y;

while(str1[i] != str2[i] )
{
    if (str2[i] != str1[i])
    {
        y=i;
    }
    i++;

}

if(y>0)
printf("Indice do primeiro caractere que contem a string 2: %d ", y);
else
printf("A string 2 nao esta contida na string 1. \n");

}

Comment: O problema que você está tentando resolver se chama `substring`. Procurar por algoritmos de busca de substrings e entendê-los a fundo vai te ajudar bastante
Answer: Na sua implementação tem a lógica que percorre as letras da frase principal, mas ficou a faltar a lógica que vê se cada letra é igual as letras da segunda string.
Tentando aproveitar o máximo da sua lógica pode fazer assim:
void str_conteudo( char str1[], char str2[]) {
    int i=0,j, k;
    int y = -1; //y começa a -1, pois estava sem valor de inicio

    while(str1[i] != '\0') { // enquanto a string principal não termina
        if (str2[0] == str1[i]) { //se a letra em que vai é igual à 1a letra da substring
            //percorrer enquanto ambas as letras são iguais e até ao fim da substring
            for (j=i+1, k=1; str1[j]!='\0' && str2[k]!='\0' && str1[j] == str2[k];++j,k++);

            if (str2[k] == '\0'){ //se a segunda foi até ao fim então achou
                y = i;
                break;
            }
        }
        i++;
    }

    if(y>=0) // >= 0 e não > 0
        printf("Indice do primeiro caractere que contem a string 2: %d \n", y);
    else
        printf("A string 2 nao esta contida na string 1. \n");
}

Testes
str_conteudo ("Frase de teste","de"); //6
str_conteudo ("Frase de teste","teste"); //9
str_conteudo ("Frase de teste","Frase"); //0
str_conteudo ("Frase de teste","cuFra"); // não contem
str_conteudo ("Frase de teste","testem"); // não contem

Veja estes testes no Ideone
A maior diferença para o código que tinha está no que foi adicionado dentro do if no while.
Nunca é boa ideia este tipo de funções escreverem ou lerem conteudo. Devem apenas retornar o resultado, dando liberdade a quem chama de fazer o que quiser com esse resultado. Para alem disto o próprio if que tem no while nem seria necessário se alterasse mais algumas coisas.
Pegando nestes pontos que mencionei eu trocava a função para algo como:
int str_conteudo( char str1[], char str2[]) {
    int i=0, j, k;
    for(i = 0; str1[i] != '\0'; ++i) {
        for (j = i,k = 0;str1[j]!= '\0' && str2[k] != '\0' && str1[j] == str2[k]; ++j,k++);
        if (str2[k] == '\0'){
            return i;
        }
    }
    return -1;
}

Naturalmente que podia ter trocado a iteração e acesso para sintaxe de ponteiros que ficaria mais curto, mas optei por manter com índice para tornar a solução comparável e parecida com a sua.
Agora os testes tem que passar a mostrar o valor obtido pela função, que devolve -1 sempre que não achar a substring:
printf("%d\n", str_conteudo ("Frase de teste","de")); //6
printf("%d\n", str_conteudo ("Frase de teste","teste")); //9
printf("%d\n", str_conteudo ("Frase de teste","Frase")); //0
printf("%d\n", str_conteudo ("Frase de teste","cuFra")); //-1
printf("%d\n", str_conteudo ("Frase de teste","testem")); //-1

Veja estes testes também no Ideone
Apenas para referência, deixo o mesmo exemplo de cima implementado com notação de ponteiros, ainda que exatamente a mesma solução:
int str_conteudo( char *str1, char *str2) {
    char *curr1 = str1, *s1, *s2;
    while(*curr1){
        for(s1 = curr1, s2 = str2; *s1 && *s2 && *s1 == *s2; ++s1, ++s2);
        if (!*s2) return curr1 - str1;
        curr1++;
    }
    return -1;
}

Como nota final, a lógica que está a implementar é a que a função nativa strstr fornece.
Comment: Não vou fazer uma agora, mas se fosse exemplificar, faria um loop e dentro uma state machine. Um ponteiro na agulha, outro no palheiro, e avançaria conforme o estado (procurando, comparando, resetando)
Comment: @JeffersonQuesado não esqueça do rewind no caso da minha, se não for feito corretamente ele vai perder uma substring em algumas situações. (tinha exemplificado errado aqui)
Comment: @Bacco E voltar depois com o ponteiro atrás caso não encontre um *full match* ?
Comment: sim, ainda assim seria mais otimizado nos casos que não encontrasse parcial ou que encontrasse inteiro - os unicos casos de rewind seriam parcial incompleto - Se quiser chamar de 2 loops, seriam "2 loops ocasionais" :)
Comment: @Bacco Tecnicamente seria um loop, apesar de que feito manualmente :D. Mas sim não seriam 2 loops escritos em forma de `for`/`while`. É certamente uma ideia interessante. Vou refrasear para não ferir suscetibilidades! :p
Comment: Lembrando que tou falando como exercício. Na prática eu acho que não implementaria isso pra uso real kkk. Aliás, eu vi um muito legal de busca otimizada de multiplas strings numa passada só, esse sim eu quero entender e fazer pra uso real.
Comment: @Isac essa alternativa da sua resposta é a implementação _naïve_, com tempo `O(|str1| * |str2|)`; dá para otimizar para `O( (|str1| - |str2|) * |str2|)`. Ou seja, essa alternativa vai ser sempre quadrática. Já a ideia do Bacco é `O(|str1| + |str2|)`
Comment: Parece-me que a complexidade é igual, pois no segundo exemplo que eu tenho para nenhuma letra igual a minha solução é O(|str1|) que seria igual ao exemplo do Bacco. Porque deixar o ponteiro avançar e depois andar com ele para trás é basicamente o inner `for` que eu tenho mas escrito de outra forma. A menos que eu não esteja a visualizar a solução dele a 100%. Para todos os efeitos, em grande parte dos casos o meu *inner* `for` funciona como um `if`.
Comment: @Bacco o KMP que usa um FSA não precisa de um _rewind_ ao andar na `str1`/string grande que pode conter `str2`. Ele resolve em uma passada, e montar esse autômato baseado na `str2` eu acho que é linear.
Comment: @JeffersonQuesado fico pensando que pra achar "ababac" dentro de "xxxxabababacxxx" sem rewind não dá certo, dá? Pq está contido, mas na primeira passada vai confundir os 5 primeiros caracteres depois dos x.
Comment: @Bacco dá sim, e quando eu era atleta da programação eu fazia em uma passada. Deixa eu estudar e postarei a resposta aqui, porque não lembro mais como é xD
Comment: Vou ver só mais tarde, pq agora realmente preciso dormir. Quero fazer uma de multiplas strings e alta performance, pq é pra substituir um LIKE no SQLite numa aplicação minha.
Comment: Se tiverem essas soluções depois postem para partilhar conhecimento! Que eu fiquei curioso.


Inverse theorem proof question

Question: The question pertains to the notes found at: https://ocw.mit.edu/courses/mathematics/18-101-analysis-ii-fall-2005/lecture-notes/lecture6.pdf.
In the proof, $U_1$ is defined to be a  $\delta$ open rectangle and $V$ a $\delta/4$ open ball. The inverse theorem states that $U_1$, $V$ are both neighbourhoods of $a$ and $f(a)$ respectively. When applying the inverse theorem, does this mean that $U_1$ has to be a rectangle and $V$ an open ball?
Answer: The theorem says nothing about how the neighborhoods must be constructed. It only says that if the theorem is applicable then there exists a diffeomorphism between $U_1$ and $V$ (which implies that both are open sets). In many cases it's not trivial to invert the function explicitly (think of a very complicated function $f$) and specify the corresponding neigborhoods $U_1$ and $V$ - you only know that they do exist.
Let's consider the following example:
$$f:\mathbb{R}^2\to \mathbb{R}^2, f{x \choose y} = {2x^2 \choose 3y^2}
.$$
Can we apply the inverse function theorem at ${0 \choose 0}$? No, but at point ${1 \choose 1}$ we can. We can even calculate the inverse function explicitly:
$$f^{-1}:\mathbb{R}^2\to \mathbb{R}^2, f^{-1}{x \choose y} = {\frac{1}{\sqrt{2}}\sqrt{x} \choose \frac{1}{\sqrt{3}}\sqrt{y}}
.$$
How about the sets $U_1$ and $V$? Well, regarding $U_1$ we can take any open set as long as $x>0$ and $y>0$. We could either define a rectangle as in the proof or some other weird set as long as it is open and $x>0$ and $y>0$. Note that we don't specify $V$ directly but $V$ is obtained implicitly by defining $U_1$. $V$ is always open due to continuity of $f$.

Inverse theorem proof question


Execute web service method and return immediately

Question: C# ASP.NET 3.5
Is it possible to "fire and forget" a method in a web service that is not asynchronous or one-way?
There is a method that returns a value (after some processing), which I don't need. It is used by another group (who wrote the service). Basically, it just notifies that user x did action y. I just need to call the method and move on without waiting for the result.
I tried using a BackgroundWorker() with RunWorkerAsync, but the method does not fire for some reason. I cannot change the web service method as I have no access to their code. Should I be using BackgroundWorker, Invoke, ThreadPool, something else? I don't need the result returned, and I don't need to know if it fails. Basically, call the method, and if it works, great. If not, I don't want to stop or slow processing down.
<code>public static void Test()
{
    var worker = new BackgroundWorker();
    worker.DoWork += Test2;
    worker.RunWorkerAsync(new object[] {12345, "test"});
}

private static void Test2(object sender, DoWorkEventArgs e)
{
   // Write to log that we got into the method - does not
   object[] args = e.Argument as object[];
   int num = Convert.ToInt32(args[0]);
   string name = (string)args[1];
   // call web service method here....
}
</code>
Comment: It depends on your web site architecture. How do you call your service? Do you create new instance of wcf client proxy every time? Is it a page class field (maybe injected)? Please add the missing code.
Answer: Intsead of using Background Worker you can try the following
<code>    public static void Test()
    {
        System.Threading.ThreadPool.QueueUserWorkItem(delegate
        {
            Test2(new object[] { 12345, "test" });
        });
    }

    private static void Test2(object data)
    {
        // Write to log that we got into the method - does not
        object[] args = data as object[];
        int num = Convert.ToInt32(args[0]);
        string name = (string)args[1];
        // call web service method here....
    }
</code>
Answer: The feature that is requested, by definition IS WCF OneWay. It is impossible to implement the required behavior completely client-side.
IIS by default (a common host of WCF services) is allowed to kill any process that was kicked off by a closed connection. This means that the client must stay connected for the duration of the process (which in effect means waiting for the result). Additionally it is possible the request can timeout and the "fire and forget" process is killed off.
If you only want to reduce the resources taken up at the client to the minimum whilst the request is in flight I would run the request asynchronously. If you only have access to .net<=4.0 then the easiest way to do this is to generate the async calls (I mean APM async and NOT async/await/TPL async) using the "add service reference" option and tick the "generate async methods" option.
You would have to also learn the APM programming model (which is pretty nasty).
Alternatively you could run the WCF call on a separate Thread. But note, this uses significant additional resources.
Answer: There is a document here on Asysn/Sync wfc calls. http://msdn.microsoft.com/en-us/library/ms734701.aspx.
Comment: -1 He explicitly asked about web service calls which are _not_ async or one-way.
Comment: Why is it tagged as wcf? An async http post will work for asmx calls. I have done this before will look for an example.
Comment: You would have to ask the person who tagged it, not me. Maybe he's not using legacy code (ASMX).
Comment: My bad, it looks as if the question being asked is sending an async response that is not configured as async or "one-way" but still using wcf.
Comment: @KendrickLamar Actually, it doesn't work. If either the client is killed or the request times out before the method returns, (assuming IIS hosting) the Thread running the method could be killed off.


How transaction function in Codeigniter 3 works with the query?

Question: So i have this query in my Models.
$this->db->trans_begin();
$this->db->insert($somequeryhere);
$this->db->insert($somequeryhere2);
$this->db->insert($somequeryhere3);
$this->db->insert($somequeryhere4);
$this->db->update($somequeryhere7);
$this->db->update($somequeryhere21);
$this->db->delete($somequeryhere10);
if($this->db->trans_status() === FALSE){
   $this->db->trans_rollback(); return false;
}else{
   $this->db->trans_commit(); return true;
}

The transaction sure works well. But it's confusing when i tried to die the PHP process in the middle of query like below query.
$this->db->trans_begin();
$this->db->insert($somequeryhere);
$this->db->insert($somequeryhere2);
$this->db->insert($somequeryhere3);
$this->db->insert($somequeryhere4);
die;
$this->db->update($somequeryhere7);
$this->db->update($somequeryhere21);
$this->db->delete($somequeryhere10);
if($this->db->trans_status() === FALSE){
   $this->db->trans_rollback(); return false;
}else{
   $this->db->trans_commit(); return true;
}

The transaction still works. I thought the PHP didn't reach $this->db->trans_status() so the transaction will not working, but this also works like  using or without using $this->db->trans_status(). Could someone explain this ?
I have tried to used $this->db->trans_start(); and $this->db->trans_complete(); and the transaction rollback still executed.
Comment: you are using transaction manual mode.https://www.codeigniter.com/user_guide/database/transactions.html.
try `$this->db->trans_start();` i think then transaction will not commit if you put die
Comment: @MadhawaPriyashantha ok, i will try.
Comment: @MadhawaPriyashantha i have tried it, and the transaction still execute even i used `$this->db->trans_start();`  and `$this->db->trans_complete();`
Answer: If you Put a Die in middle of the code after trans_begin().
it will not commit, If you want to check the status of insert update data, you must not use the trans method for this one.
Because for trans method - commit or rollback need must to execute the query
//$this->db->trans_begin();
$this->db->insert($somequeryhere);
$this->db->insert($somequeryhere2);
$this->db->insert($somequeryhere3);
$this->db->insert($somequeryhere4);
die;
$this->db->update($somequeryhere7);
$this->db->update($somequeryhere21);
$this->db->delete($somequeryhere10);


Laravel: use Eloquent belongsto , get data from both tables?

Question: In Controller, I would like to pass the only one variable with specifies column from parent in it. Now,I'm using
View::make('store.product')->with('products', Product::find($id)
->join('design','product.design_id','=','design.id')
->join('user','design.user_id','=','user.id')
->select('user.name','design.title','product.price')
->get();

My question is
1.Is there a better way to do this by using Belongsto?
2.If can do, Is it work the same with Hasmany?
This is my table structure.
User
id | name
1  | 'John'

Design
id | user_id |  title
1  |    1    | 'Chill'
2  |    1    |  'Mad'

Product
id | design_id | price
1  |     1     |  20
2  |     1     |  30

And Model be like this
Product belongsto Design ,
Design  belongsto User
Answer: Add a method to your Users like so for your designs that the user has;
public function designs(){
    $this->hasMany('Design');
}

For the designs model add the following methods;
public function user(){
    $this->belongsTo('User');
}

public function products(){
    $this->hasMany('Product');
}

For your products model
public function design(){
    $this->belongsTo('Design');
}

These will set up the relationship allowing you to eager load the data on your models.
This can be done like so;
$variable = Product::with('designs')->find(1); //This will load the product with the related designs

If you want all the designs and the users that belong to the designs do the following;
$variable = Product::with('designs', 'design.user')->find(1); //This will load the designs that relate to the Product and include the user that that design belongs to on the Design model.

To access the properties use the following;
$variable->designs //This will return a collection of all the designs.
$variable->designs->first()->user //This will return the user model that the design belongs to.

An example of displaying the information;
@foreach ($variable->designs as $design)
    {{ $design->user->username }}
@endforeach

Please note: i have not tested this code.
Comment: Almost there! If i want a related user too, Can do that?
Comment: @Johny edited to show how to access the information. To get the related users as well use Product::with('designs', 'design.user')->find(1);


User error : "2" is an invalid render array key dans Drupal\Core\Render\Element::children()

Question: I face off this message on certains pages, somtimes relate to twig template part, sometimes to other things.
In watchdog:
    User error : "2" is an invalid render array key dans Drupal\Core\Render\Element::children() (/home//www/pfdev/multid9/recommended-project/web/core/lib/Drupal/Core/Render/Element.php ligne 98)
#0 /home//www/pfdev/multid9/recommended-project/web/core/includes/bootstrap.inc(347): _drupal_error_handler_real(256, '"2" is an inval...', '/home/provencef...', 98)
#1 [internal function]: _drupal_error_handler(256, '"2" is an inval...', '/home/provencef...', 98)
#2 /home//www/pfdev/multid9/recommended-project/web/core/lib/Drupal/Core/Render/Element.php(98): trigger_error('"2" is an inval...', 256)
#3 /home//www/pfdev/multid9/recommended-project/web/core/lib/Drupal/Core/Render/Renderer.php(404): Drupal\Core\Render\Element::children(Array, true)
#4 /home//www/pfdev/multid9/recommended-project/web/core/lib/Drupal/Core/Render/Renderer.php(204): Drupal\Core\Render\Renderer->doRender(Array, false)
#5 /home//www/pfdev/multid9/recommended-project/web/core/lib/Drupal/Core/Template/TwigExtension.php(479): Drupal\Core\Render\Renderer->render(Array)
#6 /home//www/pfdev/multid9/recommended-project/vendor/twig/twig/src/Environment.php(418) : eval()'d code(458): Drupal\Core\Template\TwigExtension->escapeFilter(Object(Drupal\Core\Template\TwigEnvironment), Array, 'html', NULL, true)

The othe rpost on this subject lead me to check my array sinto .theme like:
function starter_d9_2022_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'views_view__' . $variables['view']->id();
  // If you want you can add a template suggestion for all views
  // based on their ID:
  $suggestions[] = sprintf('views_view__%s', $variables['view']->id());

  // Or you can check the ID, add suggestions, do whatever you want
  // ...
}
function starter_d9_2022_theme_suggestions_views_view(array $variables) {
  return [
    'views_view_display__' . $variables['view']->current_display,
    // Suggestion pour chaque affichages de la vue
  ];
}

but no effect instead of a WSOD. So I have no clue to fix this. Do someone know ?
Thanks
EDIt: after advices, it appear this correction goes wrong in the IDE(VS Code). Because of comment ?
function starter_d9_2022_theme_suggestions_views_view(array $variables) {
  //return [
    'views_view_display__' . $variables['view']->current_display;
    // Suggestion pour chaque affichages de la vue
  //];
}

Answer: It is hard for me to realize what's your goal here, but there are few things to note:

$suggestions[] = 'views_view__' . $variables['view']->id();
has the same result as
$suggestions[] = sprintf('views_view__%s', $variables['view']->id());
so you should take one or the other, not both.
inside this hook: function starter_d9_2022_theme_suggestions_views_view(array &$variables) {} (please note the ampersand), one could work directly with the $variables array and it's not needed to return anything.

As for the WSOD, in Drupal it's recommended to enable the verbose errors handling on local environment or if it's not possible, at least check the admin's logs for the error.
Comment: Thanks for your advices. I will modify the code and see if error disappear. I will keep you in touch.


RuntimeException (Android)

Question: Eu quero colocar o atendenteBalaoProdutoNome do lado do AtendenteBalaoProdutoValor, assim:

para fazer isso, eu tentei isto:
atendente.xml
<?xml version="1.0" encoding="utf-8"?>
<merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

<RelativeLayout
style="@style/layoutAtendenteBalao"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+atendente/rltAtendenteBalao">

<TextView
    style="@style/campoAtendenteBalaoTexto"
    android:id="@+atendente/txtTexto"/>

<RelativeLayout
    style="@style/atendenteBalaoVO"
    android:layout_width="match_parent"
    android:id="@+atendente/rltAtendenteBalaoVO">"

    <TextView
        style="@style/atendenteBalaoVOTexto1"
        android:id="@+atendente/txtAtendenteBalaoVOTexto1"/>

    <LinearLayout
        style="@style/atendenteBalaoVOTextoQuantidadeTexto2">"

        <EditText
            style="@style/atendenteBalaoVOQuantidade"
            android:id="@+atendente/txtAtendenteBalaoVOQuantidade"/>

        <TextView
            style="@style/atendenteBalaoVOTexto2"
            android:id="@+atendente/txtAtendenteBalaoVOTexto2"/>

    </LinearLayout>

    <Button
        style="@style/atendenteBalaoVOMais"
        android:id="@+atendente/btnAtendenteBalaoVOMais"/>

    <Button
        style="@style/atendenteBalaoVOMenos"
        android:id="@+atendente/btnAtendenteBalaoVOMenos"/>

</RelativeLayout>

<RelativeLayout
    style="@style/atendenteBalaoProduto"
    android:id="@+atendente/lnrProduto">

    <TextView
        style="@style/atendenteBalaoProdutoNome"
        android:id="@+atendente/txtProdutoNome"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/txtProdutoValor"/>

    <TextView
        style="@style/atendenteBalaoProdutoValor"
        android:id="@+atendente/txtProdutoValor"
        android:layout_alignParentRight="true"/>

    <LinearLayout
        style="@style/atendenteBalaoProduto2"
        android:id="@+atendente/lnrProdutoQuantidade"
        android:focusableInTouchMode="true">

        <TextView
            style="@style/atendenteBalaoProdutoRotuloQuantidade"
            android:id="@+atendente/txtProdutoQuantidadeRotulo" />

        <EditText
            style="@style/atendenteBalaoProdutoQuantidade"
            android:id="@+atendente/txtProdutoQuantidade"
            android:inputType="numberDecimal"
            android:digits="0123456789,."
            android:imeOptions="actionDone"/>

        <TextView
            style="@style/atendenteBalaoProdutoUnidade"
            android:id="@+atendente/txtProdutoUnidade"/>

        <Button
            style="@style/atendenteBalaoProdutoMenosMais"
            android:id="@+atendente/btnQtdeMenos"
            android:text="-" />

        <Button
            style="@style/atendenteBalaoProdutoMenosMais"
            android:id="@+atendente/btnQtdeMais"
            android:text="+" />

    </LinearLayout>

</RelativeLayout>

styles.xml

Mas me mostrou o seguinte log:
05-13 16:22:39.469: E/AndroidRuntime(21065): FATAL EXCEPTION: main
05-13 16:22:39.469: E/AndroidRuntime(21065): Process: br.com.xxxx.xxxx.activity, PID: 21065
05-13 16:22:39.469: E/AndroidRuntime(21065): java.lang.RuntimeException: Unable to start activity
ComponentInfo{br.com.xxxx.xxxx.activity/br.com.xxxx.xxxx.activity.ACTAtendimento}: android.view.InflateException:
Binary XML file line #195: Error inflating class br.com.xxxx.xxxx.controls.Atendente`

Quando dou um debug na linha 195 do ACTAtendimento:
Comment: Jean, Poderia incluir o xml do layout da `Activity ACTAtendimento`? Além disso, poderia incluir o código da classe `Atendimento`?
Comment: @Wakim esses códigos são muito grandes para serem inclusos aqui. Também não tem nenhuma classe `Atendimento`, a que tem é a `Atendente`, seria esta?
Comment: Jean, você pode substituir o código que tem na pergunta, porque ele não ajuda muito. Isso, confundi o mome, mas o mais importante é a classe `Atendente` e o layout da Activity `ACTAtendimento`.
Answer: Eu tinha esquecido de mudar o tipo do objeto no Atendente.java
Ficou assim:
RelariveLayout rltProduto           = (RelativeLayout) findViewById(R.atendente.lnrProduto);

RuntimeException (Android)


How do I make a page available via only a single URL?

Question: Is there a way to make the front page available via only a single URL?
The normal method is to use a <link rel="canonical"> meta tag, but this is not good for SEO.
Answer: That's what the <link rel="canonical"> meta tag is for.
I'm not sure where you've got the information that this meta tag is not good for SEO, but I'm afraid your source is incorrect; the exact opposite is true. This is what Google have to say on the matter:

Carpe diem on any duplicate content worries: we now support a format that allows you to publicly specify your preferred version of a URL. If your site has identical or vastly similar content that's accessible through multiple URLs, this format provides you with more control over the URL returned in search results. It also helps to make sure that properties such as link popularity are consolidated to your preferred version.

As you can see this is what Google recommend you do to avoid the problem of SEO penalties for duplicate content. This information is several years old and hasn't changed.
To my knowledge the following modules will add a canonical link to your documents:

Global Redirect
Redirect
Meta Tag

There may well be more though. The 2 redirect modules above will probably help you out even further, as they will automatically perform a 301 redirect to the canonical URL when any of the others are visited. Google also encourages the use of such headers in this situation.
Be sure to read the whole Official Google Webmaster blog post linked to above to understand why this method is the correct one, it's pretty important in terms of SEO these days.
Oh, and if I were you I'd be suspicious of anything else your original source for this tells you...they obviously don't know much about SEO!
Further Reference:

About rel="canonical" on Google Webmaster Tools
Canonical URL Tag - The Most Important Advancement in SEO Practices Since Sitemaps on SEOMoz
Google, Yahoo & Microsoft Unite On "Canonical Tag" To Reduce Duplicate Content Clutter on Search Engine Land

And there are literally dozens more...search Google for "SEO canonical".


Triplets 4th of power of first equals to sum of other two

Question: I was looking through the admission test for the University Normale of Pisa and I found a problem that I don't know how to solve, it state something like that:
Find all the triplets of number (x, y, z) such that:
$$
\left\{ \begin{array}\
x^4 = y + z\\
y^4 = z + x\\
z^4 = y + x
\end{array} \right.
$$
EDIT:
It ask for real number.
All: Please observe that the question was earlier tagged elementary-number-theory. This lead several posters to assume that the variables should be integers. Several answers may appear to be strange as a consequence of that./JL
Comment: Are you sure the last one isn't $x + y$ (for symmetry)?
Comment: Are $x,y,z$ real or integers? Or positive integers?
Comment: Should that last $y+y$ be $x+y$?
Comment: yes it should sorry about the typo... I am fixing it.. @vonbrand yes
Comment: @N.S. integers in general
Comment: Sorry, it is real number not integer
Comment: If the variables are real, then *elementary-number-theory* is a wrong tag. I took the liberty of changing that.
Answer: Without loss of generality we can assume that $x \geq y \geq z$. Then it is clear that $x \geq 0$ (otherwise all three are negative, which is not possible)
$$x^4=y+z \le 2x \,.$$
Thus $x^3 \leq 2 \Rightarrow x=0 \, \mbox{or} \, x=1 \,.$
If $x=0$ we have $y,z \leq 0$ and  $y=z^4 \geq 0 \Rightarrow y=0$ and $z=0$.
If $x=1$, then $z \leq y \leq 1$ and $y+z=1$. This implies that $z=0$ and $y=1$. But this doesn't work.
Thus, there is only 1 solution $(0,0,0)$.
Comment: 0^4 != 1 + 1 isn't ? I am re-reading the text, and it ask for REAL number not integer... sorry...
Comment: Ty, will fix it :)
Answer: $$y^4-x^4=x-y$$
If $x\ne y$
$$(y^2+x^2)(y+x)=-1$$
Assuming that last line should be $z^4=x+y$ we have
$$(x^2+y^2)z^4=-1$$
which has no solution.  Therefore $x$ must equal $y$.  Similarly, we can get $y=z$.  So we have
$$x^4=2x$$
The only real solutions are $x,y,$ and $z$ all equal $0$ or the cube root of $2$.
Comment: &(x^2+y^2)z^4 = -1& so z^4 = -1/(2*x^2)... What I am missing ?
Comment: @Siscia: If $x,y,z$ are real don't you think both $z^4$ and $x^2+y^2$ are positive?
Comment: @JyrkiLahtonen Of course -.-, my bad... Still don't get how we arrive to x^4 = 2x
Comment: Ok I got it... Very stupid...
Answer: 1 ~ [y + z] mod(5) and
1 ~ [z + x] mod(5) and
1 ~ [y + y] mod(5) from fermat's little theorem. Then since 5 is prime we know that each inverse must be unique. Thus this suggests that y mod(5) = z mod(5) = x mod(5) =  3 mod(5)
As for finding all specific solutions I'm not sure.
Edit: I now see that you changed it to [y + x] so x,y,z it shouldn't be equivalent to 3 mod(5) as I said above, but then x, y are inverses mod (5) and so are y,z and z,x


How can I get a song tabbed?

Question: There's a song I've been dying to play, relatively simple, but I'm not good enough to figure out how to tab it. How can I get a song tabbed if I can't do it myself?
Comment: quick query - have you googled already? There are a huge amount of tunes already online as tablature:-)
Comment: @kylex - Edited to remove the pay offer, this isnt the place for that; just ask the question, maybe someone will fill your request to some extent.  Refer you to @Jeff Atwoods answer here; http://meta.guitars.stackexchange.com/questions/102/are-questions-regarding-how-to-play-song-valid - if you cant find it on the internet, then its a valid question
Comment: I have looked for it, it's a rather obscure song apparently. The lyrics aren't even available online.
Comment: If you could name the song, and/or link to a youtube video, that might help.
Comment: I made this a real question, and it now suits neilfein's excellent answer.
Answer: What you're talking about is a transcription service. However, these can be expensive, and the ones I found on a quick Google are geared towards musicians who want to put music or tabs on their own websites. Paying someone to make what's essentially sheet music of a song you don't own (I assume this is not music you own the rights to) brings up all sorts of copyright problems. You have a few options. My answer assumes you can't find tab for this song online:

Ask a friend how to play the song. Most communities of musicians have a few people who are very good at figuring out songs from the recordings.
Buy the sheet music; even if you don't read music, it'll have chords and lyrics and some even have guitar tabulature. This is your best option, and the most legal.
Learn how to figure out the music on your own. Except for the most complex music, learning how to do this isn't all that hard, but it is a skill that takes time to develop.
Ask the musician or composer. Many obscure or local musicians will be accessible in this way.
Comment: @Neil: Follow-up, the lead singer just sent me a pretty detailed email telling me how to play the song, and the tuning he uses. So frickin' awesome!
Comment: @kylex - Glad you found what you where looking for, this might still be an acceptable answer since point 4 of @Neil Fein's answer says contact the the musician/composer.  All the other points are also good advice, although they didn't work for you.  Would be interested to know which band/musician/artist it is actually.
Comment: Is it possible you can contact the composer or their estate and simply ask?
Comment: No it's not music I own, but neither is it available to purchase. The quandary of copyright.
Comment: @Neil: I have, but have not heard back from them.
Comment: That's great! Glad to hear it.
Comment: @DRL - I cheated a *little*, I added the last point after kylex's answer to my question in the comments.
Comment: @DRL: It was from a solo project by Sim Redmond.

How can I get a song tabbed?


Receive 401 error when try to retrieve Office 365 Audit log with MS Graph API with PowerShell

Question: I am trying to retrieve the audit log to track user license allocation changes.
This is the URI I use in MS Graph Explorer. It works fine in there, I can get data I want out of it.
https://graph.microsoft.com/beta/auditLogs/directoryAudits?$filter=activityDisplayName eq 'Update user'

But when I try to query with the same URI through PowerShell with the Authentication Token generated with the exact same Office 365 credential, I got error saying Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.
Did I miss anything in terms of getting the Authentication Token?
Here is the GetAuthToken function I use
Function GetAuthToken
{
    param
        (
        [Parameter(Mandatory=$true)]
        $TenantName
        )
    Import-Module Azure
    $clientId = "ef9bcdf0-a675-4cd5-9ec3-fa549f9ee4cf"
    $redirectUri      = "https://RedirectURI.com"
    $resourceAppIdURI = "https://graph.microsoft.com"
    $authority = "https://login.microsoftonline.com/$TenantName"
    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
    $Credential = Import-Clixml -Path "C:\MIMA\tom_admin_cred.xml"
    $AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $credential.UserName,$credential.Password
    $authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId,$AADCredential)
    return $authResult
}

And this is the code I use to retrieve the report
$token = GetAuthToken -TenantName $tenant
$authHeader = @{
    'Content-Type'='application\json'
    'Authorization'=$token.CreateAuthorizationHeader()
    }
$uri = "https://graph.microsoft.com/beta/auditLogs/directoryAudits?$filter=activityDisplayName eq 'Update user'"
$auditReports = Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get

Answer: Problem fixed! The issue was caused by Azure AD App was not granted "Auditlog.Read.All" permission. "Modify permission" in the MSGraph Explorer somehow does not apply to the actual Azure AD permission settings (Or it's using a different built-in Azure AD app?).
So I have to sign in to Azure portal -> Azure AD -> App registration -> Settings and added the permissions under Required Permissions. Please note, the change does take a while to take effect. I simply waited overnight and next morning I was able to retrieve the report without 401 error.
Answer: Please try the following code:
    $token = GetAuthToken -TenantName $tenant
    $authHeader = @{
        'Content-Type'='application\json'
        'Authorization'=$token.CreateAuthorizationHeader()
        }
    $uri = "https://graph.microsoft.com/beta/auditLogs/directoryAudits?$filter=activityDisplayName eq 'Update user'"

   try{
        $auditReports = Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get
   }
   catch{
        $auditReports = $_.Exception.Response
   }

Comment: The error I am getting with catch is still "Unauthorized"


Custom form calls different form in modal, submit/ajax callback of second form not called

Question: I created 2 forms:
dms_gift_voucher/src/Form/GiftVoucherForm.php
  ...

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    ....

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#attributes' => [
        'class' => [
          'use-ajax',
        ],
      ],
      '#ajax' => [
        'callback' => [$this, 'confirmGiftVoucher'],
        'event' => 'click',
      ],
    ];

    // Dialog box dependency
    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';

    return $form;
  }

  ...

  /**
   * Callback for opening the modal form.
   */
  public function confirmGiftVoucher(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    // Get the modal form using the form builder.
    $modal_form = $this->formBuilder->getForm('Drupal\dms_gift_voucher\Form\GiftVoucherConfirmForm', $form_state->getValues());

    // Add an AJAX command to open a modal dialog with the form as the content.
    $dialog_options = [
      'width' => 'calc(100% - 20px)',
      'dialogClass' => 'modal--gift-voucher-confirm',
    ];
    $response->addCommand(new OpenModalDialogCommand($this->t('Test'), $modal_form, $dialog_options));

    return $response;
  }

dms_gift_voucher/src/Form/GiftVoucherConfirmForm.php
  ...

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $values = []) {
    ...

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Confirm'),
      '#weight' => 100,
      '#attributes' => [
        'class' => [
          'use-ajax',
        ],
      ],
      '#ajax' => [
        'callback' => [$this, 'submitModalFormAjax'],
        'event' => 'click',
      ],
    ];

    // Library
    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';

    return $form;
  }

  ...

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Never called!
  }

  /**
   * {@inheritdoc}
   */
  public function submitModalFormAjax(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    // Never called!
    return $response;
  }

The first form works correct, the submit is called, the ajax callback renders the modal with the 2nd form.
But when i submit the 2nd form, nothing happens, no submit, no ajax callback called from the 2nd form.
How can i fix this? Any suggestions.
(Every example of drupal modal forms start with a link trigger with routing, but i find it strange why this approach doesn't work).
EDIT: As suggested in the comments, routing info:
dms_gift_voucher.routing.yml
dms_gift_voucher.gift_voucher_form:
  path: '/dms_gift_voucher/form/gift_voucher'
  defaults:
    _form: '\Drupal\dms_gift_voucher\Form\GiftVoucherForm'
    _title: 'GiftVoucherForm'
  requirements:
    _access: 'TRUE'

dms_gift_voucher.gift_voucher_cofirm_form:
  path: '/dms_gift_voucher/form/gift_voucher_cofirm_form'
  defaults:
    _form: '\Drupal\dms_gift_voucher\Form\GiftVoucherConfirmForm'
    _title: 'GiftVoucherConfirmForm'
  requirements:
    _access: 'TRUE'

Comment: Because of AJAX Drupal needs to know where to submit to. Add a route to your confirmation form, if you don't have one for it already, and tell me its route name so I can give you the solution.
Comment: I added the route information .
Answer: Since you're programmatically setting a modal with
$response->addCommand(new OpenModalDialogCommand($this->t('Test'), $modal_form, $dialog_options));

For the form that is in the modal, Drupal needs to know what URL it should post the AJAX to and be told that its an AJAX request because this only gets set automatically when the url key doesn't have a value.
  '#ajax' => [
    'callback' => [$this, 'submitModalFormAjax'],
    'event' => 'click',
    'url' => \Drupal\Core\Url::fromRoute('dms_gift_voucher.gift_voucher_cofirm_form'),
    'options' => [
      'query' => [
        FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
      ],
    ],
  ];

Side note: The above isn't needed with the HTML way of opening dialog boxes, had you done:

   Should load Test webform in a Modal

because it has the URL of the form and knows its an AJAX request from the class name.
Comment: Form is not rebuild when form is return in ajax callback. Rebuild is set to true, wrapper set and $form returned. Any suggestions?
Comment: Which form doesn't get rebuild? @mgoubert
Comment: The ajax forms in drupal 8 are sometimes hard to comprehend.

The form_state (getValues()) is correct if ajaxcallback has "return $form" and $form_state->rebuild() is set to TRUE in the submit handler. But if validation error happens, the submit is never called and form_state->geValues() in buildform is empty. Mabey i should make other thread.
Comment: I'm a bit lost, would be good to see what fields you have in your form and what you have in your callbacks. So yeah make a new question with those details and issue.


When is a sample size too large?

Question:
At what point exactly is a sample size considered "really large"?
In hypothesis testing, do small differences become consistently significant when n is 100,000?
What about 100,001?
Is there a definite limit between a large and a small sample size?

An example in R or a published article would also be helpful!
Comment: With _any_ sample size you need to have a clear idea what difference is of practical importance. // If you have used that difference in a power and sample size computation (and made the right assumptions) then sample size should be just the right size to have a good chance of detecting that difference. // If you have data on essentially the entire population of interest, you should be describing the population, not testing hypotheses about it.
Comment: You might be interested by this post: https://stats.stackexchange.com/questions/2516/are-large-data-sets-inappropriate-for-hypothesis-testing
Comment: As a general proposition, questions in statistics that use vague and unquantitative terms such as "really large" are considered ... vague and unquantitative; and therefore tend not to have general answers.
Comment: @Nate I wouldn't say any sample is too large. What you should do is looking at more information, in the first place a confidence interval. If the confidence interval does not contain zero (therefore the test is significant), but contains effect sizes that are so small to be practically meaningless, you haven't found anything of *practical* significance. (The wording "real difference" is misleading, as even a very small difference may be real but not meaningful.)
Comment: If one considers it a problem when a hypothesis test has enough power to reject small differences, I tend to believe that one is  misapplying frequentist statistics.
Comment: @Pitouille, I did see that one - thank you. But, I'd like to know at what point do I have to start considering that I'm seeing statistical significance because of sample size or a real difference?
Comment: Got it, thank you!
Comment: In pondering this question, I found it helpful to consider that in many areas of chemistry and physics, interesting properties of a sample can't even be measured until it contains about $10^{15}$ times as many molecules as your tentative limit of $100,000.$
Answer: A sample is too large when it costs too much. Too much time, too much money, too much effort, too many graduate students, or too many slithy toves. From the point of view of determining the properties of the statistical population being sampled, more is better.
Some of the concerns about 'overly large' samples concern a low p-value being taken as a sign of importance or real-world 'significance'. Avoid that by paying attention to the magnitude of the effect observed. Always report the effect size and always scale it relative to real world considerations.
Other concerns about 'overly large' samples come from the idea that in a repeated testing (sequential testing) situation, sampling until the p-value is smaller than any arbitrary value will always stop with the low p-value, in theory. In practice that is not true because in the real world sampling is constrained by time, money, effort, etc. And anyway, even if you did stop with a false positive low p-value from such a protocol you would most often be protected from real world mistake by paying attention to the previous paragraph.

When is a sample size too large?


Locked out from SSH, NetBoot can be useful?

Question: I am operating on a Server that is on a datacenter.
For security reasons I've disabled root access.
So yesterday I was configuring a restricted access group on the server and accidentally put the only sudoer and ssh enabled user under the group and now I'm locked off my machine.  There are months of work and configuration and effort and time on this machine running Ubuntu server 14.04.
On my dashboard of the datacenter there is an option called NetBoot.
If I open this there are 3 options: "HardDisk, Network, Rescue". I don't know what it is but i'm guessing if I can get in in some way and edit the ~/.ssh/config.
Comment: Contact your DC provider for remote-hands.
Comment: You can restore from your backups, right?
Answer: The Rescue option will probably drop you into a root shell, or possibly a live CD environment such as Knoppix.  From there you can edit any configuration files you need.


CSS Top / Left properties and Jquery animation

Question: On a page i have two divs lets say Left_Div and Right_Div. On right div i have multiple images positioned using Top and Left properties of CSS. Left_Div is used as a left panel and On a button click I animate Left_Div and Right_Div to slide right and Left_Div becomes visible. Just like left menu on facebook iphone app.
 $("#Right_Div").animate({ marginLeft: "600px" }, 500);
 $("#LeftDiv").animate({ width: "600px", opacity: 1 }, 500);

The problem is that when Left_Div and Right_Div slide then images that are positioned by using Left and Right attributes do not move and as a result they overlap Left_Div. Anyone please help me how i can move images with DIVs.
I don't want to rest top/left properties again because there are so many images and they are loaded dynamically.
I hope that i have explained my question :)
Comment: Did you tried floating images?
Comment: Means `float:left;` for the images of left division and `float:right;` for the images of right division.
Comment: I added small fiddle to my answer, demonstrating the effect floating has when other elements are moved or re-sized. Add your specific HTML and CSS to it and start applying the floating logic you want, if you get stuck getting it to work, post your fiddle and/or code you are using and I'm sure we can get it sorted.
Answer: If you want dynamic movements you cannot give exact positions.
By saying an image is a set amount of pixels from the left the image will always be exactly there, no matter what.
You would have to use a floating logic whereby you assign for example float: left or float: right to all your components you want to line up beside each other on the left or right.
Then when you are moving an element all other elements which are set to float beside it will move along with it.
DEMO - floating example using your animation logic
In the DEMO you can now see how elements move with each other when when floating is applied.
The DEMO above has the following HTML:

My left div

My other left div

My other right div

my right div

CSS:
#Left_Div, #anotherLeftdiv{
    float: left;
}

#Right_Div, #anotherRightdiv{
 float: right;
}

Script:
$("#Left_Div").animate({ width: "150px", opacity: 1 }, 500);
$("#anotherRightdiv").animate({ marginRight: "100px" }, 500);

I hope this makes sense. Without your exact current CSS and HTML it is hard to tell you exactly what it is you have to change.
Edit
I added 4 images to the right div and placed them into the 4 corners using float and clear instead of fixed positioning.
They will simply move along with the animation of the div, as long a they do not get any fixed positions.
DEMO - Animation with floating images
The images are in a div container, by using float: left and clear: rightfor example you are telling the image to go all the way to the left and force a break to the right of it. Thus any other image using float: left will be forced to go in the row below.
The same applies to the float:right and clear: right, those settings force the image to stay right and force a break to the right of it, forcing any other float: right to go into the line below.
See the images in the HTML:

The styles to force images into their corners:
img.left{
    float: left;
    clear: right;
}

img.right{
    float: right;
    clear: right;
}

I hope this helps. You should have plenty to play around with now.
If you come across any issue now with your specific implementation or any CSS you can't work out, it would be easier to complete this question and ask a new one posting the specific code you are having issues with.
Comment: @Tanveer: Has this worked out for you or do you need any more information?
Comment: thanks @ François , You have understood my issue. Just think that in ur example, in right div we display multiple images on different positions with top left positions and when this div animates , images donot move with div they maintain their positions. Do i need to animate those images as well or there is any other way? I hope that i have explained the issue
Comment: @Tanveer: I added an example using floating images. Just keep clicking the `Run` button at the top-left to re-run the animation. Fiddle around with the code and hopefully you can start applying this to your code now :)
Comment: Thanks @ François i worked on ur idea and find out the solution. Thanks for support
Comment: You are more than welcome. Glad to hear you got it sorted out.


echo JSON_ENCODE($json) only contains data for last record

Question: I am trying to use json_encode to echo some data back to my ajax call, but I seem to receiving only a portion of the data, specifically the last record.  In the query below, when I did $q->num_rows(); it correctly returns the correct number of rows, 6.  However, when I look at the resulting JSON object, I see that it only has the last pair of values for row 6.  The data for rows 1-5 is nowhere to be found.
Can anyone see what I might be doing wrong?  Thanks.
function myAjaxFunction(){
    $muni = $this->input->POST('muni');
    $q = $this->db->query("SELECT SaleYear AS Y, NewSaleType AS T, count(*) AS C, format((sum(SalePrice) / sum(Quantity1)),0) AS R FROM tblsales WHERE  tblsales.SaleYear > 2007 AND tblsales.Quantity1 > 2000 AND (tblsales.NewSaleType = 'Industrial') AND tblsales.Municipality = '".$muni."' GROUP BY T,Y ORDER BY T,Y");
    $json_SaleYear = array();
    $json_AvrgRate = array();
    foreach ($q->result_array() as $row){
        $json_SaleYear = $row['Y'];
        $json_AvrgRate = $row['R'];
    }
    $json['Y'] = $json_SaleYear;
    $json['R'] = $json_AvrgRate;
    echo json_encode($json);
    exit;
}

Comment: `$json_SaleYear[] = $row['Y'];` and `$json_AvrgRate[] = $row['R'];`
Answer: you have declared $json_SaleYear and $json_AvrgRate as array but not used array index to define value in foreach loop ,so its having only one row record i.e last record ..
change only part of your code this
foreach ($q->result_array() as $row){
        $json_SaleYear[] = $row['Y'];
        $json_AvrgRate[] = $row['R'];
    }

Answer: You're replacing the arrays with values in the foreach loop, instead of appending to the array. So on each iteration of the loop, the $json_SaleYear/AvrgRate variables are getting overwritten with the current row's information. Once the loop completes, they contain only the last row's info.
Instead of updating the variables like this,
foreach ($q->result_array() as $row){
    $json_SaleYear = $row['Y'];
    $json_AvrgRate = $row['R'];
}

You should append to the arrays like this,
foreach ($q->result_array() as $row){
    $json_SaleYear[] = $row['Y']; // Note the []'s.
    $json_AvrgRate[] = $row['R'];
}

Answer: Replace the following
$json_SaleYear = array();
$json_AvrgRate = array();
foreach ($q->result_array() as $row){
    $json_SaleYear = $row['Y'];
    $json_AvrgRate = $row['R'];
}
$json['Y'] = $json_SaleYear;
$json['R'] = $json_AvrgRate;
echo json_encode($json);

with:
$json = array(
    'Y' => array(),
    'R' = array()
);
foreach ($q->result_array() as $row){
    $json['Y'][] = $row['Y'];
    $json['R'][] = $row['R'];
}
echo json_encode($json);

Answer: Though you have declared $json_SaleYear and $json_AvrgRate as array but you are setting its values as string. The correct format is below
function myAjaxFunction(){
    $muni = $this->input->POST('muni');
    $q = $this->db->query("SELECT SaleYear AS Y, NewSaleType AS T, count(*) AS C, format((sum(SalePrice) / sum(Quantity1)),0) AS R FROM tblsales WHERE  tblsales.SaleYear > 2007 AND tblsales.Quantity1 > 2000 AND (tblsales.NewSaleType = 'Industrial') AND tblsales.Municipality = '".$muni."' GROUP BY T,Y ORDER BY T,Y");
    $json_SaleYear = array();
    $json_AvrgRate = array();
    $counter = 0;
    foreach ($q->result_array() as $row){
      $json_SaleYear[$counter] = $row['Y'];
      $json_AvrgRate[$counter] = $row['R'];
      $counter++;
    }
    $json['Y'] = $json_SaleYear;
    $json['R'] = $json_AvrgRate;
    echo json_encode($json);
   exit;
}

Comment: I agree there is no need to use counter but in no way the answer is wrong so that it should be down voted.


If $x_n \to 0$ then does $\sum \frac{|x_n|}{n} $ converge?

Question: I am now thinking "No" but I cannot come up with a counterexample.
Answer: What about $x_n=\frac1{\log n}$?
Comment: The best known answer to this question.  $\sum\frac{1}{n\log n}$ diverges.  But that is not the end: $\sum\frac{1}{n\log n \log\log n}$ diverges.  And so on.  There is no "slowest" divergent series, in the sense of the OP.
Comment: Thank you for this. I spent a very long time trying go the other way.
Answer: Set $x_n=\dfrac1{\log n}$. You obtain a Bertrand's series
$\;\sum_{n\ge 2}\dfrac1{n^\alpha\log^\beta n}$ with $\alpha=\beta=1$.
It is known that a Bertrand's series converges if an only if $\alpha >1$ or $\alpha=1$ and $\beta>1$. And specically this one, using the integral test.


Xcode console print formatting

Question: I have this method that when called:
- (void)showContent
{
NSLog(@" 0  1  2  3  4  5  6");
for (int j = 0; j < rows; j++) {
    for (int k = 0; k < columns; k++) {
        MDLog(@"[%c]", board[j][k]);
    }
    NSLog(@"");
}
NSLog(@"---------------------------------------------------");
}

That's supposed to create an empty 6 x 7 grid (for a game of Connect Four) that looks like this:
0  1  2  3  4  5  6

[ ][ ][ ][ ][ ][ ][ ]

[ ][ ][ ][ ][ ][ ][ ]

[ ][ ][ ][ ][ ][ ][ ]

[ ][ ][ ][ ][ ][ ][ ]

[ ][ ][ ][ ][ ][ ][ ]

[ ][ ][ ][ ][ ][ ][ ]

---------------------------------------------------

However, the Xcode console doesn't print it that way at all. It displays each column vertically on top of one another. Other useful info is I have
int rows; // initializes to be 6
int columns; // initializes to be 7
char board[6][7];

Xcode prints it this way:
 0  1  2  3  4  5  6

[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]

[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]

[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]

[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]

[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]

[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]

---------------------------------------------------

Comment: try this http://stackoverflow.com/questions/3244707/nslog-without-new-line
Comment: pls add how xcode prints it ?
Comment: @TejaNandamuri check now
Comment: is MDLog does same as NSLog do ?
Comment: @TejaNandamuri yes, it's a macro. I just use it to get rid of timestamps from the console
Comment: @TejaNandamuri that worked. thanks! I'm not sure why NSLog wasn't working in the first place.
Answer: You could concatenate the string for each line and print it all at once.  Alternatively you could use printf().  printf() does not add a newline so it would create the desired outcome.
- (void)showContent
{
    NSLog(@" 0  1  2  3  4  5  6");
    for (int j = 0; j < 6; j++) {
        for (int k = 0; k < 7; k++) {
            printf("[ ]");
        }
        printf("\n");
    }
    NSLog(@"---------------------------------------------------");

}

Xcode console print formatting


Abstract Monomorphism 3 part Question

Question: I have been working on this problem for an hour now and gotten nowhere:
Let $G$ be any group and $A(G)$ the set of all 1-1 mappings of $G$, as a set, onto itself. Define $L_a : G \rightarrow  G$ by $L_a(x) = xa^{-1}$. Prove that:
(a) $L_a$ is an element of $A(G)$
(b) $L_aL_b = L_{ab}$
(c) The mapping $\psi : G \rightarrow A(G)$ defined by $\psi(a) = L_a$ is a monomorphism of $G$ into $A(G)$
Comment: What have you worked out so far?
Comment: Nowhere? Did you manage (a)? If not, what is the difficulty with (a)?
Answer: Hints which almost solve everything:
(a) You need to find a left inverse... maybe consider $L_{a^{-1}}$.
(b) Write it out and you will see that $b^{-1}a^{-1} = (ab)^{-1}$ will do the job.
(c) So if $L_a = L_b$ you need to figure out, that $a=b$ for injectivity. How can you do so? just write down what the maps do on an element $x \in G$. And use (b) for the proof that this map is a homomorphism.
Comment: Sorry I am very new here, it will not allow upvotes until I have 15 rep  points.
Comment: Thank you very much, your hints were more than enough!
Comment: I am glad that I could help. Have fun on MSE then.

Abstract Monomorphism 3 part Question


A fair coin is tossed $\text{10 times}$. What is the probability that ONLY the first two tosses will yield heads?

Question: Question

A fair coin is tossed $\text{10 times}$. What is the probability that ONLY the first two tosses will yield heads?

My Solution
Here from the question we can conclude that the event i.e tossing $10$ coin are independent,hence
probablity of head=probablity of tail$$=\frac{1}{2}$$

Hence ,
$(\frac{1}{2})^2 \times (\frac{1}{2})^8 =(\frac{1}{2})^{10}=\frac{1}{1024}$
Am i correct ?Becuase answer given is $\frac{1}{4}$
Thanks
Comment: Your answer seems correct
Comment: Do you mean to say the probability of 2 heads followed by 8 tails or are 1 or 0 heads in the first two tosses permissible as well.?
Comment: Your answer is correct, because of the word "only" in the question. Their answer would be correct if the word "only" was omitted, i.e. if the remaining 8 coin tosses could have any outcomes instead of all tails.
Comment: ... or if the word "only" came towards the end of the sentence @JaapScherphuis.
Comment: @JaapScherphuis ,Chase,Jaap still the answer is not clear .is it $\frac{1}{1024}$ or $\frac{1}{4}$
Comment: Your answer is 1/1024. Chase and I both wrote that your answer is correct. How is that not clear?
Comment: okk thank you .Actually 2 upvote on $\frac{1}{4}$ confused me .Thanks
Answer: The event in the question can happen in only one way. The total number of possible outcomes, the sample space, is
 $ 2^{10}= 1024 $. So, the probability is $ 1/1024 $.  If heads or tails were allowed in the remaining 8 tosses then the number of outcomes would be $ 2^8 = 256 $ and the probability would then be $ 256/1024 = 1/ 4 $.