How to hide header tag from angular controller

Question: I am building an angular application with multiple controllers.
Here is my index page:

          Option 1
          Option 2
          Option 3
          Option 4

The pages of the application get rendered inside the div container. The first one gets loaded is the login page. I want to hide the header when login page is loaded and only show it whenever the page that is not a login page gets loaded. What's the best way to do that?
Should I hide it in the Login page controller?
Here is my login page:

        <form id="frmLogin">
            Please enter your ID:

                <input type="text" class="form-control" id="Username" ng-model="lc.user">

            <input type="button" class="btn_main" value="Login" ng-click="Login()">

            {{lc.UserValidate}}
        </form>

and here is a base controller for my index page:
(function () {
var app=angular.module("myApp", ["ui.router"]);
app.controller("BaseCtrl", ["$scope", BaseControllerFunc]);

function BaseControllerFunc($scope) {
      //$('header').hide();
      console.log($scope.HdrSection.ShowMenu);
      $scope.HdrSection = { ShowMenu: false };
      $scope.HdrSection.ShowMenu = false;
      console.log($scope.HdrSection.ShowMenu);
   }

})();

So far I tried 2 things:
 using $('header').hide(); which works the first time page is opened but then I have no way to show the header again from any other child controller loaded by the page
and setting ng-show attribute of the header section to false in my base controller did not work as $scope.HdrSection.ShowMenu comes up as undefined
Can anyone help?
I load a number of different pages into the container div and each has its own controller. The only one I do not want header shown for is the login page
Comment: you can use ($rootScope.$broadcast and $scope.$on) event to this. in fact one of communicate between controllers is use of $broadcast. in fact when you have success login set  $scope.HdrSection.ShowMenu = true else it is false;
Comment: The issue is that $scope is undefined
Answer: Try passing explicit the $scope form the controller injection as follow:
  app.controller("BaseCtrl", ["$scope", BaseControllerFunc($scope)]);

  function BaseControllerFunc($scope) {
   ...
   }

})

Comment: That's not the issue. The issue is that I am unable to set $scope.HdrSection.ShowMenu. The $scope comes up as undefined
Comment: Try passing explicit the $scope form the controller injection like this: app.controller("BaseCtrl", ["$scope", BaseControllerFunc($scope)]); I edited my answer.
Answer: Got it to work by changing my controller code to:
(function () {
    var app=angular.module("myApp", ["ui.router"]);
    app.controller("BaseCtrl", ["$scope", BaseControllerFunc]);

    function BaseControllerFunc($scope) {
        $scope = { ShowMenu: false };
    }

})();

Now whenever the page loaded, the header is hidden and can be enabled by setting
$scope.parent = { ShowMenu: true };

from all other controllers


Receiving a KeyError for 'request' in DRF serializer when using detail_route in my ViewSet

Question: This is my ViewSet:
class PostViewSet(viewsets.ModelViewSet):
    serializer_class = PostSerializer
    permission_classes = (IsAuthenticated, IsOwnerDeleteOrReadOnly)

    def get_queryset(self):
        return Post.objects.filter(location=self.request.user.userextended.location)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user, location=self.request.user.userextended.location)

    def get_serializer_context(self):
            """
            Extra context provided to the serializer class.
            """
            return {
                'format': self.format_kwarg,
                'view': self,
                'location': self.request.user.userextended.location
            }

    @detail_route(methods=['post'], permission_classes=[IsAuthenticated, IsFromLocation])
    def like(self, request, pk=None):
        post = self.get_object()
        post.usersVoted.add(request.user)
        return Response(status=status.HTTP_204_NO_CONTENT)

    @detail_route(methods=['get'], permission_classes=[IsAuthenticated, ValidPostPkInKwargs, IsFromPostLocation])
    def replies(self, request, pk=None):
        post = self.get_object()
        replies = post.postreply_set.all()
        serializer = PostReplySerializer(replies, many=True)
        return Response(serializer.data)

And this is my PostReplySerializer:
class PostReplySerializer(serializers.ModelSerializer):
    owner = serializers.SlugRelatedField(slug_field='username', read_only=True)
    voted = serializers.SerializerMethodField()

    def get_voted(self, obj):
        return self.context['request'].user in obj.usersVoted.all()

    class Meta:
        model = PostReply
        fields = ('id', 'owner', 'post', 'voted', 'location')

The error points to the line
return self.context['request'].user in obj.usersVoted.all()

and says:
KeyError at /URL/20/replies/
'request'

Any idea why DRF says 'request' is a key error even though (from my understanding) it should be automatically in self.context?
Note that PostViewSet works perfectly fine for all other requests (if I get a Post, get a list of posts etc.). It just doesn't work for replies.
Answer: It's not in self.context because you have overridden get_serializer_context. request object is attached to context via this method. Just add request: self.request in your return statement of get_serializer_context that would solve the problem. Take a look at default implementation of get_serializer_context here https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/generics.py to understand more. Hope it helps..
EDIT
Since you are using different serializer(PostReplySerializer) in detail_route, you need to create serializer instance like serializer = PostReplySerializer(replies, many=True, context={'request': self.request})
Comment: yea.. Thats because you are using different serializer in detail_route. Try passing `context={'request': self.request}` while creating the serializer instance. like `serializer = PostReplySerializer(replies, many=True, context={'request': self.request})`. This would solve the problem.
Comment: Good question. Actually take a look at the actual code of view set that get the correct serializer https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/generics.py#L104  here whatever seraizer you are giving in `serializer_class` will only get the `context` automatically. Other serializers you have to manually give the context while creating the serializer instance. Hope this is helpful..
Comment: Strange. Even when I add `'request': self.request,` in the return statement, I still get the same error. could it possibly have something to do with the fact that the serializer I am using in my detail_route is different than the one I am using in my viewset? Edit: Even when I remove `get_serializer_context()` completely from my viewset and not override it, I still get the same error as well for some reason.
Comment: Oh okay thanks! Any idea why the detail_route does not receive the serializer contexts even though it is part of the same viewset? Is there any documentation which mentions it? I'm asking just so I can understand what exactly is going on. Thanks in advance!


Drupal add class to body if page is unpublished

Question: I would like to be able to add an unpublished class to the body tag of a node (for both its main view and edit view) if the node has been unpublished.
How can I do this?

Steps I have taken:
1) Node Object
The node object contains if a node has been published or unpublished (with $node -> Status), but I am not sure how to test this for each node and then add it to the body class.
This question is similar, but the provided answer doesn't work.
2) Drupal 6
This page explains how to do it for Drupal 6, but the code doesn't work for Drupal 7.
Answer: in your theme's template.php:
function mytemplate_preprocess_html(&$vars) {
  $node = menu_get_object();
  if ($node && isset($node->nid)) {
    if ($node->status) {
      $vars['classes_array'][] = 'published';
    } else {
      $vars['classes_array'][] = 'unpublished';
    }
  }
}

Comment: This will work for EACH theme you add it to, so if you are using a backend theme you have to add it to the template.php file for that theme as well as your front-end theme.


Best way to validate an email address in WinForms

Question: I have a simple textbox with an email address.
I need to know the best and easiest way to find out whether that email address is valid or not. I want to know how I can do that.
I have tried using the below code but it does not display any message for me? Can anyone point the mistake I am making?
Public Function IsValidEmailAddress(ByVal email As String) As Boolean
    Try
        Dim ma As New MailAddress(email)
        MsgBox(True, MsgBoxStyle.Information)
    Catch
        MsgBox(False, MsgBoxStyle.Information)
    End Try
End Function

I am calling this function like this:
Call IsValidEmailAddress(txtEmail.txt)

Comment: I don't know what `MailAddress()` does, but a lot of email address validation routines get it wrong, because the rules are more complicated than most people realize (https://en.wikipedia.org/wiki/E-mail_address#Syntax). So be careful that you don't end up excluding users w/weird email addresses.
Comment: @Bill-Thanks for the info and i'm going to have a look at the link.
Comment: possible duplicate of [How do I validate email address formatting with the .NET Framework?](http://stackoverflow.com/questions/1331084/how-do-i-validate-email-address-formatting-with-the-net-framework)
Answer: Assuming that your call code is not a typo, the problem is you are not using the correct property:
Call IsValidEmailAddress(txtEmail.txt)

should be:
Call IsValidEmailAddress(txtEmail.Text)

I have verified that the IsValidEmailAddress works correctly.
Comment: @Kiran: My original answer was incorrect, so I modified it to show what I believe is the problem. I have verified that IsValidEmailAddress does work correctly when it is called correctly.
Comment: @Competent_tech-First thanks for the info and I am surprised that What's going wrong with my code!I'm unable to get any messages.Is there any fault with my code?
Comment: Ah silly mistake again!Thanks for pointing out the right mistake.
Comment: Yes,I have checked your modified code.Now everything goes fine.


$\bmod p\!:\ x^2\equiv 1\iff x\equiv \pm1\ $ for prime $p$

Question: Let $p$ be a prime. Show that for all integers $x$, $x^2\equiv 1 (\text{mod} \ p) $ if and only if $x \equiv 1 (\text{mod} \ p)$ or $ x \equiv p-1 \ (\text{mod} \ p ). $

I know that I have to prove this both forward and backward. I'm not really sure where to begin
Comment: $x^2-1=(x-1)(x+1)$
Answer: The direction $(\Leftarrow)$ is clear. For $(\Rightarrow),\,$ if $x^2 \equiv 1 \pmod p$, we have $$x^2 - 1 \equiv 0 \!\!\!\pmod p \iff (x - 1)(x + 1) \equiv 0 \!\!\!\pmod p \iff p\mid (x - 1)(x + 1)$$
By Euclid's Lemma, since $p$ is prime, $p$ divides the product iff it divides one of the terms, and the result follows.
Answer: The proof in T. Bongers answer is perhaps the most direct way to proceed. A slightly more general viewpoint lends further insight, since it relates to our prior intuition about the number of roots a polynomial may have. Recall that if $x=1$ is a root of a polynomial $f(x)$ then, by the Factor Theorem, we infer: $\ f(x) = (x-1) g(x)$. Now suppose that $x = r \ne 1$ is a different root. Now eval'ing at $\,x\!=\!r\,$ $\Rightarrow f(r) = (r-1) g(r)\equiv 0.$ Since $r-1\not\equiv0,\,$ we know, by Bezout, that it has an inverse $s.$ Multiplying by $s$ we infer $g(r)\equiv 0.$ Hence every other root of $f$ is a root of the lower degree polynomial $g$. Thus if $f$ is quadratic then the only other root of $f$ is the root of the linear polynomial $g$. In particular, a quadratic has at most two roots.
By induction on the degree of $f$ the same proof shows that a nonzero polynomial has no more roots than its degree. Note that the only property of the integers mod $p$ that we employed is that nonzero elements are cancellable. Thus the proof will work in any "number system" that has this property, i.e. any integral domain. In fact, it is easy to show that this property characterizes integral domains, i.e. every nonzero polynomial has no more roots than its degree $\iff$ every nonzero element is cancellable.


Maximum of a convex function in an interval

Question: Let $f:[a,b]\rightarrow \mathbb{R}$ a convex function. Does $f$ have a maximum in $[a,b]$?.
I have thought that if $f$ is not continous at $x=a$ or $x=b$ then I can find a counterexample for which it does not exist a global maximum. The same thing for minimum. Is it right?
Answer: If $f$ is convex, then it is continuous (and therefore upper semicontinuous) on $(a,b)$.
I claim that $f$ is upper semicontinuous at $a$ and $b$. If $x \to a$ from the right, we can write $x = \lambda a + (1-\lambda) b$, then by convexity
$$f(x) \leq \lambda f(a) + (1-\lambda) f(b),$$
and therefore
$$\limsup_{x \to a} f(x) \leq \limsup_{\lambda \to 1}(\lambda f(a) + (1-\lambda) f(b)) = f(a).$$
A similar argument works for $x \to b$ from the left.
Since $f$ is upper semicontinuous on the compact set $[a,b]$, it attains a maximum. (Intuitively, the idea here is that if $f$ is discontinuous at an end point, the discontinuity must be an "upward jump" in order to preserve convexity.)
But $f$ need not attain a minimum. For example, consider
$$f(x) = \begin{cases} (x-b)^2, \ \ x \in [a,b)\\ 1, \ \ x=b.  \end{cases}$$
Comment: How prove the idea for the maximum?
Comment: @pawel [Have a look at this](https://math.stackexchange.com/questions/1698452/maximum-of-a-upper-semicontinuous-function#1698489)


Calculating cumulative values in laravel

Question: I am looking for a way to calculate cumulative of values of database in laravel.
Currently I retrieve a collection of values, one for each day. I would like to be able to show the cumulative value on the page. I want something like this

Code in my controller is :

Here I retreive the values of fabrication and erection from form. I want to calculate cumulative of fabrication and erection value for each day...
Comment: post your code!
Comment: I have edited the question.. can u please check it
Comment: Post your code as code not as an image
Answer: You can simply do this in the view:
<?php $cumulative = 0; ?>

@foreach ($collection as $object)
    <?php $cumulative += $object->value; ?>
    {{ $object->value }} | {{ $cumulative }}
@endforeach

Comment: Logic like this shouldn't be done on the view, it should be at the very least done on the controller and past through to the view, this would mean you can use the $collection->each(function () {}) format too.
Comment: @James why not? It's a simple iteration. Of course, you can prepare the data before passing it to the view, but I wouldn't do that for such a simple operation.
Comment: Logic should be kept away from your views and only data should really be passed through, it is generally taught that you do not place logic into a view (loops and if are acceptable) this breaks down your business logic from views. It helps with code readability as I know the furthest point logic should be is the controller. The strength of an MVC framework relies on Models being used to run queries and calculations, views for displaying HTML and Controllers for passing data and running logic (although delegation to other classes is usually expected)
Comment: An extension of this is if you decide to implement an API, suddenly important logic is in the view that you haven't touched in months and you can't work out why are not getting the same data to your endpoint. It's more best practice than anything else
Comment: @James well, we pass the data here and work with it. You can also work with collection data using complicated collection helpers chaining, I don't see anything wrong in that. It doesn't violate MVC.
Answer: Create a function and follow with that
public function CumulativeCalculator($accounts){

    $driverAccounts     = [];
    $cumulativePayments = 0;
    foreach($accounts as $account){

        $cumulativePayments += $account->value;
        $currentDriverAccounts  = [];
        $currentDriverAccounts['id'] = $account->id;
        $currentDriverAccounts['realValue'] = $account->value;
        $currentDriverAccounts['cumulativeValue']  = $cumulativePayments;
        array_push($driverAccounts,$currentDriverAccounts);
    }
    return $driverAccounts;

}

In your View do this

        Values
        Cumulative Values

        @foreach($driverAccounts as $dataValue)

                {{$dataValue['realValue']}}
                {{$dataValue['cumulativeValue']}}

        @endforeach

That will work for you, sorry i was in a hurry but it will work.


MySQL Add column with default value, Syntax with QUOTES

Question: I am doing well with mySql, but when it comes to some quirks I am struck.
This is something I used for years successfully

$sql = "ALTER TABLE " . $Tablu . " ADD " . $Colu . " varchar(" . intVal($Siza) .")";

What I want now is just add a DEFAULT value for the new column I am adding.
Please provide a syntax WITH THE EXISTING STRUCTURE of the query. That is with THE QUOTES
I am trying this

$sql = "ALTER TABLE " . $Tablu . " ADD " . $Colu . " varchar(" . intVal($Siza) .") DEFAULT ('" . $defa . "')";

But it is NOT working
I CANNOT understand the without-quotes-mysql game at all.
Thanks in advance
Comment: What have you done to add `DEFAULT`? Did you try something?
Comment: Yes, I have edited the original to show what I am currently trying
Comment: Tried with a '=' after DEFAULT, tried with 'SET' before DEFAULT, nothing works.
Comment: MySQL is and most of its users are NOT consistent all over the net. The greatest evil is the quotes-no quotes play. The given answer here worked for String field. But the same is NOT working for a memo field. Still looking for a solution..
Answer: you query is ok .. you just need to remove those brackets () around $defa.. like this-
$sql = "ALTER TABLE " . $Tablu . " ADD " . $Colu . " varchar(" . intVal($Siza) .") DEFAULT '" . $defa . "'";

Comment: Thank you Manoj. I thought I had tried all alternatives. Anyway, it worked.
Comment: But Manoj, It worked for string field. But with a MEMO field, no luck. Any ideas?

$sql = "ALTER TABLE " . $Tablu . " ADD " . $Colu . " Text DEFAULT '" . $defa . "'";

Answer: This might be the correct way to do it.
$sql = "ALTER TABLE " . $Tablu . " ADD " . $Colu . " varchar(" . intVal($Siza) ." DEFAULT 'default_value')";

Comment: Syntax is correct and what you posted latter is also correct but one reson this might not be working is your `$Siza` could be less than the length of `$defa`.
Answer: You can set the default value in the quotes itself using
SET DEFAULT 'value' OR SET DEFAULT NULL
Your query will be like
$sql = "ALTER TABLE " . $Tablu . " ADD " . $Colu . " varchar(" . intVal($Siza) .")" . " SET DEFAULT " . $defa;
Answer: Try this
$size = intVal($Siza);
$sql = "ALTER TABLE {$Tablu} ADD {$Colu} VARCHAR({$size}) DEFAULT '{$defa}'";

Comment: Please add some explanation to your answer


Links converting to plain text

Question: I've got a function that should generate a link as such Set Password, which does happen, but it is generating as plain text.
My guess is that this is due to my use of the t() and l() functions in the manner I'm using them.
Here's my code:
  global $user;
  $account = new stdClass();
  $account->uid = $user->uid;
  $account->login = $user->login;
  $account->pass = $user->pass;
  $link = l('Set Password', user_pass_reset_url($account));
  $token = t(token_replace(variable_get('listing_edit_free_activated_page', 'Your free content has been activated. Thanks! @link')), array('@link' => $link));

As you can tell, I'm attempting to generate a one-time user login link with the text, "Set Password". The token_replace() isn't really relevant to this problem.
Am I completely without options here? I want to use both t() and l() here - there's not really an easy way to not use both that I can see.
How do I use both while still maintaining the structure of $link as a link?
Comment: what are you trying to translate? `Set Password` or `Your free content has been activated. Thanks!` i dont get it
Comment: Your free content and set password should both be translatable. But the former, not the latter specifically.
Answer: The t function's first argument is a string, and the second is a keyed array of arguments (search => replace).
The string your passing in is:
token_replace(variable_get('listing_edit_free_activated_page', 'Your free content has been activated. Thanks!'))

And the replacement your searching for it @link.
As the string @link does not appear in the string your passing in no replacements are made.
Here is an example where a replacement will be made:
$text = t("@name's blog", array('@name' => format_username($account)));

Comment: The variable_get is delivering a @link in this case, my apologies for not clarifying that. You can just as well imagine the default string containing it.
Comment: I fixed the example to be clearer.
Answer: The answer I was looking for was to change the placeholder to !link.
@link gives only the plain text
!link gives the raw information
%link HTML escapes and highlights
This example page is for Drupal 6, but has more information on the placeholders:
https://api.drupal.org/api/drupal/includes%21common.inc/function/t/6

Links converting to plain text


CKEditor scayt Plugin module

Question: I'm trying to build a scayt module to be able to use the CKEditor scayt Plugin. I tried to use this module but it did not work for me. https://github.com/nikhildodeja/scayt  I created my own but I get a WSOD when I veiw a node creat page. The module is below. What am I doing wrong?
        <?php

    /**
    * @file
    * Definition of \Drupal\scayt\Plugin\CKEditorPlugin\Scayt.
    */

    namespace Drupal\scayt\Plugin\CKEditorPlugin;

    use Drupal\ckeditor\CKEditorPluginBase;
    use Drupal\editor\Entity\Editor;

    /**
    * Defines the "Scayt" plugin.
    *
    * @CKEditorPlugin(
    *   id = "scayt",
    *   label = @Translation("Scayt CKEditor")
    * )
    */

    class Scayt extends CKEditorPluginBase{

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::getDependencies().
    */
    function getDependencies(Editor $editor) {
    return array('panelbutton','floatpanel','menu','menubutton','dialogui','button');
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::getLibraries().
    */
    function getLibraries(Editor $editor) {
    return array();
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::isInternal().
    */
    function isInternal() {
    return FALSE;
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::getFile().
    */
    function getFile() {
        return 'libraries/scayt/plugin.js';
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginButtonsInterface::getButtons().
    */
    function getButtons() {
    return array(
      'Scayt' => array(
        'label' => t('Spell Check'),
        'image' => 'libraries/scayt/icons/scayt.png',
      ),
    );
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::getConfig().
    */
    public function getConfig(Editor $editor) {
    return array();
    }
    }

Comment: If its a WSOD there must be an error log somewhere.
Comment: Going to assume you don't have the Panel Button module + plugin installed. Beyond that you will need to provide error logs.
Comment: I do have Panel button installed and a few other plugins. watchdog shows no errors. I was able to get the button into the ckeditor toolbar. But after messing with my module I could not load the node create page
Answer: Without seeing the error it's difficult to know, but you do at least need to extend CKEditorPluginBase rather than PluginBase:
use Drupal\ckeditor\CKEditorPluginBase;

class Scayt extends CKEditorPluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface {

Otherwise the required interface methods won't be satisfied.
Comment: You are right I should use both of these: use Drupal\editor\Entity\Editor;
use Drupal\ckeditor\CKEditorPluginBase;
Comment: I also left out its dependencies: panelbutton','floatpanel','menu','menubutton','dialogui','button
Comment: I also looked at a Drupal 7 site that has Scayt working and found there are 2 scayt buttons that need to be added. One is called Spell check and the other "Spell Check as You Type" button to your toolbar
Comment: I got Scayt work. I updated my first post with the code. I am trying now to enable scayt when the node opens? Also in Drupal 8 how can I add ckeditor config like this: config.disableNativeSpellChecker = false;
Comment: You need to do a combination of things. Check the CKEditor CodeSnippet module for tips on what to do in all of those cases.

CKEditor scayt Plugin module


Piano parallel chord jump technique?

Question: Trying to learn blues piano, there are lots of times both left and right hands make the same jump, say from I to V.
Besides "keep practicing", are there any helpful tricks to landing in the right place with both hands? Any way of spotting where you land, etc?
Comment: Take a look at [this answer](https://music.stackexchange.com/a/111569/70803). The question is unrelated, but the answer describes a practice technique relevant here. Specifically, look at the portion of the answer labeled 1a–c.
Answer: Only the most simplistic arrangement of a I - IV (surely I7 - IV7 if this is the blues?) involves the same jump in both hands.  You're not going to play anything as lumpy as this, are you?

This is more likely, and more useful.  No jumps involved (note the fingerings I've added).

But there are times when you'll need to jump.  Here's a starter exercise,  (Again, note the fingerings.)  Keep your hand quite close to the keys, move it in a shallow arc.

Don't scrunch your hand up - because your next exercise might be this:
Answer: Make sure you have a good posture, get good fingerings, and practice. An important thing is knowing when to jump. For example, you can switch from C major to 2nd inversion F major by just moving 2 fingers
A good way to practice chord jumps is just playing a major / minor scale and adding a major / minor third and a perfect fifth, like this

Once you can do that at a good speed, start practicing bigger jumps, for example

Make sure to practice in different keys as well, as black keys can make it a lot harder.
Comment: CHROMATIC scale?
Comment: @LaurencePayne sorry, I meant major / minor scale. Edited my answer
Comment: Your example actually shows a major scale, harmonised with major/minor triads.
Answer:
...Any way of spotting where you land, etc?

Using your I V example...

...that rhythm notation is a bit contrived, but I'm trying to approximate the idea of holding down the common piano key as a way to concentrate on it as the "spot" to target. Literally striking that common key with a quarter note while releasing the other fingers with the eighth note rest is just a way to emphatically take notice of that key as a target for the position change.
In the fingering notice the part highlighted in yellow, those are the fingering changes for the common piano key, the Gs. The technique (the trick) is make the change of position a matter of replacing finger 1 with finger 5 on the same piano key, and vice/versa on the chord and direct on movement. When fingers 1 and 5 are targeted as a finger exchange on the same piano key the rest of it becomes just a matter of letting the other fingers fall in place according to the basic "five-finger" position to complete the chord in thirds.
As I said, the notation is contrived. I just meant something that would highlight the finger exchange on a common piano key. In reality, I think this becomes more of a "mental image" of the keyboard matter. You note where a finger is spatially with your "mental map", or whatever you want to call it, and you just execute: "put 5 where 1 is."
This isn't the only way to do it. You can also use tactile clues to make a jump on the keyboard by feeling the groupings of 2 and 3 black keys as your fingers brush lightly over the tops of those keys.
Of course if your chord change situation changes, the fingering changes will be different too, but the idea is to think about what technique (not trick) to apply. I would imagine most cases for "jumps" will either target a common piano key or an adjacent key. If, for example, the jump was I IV, you would still focus on the change of fingers 5 and 1, but instead of replacing fingers on a common piano key, you would target the lower, adjacent key.
If you haven't practiced things like five-finger patterns, repeated notes, silent finger exchanges, you should. They will be the basis for a whole lot of fingering solutions.
Comment: That's super helpful and what I was looking for, I will mark it answered shortly.  Are there any books with "five-finger patterns " etc?   Especially with some exposition not just exercises?   While I wait for COVID to moderate in craziness before I get a teacher...  (The other posts were nice, but this post has a technique not just exercises.)
Comment: imslp.org has lots of piano method stuff. There's different kinds, dry technical https://imslp.org/wiki/Preparatory_Exercises_(Faelten%2C_Carl), simple classical https://imslp.org/wiki/Les_cinq_doigts%2C_Op.777_(Czerny%2C_Carl), and this unique one is contrapuntal! https://imslp.org/wiki/200_Short_Two-Part_Canons%2C_Op.14_(Kunz%2C_Konrad_Max). At the site look for 'piano method', 'preparatory exercises', etc.
Comment: I would happily pay for a book of piano exercises with the detailed explanation you provided.  There's lots of exercises with fingerings, just none with good rationale explanations that I have seen.  Also -- how does one get the staff and music displayed in this forum like you and the other answers did?
Comment: I used Musescore to make the staff notation. There are other notation programs like Sibelius and Encore, but Musescore is open source (free cost) so it's easy to just download it and start working.

Piano parallel chord jump technique?


Left Right Hand Co-ordination on Piano

Question:
Possible Duplicate:
How can I significantly improve my hand independence on piano?

I'm a intermediate piano student (I can play almost without a break if you give me notes but am still poor on chords). Recently, I picked up songs with chords in them which require a rhythm (like Piano Man) on the left hand and notes on the right (The lyrics). I am unable to manage my left and right coordination; for some reason my hands love symmetry and if i trying to play a rhythm chord on my left hand and lyrics on my right, I end up doing the lyrics on both or chords on both. I am unable to get my left and right hands do different things. How do I improve this?
I know the obvious answer is "practice". But my question is HOW? What specifically do I need to do in order to improve this aspect.
Answer: Here are two things you should practice. The first is more an exercise, the second repertoire.

Play two-handed scales at different rates with each hand. For every two notes in the right hand, play one in the left hand. Similarly, to further teach hand independence, play each with a different articulation. Left hand legato, right hand staccato. This can be practiced by keeping the left hand's fingers always on a note, and lifting the right hand off after each note played, to encourage hand and arm independence. You can easily make up other variations. The key, as with all practice, is to start exactly as slowly as you need to play it perfectly. Do not speed up until you can play it perfectly at whatever tempo you are currently at.
Some of the best music to learn this skill is counterpoint. Counterpoint has various voices acting independently. I would suggest starting with works of J.S. Bach, perhaps the six little preludes. Find one you like and can play well with a few months practice. There are many other compositions and composers in this section, too, though they vary in difficulty. Fugues are fantastic for learning hand and finger independence, but they are more difficult, as they generally have 4 or 5 voices at once.
Answer: What I do is just sloooow it down.
Take just ONE bar, and figure out which fingers go first and which fingers wait for what.
Play JUST the notes NOT in time.
Dont' care about rhythm or staying in a tempo until you know
- which notes you'll be playing
- which fingering you'll be using (write the fingering DOWN if it's not obvious so you always play the same passage with the same fingering)
- which notes of either hand play together and which notes don't play together.
Ya just have to slog through it until your fingers reflexively know the song.
Pick another song? - new set of reflexes.  That's what makes learning a song slow.
That's why bands can pick up a song so much quicker.
For a piano soloist, each hand is a "guy" needing it's own brain.
But you've only one brain so it has to switch off.
In a band, you're just playing one part and the keyboard dude usually just
fills in "in between chords" - much easier than a piano solo where you're
playing bass, chord, melody, rhythm alllll by yourself.
Good luck to ya.

Left Right Hand Co-ordination on Piano


Erro - Update de senha bcrypt mongoose sem encriptação

Question: Não estou conseguindo encriptar minha senha durante um update usando bcrypt no mongoose. A senha é alterada sem problemas, mas sem encriptação.
Segue o schema:
var mongoose= require('mongoose');
module.exports= function(){
var schema= mongoose.Schema({
    email:{
        type: String,
        required: true
    },
    senha:{
        type: String,
        required: true,
        bcrypt: true
    },

});

schema.plugin(require('mongoose-bcrypt'));
return mongoose.model('Usuario', schema);}

Segue trecho do controller:
controller.updateUsuario= function(req, res){

    var Usuario= app.models.usuario;

    var _id= req.params.id;

    // Atualização de cadastro
    if(_id){
        Usuario.findByIdAndUpdate(_id, req.body).exec()
            .then(
                function(usuario){
                    res.json(usuario);
                },
                function(erro){
                    console.error(erro);
                    res.status(500).json(erro);
                }
            );
    }};

Answer: O problema é que o findByIdAndUpdate, assim como a maior parte das funções da família update do mongoose, não instanciam o Model e por isso, não executam:

defaults
setters
validators
middleware

Há uma nota sobre isso no final da documentação do método findByIdAndUpdate [1]. O recomendado é substituir com:
Model.findById(id, function (err, doc) {
  if (err) ..
  doc.name = 'jason borne';
  doc.save(callback);
})

Claro, aí você está fazendo duas queries e fica a seu critério se isso é um problema ou não. Suponho que quando está atualizando o usuário, já o autenticou e portanto já tem o seu documento na memória. Nesse caso, você não teria que dar esse find, só arrumar um jeito de dividir a instância usada na autenticação com a rota.
Usando passport, em geral, há uma instância do documento (ou o que quer que seja passado para passport.deserializeUser na propriedadereq.user`.
[1] - http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate
Answer: Sou iniciante, mas acredito que o codigo abaixo te ajudaria:
controller.updateUsuario= function(req, res){
var Usuario= app.models.usuario;
var _id = req.body._id;
var dados = {
        "nome" : req.body.nome,
        "email" : req.body.email
};

// Atualização de cadastro
if(_id){
    Usuario.findByIdAndUpdate(_id, dados).exec()
        .then(
            function(usuario){
                res.json(usuario);
            },
            function(erro){
                console.error(erro);
                res.status(500).json(erro);
            }
        );
}};


Unexpected keyword error when running rspec test

Question: All,
When running my rspec tests the script is failing before running the tests. It looks like it is expecting an "end" somewhere in the function "up_votes" but I can't see where?  Is it anything else possibly?
Up_votes function description:
The function is supposed to add to the array if the value of the vote is 1 and doesn't add it, if it is -1.  Once that loop is completed, then it is supposed to sum the total number of votes(up votes) in that array.
Error output:
/Users/user/.rvm/rubies/ruby-  2.2.1/lib/ruby/gems/2.2.0/gems/activesupport-  4.2.1/lib/active_support/dependencies.rb:274:in `require':     /Users/user/code/bloccit/app/models/post.rb:63: syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)

Post.rb file which contains the up_votes method:
class Post < ActiveRecord::Base
 has_many :comments, dependent: :destroy
 has_many :votes
 has_one :summary
 belongs_to :user #means the post table has the user table's primary key in it
 belongs_to :topic
 mount_uploader :avatar, AvatarUploader
 default_scope {order('created_at DESC')}

 validates :title, length: {minimum: 5},  presence: true
 validates :body,  length: {minimum: 20}, presence: true

 def markdown_title
  (render_as_markdown).render(self.title).html_safe
 end

 def markdown_body
  (render_as_markdown).render(self.body).html_safe
 end

 def up_votes
  vote_array = []
  sum = 0
    vote_array = @post.votes.value.each do |vote| unless  @post.votes.value == -1
     vote_catch = vote_array
    end
     vote_catch.each do |vote|
     sum += vote
    end
     sum
  end
  end

Rspec test being run:
require 'rails_helper'

describe Post do
describe "vote methods" do

before do
  @post = Post.create(title: 'Post title', body: 'Post bodies must be pretty long.')
  3.times { @post.votes.create(value: 1)}
  2.times { @post.votes.create(value: -1)}
end

describe '#up_votes' do
  it "counts the number of votes with value = 1" do
    expect(@post.up_votes ).to eq(3)
  end
end

describe '#down_votes' do
  it "counts the number of votes with values = -1" do
    expect(@post.down_votes ).to eq(2)
  end
end

describe '#points' do
  it "returns the sum of all down and up votes" do
    expect(@post.points ).to eq(1) # 3 - 2
  end
end
end
end

Vote schema
create_table "votes", force: :cascade do |t|
 t.integer  "value"
 t.integer  "post_id"
 t.integer  "user_id"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
end

Comment: The error message says that your `post.rb` model has at least 63 lines. It seems like you did not post the whole file.
Comment: That's all of it.  The other lines are commented out.  Not sure why it is saying line 63.  I'll post all of it just in case.
Answer: This may just be how you put your code here but...
vote_catch.each

is not inline with its "end". Also, the "end" of the up_votes doesn't line up with the end of the function.
EDIT:
The error is where the unless condition is pair with the #each method call.
here's an example:
2.2.1 :008 > x.each do |vote| unless x == -1
2.2.1 :009?>     puts vote
2.2.1 :010?>     end
2.2.1 :011?>   end
0
1
2
3
4
5
...
10
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Comment: @SaintClaire33 You need a second end for the unless statement. Pairing the unless with the block is weird.
Comment: No that's not it.  Its hard to align the code in stack overflow.
Comment: @SaintClaire33 are you ending the whole class?
Comment: Yes. The second end after sum is ending the class.
Comment: Thanks @userFriendly that worked.  I got another error after running the tests:  1) Post vote methods #up_votes counts the number of votes with value = 1
     Failure/Error: expect(@post.up_votes ).to eq(3)
     NoMethodError:
       undefined method `votes' for nil:NilClass
     # ./app/models/post.rb:29:in `up_votes'
     # ./spec/models/post_spec.rb:14:in `block (4 levels) in '
Comment: I'm trying to get the value from the votes table.
Comment: @SaintClaire33 is `@post` in the test being initialized?
Comment: Let me post the entire rspec test above.
Comment: @SaintClaire33 I can't seem to find the problem. I suggest posting a new question with the new error message. Best of luck.
Comment: I was thinking the same thing!  Okay thanks for your help again. Cheers :)


Correlations conundrum

Question: A= a certain gene, B= observation, C= observation.
A is not correlated with B
A is not correlated with C
However,
B and C are correlated if A is present.
B and C are not correlated if A is not present.
How can I explain this?
Edited to add:
I'm not looking for a biological explanation, but more a statistical one. I don't quite understand how independent correlations are not present, but a combination is. Maybe it's my small N giving a type I or type II error? Apparently A is playing a role in the correlation between B and C, but not with B and C independently.
Random example: gene A is not correlated with eating more apples (B) or eating more oranges (C). However, people who eat more apples also eat more oranges, but only if they have gene A. How?
Comment: By "A is present", do you mean that when $A=1$, $B$ and $C$ are correlated and when $A=0$ they are not correlated? Or do you mean when you have data on $A$ (anything) they are correlated, but when data is missing on $A$ they are not? Additionally, what are you measuring $A$ with, are you looking at overexpression, a knock down, SNP state, CNV state, or something else?
Comment: Hi Chris, thanks for the comment. Yes, when  A=1, B and C are correlated and when A=0 they are not correlated. A is the presence/carriage of a certain SNP. I don't quite understand how independent correlations are not present, but a combination is. Maybe it's my small N giving a type I or type II error.
Comment: You'll want to look up the term 'statistical interaction'
Answer: What exactly do you mean by "How can I explain this?"  Given the context, I'd say any satisfying or deep explanation will have to come from biology.
However, if you're asking "I don't see how this can ever be the case for any random variables (A, B, C) -- please show me an example," here's a simple one:
<code>n_obs <- 10^5
df <- data.frame(A=sample(c(0, 1), n_obs, replace=TRUE, prob=c(0.25, 0.75)))
df$B <- runif(n_obs)
df$C <- ifelse(df$A, df$B, runif(n_obs))

cor(df$A, df$B)  # Essentially zero
cor(df$A, df$C)  # Essentially zero
with(subset(df, A == 1), cor(B, C))  # Given A==1, perfect correlation between B and C
with(subset(df, A == 0), cor(B, C))  # Given A==0, zero correlation between B and C
</code>
In this example $A \in \left\{0, 1\right\}$, and $B$ and $C$ are both uniform on $\left[0, 1\right]$.  Conditional on $A=0$ they are independent; conditional on $A=1$ they are perfectly correlated.
The key in this example is that the marginal distributions of B and C do not change with A. That still leaves room to play around with their joint distribution, e.g. by making them independent under one value of A and perfectly correlated under the other.
Comment: It would probably help the poster to explain in words what's happening in this example instead of only providing computer code.
Comment: Thank you Adrian, I'm indeed not looking for a biological explanation, but more a statistical one. "# Given A==1, perfect correlation between B and C" - how can this be if A is not correlated with B or with C? I think that's the part I find difficult to understand. Apparently A is playing a role in the correlation between B and C, but not with B and C independently.

Random example: gene A is not correlated with eating more apples (B) or eating more oranges (C). However, people who eat more apples also eat more oranges, but only if they have gene A. How?
Comment: That's what the scatterplot is for
Comment: Do you know how to use R? You could play around with the toy example I wrote -- maybe that would give you a feel for what's going on. Just think of B ~ Uniform[0, 1] as the number of apples the person eats per day.
Comment: @Susan you should edit your original post to include the details in your comment.
Comment: Thank you, I have included the information. Unfortunately I don't know R well enough to play around with the numbers.
Answer: I'll give an intuitive example.

Let $A$ be the event that the Philadelphia Eagles are playing the New York Giants.
Let $B$ be the event that the Philadelphia Eagles win.
Let $C$ be the event that the New York Giants lose.

Let's also assume the New York Giants and Philadelphia Eagles are evenly matched and both teams are about .500 teams against other opponents. Then we have:

The event $A$ (Eagles playing Giants) is not correlated with either team winning or losing.
If the Eagles play the Giants, event $B$ (Eagles winning) is perfectly correlated with event $C$ (Giants losing).
If the Eagles are not playing the Giants, event $B$ and event $C$ are not correlated.

Correlations conundrum


Boundedness in $(M_{\phi}f)(x)=\phi(x)f(x)$ and $(Kf)(x)=\int_a^bk(x,t)f(t) dt$

Question: I'm currently practicing (for a comprehensive exit exam) how to prove something is bounded. Here are 2 questions I'm concerned about:

Let $\phi$ be a continuous function on the interval $[a,b]$.
Define $M_{\phi}:L^2[a,b] \to L^2[a,b]$ by $(M_{\phi}f)(x)=\phi(x)f(x)$
Show that $M_{\phi}$ is a bounded linear operator on $L^2[a,b]$

Let $k(x,t)$ be a continuous function on the square $[a,b]$ x $[a,b]$
Define $K:L^2[a,b] \to L^2[a,b]$ by $(Kf)(x)=\int_a^bk(x,t)f(t) dt$
Show that $K$ is a bounded linear operator on $L^2[a,b]$

My Approach:

$\left |(M_{\phi}f)(x) \right |=\left |\phi(x)f(x) \right |$. Since $\phi$ is a continuous function on the interval $[a,b]$, then $|\phi(x)| \le k_0$ where $k_0$ is a real number for all $x$ in the space. Therefore $$\left |(M_{\phi}f)(x) \right |=\left |\phi(x)f(x) \right | \le k_0 ||f||$$
Similarly, $|k(x,t)| \le k_0$ for all $(x,t) \in J=[a,b]*[a,b]$. Therefore, $$\left| (Kf)(x)\right |=\left|\int_a^bk(x,t)f(t)dt \right| \le k_0||f||$$

Is this the proper way to prove these? Thank you.
Answer: Not quite, sorry. To show an operator $T$ on $L^2$ to itself is bounded, you must show that there is a constant $C$ such that
$$\|Tf\|_{L^2} \le C \|f\|_{L^2}$$
for all $f \in L^2$. So pointwise bounds aren't quite what you're looking for.

But your proof of (1) can be adapted: Choosing $k_0$ large enough that $|\varphi(x)| \le k_0$ for all $x$, we see that
$$|M_{\varphi} f|(x) = |\varphi(x)| |f(x)| \le k_0 |f(x)|$$
Now square this inequality and integrate to find that
$$\int_a^b |M_{\varphi}f|^2 dx \le k_0^2 \int_a^b |f|^2 dx$$
Taking a square root shows that $\|M_{\varphi} f\|_{L^2} \le k_0 \|f\|_{L^2}$.
Answer: There are several approaches that will work for $K$. I'll choose the direct approach. Start with the Cauchy-Schwarz inequality
$$
            |Kf(x)|^{2} \le \left[\int_{a}^{b}|k(x,t)||f(t)|\,dt\right]^{2}
           \le \int_{a}^{b}|k(x,t)|^{2}\,dt\int_{a}^{b}|f(t)|^{2}\,dt=\int_{a}^{b}|k(x,t)|^{2}\,dt\cdot\|f\|^{2}_{L^{2}}.
$$
Integrating with respect to $x$ gives
$$
    \|Kf\|_{L^{2}}^{2} \le \int_{a}^{b}\int_{a}^{b}|k(x,t)|^{2}\,dx\,dt\cdot\|f\|^{2}_{L^{2}}.
$$
Because $k$ is continuous on $[a,b]\times[a,b]$, then it is bounded by some constant $M$ on that region. So, $\|Kf\| \le M(b-a)\|f\|$. Notice that $K$ is bounded under the weaker assumption that $k \in L^{2}([a,b]\times[a,b])$.


Show that there are descending open sets $\{G_n\}$ so that $E\subseteq G_n$ for all $n \in \mathbb N$ and $ \lim_{n\to\infty} m(G_n)=m(E)$

Question: I have the following question from an elementary course on Measure Theory:

Let $E$ be a measurable set with $m(E)<\infty$. Show that there is a descending sequence of open sets $\{G_n\}$ so that $E\subseteq G_n$ for all $n \ \in \mathbb N$ and $ \lim_{n\to\infty} m(G_n)=m(E)$.

What I've done so far:
We know that there is a $G_{\delta}$ - set $G_1$ such that $E\subseteq G_1$ and $m(G_1\setminus E)=0$. Then since $G_1$ is measurable we can find a set $G_2$ satisfying the same conditions. Continuing this way we can find an ascending sequence of sets. I don't know how to get a descending one. Am I on the right track or should I try a different approach?
Any hints/ideas are much appreciated.
Thanks in advance for any replies.
Comment: If you can approximate from below, then approximate $\bar E$ from below, which will yield an approximation of $E$ from above. If $m$ is not finite, you need to be a bit carefull with $\bar E$ - you'll need to fix some measurable superset $G$ of $E$ with finite measure first, then use $G \setminus E$ instead of $\bar E$. To make the resulting sets open, you'll have to start with an approximation from closed sets I guess...
Comment: How will it give an approximation of $E$ from above?
Answer: Since E is measurable, for each $ n\in \mathbb{N} $ , there is an open set $E_{n}$ such that $ E\subseteq E_{n} $ and $m(E_n\setminus E)<1/n$. Define $ G_{n}=\cap_{j=1}^{n}E_{j} $ for each $ n\in \mathbb{N} $. Then for each $ n\in \mathbb{N} $,  $ G_{n}$ is open and {$ G_{n}$} is a descending sequence. Since $ G_{n}\subseteq E_{n} $ , we have $m(G_n\setminus E)<1/n$  for each $n\in \mathbb{N}$. Since $m(E)<\infty$ by excision property of measure also we have $m(G_n)-m(E)<1/n.$
So we have that $$ \lim_{n\to\infty} m(G_n)=m(E)$$ $\square$


K5 Graph Avoidance Coloring Game

Question: Graph Avoidance Game
Two players take turns coloring the edges of the complete graph, $K_5$. The first player colors edges blue and the second player colors edges red.  To win, the player must force their opponent to create a triangle with their colors.
I want to prove that the second player can always win.
Also, is it possible that some player can always force a red and blue C5?
Comment: There aren't that many possible configurations.  It should be pretty straightforward to construct the complete game tree on a computer and find the winner.
Comment: There is a useful heuristic: if some player colors some $V$, he/she cannot play on the third side: let us call this an obstruction. The second player cannot lose by xavier's observation, and since the first player gets the first obstruction, the first player always loses if the second player goes with the *parallel* approach.
Comment: @JackD'Aurizio  Could you please expound?  I am not familiar with xavier's observation.
Answer: (This is not an answer, but I need to post a graph.)
The question poser is not correct "that a draw isn't possible under $K_5$" as the following example illustrates:

K5 Graph Avoidance Coloring Game


How to create a view of Users and use uid field with Display Suite view mode

Question: I have been able to create a view of Users with format of Fields. I added user fields, and and found the UID field as well which I can use to link a field to the user's profile page.
However, I prefer to output views with the Content format and create a view mode for the view. For users, there is no Content format, and I assume the equivalent is User format.
However, when I created my display mode on the user profile and set it to a display suite layout, I found that there is no UID field (I did see Username, but that wont help). Does display suite not provide us this field?
Answer: Just as it does not provide a nid field for nodes, so it does not provide a uid field for users.
For format in your view you can also show 'Display Suite' which will open up more ds-goodness.
To show the uid you need to add a ds code field. it is best used with the token module installed as well.

Add the token [user:uid] as the field value.

The field will now become available for display suite to use. You could also use html in the code field, and for instance use the [user:uid] token to create a link, as in:
[user:name]

Also note that you do not need to display the primary identifier of an entity (uid for users) in order to use it in views relationships. As users is the base table it will already be available.
Comment: Thanks for the detailed response. My only issue with it is that I found that when I set the format of the Field Code section to be 'Plain Text', the resulting value of the field was [uid]. I was able to fix this by setting the format to PHP. However, I would like to turn off the PHP filter, to prevent people from putting actual PHP code in the database. How could I recreate this field in code?
Comment: Use Full HTML as the text format (it does not work with plain text). Also check if you have you token installed. And the token is [user:uid], not [uid]


How do we show timezone in different format?

Question: I want to show timezone in a different format. I have a variable that gets the timezone of the user called as timeZone returning value of timezone as Asia/Calcutta.
console.log(timeZone) // "Asia/Calcutta"

But is it possible to show timezone in different format like PDT or UTC or IST with moment.js?

Timeformat: 2019-01-28 24:59:59 UTC
Comment: Please add an example time (including timezone).
Comment: I have updated the question with time format.
Answer: Timezones depending on locations are not something that can be calculated. You need a database which handles this for you.
moment-timezone is one of the most famous.
If you install moment-timezone you can do
var moment = require('moment-timezone');
moment().tz("America/Los_Angeles").format();

Among other options, as stated here: https://momentjs.com/timezone/
Comment: Why do I require to add jun? Can't I just change that timezone to other formats without having to put date?
Comment: @Santosh `jun` is just a `moment` date. You can see how it works and all the documentation in the link I passed you. PD: Edited my answer.


Why does my Phonegap app cover the status bar of my mobile device?

Question: I am developing a phonegap app and for whatever reason the app is covering the status bar and I need to make sure this doesn't happen. The following picture is when I emulate the app on my iphone:

Here is a snippet of the code:

My first page

When is the last time you talked to your           ex?

Less than a week

1 to 3 weeks

Several months or more

Next

Answer: I was having the same issue with the status bar on my cordova iOS app.
Check the official cordova status bar plugin. It solved the problem for me.
Install the plugin
https://github.com/apache/cordova-plugin-statusbar
What you are looking for is
<preference name="StatusBarOverlaysWebView" value="false" />

Add that to your config.xml
Edit: the plugin also allow you to color the background and text of the statusbar the way you want, which is pretty neat.
Comment: Does this work for Android too? I got it to work but there is that padding at the top.
Comment: @StackOverflow the doc says "The StatusBar object provides some functions to customize the iOS and Android StatusBar". My guess is yes.
Answer: You have three options to solve it:
1. Is hide the Status Bar in Plist properties.

2. Hide Status Bar when app is launching
[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];

3. Is do a padding when detect iOS
// Pre-requisites:
// 1. Device core plugin
// 2. Splashscreen core plugin (3.1.0)
// 3. config.xml:  <preference name="AutoHideSplashScreen" value="false" />
// 4. config.xml:  <preference name="DisallowOverscroll" value="true" />

function onDeviceReady() {
    if (parseFloat(window.device.version) >= 7.0) {
          document.body.style.marginTop = "20px";
          // OR do whatever layout you need here, to expand a navigation bar etc
    }
    navigator.splashscreen.hide();
}

document.addEventListener('deviceready', onDeviceReady, false);

Comment: Steps 1 and 2 would stay after a build
Answer: Add the cordova statusbar plugin for your app by typing
cordova plugin add cordova-plugin-statusbar

Then in your config.xml, in the section for iOS platform, add the two <preference...> tags, like the following:
<platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
    <preference name="StatusBarOverlaysWebView" value="false" />
    <preference name="StatusBarBackgroundColor" value="#000000" />
</platform>


$k > \operatorname{rank}(A)+\operatorname{rank}(B) \Rightarrow \dim\{Au_1-Bv_1,Au_2-Bv_2,\dots,Au_k-Bv_k\} < k$

Question:
Let $A, B \in M_n, \operatorname{Im}(A)\cap\operatorname{Im}(B)=\{0\}$ and 2 subsets of $\mathbb{R}^n$ are $\{u_1,u_2,\dots,u_k\}, \{v_1,v_2,\dots,v_k\}$.
  Prove that: If $k>\operatorname{rank}(A)+\operatorname{rank}(B)$, there are always $\lambda_1,\lambda_2,\dots,\lambda_k\in\mathbb{R}, \lambda_1^2+\lambda_2^2+\dots+\lambda_k^2>0$ such that
$$\lambda_1Au_1+\lambda_2Au_2+\dots+\lambda_kAu_k=\lambda_1Bv_1+\lambda_2Bv_2+\dots+\lambda_kBv_k$$

My attemp: rewrite equality
$$\lambda_1(Au_1-Bv_1)+\lambda_2(Au_2-Bv_2)+\dots+\lambda_k(Au_k-Bv_k)=0$$
My idea is proving that $\dim\{Au_1-Bv_1,Au_2-Bv_2,\dots,Au_k-Bv_k\} < k$ from the inequality $k>\operatorname{rank}(A)+\operatorname{rank}(B)$
I think that we may use Sylvester's inequality $\operatorname{rank}(A)+\operatorname{rank}(B)=\operatorname{rank}(A)+\operatorname{rank}(-B) \ge \operatorname{rank}(A-B)$ but nothing works for me now.
Hope to see your suggestions. Thank you.
Answer: Hint: Note that $\{Au_1-Bv_1,Au_2-Bv_2,\dots,Au_k-Bv_k\} \subset \operatorname{Im}(A) + \operatorname{Im}(B)$, and $\dim(\operatorname{Im}(A) + \operatorname{Im}(B)) = \operatorname{rank}(A) + \operatorname{rank}(B)$.
Comment: ohhhh, I forgot $\operatorname{Im}(A)\cap\operatorname{Im}(B) = \{0\} \Rightarrow k> \dim\left(\operatorname{Im}(A) \oplus \operatorname{Im}(B)\right)$. Thank you.


Redirect to local network without allow_localnet

Question: I'd like to redirect incoming external traffic to a service which listens on 127.0.0.1. The redirection is easy - just:
iptables -t nat -A PREROUTING \
    -d local_ip --dport 80 \
    -j DNAT --to-destination 127.0.0.1:port

but this leaves the packet on eth0 and it's just logged as martian and dropped by default. I can enable route_localnet on eth0 to fix this, but that exposes the whole interface to weird routing tricks.
How do I forward it correctly without route_localnet?
Comment: If you really cannot reconfigure the service to listen on eth0... Not sure if it's gonna work (cannot check it right now), but I'd try with DNAT instead of REDIRECT. The last resort option is to use SSH tunnel internally.
Comment: DNAT gives the same result (i.e. packet doesn't change the interface and gets logged as martian on eth0)
Answer: The correct way to handle this is to have the application listen on the correct interface and/or IP address, not 127.0.0.1, and use iptables only to allow traffic, not to play weird NAT tricks.
Comment: @viraptor It looks like the question to me. You've shown no good reason why you should need to do something bizarre and difficult to manage like this, so we can only surmise that you're trying to "do it wrong", whatever it is.
Comment: Sure it's true, but that wasn't the question :)
Comment: Sample scenario: application binds to one interface/address and doesn't support 0.0.0.0. Provide access from 2 different interfaces even though it binds to one only.


Drupal: using a view on a Page/Panel, prevent default listing of content

Question: I have a panel/page that has a view (it's a view page) that some fields and filters that allows user for search for content of a certain content type. The problem is that views by default displays all of the content (even if the user hasn't performed a search yet).
So how do I setup the view so that it doesn't display results by default? I.e. only display results when user has performed a search.
Answer: For doing that you should set the default value of the exposed filters in some combination that doesn't return anything, in this way when the user visits the page they will not see any result and those filters will have the values that you choose by default.
The other alternative is extracting the exposed filter form from code and placing that in a block, if you want to do this take a look to this post http://www.angrydonuts.com/displaying_views_exposed_filters
Comment: The first solution in the link didn't work but i found this solution for views which does
http://www.computerminds.co.uk/displaying-exposed-filter-form-views-drupal-6-views-2


Is possible to use keywords a, mx and include together in SPF?

Question: Is it possible to use them in the same SPF record? For example:
Value TXT: v=spf1 mx a ptr ip4:188.8.131.52/23 a:cdmon.com mx:mail.solarmora.com include:srv.cat ~all
Answer: Yes, you can all those keywords combined, just make sure you don't hit the lookup limit of at maximum 10 address records lookups: https://www.rfc-editor.org/rfc/rfc7208#section-4.6.4

The a and ptr keywords result in one lookup

the ptr keyword is deprecated and should not be used anymore

the mx keyword results in as many lookups as the MX record returns domains
the include keywords includes the referenced SPF record, which is:

$ dig srv.cat TXT +short
"v=spf1 a a:include"

Whereas a:include leads to an error as the domain include does not exist.
Answer: It is technically possible to mix any mechanisms, but anything other than the ip4 and ip6 mechanisms will cause additional DNS lookups, and there is the overall limit of 10 DNS queries (RFC 7208, 4.6.4). Every a causes one additional lookup and every mx several, depending on the amount of MX servers behind it. Also, an include might have chained mechanism that are also counted to the limit.
You should carefully think which servers really send email from the domain as an envelope sender and limit your SPF record to only contain the required servers. As your SPF record is now put together it seems you do not have this knowledge and try and add everything "just in case". The policy ends with ~all, which makes everything else only softfail. This does not prevent abuse efficiently; consider using -all, instead.
Also, do not use ptr (RFC 7208, 5.5):

Note: This mechanism is slow, it is not as reliable as other
mechanisms in cases of DNS errors, and it places a large burden on
the .arpa name servers.  If used, proper PTR records have to be in
place for the domain's hosts and the ptr mechanism SHOULD be one of
the last mechanisms checked.  After many years of SPF deployment
experience, it has been concluded that it is unnecessary and more
reliable alternatives should be used instead.  It is, however, still
in use as part of the SPF protocol, so compliant check_host()
implementations MUST support it.


External CSS not being applied, but same code works when pasted as Internal

Question: I'm a newbie learning the ways of html/css via online tutorials. Only now I've run into a little problem that I can't quite figure out, and I've tried suggestions to similar issues from this very site and more.
As the title says, my external css file just does not seem to work at all, though said code works fine if I apply it internally. I keep rereading the code trying to spot mistakes, but even css lint and codepen just seem to say I have overqualified  elements, and not much else. I've tried just using the class names e.g. .Attack instead of td.Attack, but that didn't help.
The html is basically a table with some images, and I am only trying to apply a single stylesheet. Here is tcgdatabase.css
body {
    background-color:transparent;
    }

p {
    color:#2E2435;
    text-align:justify;
    }

td {
    text-align:left;
    }
td.Name {
    text-align:left;
    width:250px;
    font-size:30px;
    font-weight:bold;
    }
td.Type {
    width:50px;
    }
td.Stage {
    text-align:left;
    width:120px;
    font-size:15px;
    font-weight:bold;
    }
td.HP,td.AP {
    width:50px;
    font-style:italic;
    font-size:30px;
    }
span.Points {
    font-size:15px;
    }
td.Attack,td.BaseDamage {
    height:30px;
    font-weight:bold;
    font-size:20px;
    }
td.Effect,td.Flavour {
    text-align:justify;
    }
td.WRR,td.WRRType {
    height:20px;
    font-weight:bold;
    }
th {
    text-align:center;
    }

here is the html page, I even left the css in there enclosed with the  to show how I added it internally:
<!DOCTYPE html>

            <title>oddities</title>
            <meta charset="UTF-8">
            <link ref="stylesheet" type="text/css" href="file:///C:/Users/Admin/Documents/TCG/JBSet1/tcgdatabase.css">

                    Legendary
                    Yveltal
                    110HP
                    0AP

                    Take In

                        Attach up to 3 Pokémon from your hand to this Pokémon and heal 10 damage from this
                        Pokémon times the number of Pokémon cards just attached in this way. Each Pokémon attached
                        in this way provides 1 Energy of their type at a time (If they have more than 1 type,
                        they provide Energy of each of their types, but only 1 at a time).

                    Riot Ballista

                        Discard 1 card attached to this Pokémon. If that card is a Pokémon, this
                        attack does damage equal to the discarded Pokémon's HP. If it is not a
                        Pokémon, this attack does 50 damage and this Pokémon does 50 damage to
                        itself.

                    weakness: x2

                        "This terrible beast has long since turned a blind eye to the havoc it
                        wreaks in its wake" - Anon.

                    resistance: -20

                    retreat cost: x2

                    Illus. NavaskaIII
                    ??/??
                    UR

I feel like I am missing something completely obvious, I really would appreciate the help!
Comment: Do you mean if the href is correct? If so, I have checked. I pasted the same on my web browser (chrome) and the .css shows up.
Answer: In your link element change
    ref="stylesheet" to rel="stylesheet"
notice the 'f' should be 'l'
Comment: Oh wow, that was it! Thank you so much! As embarassed as I am for not spotting that, how did css lint not see that!?
Comment: oh wait because I never put the htm in css lint.  Codepen did not see it though!
Answer: Check your path to the CSS file. I would recommend using a relative path to the file.
Change href="file:///C:/Users/Admin/Documents/TCG/JBSet1/tcgdatabase.css" to something like href="/path/to/JBSet1/tcgdatabase.css".
If the CSS file is in the same folder as the HTML file, you can just use href="tcgdatabase.css".
Edit:
As stated above, also change ref="stylesheet" to rel="stylesheet".
Comment: It's in the same folder, and originally it was just "tcgdatabase.css". It didn't work. Just tried it again, same result. Even your last suggestion too :(
Comment: Make the change and do a force refresh using `Ctrl + F5` in case it is cached.
Comment: the ref was the problem, thank you so much! Such a silly mistake
Answer: Follow this syntax:
<link rel="stylesheet" href="style.css" type="text/css">

Path of css file has to be relative or absolute path..


How do I create the UI of the Stocks application on the iPhone?

Question: I'm not interested in getting the stock data, but I want to create a smilar application that will have the exact same UI as Apple's Stocks application on the iPhone.
Does anybody know of a tutorial or open code repo that can show me how to do this?
Comment: You'd probably get some downvotes for this question. You should google and I'm sure you'll find many resources. Also for the UI, you must do it with code and some image files, so that's not understandable what you're looking for.

Also check out Apple sample codes. You'll find helpful stuff there.
Comment: There was a WWDC video (from 2012 or 2011) that introduced Core Graphics by drawing something similar to the Stocks app (or at least the chart part of the app).
Comment: That would be a copyright violation, if you do it exactly the same.
Answer: There will be no such tutorial, because the stocks app use a huge number of different technics, and graphical effects.
If you read the ViewController Programming Guide, and then CoreGraphics (Quartz) Guide, then you are near to do it yourself.
Ask again if you have a more specific question.


How can I invoke Drush command inside hook_cron?

Question: I have module that provides drush integration.
Now I want to create modules with hook_cron where I want to launch drush command.
How can I run Drush command programmatically?
Answer: You should not call drush from inside a Drupal module.  Instead, factor out the functionality of your Drush commands into separate functions that can be called from module code and drush commandfiles alike.  Your module code should do all user access / permissions checks before calling the API functions (usually via the access checks provided by Drupal's menu system); the Drush commands should call the API functions directly, without access checks.


Do I need to apply Rouche's theorem twice in this proof?

Question: Here's the problem I'm trying to proof:

Let functions $f(z)$ and $g(z)$ be both analytic in the disc $|z| ≤ 2$, let $|f(z)| > |g(z)|$ on the circle $|z| = 2 $and let $|g(z)| > |f(z)|$ on the circle $|z| = 1$. Prove that the number of zeros of the function f(z) in the disc $|z| < 2$ is greater or equal the number of zeros of the function $g(z)$ inside the disc $|z| < 1$.

I'm wondering how I may want to use Rouche's Theorem. From the given conditions, we can find out that in the disc $|z| ≤ 2$, $f(z)$ and $f(z)+g(z)$ have the same number of zeros, and in the disc $|z| ≤ 1$, $g(z)$ and $f(z)+g(z)$ have the same number of zeros and counting multiplicities. What should I do next? How can I show that the number of zeros of the function f(z) in the disc $|z| < 2$ is greater or equal the number of zeros of the function $g(z)$ inside the disc $|z| < 1$? Is there anything other than Rouche's theorem I should consider? Thanks for the help!
Answer: Let $N(r, f)$ denote the number of zeros of the holomorphic function $f$ in the disk $|z| < r$, counted with multiplicity.
You correctly demonstrated that $N(2, f) = N(2,f+g)$ and $N(1, g) = N(1, f+g)$.
It only remains to observe that $N(2, f+g) \ge N(1, f+g)$, which is obvious from the definition. Then
$$
 N(2, f) = N(2,f+g) \ge N(1, f+g) = N(1, g)
$$
is the desired conclusion.

Do I need to apply Rouche’s theorem twice in this proof?


How can you read data from columns in a text file into 3 1D numpy arrays in python

Question: I have data in a text file with 3 columns and 4 rows like this:
 5 6.4 17
 6 5.8 16
 7 5.5 3.9
 8 5.3 10.4

I want to read this data from the text file into 3 1D arrays each with 4 elements
I have this code:
import numpy as np
with open('data.txt','rt') as filedata:
        values=np.genfromtxt('data.txt', unpack=True)
this has created a 2D (3,4) array.
I managed to split it into 3 subarrays using np.slice(values,4) but then I didn't know how to rename and subsequently use those subarrays
Comment: You can simply do `a,b,c = np.genfromtxt('data.txt', unpack=True)` and this should create 3 1D numpy arrays with names `a`, `b` and `c`.
Comment: @Ardweaden Thank you that really helps!
Comment: @Ardweaden - Can you change the data type of the respective 1D numpy arrays within the numpy routine you use?
Answer: You can use python's slice notation:
import numpy as np
with open('data.txt','rt') as filedata:
        values = np.genfromtxt('data.txt', unpack=True)

array1 = values[:, 0]
array2 = values[:, 1]
array3 = values[:, 2]

When you use slicing the first value defines the range in rows and the second in columns. So by typing values[:, 0] you say give me all elements in 0th column. The semicolon lets you specify a range. For example, values[0:2, 0] says give me the first two elements in the 0th column. You can look at the slicing notation in more detail here.


How to find the solutions for the equation $2^x = 4x$?

Question: How do I solve the equation $2^x = 4x$? So, the obvious answer by inspection is $x=4$, but I need an analytical solution to this, something rigorous pls.
Comment: See https://en.wikipedia.org/wiki/Lambertw#Example_1
Comment: Welcome to MSE. Please be careful with the tags, Your question is not about `algebraic-number-theory`.
Comment: I'm sorry. Thanks. What Tag would have been appropriate pls?
Comment: Thanks. But is the Lambert W.  Function's method an analytical approach? I'm confused. I hear it's numerical.
Comment: Related: https://math.stackexchange.com/questions/1699104/solving-4x-ex-without-graphing-and-looking-for-intersection
Comment: @user517110 Please, if you are ok, you can accept the answer and set it as solved. Thanks!
Answer: Let $f(x)=2^x-4x$.
Thus, $$f''(x)=2^x\ln^22>0,$$ which says that $f$ is a convex function, which gives that our equation has two real roots maximum.
But $4$ and $0<x_1<1$ are roots.
The value of $x_1$ we can not get by elementary functions.
Answer: $$2^x=4x$$
$e^{x\ln(2)}=4x\quad\to\quad xe^{-x\ln(2)}=\frac14\quad\to\quad \left(-x\ln(2)\right)e^{\left(-x\ln(2)\right)}= -\frac{\ln(2)}{4}$
The general solution of this kind of equation cannot be expressed with a finite number of elementary functions. We need infinite series or a special function : The Lambert's W function, https://en.wikipedia.org/wiki/Lambert_W_function
$$-x\ln(2)=W\left(-\frac{\ln(2)}{4} \right)$$
The result is :
$$x=-\frac{1}{\ln(2)}W\left(-\frac{\ln(2)}{4} \right)$$
The $W(X)$ function is a multi-valuated function. In the real range $-e^{-1}<X<0$ they are two real roots :
$$\begin{cases}W_{-1}\left(-\frac{\ln(2)}{4} \right)=-4\ln(2) \quad\to\quad x=4\\W_0\left(-\frac{\ln(2)}{4} \right)\simeq-0.214811 \quad\to\quad x \simeq 0.3099069  \end{cases}$$
The second root is not rational. An approximate is computed thanks to any mathematical software where the Lambert function is implemented. Or alternatively with recursive numerical calculus (Newton-Raphson method for example).
Answer: A bit of  detail:
$ f''(x) \gt 0$, $f= 2^x-4x$ convex, does not , by itself, imply  that  $f(x) = 0$ has $2$ distinct zeroes.
1)$y= x^2 +1$, convex, has no zeroes ,
2) $y= x^2,$ $x_1=x_2 =0$, double zero.
But since $f(x) = 2^x -4x$ is convex, and:
positive at $x= 0,$
negative at $x=1$ ,
positive for $x \gt 4,$
we conclude that $f(x)$ has  two distinct roots:
$x_1 = 4$, by inspection, and $0 \lt x_2\lt 1$.
Comment: Gimusi, you are really nice. I watch you racing ahead! Formidable!Keep it up as long you enjoy it.
Comment: nice pointing out Peter !
Answer: For a rigorous proof you have to study the function $f(x)=2^x-4x$ showing analitically that it can't have more than two roots.
Comment: Bit how do I show one of the solutions s 4?
Comment: @user517110 you can show and prove analitically that you have only two roots and find also the range, the trivial root can be found by inspection (it is sufficient that it works), the other can be found by numerical methods
Comment: @user517110 in other words what you need is to prove that only 2 solution exist, the calculation of the roots is another kind of issue
Comment: Oh! Since the function is a continuous one on R. Will the Intermediate Value Theorem suffice that there's a root in the interval [0,1] for example? Since f(0)*f(1)<0
Comment: @user517110 tio prove the existence of ony two roots you have to show that f has a minimum <0 and that it can "touch" x axis more than 2 times by decreasing/increasing or convexity arguments.
Comment: ops...it can't touch I mean!


In the following example in this MIT lecture, how did we establish that a $2^{n+1} \cdot 2^{n+1} = 4(2^n \cdot 2^n)$?

Question: In the following example at the minute 1:06:43 in this video: https://www.youtube.com/watch?v=z8HKWUWS-lA&t=1810s
While using proof by induction, to make use of the assumption, while validating the implication/inductive step, the 2^n+1 square is divided into 4 squares each is 2^n * 2^n.
Now how is that established, how is (2^n+1 * 2^n+1) = 4(2^n * 2^n)?
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Answer: You have
$$\begin{equation}\begin{aligned}
(2^{n+1})(2^{n+1}) & = (2(2^{n}))(2(2^{n})) \\
& = 2(2^{n})2(2^{n}) \\
& = 4(2^{n})(2^{n})
\end{aligned}\end{equation}\tag{1}\label{eq1A}$$
Answer: This boils down to exponent rules ($a^{m+n} = a^m a^n$) and commuting terms:
\begin{align*}
\left(2^{n+1} \cdot 2^{n+1}\right) & = \left((2^n)(2) \cdot (2^n)(2) \right) \\
& = 4(2^n \cdot 2^n)
\end{align*}


Onload events seq

Question: I'm experimenting with write method & onload event. Here is my code:
<!DOCTYPE html>

Hello World!

What would be be the sequence of events in this case? Would the browser first create body element & call "body loaded" or the img element would be created first?
Comment: What happens when you run the code in your browser?
Comment: Why don't you try it yourself? Maybe use a debugger like [Firebug](https://addons.mozilla.org/de/firefox/addon/firebug/). Your question does not indicate that you ran into any problems. I think you will learn a lot more if you step through the code yourself.
Comment: You want to know when the IMG is *created* or *loaded*? Two very different things.
Answer: I would suggest you to create a div than use innerHTML property to write something in to it. A sample code would be:

Javascript part:

Onload events seq


Access instance of currently viewed fragment attached using viewpager

Question: I have implemented swipe fragments using
https://developer.android.com/training/animation/screen-slide.html
or
https://developer.android.com/training/implementing-navigation/lateral.html

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/some_background_fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

    <android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</RelativeLayout>

Here is MyActivity.java:
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_overlay);

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
        mPager.setCurrentItem(1);
    }
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter{
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0)
                return new Page0Fragment();
            else
                return new Page1Fragment();
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }

Now I am trying to access the currently viewed fragment like this
 public void myonclickmethod(View view) {
    FragmentManager fm = getSupportFragmentManager();
    fragment = fm.findFragmentById(R.id.pager);//<=**This is coming as instance of Page0Fragment inspite of me intializing the activity with Page1Fragment and also currently standing on Page1Fragment without any swiping**
 }

Answer: First, you need to change your ScreenSlidePagerAdapter to return the same instance everytime instead of new Page0Fragment like:
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter{
            List<Fragment> fragments = new ArrayList<>();
            public ScreenSlidePagerAdapter(FragmentManager fm) {
                super(fm);
                fragments.add(new Page0Fragment());
                fragments.add(new Page1Fragment());
            }

            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

Now for getting visible fragment, do like:
public void myonclickmethod(View view) {
    int currentPosition = mPager.getCurrentItem();
    if(currentPosition == 0 {
        Page0Fragment page0Fragment = (Page0Fragment)mPagerAdapter.getItem(currentPosition);
        page0Fragment.doSomething();
    } else {
        Page1Fragment page1Fragment =(Page1Fragment)mPagerAdapter.getItem(currentPosition);
       pag1Fragment.doSomething();

 }

Answer: You can get the current fragment by calling getItem() with the current position on your adapter like this
    public void myonclickmethod() {
       Fragment fragment = adapter.getItem(viewpager.getCurrentItem())
}

Comment: This is correct but as the adapter returns the new Fragment() inside getItem() method, calling this method won't give the same fragment instance which is inflated in ViewPager. so calling any method from retrieved fragment will result mostly in NullPointerException. So @OP change your adapter as well.
Comment: @sam_0829 Exactly I had to currect my getItem() implementation to cache instances created earlier to make it fully working.


Initial Xtradb Cluster setup -- each node comes up isolated

Question: I'm setting up a percona-xtradb-cluster-57 (3 nodes) on Ubuntu 16.04. They are to communicate using a private network, 10.254.10.101 through 10.254.10.103.
When I follow the instructions on Percona's site just as written, after bootstrapping the first node I bring up one of the other two normally. However, SHOW STATUS like 'ws_rep%'; results in a cluster size of 1 and a different cluster ID than the bootstrapped node.
I've checked the firewall, turned off the firewall, attempted to connect to each node on ports 3306 and 4567, and double-checked that each machine is seeing its neighbors as a single hop. All of this is as it would be accepted. Ports 4444 and 4568 are also open, though netstat doesn't show them listening. FWIW 4444 and 4568 are also not listening on a working cluster in the same software environment (that one is spread over multiple data centers).
Using SST for replication, with the SST user created on each node. I've also only done it on the bootstrapped node.
Here's the config:
[mysqld]
wsrep_provider=/usr/lib/libgalera_smm.so

wsrep_cluster_name=dbcluster
wsrep_cluster_address=gcomm://10.254.10.101,10.254.10.102,10.254.10.103

wsrep_node_name=pxc1
wsrep_node_address=10.254.10.101

wsrep_sst_method=xtrabackup-v2
wsrep_sst_auth=sst-user:sst-pass

pxc_strict_mode=ENFORCING

binlog_format=ROW
default_storage_engine=InnoDB
innodb_autoinc_lock_mode=2

What diagnostic data would you like to see to help trace this issue? First thing that hits me is a network issue, but I've done all the usual stuff there as described above.
Watching the logs at startup, the two nodes that weren't bootstrapped don't appear to even look for the other nodes.
2017-11-15T15:23:20.255455Z mysqld_safe Logging to '/var/log/mysqld.log'.
2017-11-15T15:23:20.272183Z mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
2017-11-15T15:23:20.279082Z mysqld_safe Skipping wsrep-recover for 71bf4cd8-ca02-11e7-8b84-630bd10b8205:14 pair
2017-11-15T15:23:20.280168Z mysqld_safe Assigning 71bf4cd8-ca02-11e7-8b84-630bd10b8205:14 to wsrep_start_position

2017-11-15T15:23:20.481916Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-11-15T15:23:20.483755Z 0 [Note] /usr/sbin/mysqld (mysqld 5.7.19-17-57-log) starting as process 29150 ...
2017-11-15T15:23:20.487158Z 0 [Warning] No argument was provided to --log-bin, and --log-bin-index was not used; so replication may break when this MySQL server acts as a master and has his hostname changed!! Please use '--log-bin=app3-bin' to avoid this problem.
2017-11-15T15:23:20.487910Z 0 [Note] WSREP: Setting wsrep_ready to false
2017-11-15T15:23:20.488055Z 0 [Note] WSREP: No pre-stored wsrep-start position found. Skipping position initialization.
2017-11-15T15:23:20.488173Z 0 [Note] WSREP: wsrep_load(): loading provider library '/usr/lib/galera3/libgalera_smm.so'
2017-11-15T15:23:20.491810Z 0 [Note] WSREP: wsrep_load(): Galera 3.22(r8678538) by Codership Oy <email@example.com> loaded successfully.
2017-11-15T15:23:20.491980Z 0 [Note] WSREP: CRC-32C: using hardware acceleration.
2017-11-15T15:23:20.492510Z 0 [Note] WSREP: Found saved state: 71bf4cd8-ca02-11e7-8b84-630bd10b8205:14, safe_to_bootsrap: 1
2017-11-15T15:23:20.493950Z 0 [Note] WSREP: Passing config to GCS: base_dir = /var/lib/mysql/; base_host = 10.254.10.103; base_port = 4567; cert.log_conflicts = no; debug = no; evs.auto_evict = 0; evs.delay_margin = PT1S; evs.delayed_keep_period = PT30S; evs.inactive_check_period = PT0.5S; evs.inactive_timeout = PT15S; evs.join_retrans_period = PT1S; evs.max_install_timeouts = 3; evs.send_window = 10; evs.stats_report_period = PT1M; evs.suspect_timeout = PT5S; evs.user_send_window = 4; evs.view_forget_timeout = PT24H; gcache.dir = /var/lib/mysql/; gcache.keep_pages_count = 0; gcache.keep_pages_size = 0; gcache.mem_size = 0; gcache.name = /var/lib/mysql//galera.cache; gcache.page_size = 128M; gcache.recover = no; gcache.size = 128M; gcomm.thread_prio = ; gcs.fc_debug = 0; gcs.fc_factor = 1; gcs.fc_limit = 100; gcs.fc_master_slave = no; gcs.max_packet_size = 64500; gcs.max_throttle = 0.25; gcs.recv_q_hard_limit = 9223372036854775807; gcs.recv_q_soft_limit = 0.25; gcs.sync_donor = no; gmcast.segment = 0; gmcast.version = 0; pc.announce_timeout = PT3S; pc.checksum = false; pc.ignore_quorum = false; pc.ignore_sb = false; pc.npvo = false; pc.recovery = 1; pc.version = 0; pc.wait_prim = true; pc.wait_prim_timeout = PT30S; pc.weight = 1; protonet.backend = asio; protonet.version = 0; repl.causal_read_timeout = PT30S; repl.commit_order = 3; repl.key_format = FLAT8; repl.max_ws_size = 2147483647; repl.proto_max = 7; socket.checksum = 2; socket.recv_buf_size = 212992;
2017-11-15T15:23:20.513602Z 0 [Note] WSREP: GCache history reset: 71bf4cd8-ca02-11e7-8b84-630bd10b8205:0 -> 71bf4cd8-ca02-11e7-8b84-630bd10b8205:14
2017-11-15T15:23:20.514428Z 0 [Note] WSREP: Assign initial position for certification: 14, protocol version: -1
2017-11-15T15:23:20.514546Z 0 [Note] WSREP: Preparing to initiate SST/IST
2017-11-15T15:23:20.514663Z 0 [Note] WSREP: Starting replication
2017-11-15T15:23:20.514791Z 0 [Note] WSREP: Setting initial position to 71bf4cd8-ca02-11e7-8b84-630bd10b8205:14
2017-11-15T15:23:20.515118Z 0 [Note] WSREP: Using CRC-32C for message checksums.
2017-11-15T15:23:20.515346Z 0 [Note] WSREP: gcomm thread scheduling priority set to other:0
2017-11-15T15:23:20.515543Z 0 [Warning] WSREP: Fail to access the file (/var/lib/mysql//gvwstate.dat) error (No such file or directory). It is possible if node is booting for first time or re-booting after a graceful shutdown 2017-11-15T15:23:20.515662Z 0 [Note] WSREP: Restoring primary-component from disk failed. Either node is booting for first time or re-booting after a graceful shutdown
2017-11-15T15:23:20.516044Z 0 [Note] WSREP: GMCast version 0
2017-11-15T15:23:20.516252Z 0 [Note] WSREP: (e997d882, 'tcp://0.0.0.0:4567') listening at tcp://0.0.0.0:4567
2017-11-15T15:23:20.516316Z 0 [Note] WSREP: (e997d882, 'tcp://0.0.0.0:4567') multicast: , ttl: 1
2017-11-15T15:23:20.516739Z 0 [Note] WSREP: EVS version 0
2017-11-15T15:23:20.516889Z 0 [Note] WSREP: gcomm: connecting to group 'pxc-cluster', peer ''
2017-11-15T15:23:20.516986Z 0 [Note] WSREP: start_prim is enabled, turn off pc_recovery
2017-11-15T15:23:20.517230Z 0 [Note] WSREP: Node e997d882 state primary
2017-11-15T15:23:20.517313Z 0 [Note] WSREP: Current view of cluster as seen by this node
view (view_id(PRIM,e997d882,1)
memb {
        e997d882,0
        }
joined {
        }
left {
        }
partitioned {
        }
)
2017-11-15T15:23:20.517372Z 0 [Note] WSREP: Save the discovered primary-component to disk
2017-11-15T15:23:20.517555Z 0 [Note] WSREP: gcomm: connected
2017-11-15T15:23:20.517672Z 0 [Note] WSREP: Shifting CLOSED -> OPEN (TO: 0)
2017-11-15T15:23:20.517836Z 0 [Note] WSREP: New COMPONENT: primary = yes, bootstrap = no, my_idx = 0, memb_num = 1
2017-11-15T15:23:20.517987Z 0 [Note] WSREP: STATE_EXCHANGE: sent state UUID: e9982b85-ca18-11e7-bcf3-22cba208212d

2017-11-15T15:23:20.518021Z 0 [Note] WSREP: STATE EXCHANGE: sent state msg: e9982b85-ca18-11e7-bcf3-22cba208212d 2017-11-15T15:23:20.518038Z 0 [Note] WSREP: STATE EXCHANGE: got state msg: e9982b85-ca18-11e7-bcf3-22cba208212d from 0 (pxc-cluster-node-1)
2017-11-15T15:23:20.518054Z 0 [Note] WSREP: Quorum results:
        version    = 4,
        component  = PRIMARY,
        conf_id    = 0,
        members    = 1/1 (primary/total),
        act_id     = 14,
        last_appl. = -1,
        protocols  = 0/7/3 (gcs/repl/appl),
        group UUID = 71bf4cd8-ca02-11e7-8b84-630bd10b8205
2017-11-15T15:23:20.518071Z 0 [Note] WSREP: Flow-control interval: [100, 100]
2017-11-15T15:23:20.518084Z 0 [Note] WSREP: Trying to continue unpaused monitor
2017-11-15T15:23:20.518097Z 0 [Note] WSREP: Restored state OPEN -> JOINED (14)
2017-11-15T15:23:20.518141Z 0 [Note] WSREP: Member 0.0 (pxc-cluster-node-1) synced with group.
2017-11-15T15:23:20.517998Z 0 [Note] WSREP: Waiting for SST/IST to complete.
2017-11-15T15:23:20.518154Z 0 [Note] WSREP: Shifting JOINED -> SYNCED (TO: 14)
2017-11-15T15:23:20.518501Z 1 [Note] WSREP: New cluster view: global state: 71bf4cd8-ca02-11e7-8b84-630bd10b8205:14, view# 1: Primary, number of nodes: 1, my index: 0, protocol version 3
2017-11-15T15:23:20.518541Z 1 [Note] WSREP: Setting wsrep_ready to true
2017-11-15T15:23:20.518594Z 0 [Note] WSREP: SST complete, seqno: 14
2017-11-15T15:23:20.520410Z 0 [Note] InnoDB: PUNCH HOLE support available
2017-11-15T15:23:20.520445Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-11-15T15:23:20.520460Z 0 [Note] InnoDB: Uses event mutexes
2017-11-15T15:23:20.520467Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2017-11-15T15:23:20.520474Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.8
2017-11-15T15:23:20.520481Z 0 [Note] InnoDB: Using Linux native AIO
2017-11-15T15:23:20.520824Z 0 [Note] InnoDB: Number of pools: 1
2017-11-15T15:23:20.520978Z 0 [Note] InnoDB: Using CPU crc32 instructions
2017-11-15T15:23:20.522918Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2017-11-15T15:23:20.528901Z 0 [Note] InnoDB: Completed initialization of buffer pool
2017-11-15T15:23:20.531671Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2017-11-15T15:23:20.543934Z 0 [Note] InnoDB: Crash recovery did not find the parallel doublewrite buffer at /var/lib/mysql/xb_doublewrite
2017-11-15T15:23:20.544844Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2017-11-15T15:23:20.560093Z 0 [Note] InnoDB: Created parallel doublewrite buffer at /var/lib/mysql/xb_doublewrite, size 3932160 bytes
2017-11-15T15:23:20.566433Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2017-11-15T15:23:20.566788Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2017-11-15T15:23:20.588535Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2017-11-15T15:23:20.589701Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2017-11-15T15:23:20.589810Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2017-11-15T15:23:20.590375Z 0 [Note] InnoDB: Waiting for purge to start
2017-11-15T15:23:20.640641Z 0 [Note] InnoDB: Percona XtraDB (http://www.percona.com) 5.7.19-17 started; log sequence number 2548109
2017-11-15T15:23:20.641178Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2017-11-15T15:23:20.641384Z 0 [Note] Plugin 'FEDERATED' is disabled.
2017-11-15T15:23:20.643176Z 0 [Note] InnoDB: Buffer pool(s) load completed at 171115  9:23:20
2017-11-15T15:23:20.650925Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
2017-11-15T15:23:20.650959Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.
2017-11-15T15:23:20.651471Z 0 [Warning] CA certificate ca.pem is self signed.
2017-11-15T15:23:20.651529Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.
2017-11-15T15:23:20.651638Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
2017-11-15T15:23:20.651688Z 0 [Note] IPv6 is available.
2017-11-15T15:23:20.651706Z 0 [Note]   - '::' resolves to '::';
2017-11-15T15:23:20.651733Z 0 [Note] Server socket created on IP: '::'.
2017-11-15T15:23:20.661454Z 0 [Note] Event Scheduler: Loaded 0 events
2017-11-15T15:23:20.662904Z 0 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.7.19-17-57-log'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  Percona XtraDB Cluster (GPL), Release rel17, Revision 35cdc81, WSREP version 29.22, wsrep_29.22
2017-11-15T15:23:20.662945Z 0 [Note] Executing 'SELECT * FROM INFORMATION_SCHEMA.TABLES;' to get a list of tables using the deprecated partition engine. You may use the startup option '--disable-partition-engine-check' to skip this check.
2017-11-15T15:23:20.663009Z 0 [Note] Beginning of list of non-natively partitioned tables
2017-11-15T15:23:20.663172Z 1 [Note] WSREP: Initialized wsrep sidno 2
2017-11-15T15:23:20.663199Z 1 [Note] WSREP: wsrep_notify_cmd is not defined, skipping notification.
2017-11-15T15:23:20.663233Z 1 [Note] WSREP: REPL Protocols: 7 (3, 2)
2017-11-15T15:23:20.663248Z 1 [Note] WSREP: Assign initial position for certification: 14, protocol version: 3
2017-11-15T15:23:20.663291Z 0 [Note] WSREP: Service thread queue flushed.
2017-11-15T15:23:20.663350Z 1 [Note] WSREP: GCache history reset: 71bf4cd8-ca02-11e7-8b84-630bd10b8205:0 -> 71bf4cd8-ca02-11e7-8b84-630bd10b8205:14
2017-11-15T15:23:20.663818Z 1 [Note] WSREP: Synchronized with group, ready for connections
2017-11-15T15:23:20.663839Z 1 [Note] WSREP: wsrep_notify_cmd is not defined, skipping notification.
2017-11-15T15:23:20.679843Z 0 [Note] End of list of non-natively partitioned tables

Answer: I think your problem might be:
2017-11-15T15:23:20.516889Z 0 [Note] WSREP: gcomm: connecting to group 'pxc-cluster', peer ''

Assuming this is your second node and your first node is configured with:
wsrep_cluster_name=dbcluster

They will not see each other, make sure they have the same cluster name.
Comment: I thought I got it copy/parted correctly between the servers, but I certainly could have missed that. I've implemented MariaDB instead, and have it working. Thank you for the suggestion!


If my RAID card fails, how likely is it to corrupt the RAID?

Question: My RAID card does not currently have a battery installed and its write mode is set to write-through. Data is rarely written to the RAID - large batches of data come in maybe every other week. Daily use is read-only. The card hosts 4 different RAID volumes, each being around 12 TB large.
I'm trying to assess the risk of my RAID being unrecoverable if the card fails. Have you ever seen a RAID card turn bad and render the RAID unusable when the card was replaced?
Comment: What if it's not the RAID card that fails?  What if the expansion slot it's plugged into has an electrical fault?  What if it's actually the cable that's gone bad?  You're focusing on a single point of failure and trying to mitigate it.  You should be trying to mitigate the *result* of failure, not just the cause.  If you're paranoid about losing your RAID array, keep it backed up.
Comment: What are you replacing it with?  I've never had issues replacing a failed RAID card with a same model replacement, but have never used that brand, or tried replacing a failed RAID card with a different make or model before...
Comment: I'd replace it with the same model. Just wondering how likely it would be.
Comment: This isn't an answerable question.  There are hundreds of ways that any computer component can fail, from simply keeling over dead to exploding in a rain of fire and sparks.  The only possible answer would be "it depends on how it fails."  Just remember that **RAID is not a backup mechanism** and plan accordingly with off-machine backups.
Comment: @Charles I know there are lots of ways for a RAID to fail, but the question is intended to gauge how much risk is involved. If there is a lot of risk, I can spend more money on mitigating that risk. If there's hardly any risk at all, I can worry about other things.
Comment: Charles is correct.  The risk of the RAID card *specifically* corrupting your data when it fails is low.  But doesn't rule out rule out other sources of corruption or possibilities of failure.  If you care about the data, back it up.  RAID is not a backup.
Comment: Thanks for the insight. You're correct. For what it's worth, I do keep a backup, but to restore everything after a catastrophic failure would require restoring _and_ reprocessing all the backup data. That would take a lot of time. I'm trying to decide if I need to keep a more current backup of the RAID on a new nearby server (which would be expensive but eliminate the reprocessing) or if the multi-week restore time is acceptable considering the small size of the risk.
Comment: Sounds like a business decision which I'd pawn off on my boss.  "If you want to be able to restore this system in hours, rather than weeks, it will require keeping a current backup on disk, costing $X.  If not, we save the money, but we'll be restoring for weeks in the unlikely event of a data failure."  CYA, not to mention save yourself the headache.
Answer: With write-through and a modern file system your drive should always be left in a consistant state on power failure as data is written both to the cache and the disk.  It is write-back that requires a BBU because data is written to cache and then to disk.
Obviously it can still be nonsensical or not what you had open depending on the functionality of any open apps.
As people have said in the comments RAID is not a backup, drives do fail in groups under the added load of a rebuild, users do delete data by mistake, etc.
Comment: Just to add to that line about nonsensical data, I have actually seen this corrupt the data on a RAID 5 array and destroy years of work because no one bothered to back it up.  POS app (which was running from the RAID 5 array) crashed really hard one day and required a hard boot of the server... when the server came back up, the file system was totally hosed.  "It's on RAID, so there's no risk of data loss!"  Yeah, not so much.  Many man-years of work lost to save a few grand on tape backups.