FragmentTransaction animation to slide in over top

Question: I am trying to achieve the following effect using FragmentTransaction.setCustomAnimations.

Fragment A is showing
Replace Fragment A with Fragment B. Fragment A should remain visible during the replacement.  Fragment B should slide in from the right. Fragment B should slide in OVER THE TOP of Fragment A.

I have no problem getting the slide in animation setup. My problem is that I cannot figure out how to make Fragment A stay where it is and be UNDER Fragment B while the slide in animation is running. No matter what I do it seems that Fragment A is on top.
How can I achieve this?
Here is the FragmentTransaction code:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_right, R.anim.nothing, R.anim.nothing,
    R.anim.slide_out_right);
ft.replace(R.id.fragment_content, fragment, name);
ft.addToBackStack(name);
ft.commit();

As you can see I have defined an animation R.anim.nothing for the "out" animation because I actually don't want Fragment A to do anything other than just stay where it is during the transaction.
Here are the animation resources:
slide_in_right.xml
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_mediumAnimTime"
    android:fromXDelta="100%p"
    android:toXDelta="0"
    android:zAdjustment="top" />

nothing.xml
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_mediumAnimTime"
    android:fromAlpha="1.0"
    android:toAlpha="1.0"
    android:zAdjustment="bottom" />

Comment: I have filed a bug report because the current Z ordering is just plain wrong.
https://code.google.com/p/android/issues/detail?id=163384&thanks=163384&ts=1428443402
Answer: Update (June 16, 2020)
Starting from fragment library 1.2.0 the recommanded way to fix this issue is to use FragmentContainerView with FragmentTransaction.setCustomAnimations().
According to the documentation:

Fragments using exit animations are drawn before all others for
  FragmentContainerView. This ensures that exiting Fragments do not
  appear on top of the view.

Steps to fix this issue are:

Update fragment library to 1.2.0 or more androidx.fragment:fragment:1.2.0;
Replace your xml fragment container (<fragment>, <FrameLayout>, or else) by <androidx.fragment.app.FragmentContainerView>;
Use FragmentTransaction.setCustomAnimations() to animate your fragments transitions.

Previous answer (Nov 19, 2015)
Starting from Lollipop, you can increase de translationZ of your entering fragment. It will appear above the exiting one.
For example:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ViewCompat.setTranslationZ(getView(), 100.f);
}

If you want to modify the translationZ value only for the duration of the animation, you should do something like this:
@Override
public Animation onCreateAnimation(int transit, final boolean enter, int nextAnim) {
    Animation nextAnimation = AnimationUtils.loadAnimation(getContext(), nextAnim);
    nextAnimation.setAnimationListener(new Animation.AnimationListener() {

        private float mOldTranslationZ;

        @Override
        public void onAnimationStart(Animation animation) {
            if (getView() != null && enter) {
                mOldTranslationZ = ViewCompat.getTranslationZ(getView());
                ViewCompat.setTranslationZ(getView(), 100.f);
            }
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            if (getView() != null && enter) {
                ViewCompat.setTranslationZ(getView(), mOldTranslationZ);
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    });
    return nextAnimation;
}

Comment: Worth noting that decreasing the elevation at the ned can cause some flickering because of timing issues, meaning that the replaced fragment did not complete yet the animation. I solved it by returning the elevation with a small delay.
Comment: Doesnot work for me. It gives android.content.res.Resources$NotFoundException: Resource ID #0x0 error
Comment: Good job on finding this, was looking for this solution long ago and now it is solved.
Comment: Thanks. Seems to work. May I know why for overriding `onCreateAnimation`, we need to manually construct Animation via `AnimationUtils.loadAnimation`? I do realize if I try to obtain `Animation` via super.onCreateAnimation, it is null.
Comment: @CheokYanCheng Because `Fragment.onCreateAnimation()` method does nothing by default and just returns null. This method is just there to leave you the possibility to create yourself the animation.

If you take a look at the method `FragmentManager.loadAnimation()` you will see it first tries to get an animation from `fragment.onCreateAnimation()` and if it returns null the FragmentManager creates the animation itself.
Comment: @RohitSingh you can try the updated solution and it should work
Comment: This seems to choke during a switch from day mode to night mode.
Comment: Even with the new fragment version doesn't slide over
Answer: I don't know if you still need an answer but I recently needed to do the same and I found a way to do what you want.
I made something like this :
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();

MyFragment next = getMyFragment();

ft.add(R.id.MyLayout,next);
ft.setCustomAnimations(R.anim.slide_in_right,0);
ft.show(next);
ft.commit();

I display my Fragment in a FrameLayout.
It work fines but the older Fragment is still in my View, I let android manage it like he wants because if I put:
ft.remove(myolderFrag);

it is not displayed during the animation.
slide_in_right.xml
    <?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate android:duration="150" android:fromXDelta="100%p"
android:interpolator="@android:anim/linear_interpolator"
android:toXDelta="0" />
 </set>

Comment: @domji84
`

`
Comment: Thank you and I am still looking for a solution. Your answer is accurate but unfortunately it doesn't completely address the problem. I can't leave the old fragment in memory or it will eat up too much memory. I took the approach of creating a bitmap from the outgoing view and placing that under the view that the new fragment is being added to. That achieves the effect but again I am having memory problems because the bitmap is too big. I am looking into a couple other approaches including ViewPager w/ FragmentStatePagerAdapter and one FrameLayout per Fragment. Will post back later.
Comment: Thanks. `overridePendingTransition(R.anim.my_animation, 0)` is the line I was looking for.
Comment: On support v22 it seems all this does is make the old fragment disappear when the transition starts.
Answer: I found a solution which works for me. I ended up using a ViewPager with a FragmentStatePagerAdapter. The ViewPager provides the swiping behavior and the FragmentStatePagerAdapter swaps in the fragments. The final trick to achieve the effect of having one page visible "under" the incoming page is to use a PageTransformer. The PageTransformer overrides the ViewPager's default transition between pages. Here is an example PageTransformer that achieves the effect with translation and a small amount of scaling on the left-hand side page.
public class ScalePageTransformer implements PageTransformer {
    private static final float SCALE_FACTOR = 0.95f;

    private final ViewPager mViewPager;

    public ScalePageTransformer(ViewPager viewPager) {
            this.mViewPager = viewPager;
    }

    @SuppressLint("NewApi")
    @Override
    public void transformPage(View page, float position) {
        if (position <= 0) {
            // apply zoom effect and offset translation only for pages to
            // the left
            final float transformValue = Math.abs(Math.abs(position) - 1) * (1.0f - SCALE_FACTOR) + SCALE_FACTOR;
            int pageWidth = mViewPager.getWidth();
            final float translateValue = position * -pageWidth;
            page.setScaleX(transformValue);
            page.setScaleY(transformValue);
            if (translateValue > -pageWidth) {
                page.setTranslationX(translateValue);
            } else {
                page.setTranslationX(0);
            }
        }
    }

}

Comment: Great solution, but unfortunately does not fit if you want to change the stack, especially in the direction of decreasing - it leads to glare (redrawing the entire element).
Answer: After more experimentation (hence this is my second answer), the problem seems to be that R.anim.nothing means 'disappear' when we want another animation that explicitly says 'stay put.'  The solution is to define a true 'do nothing' animation like this:
Make file no_animation.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:interpolator="@android:anim/linear_interpolator"
        android:fromXScale="1.0"
        android:toXScale="1.0"
        android:fromYScale="1.0"
        android:toYScale="1.0"
        android:duration="200"
        />
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromAlpha="1.0"
        android:toAlpha="0.0"
        android:duration="200"
        android:startOffset="200"
        />
</set>

Now simply do as you would otherwise:
getActivity().getSupportFragmentManager().beginTransaction()
                .setCustomAnimations(R.anim.slide_in_right, R.anim.no_animation)
                .replace(R.id.container, inFrag, FRAGMENT_TAG)
                .addToBackStack("Some text")
                .commit();

Comment: Nice thought but this is not working as the transaction instantly remove the fragment and i can see the white screen below the second fragment during animation.
Comment: Confused as to why you thought it needed this. I just used 0 where I wanted no transition and it worked great. Which is what it looks like you did above.
Comment: In my case, the "do nothing" animation was alright when using `add` but causing trouble when using `replace`. Replacing it with `0` did the trick. Thanks, @NineToeNerd
Comment: I will try this but I had though about doing a proper "stay_put" animation and all it did was cover the sliding animation of the new fragment with the old fragment staying on the foreground. But I see you offset the start of the no_animation so maybe it does the trick. I'll let you know what I think of your solution.
Answer: I found an alternate solution (not heavily tested) that I find more elegant than the proposals so far:
final IncomingFragment newFrag = new IncomingFragment();
newFrag.setEnterAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    clearSelection();
                    inFrag.clearEnterAnimationListener();

                    getFragmentManager().beginTransaction().remove(OutgoingFragment.this).commit();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });

 getActivity().getSupportFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.slide_in_from_right, 0)
                    .add(R.id.container, inFrag)
                    .addToBackStack(null)
                    .commit();

This is being called from within an inner class of the OutgoingFragment class.
A new fragment is being inserted, the animation completes, then the old fragment is being removed.
There may be some memory problems with this in some applications but it is better than retaining both fragments indefinitely.
Comment: Where did the IncomingFragment and OutgoingFragment classes come from? Are they custom? Not quite understanding the implementation behind this. Perhaps when it was written there was such a function as `Fragment.setEnterAnimationListener(...)` ... or is that a custom function for that fragment?
Comment: For me this is the best solution so far. I used to do the same but by pausing the system with a Handler during the animation and then removing the previous fragment, but this is a lot better.
Answer: Based on jfrite answer attaching my implementations
import android.content.res.Resources;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.util.Log;

public final class AnimationHelper {
    private AnimationHelper() {

    }

    private static String TAG = AnimationHelper.class.getSimpleName();
    private static final float ELEVATION_WHILE_ENTER_ANIMATION_IS_RUNNING = 100f;
    private static final int RESTORE_ANIMATION_DELAY = 16;

    /**
     * When replacing fragments with animations, by default the new fragment is placed below the replaced fragment. This
     * method returns an animation object that sets high elevation at the beginning of the animation and resets the
     * elevation when the animation completes. The {@link Animation} object that is returned is not the actual object
     * that is used for the animating the fragment but the callbacks are called at the appropriate time. The method
     * {@link Fragment#onCreateAnimation(int, boolean, int)} by default returns null, therefor, this method can be used
     * as the return value for {@link Fragment#onCreateAnimation(int, boolean, int)} method although it can return
     * null.
     * @param enter True if fragment is 'entering'.
     * @param nextAnim Animation resource id that is about to play.
     * @param fragment The animated fragment.
     * @return If nextAnim is a valid resource id and 'enter' is true, returns an {@link Animation} object with the
     * described above behavior, otherwise returns null.
     */
    @Nullable
    public static Animation increaseElevationWhileAnimating(boolean enter, int nextAnim,
                                                            @NonNull Fragment fragment) {
        if (!enter || nextAnim == 0) {
            return null;
        }
        Animation nextAnimation;
        try {
            nextAnimation = AnimationUtils.loadAnimation(fragment.getContext(), nextAnim);
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Can't find animation resource", e);
            return null;
        }
        nextAnimation.setAnimationListener(new Animation.AnimationListener() {
            private float oldTranslationZ;

            @Override
            public void onAnimationStart(Animation animation) {
                if (fragment.getView() != null && !fragment.isDetached()) {
                    oldTranslationZ = ViewCompat.getTranslationZ(fragment.getView());
                    ViewCompat.setTranslationZ(fragment.getView(), ELEVATION_WHILE_ENTER_ANIMATION_IS_RUNNING);
                }
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (fragment.getView() != null && !fragment.isDetached()) {
                    fragment.getView().postDelayed(() -> {
                        // Decreasing the elevation at the ned can cause some flickering because of timing issues,
                        // Meaning that the replaced fragment did not complete yet the animation. Resting the animation
                        // with a minor delay solves the problem.
                        if (!fragment.isDetached()) {
                            ViewCompat.setTranslationZ(fragment.getView(), oldTranslationZ);
                        }
                    }, RESTORE_ANIMATION_DELAY);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        return nextAnimation;
    }
}

Here is how I use the helper form the fragment.
@Override
    public Animation onCreateAnimation(int transit, final boolean enter, int nextAnim) {
        return AnimationHelper.increaseElevationWhileAnimating(enter, nextAnim, this);
    }

Here is how i start the fragment with animation
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.anim.slide_in, R.anim.hold, R.anim.hold, R.anim.slide_out);

Comment: This fixes the issue when a new fragment is loaded, but there's a problem when pressing back button. How could I "reverse" the animation and avoid transition issues?
Comment: @moyo not sure i understood your question. anyway, i ended up adding this line:
if (!enter || nextAnim == 0 || nextAnim == R.anim.hold) {
            return null;
        }
Answer: Add an elevation to the layout.
I added an elevation to the fragment that slides in from the bottom of 30sp and it worked.
I have tried many solutions suggested here. Here are the full code and output that combines all the idea + adding elevation.
Output:
Without elevation:

With elevation:

Full Code:
Add an elevation to the root
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:elevation="30sp">
     ----

     ----
 </RelativeLayout>

How to slide in the fragment from the bottom?
getSupportFragmentManager()
            .beginTransaction()
            .setCustomAnimations(R.anim.slide_in_bottom, R.anim.do_nothing, R.anim.do_nothing, R.anim.slide_out_bottom)
            .replace(R.id.fragmentContainer, currentFragment, "TAG")
            .addToBackStack("TAG")
            .commit();

How to do the reverse when the back button is pressed?
getSupportFragmentManager()
            .popBackStack();

Since we have already defined enter and exit animation on
  setCustomAnimations() method. Calling popBackStack(); takes care
  of the reverse animation.

R.anim.slide_in_bottom
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <translate
       android:duration="500"
       android:fromYDelta="100%"
       android:toYDelta="0%">
    </translate>
</set>

R.anim.slide_out_bottom
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <translate
        android:duration="500"
        android:fromYDelta="0%"
        android:toYDelta="100%">
    </translate>
</set>

R.anim.do_nothing
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:interpolator="@android:anim/linear_interpolator"
        android:fromXScale="1.0"
        android:toXScale="1.0"
        android:fromYScale="1.0"
        android:toYScale="1.0"
        android:duration="500"/>
     <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromAlpha="1.0"
        android:toAlpha="1.0"
        android:duration="500"
        android:startOffset="500" />
</set>

Comment: This is a pretty good solution. I still need to tweek the animations and want to do stuff once they have completed. Good work Rohit Singh
Answer: Answer when using fragment manager
   getSupportFragmentManager()
            .beginTransaction()
            .setCustomAnimations(
                R.anim.slide_in_from_left,
                R.anim.slide_free_animation,
                R.anim.slide_free_animation,
                R.anim.slide_out_to_left
            )
            .replace(R.id.fragmentContainer, currentFragment, "TAG")
            .addToBackStack("TAG")
            .commit()

Answer when using Navigation:
     <action
            android:id="@+id/action_firstFragment_to_secondFragment"
            app:destination="@id/secondFragment"
            app:enterAnim="@anim/slide_in_from_left"
            app:exitAnim="@anim/slide_free_animation"
            app:popEnterAnim="@anim/slide_free_animation"
            app:popExitAnim="@anim/slide_out_to_left" />

slide_in_from_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">

    <translate
        android:duration="500"
        android:fromXDelta="-100%p"
        android:fromYDelta="0%"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toXDelta="0%"
        android:toYDelta="0%" />

</set>

slide_out_to_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">

    <translate
        android:duration="500"
        android:fromXDelta="0%"
        android:fromYDelta="0%"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:toXDelta="-100%p"
        android:toYDelta="0%" />

</set>

slide_free_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <alpha
        android:duration="300"
        android:fromAlpha="1.0"
        android:startOffset="200"
        android:toAlpha="0.0" />

</set>

Answer: Quite a lot of steps but was able to do this with a mix of transitions and animations
 supportFragmentManager
         .beginTransaction()
         .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN
         .setCustomAnimations(R.anim.nothing, R.anim.scale_out)
         .replace(R.id.fragment_container, fragment)
         .commit()

Nothing.xml
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@integer/transition_animation_time" />

Scale out - Animates old fragment on the way out
<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fromXScale="100%"
    android:fromYScale="100%"
    android:toXScale="90%"
    android:toYScale="90%"
    android:pivotY="50%"
    android:pivotX="50%"/>

Fragment.kotlin
   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val inflater = TransitionInflater.from(requireContext())
        enterTransition = inflater.inflateTransition(R.transition.slide)
    }

res/transition/slide.xml - Animates new fragment on the way in
<?xml version="1.0" encoding="utf-8"?>
<slide xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:slideEdge="bottom" />

Answer: FragmentTransaction ft = ((AppCompatActivity) context).getSupportFragmentManager().beginTransaction();
                ft.setCustomAnimations(0, R.anim.slide_out_to_right);
            if (!fragment.isAdded())
            {
                ft.add(R.id.fragmentContainerFrameMyOrders, fragment);
                ft.show(fragment);
            }
            else
                ft.replace(R.id.fragmentContainerFrameMyOrders, fragment);
            ft.commit();

Answer: This is my current workaround for anybody interested.
In the function for adding the new Fragment:
final Fragment toRemove = fragmentManager.findFragmentById(containerID);
if (toRemove != null) {
    new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                fragmentManager.beginTransaction().hide(toRemove).commit();
            }
        },
        getResources().getInteger(android.R.integer.config_mediumAnimTime) + 100);
        // Use whatever duration you chose for your animation for this handler
        // I added an extra 100 ms because the first transaction wasn't always
        // fast enough
}
fragmentManager.beginTransaction()
    .setCustomAnimations(enter, 0, 0, popExit).add(containerID, fragmentToAdd)
    .addToBackStack(tag).commit();

and in onCreate:
final FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.addOnBackStackChangedListener(
        new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                Fragment current = fragmentManager.findFragmentById(containerID);
                if (current != null && current.isHidden()) {
                    fragmentManager.beginTransaction().show(current).commit();
                }
            }
        });

I would prefer some sort of AnimationListener instead of a Handler above, but I didn't see any way you could use one to detect the end of the transaction animation that wasn't tied to the fragment like onCreateAnimation(). Any suggestions/edits with an appropriate listener would be appreciated.
I will point out the Fragments I am adding this way are lightweight so it isn't a problem for me to have them in the fragment container along with the fragment they are on top of.
If you want to remove the fragment you could put fragmentManager.beginTransaction().remove(toRemove).commitAllowingStateLoss(); in the Handler's Runnable, and in the OnBackStackChangedListener:
// Use back stack entry tag to get the fragment
Fragment current = getCurrentFragment();
if (current != null && !current.isAdded()) {
    fragmentManager.beginTransaction()
        .add(containerId, current, current.getTag())
        .commitNowAllowingStateLoss();
}

Note the above solution doesn't work for the first fragment in the container (because it isn't in the back stack) so you would have to have another way to restore that one, perhaps save a reference to the first fragment somehow... But if you don't use the back stack and always replace fragments manually, this is not an issue. OR you could add all fragments to the back stack (including the first one) and override onBackPressed to make sure your activity exits instead of showing a blank screen when only one fragment is left in the back stack.
EDIT:
I discovered the following functions that could probably replace FragmentTransaction.remove() and FragmentTransaction.add() above:
FragmentTransaction.detach():

Detach the given fragment from the UI. This is the same state as when it is put on the back stack: the fragment is removed from the UI, however its state is still being actively managed by the fragment manager. When going into this state its view hierarchy is destroyed.

FragmentTransaction.attach():

Re-attach a fragment after it had previously been detached from the UI with detach(Fragment). This causes its view hierarchy to be re-created, attached to the UI, and displayed.
Answer: I have the same problem, and all of the solutions looks like overkill. Hiding fragments lead to errors when you should remove fragment after animation finished, but you don't know when it happens.

I found simplest solution: just set for previous fragment negative translationZ in transaction:
childFragmentManager.fragments.lastOrNull()?.let { it.view?.translationZ = -1f }

Whole transaction looks like:
childFragmentManager.commit {
    setCustomAnimations(...)
    childFragmentManager.fragments.lastOrNull()?.let { it.view?.elevation = -1f }
    replace(..., ...)
    addToBackStack(...)
}

That's all.
It shouldn't affect any behavior of your views. Everything should works as usual. Animation to back also works correctly (with correct order).


How to send mail if they didn't used the module at all in Laravel

Question: Basically, I want send a reminder to the user to used modules in the system. If the didn't used one of the module means need remind them by sending an automated mail. I have created a DB table which contain user_id, module_id and last_used_module. So How i will send the mail to the user.
I try to used null value for last_used_module but its didn't work because last_module_used time is the same with created at and updated at. So, i cant used that.Anyone can help with this?
I got some idea to solve this issue which is if user_id and module_id exist in table means no need to the mail. I don't know hw implement this.
<code> foreach($ModuleAutoMail as $module) {
                                if($mail->condition_id=='3' ){

                                $last_used_module = Carbon::parse($module->last_used_module);
                                $DeferenceInDays = Carbon::parse(Carbon::now())->diffInDays($last_used_module);

                                if(is_null($last_used_module)){
                                    $ableToSendMail = true;
                                }
                                elseif ($DeferenceInDays > 7) {
                                    $ableToSendMail = false;
                                }
                                else {
                                    if ($emailCheck< 1){
                                        $ableToSendMail = true;
                                    }
                                }
                            }
                        }
                        if ($ableToSendMail) { //saving and sent email
                        $mails = new EmailSave;
                        $mails->user_id = $user->id;
                        $mails->email_id =$mail->id;
                        Mail::to($user->email)->send(new Automail($mail));
                        $mails->save();
                    }
</code>
Comment: I didn't get your problem, do you want to send an email to user that's not used your module ?
Comment: ya... We have 50++ module in our system so the user should utilise it. If the didnt used one of the module means need remain the thm by an automated mail
Comment: Ok, so you have to update last_used_module every time he uses the module. Then, you can make your verifications.
Comment: Just one thing: your variable should be 'differenceInDays'. Also try to use camelCase on variables :)
Comment: what is camelCase on variables?
Comment: It will updated automatically in DB table
Comment: camelCase: https://en.wikipedia.org/wiki/Camel_case
Comment: So, what's your main problem? Why you can't use last_used_module ?
Comment: last_used_module, created_at and updated_at always have same value in which i believe it is also filled so it is never null. This should be the reason why it is always break. I can't think other solution also.
Comment: So, I think the update of last_used_module it's broken, if there is a update the updated_at should be other value than created_at. Verify if this update it's correct.
Comment: Sorry, I didnt get it.
Comment: Couldn't you just set your `last_used_module` to null when you first create your module?
Comment: I think cant like that. But i have an idea which is if user_id is not exist means thn send mail for each module else if user_id exist thn need check which module_id is not exist thn send mail.
Answer: Mail Trap

Register on Mail Trap
Copy the SMTP login password form Mail trap
Paste in ENV file
Create Mailable

Mail::send('emails.reminder', ['user' => $user], function ($m) use
  ($user) {
                  $m->from('firstname.lastname@example.com', 'Your Application');
                  $m->to($user->email, $user->name)->subject('Your Reminder!');
              });

Visit This Tutorial


gcov cannot open graph file

Question: I'm getting the following error when trying to run gcov as part of my Travis CI build:
$ gcov src/bgrep.c
bgrep.gcno:cannot open graph file

My .travis.yml:
language: c
compiler: gcc
sudo: false

before_script:
  - uname -a
  - printenv
  - gcov --version

script:
  - scons coverage=1
  - ls -l src/
  - test/run_test.py
  - ls -l src/
  - gcov src/bgrep.c
  - ls -l src/
  - ls -l

after_success:
  - bash <(curl -s https://codecov.io/bash)

I can run the exact sequence of commands (scons, test/run_test.py, gcov src/bgrep.c) on my Fedora machine, and gcov produces grep.gcov as expected.
Travis is using gcov (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3. You can see an example build log here.
What am I (or Travis) doing wrong?
Comment: Could you run `find` as well?
Comment: This appears to be a difference in behavior between different versions of `gcov`. Apparently that of my newer Fedora is smart enough to find the data files when I give `gcov` a path like `src/bgrep.c`. Older gcov requires a `-o` option.
Comment: Interesting. Does that mean it's resolved?
Comment: Yeah. I'm eventually going to add an answer.
Answer: I had the same problem with gcov and travis. It seems that gcov indeed requires that the *.gcda and *.gcno files must be in the same directory as the *.c files. And additionally the -o option must be given which points then to the same directory...
So, I have the source files in folder src/ and the binaries in build/coverage/. First, I tried with 'gcov -o build/coverage/ src/*.c' which did not work. Second attempt was with copying the *.gc* files to src/ and executing 'gcov src/*.c' which also did not work. It finally worked with 'gcov -o src/ src/*.c'.

gcov cannot open graph file


Water pressure issue when 2 sources running

Question: In our house, if 1 water source is being used it works. But if the horse buckets are being filled (outdoor spigot) all you get is air sound on any other fixture. Even if you try and use hot water (with hot water heater tank full) which is not hooked up outside. Also if you flush the toilet while in the shower it turns to a trickle. Must have washer and dishwasher off for showers etc.
Is there an easy fix? What is causing this?
We have 2 wells one hand-dug and one artesian and a 100 year old home.
We also recently changed the artesian pump and around the same time the filter needed changing every 2-3 days cause was filled with sand and water would get slow even for 1 fixture. That issue seems to have resolved on its own but we're still planning on putting in a DIY bigger filter. This is a separate issue the other issue has been continuous.

Just added these pics. One picture is of the pressure switch on the 20ft hand-dug well reading 40ish. The other pressure gauge is at the base of one of the tanks reading 25 psi. Seems this may be low. How do we increase the pressure? Both wells are hooked up to the house we seem to have the same issue of whether both pumps are on or just one.
People are washing clothes it's now not filling and the pressure is reading 45psi on hand dug and 30 psi on artesian both up about 5 psi.
I just took off the cover of the pressure switch. Can I just turn one of these screws to adjust the pressure? Which one and how many rotations?
I adjusted the pressure switch 4-5 turns with both pumps off. Dropped the pressure and turned on the drilled well. Still only gets to 25 psi without the help of the hand-dug well? I'm gonna put the pressure switch back to where it was and wait for advice.
Comment: is you valve on the street side fully open. Did you notice a leak somewhere. Is you pressure regulator working.
Comment: Is this a well or city water?
Comment: 1 hand dug well 20 ft 1 450 ft artesian both run
Comment: No leaks noticed. One other thing I noticed is the bathroom sink shoots a stream that is not solid and has been blocked up before. We removed the screen to clean where the water comes out to resolve. Maybe are plumbing is clogged?
Comment: Th only other clog I have been sure of has been on the shower drain though not on the clean water side.
Comment: What are the pipe sizes? Apart from clogged pipes, undersized pipes can contribute to this. Generally if it needs a pump, it's just a drilled well, not an artesian well (which would be pressurized without a pump. The very definition of artesian well. Though there can be edge cases where the well overflows without a pump, but has pressure so low a pump is needed.) The "Spin-down screen with debris reservoir and dump valve" type filters are handy for sand, as you can just dump accumulated sand in a few seconds of flushing, no need to take it apart, or replace a filter element.
Comment: Yes drilled well. Thanks for tip on filter
Comment: See https://diy.stackexchange.com/a/129456/18078 regarding **how** to adjust the pressure switch. And always be sure the power supply is cut off before opening that cover. If the pump won't reach cutoff pressure, there's a problem with the (recent) pump.
Answer: Seeing it's a well, you need to look at your well pressure tank. There should be a pressure gauge on it. Watch what it's doing, it should maintain between 40 - 60 psi. Possible problems is your well pump is wore out, or your pressure switch isn't maintaining adequate pressure in the tank. You say you have two wells. Are they both connected to the house?
Comment: Add a flow restrictor to each faucet or spigot to keep pressure from dropping too low, allowing air to enter the system. Disadvantage:  it will take longer to fill things.
Comment: I see hints of galvanized/iron pipe, is the house plumbed with pipe or tubing? galvanized or iron pipe will corrode closed after many years causing pressure drops because of flow restrictions. Also check your gauges, there should not be that much pressure difference between two parallel pump systems.


What does the ~ symbol mean next to the files that are listed with ls?

Question: I created a file named xxx on my Desktop and then I (re)moved it using terminal. Now when I execute ls on Desktop I see a file named xxx~ that is not visible at GUI. What does it mean?
Comment: Backup automatically created from a program, more commonly text editors
Comment: @OrganicMarble is right. I just couldn't see the fact that how all those files are derived from other files that I used with gedit. The question he/she marked mine as a duplicate of has all the answers and more I'd need. Thank you.
Comment: You will find your answer here: http://askubuntu.com/questions/83026/prevent-gedit-from-creating-files-with-the-tilde-suffix; this question is a duplicate of that one (or at least you will find your answer there).
Answer: It indicates that is a backup file


After adding "greeter-show-manual-login=true" I can't log in

Question: After I entered this command in terminal:
sudo sh -c 'echo "greeter-show-manual-login=true" >> /etc/lightdm/lightdm.conf'

and I reboot my PC I cannot login. After I select the os in GRUB it takes me to a black  screen and I can't do anything even though Ubuntu seems to run; everytime I turn off my computer via the power button the Ubuntu logo appear. I think it has got to do with lightdm. I have tried to run in safe graphics mode but nothing happen what should I do?
Answer: As far as I know, /etc/lightdm/lightdm.conf doesn't exist in Ubuntu 14.04 ! I tried
locate /etc/lightdm/lightdm.conf

in my Ubuntu 14.04 and this is what I got :-
/etc/init/lightdm.conf
/usr/share/doc/lightdm/lightdm.conf.gz
/usr/share/lightdm/lightdm.conf.d
/usr/share/lightdm/lightdm.conf.d/50-greeter-wrapper.conf
/usr/share/lightdm/lightdm.conf.d/50-guest-wrapper.conf
/usr/share/lightdm/lightdm.conf.d/50-ubuntu.conf
/usr/share/lightdm/lightdm.conf.d/50-unity-greeter.conf
/usr/share/lightdm/lightdm.conf.d/50-xserver-command.conf
/var/lib/dpkg/info/lightdm.conffiles
/var/lib/dpkg/info/lightdm.config

Therefore it is clear that /etc/lightdm/lightdm.conf doesn't exist. Well, I must add that it is not present there. Instead use /usr/share/lightdm/lightdm.conf.d/50-ubuntu.conf . Its content is same as that of /etc/lightdm/lightdm.conf as shown below:-
[SeatDefaults]
user-session=ubuntu

So remember:-

The equivalent of /etc/lighdm/lightdm.conf in Ubuntu 14.04 is
  /usr/share/lightdm/lightdm.conf.d/50-ubuntu.conf .

Therefore you might edit your above command to :-
sudo sh -c 'echo "greeter-show-manual-login=true" >> /usr/share/lightdm/lightdm.conf.d/50-ubuntu.conf'

and it might work!
Answer: I hope this will help you
When you power on the computer, and ubuntu will load, try to press [Left Control] + [Left Alt] + [F1]
Then log in to the system via terminal, then go to the path /etc/lightgdm by command:
cd /etc/lightdm/

Then edit the file lightdm.conf with your editor like: nano or vi (nano is much more easier here). It will ask you for your password again
sudo nano lightdm.conf

And delete the whole line that you added
greeter-show-manual-login=true

Then save it with keyboard command [Left Control] + [x], it will ask you "Save modified buffer" press key [y] and then it will ask "File Name to Write: lightdm.conf" just press [Enter]
Finally type
sudo reboot

Comment: In ubuntu 14.04 they moved and renamed that file. Go to "/usr/share/lightdm/lightdm.conf.d" and there is a file named "50-ubuntu.conf" just add that line "greeter-show-manual-login=true" at the bottom of that file, and reboot system.
Comment: @xylo Uhhh..isn't that my answer below?
Comment: I'm on my android, your answer did not load so i did not read it. Sorry mate :)
Comment: Or use live cd, and then edit the file.
Comment: it worked so thank you very much but if i want to have a root acount and lightdm is causing me these problems how can i have a root account
Comment: @xylo its fine!
Comment: @Zorbacator "if i want to have a root acount and lightdm is causing me these problems how can i have a root account" Its not clear what you are asking here... Can you elaborate? If it is relevant to this question then post about this problem too here it self. Else make it a separate question...


The Ubuntu installer can't see the Windows 8 partition during installation

Question: I tried to install Ubuntu 12.10 alongside Windows 8, but when I get to the installation type screen I don't have any option for installing alongside Windows 8. Ubuntu says I have no other operating systems and my partitions appear as free space. What can I do?
Comment: Possible Duplicate: http://askubuntu.com/q/221835/44179
Answer: Maby try to shrink your partions in windows 8 and install ubuntu on that partion. Totaly save normal.
http://www.howtogeek.com/howto/windows-vista/resize-a-partition-for-free-in-windows-vista/
Running ubuntu 12.10 / windows 8 on toshiba satellite C660
Comment: made a new partion but still cant see it in ubuntu installer
Comment: Install ubuntu on that partion using advanced installation available on the installer normal. Are you sure you did nothing unusual with your windows installation?


VS2010 remote debugging with default transport problem

Question: I need to do remote debugging of managed code (.NET) on a server hosted on a different network. Neither the client or server is on a domain so i have to use the public ip of the server.
I'm trying to use Visual Studio -> Attach to process -> default transport with the qualifier email@example.com but it's not working.
I get the error message : "Unable to connect to the Microsoft Visual Studio Remote Debugging Monitor named 'email@example.com'. There is no server by the specified name running on the remote computer"
This error message tells me i can connect just fine but it can't find the msvsmon instance (which is 'john@WEB-001'). So i tried to use the combination of qualifiers such as WEB-001\email@example.com and xx.xx.xx.xx\john@WEB-001 but neither are working.
If I choose the transport "Remote (Native only with no authentication)" it connects just fine and I can see the process list on the server but it is pretty much useless because I can't debug managed code.
The administrator 'john' exists on both computer with the same password
Windows 2008 R2 X64 (Server)
Remote debugging component (VS2010) X64 installed
Firewall off
Msvsmon new server named 'john@WEB-001' running as john
Windows 7 X64 (Client)
Visual studio 2010 running as john
Firewall off
Any idea how to fix this, or is this scenario not supported? Thanks
Answer: having you tried putting web-001 in your hosts file, and connecting as john@web-001?
Comment: Good idea, but it doesn't work.

"Unable to connect to the Microsoft Visual Studio Remote Debugging Monitor named 'john@WEB-001'. There is no server by the specified name running on the remote computer"

Weird.
Comment: Maybe enable auditing on both ends and watch your security eventlog for fails and successes.
Answer: Try adding the server name to your hosts file:
<code>192.168.1.100 WEB-001
</code>
Replace the IP with your own. Native code debugging is done over plain TCP/IP with no security but native code requires DCOM to enforce security, I don't understand the reason but ....
Answer: I know this is an old thread now but.
When the remote debugger is first installed you can set a firewall setting that allows all web traffic or only subnet connections. Run the configuration again to allow all web traffic.
Also, as the Administrator account, not a user in the Administrator group, Shift+r-click on the debugger shortcut to execute as a different user. Enter in the other user account that has the same username and password as the machine you are debugging with, in this case john.
This is the process I have to use.


Validation should stop with the first condition violation

Question: I have specification and I want to stop validation with first false result.
at now check all validation and then return result.
ISpecification:
 public interface ISpecification<T>
    {
        SpecificationResult IsSatisfiedBy(T value);
    }

Specification:
public abstract class Specification<T> : ISpecification<T>
{
    public Specification<T> And(ISpecification<T> right)
    {
        return new AndSpecification<T>(this, right);
    }
    public Specification<T> Or(ISpecification<T> right)
    {
        return new OrSpecification<T>(this, right);
    }
    public Specification<T> Not()
    {
        return new NotSpecification<T>(this);
    }

    public abstract SpecificationResult IsSatisfiedBy(T entity);
}

AndSpecification
    public class AndSpecification<T> : Specification<T>
{
    private readonly ISpecification<T> _leftSpec;
    private readonly ISpecification<T> _rightSpec;
    public AndSpecification(ISpecification<T> leftSpec, ISpecification<T> rightSpec)
    {
        _leftSpec = leftSpec;
        _rightSpec = rightSpec;
    }
    public override SpecificationResult IsSatisfiedBy(T entity)
    {
        return new SpecificationResult()
        {
            IsSatisfied = _leftSpec.IsSatisfiedBy(entity).IsSatisfied && _rightSpec.IsSatisfiedBy(entity).IsSatisfied,
            Message = new StringBuilder().Append(_leftSpec.IsSatisfiedBy(entity).Message).Append(_rightSpec.IsSatisfiedBy(entity).Message).ToString(),
        };
    }
}

my custom validation :
    public class UserIsActive : Specification<User>
{
    public override SpecificationResult IsSatisfiedBy(User user)
    {
        if (user.Status != UserStatus.Active)
        {
            return new SpecificationResult
            {
                IsSatisfied = false,
                Message = "حساب کاربری  شما غیرفعال میباشد لطفا با پشتیبانی تماس بگیرید"
            };
        }
        return new SpecificationResult
        {
            IsSatisfied = true,
            Message = string.Empty
        };
    }
}

public class UserIsNotExpoire : Specification<User>
{
    public override SpecificationResult IsSatisfiedBy(User user)
    {
        if (user.IsExpired)
        {
            return new SpecificationResult
            {
                IsSatisfied = false,
                Message = "حساب کاربری  شما منقضی شده است لطفا با پشتیبانی تماس بگیرید"
            };
        }
        return new SpecificationResult
        {
            IsSatisfied = true,
            Message = string.Empty
        };
    }
}

public class UserIsNotNull : Specification<User>
{
    public override SpecificationResult IsSatisfiedBy(User user)
    {
        if (user==null)
        {
            return new SpecificationResult
            {
                IsSatisfied = false,
                Message = "نام کاربری یا کلمه عبور اشتباه است"
            };
        }
        return new SpecificationResult
        {
            IsSatisfied = true,
            Message = string.Empty
        };
    }
}

and this how I use specification.
var validation = new UserIsActive().And(new UserIsNotExpoire().And(new UserIsNotNull()));

           var result = validation.IsSatisfiedBy(user);
            if (!result.IsSatisfied)
                return Ok(new
                {
                    success = false,
                    errorMessage = result.Message,
                });

Comment: A specific reason to reinvent the wheel, when there is fluent validation (not affiliated but happy user)?
Comment: @Fildor what do you mean?
Comment: I was talking about [FluentValidation](https://docs.fluentvalidation.net/en/latest/)
Answer: If I understand your goal correctly it happens because you build the message unconditionally (also you are validating the condition twice). Change your code to something like:
public override SpecificationResult IsSatisfiedBy(T entity)
{
    if (_leftSpec.IsSatisfiedBy(entity) is {IsSatisfied: false} left)
    {
        return new SpecificationResult
        {
            IsSatisfied = false,
            Message = left.Message
        };
    }

    if (_rightSpec.IsSatisfiedBy(entity) is {IsSatisfied: false} right)
    {
        return new SpecificationResult
        {
            IsSatisfied = false,
            Message = right.Message
        };
    }
    return new SpecificationResult
    {
        IsSatisfied = true,
        Message = String.Empty
    };
}

P.S.
Consider using FluentValidation library.
Comment: @Soheil Check your `And` implementation, you are calling `IsSatisfiedBy` to determine the `IsSatisfied` of the result and then you are calling it again to fill the message, so `_left` and `_right` will be validated twice.
Comment: twice ?!?!, could you explain it
Comment: you are right.
I want the rest of the validation to stop after the first violation.
Comment: @Soheil then try using the suggested solution


Bitbake stopped in do_fetch

Question: I have been trying to create a Linux image for the VAR-SOM-MX8X. Its been a rough beginning, but I have managed to create the layers and so. I have bitbaked 2 days ago and left the system working, I already knew it was going to be a long way.
The problem is since yesterday at 23:26  the log inside of my tmp/buildstats/ shows me the build has been trying to download me this Git package,
git clone --branch imx_5.4.24_2.1.0  https://source.codeaurora.org/external/imx/linux-imx.git

I have tried to download it by myself with git clone and it starts, its huge, but it downloads properly. The problem is the bitbake download doesn't look like its working, the progress bar has stayed all day long in 41% and it doesn't look like its working.
-- UPDATE
okey, I didn't know you could actually stop bitbake by Ctr+C twice, one first and another after the "wait for executiioning tasks" dialogue appears. Anyway my download has not gone far, my system stays downloading the same git path all the time and it doesnt make any change, once it has managed to go to 100% but then it has stopped there forever. Any idea why is this happening?
Comment: Can it be RAM related issue? I am bitbaking it in a virtual machine with not much RAM, my PC only has 4GB and almost crashed when the virtual machine used 2GB, so I put 1GB only.
Answer: I have finally managed to get the image, the problem may be about connectivity issue. First, I tried to do it in my work laptop in my office but it was too slow. Finally, trying to do it in my home PC I have managed to get the image, some recipes fail, but with
bitbake <image_name> -c cleanall

I have managed to get everything done. Moreover, nodejs didnt compile properly, so I remove it out of my local.conf file and everythign worked fine.

Bitbake stopped in do_fetch


Pandas: top N rows, top N rows per group, equivalent for ROW_NUMBER OVER(PARTITION BY ... ORDER BY ...)

Question: What is the python equivalent to the TOP function in T-SQL? I'm looking to filter my dataframe to the top 50K rows.  I've looked online and I can't find a simple example.
Comment: MaxU handily beat me to an answer, and did a better job than I would have.  For future reference, here's a [nice page](http://pandas.pydata.org/pandas-docs/stable/indexing.html) on indexing data frames.
Answer: UPDATE: - shows different pandas approaches, including:
top N rows per group
top N rows with offset
equivalent for SQL aggregate functions:
ROW_NUMBER() / RANK() OVER(PARTITION BY ... ORDER BY ...)
sample DF:
df = pd.DataFrame({
  'dep': np.random.choice(list('ABC'), 20),
  'manager_id': np.random.randint(0, 10, 20),
  'salary': np.random.randint(5000, 5006, 20)
})

----------------------- Original DF ------------------------
In [2]: df
Out[2]:
   dep  manager_id  salary
0    B           5    5005
1    A           6    5001
2    C           8    5000
3    A           7    5000
4    B           0    5002
5    A           3    5003
6    A           2    5004
7    A           2    5004
8    C           3    5002
9    C           4    5001
10   A           9    5002
11   C           9    5000
12   B           8    5004
13   A           1    5003
14   C           7    5005
15   B           0    5002
16   B           2    5003
17   A           4    5000
18   B           2    5003
19   B           7    5003

------------------ top 5 rows (sorted by original index) -------------------
In [3]: df.head(5)
Out[3]:
  dep  manager_id  salary
0   B           5    5005
1   A           6    5001
2   C           8    5000
3   A           7    5000
4   B           0    5002

--- top 5 rows (sorted by manager_id DESC, dep ASC) ----
In [4]: df.sort_values(by=['manager_id', 'dep'], ascending=[False,True]).head(5)
Out[4]:
   dep  manager_id  salary
10   A           9    5002
11   C           9    5000
12   B           8    5004
2    C           8    5000
3    A           7    5000

--- equivalent for SELECT * FROM tab ORDER BY salary DESC LIMIT 5 OFFSET 3 ---
In [19]: df.nlargest(5+3, columns=['salary']).tail(5)
Out[19]:
   dep  manager_id  salary
7    A           2    5004
12   B           8    5004
5    A           3    5003
13   A           1    5003
16   B           2    5003

---- top 2 salaries in each department (no duplicates) -----
--- equivalent for SQL: row_number() over(partition by DEP order by SALARY desc) ---
In [7]: (df.assign(rn=df.sort_values(['salary'], ascending=False)
   ...:                 .groupby(['dep'])
   ...:                 .cumcount() + 1)
   ...:    .query('rn < 3')
   ...:    .sort_values(['dep','rn'])
   ...: )
Out[7]:
   dep  manager_id  salary  rn
6    A           2    5004   1
7    A           2    5004   2
0    B           5    5005   1
12   B           8    5004   2
14   C           7    5005   1
8    C           3    5002   2

--- top 2 salaries in each department (using "nlargest") ----
In [15]: df.loc[df.groupby('dep')['salary'].nlargest(2).reset_index()['level_1']]
Out[15]:
   dep  manager_id  salary
6    A           2    5004
7    A           2    5004
0    B           5    5005
12   B           8    5004
14   C           7    5005
8    C           3    5002

--- second and third highest salaries in each department ---
In [16]: (df.assign(rn=df.sort_values(['salary'], ascending=False)
   ....:                 .groupby(['dep'])
   ....:                 .cumcount() + 1)
   ....:    .query('rn >= 2 and rn <= 3')
   ....:    .sort_values(['dep','rn'])
   ....: )
Out[16]:
   dep  manager_id  salary  rn
7    A           2    5004   2
13   A           1    5003   3
12   B           8    5004   2
18   B           2    5003   3
8    C           3    5002   2
9    C           4    5001   3

--- top 2 salaries in each department (with duplicates) ----
--- equivalent for SQL: rank() over(partition by DEP order by SALARY desc)  ---
In [18]: (df.assign(rnk=df.groupby(['dep'])['salary']
   ....:                  .rank(method='min', ascending=False))
   ....:    .query('rnk < 3')
   ....:    .sort_values(['dep','rnk'])
   ....: )
Out[18]:
   dep  manager_id  salary  rnk
6    A           2    5004  1.0
7    A           2    5004  1.0
0    B           5    5005  1.0
12   B           8    5004  2.0
14   C           7    5005  1.0
8    C           3    5002  2.0

Comment: if u would like to do a pull request for anything that is not in the docs http://pandas.pydata.org/pandas-docs/stable/comparison_with_sql.html (or not clear), would be great!
Comment: @Jeff, i'll try. It will take me some time, though to become familiar with GitHub and making pull requests
Comment: This is fantastic, thanks MaxU. Note that if you get a 'cannot reindex from a duplicate axis' error you can solve this by resetting your index: df = df.reset_index()


Is a subset of an inner product space also an inner product space?

Question: My question may seem trivial but it's important that I know this. I know for a fact that a subspace of an inner product space is also an inner product space, but how about an arbitrary subset? Could I argue that since we are allowed to pick any subset, we could pick one that is not a subspace and since it is not a subspace it is not eligible as an inner product space?
Thank you!
Comment: of course you can choose any subset, so also one that is not a subspace.
Comment: Unless you're talking about the trivial vector space $\{0\}$ which has only the additive identity vector of the underlying field, in which case any nonempty subset is actually a subspace.
Comment: A small note: you should actually present a subset that is not a *vector* space, for it can fail to be vector *sub*-space yet still admit a vector space structure, or even inner product space. Anyhow, this inner product space would never be a sub inner product space, which is what you're interested in (I believe, correct me if I'm wrong).
Answer: A subset of an inner product space does not have to be an inner product space.
As you said, we can pick a subset that is not a subspace, hence not an inner product space.
Answer: An inner product space is by definition a vector space. Therefore, if a subset is not a subspace, then it cannot be an inner product space.
You can still talk about many properties that you might be interested in, such as perpendicularity and so forth.
For instance, you could take a subset $S$ of an inner product space $H$, and examine $\langle x,y \rangle$ for $x,y \in S$. For a subset of $S'$ you could also define $$(S')^\perp = \{ x \in S : \langle x,y \rangle =0 \text{ for all } y \in S\},$$ however $(S')^\perp$ would not necessarily be a subspace either.


Does extending an abstract class in Dart give the subclass another constructor

Question: I created an abstract class with final variables, because of that I needed to create a constructor inside of it to instantiate the variables. Will this constructor be added to all classes that extend the abstract class? I am thinking not so because some of my subclasses will have additional final variables that would need to be instantiated. If this is the case what role does the abstract class' constructor play?
For reference:
abstract class SuperClass {
  final String item
  SuperClass(item)
  : item = item;
}

class SubClass {
  final String item
  final String item2
  SubClass(item, item2)
  : item = item,
  item2 = item2;
}

Is extending the best option in this case and if so will the super class' constructor be seen?
Answer: The abstract class in your case is just a normal class because it does not have any abstract properties/methods. The only thing that you can not do is create an instance of that abstract class.
Extending the SuperClass makes sense because you will no longer need to define fields that are declared in the super class, like the "item" field.
In order to benefit from it, you need to write your subclass slightly different:
abstract class SuperClass {
  final String item;
  SuperClass(this.item);
}

class SubClass extends SuperClass {
  final String item2;
  SubClass(String item, this.item2) : super(item);
}

Please note that the subclass constructor calls the superclass' constructor and passes the item value to it. You still have to declare the item value in your subclass' constructor though; otherwise, you would not have a chance to initialize it, which is required because it is final in the superclass.
Comment: @joshpetit, thanks for editing. I would like to make it clear that you will still need to have constructor in the SubClass. As the only place to call super constructor is from subclass' constructor and you must call super constructor.
Comment: Yes, that explains the purpose of the superclass constructor also. So it doesn't necessarily create a new constructor in the subclass, I just have to ensure that the superclass' constructor is called at some point. Awesome, thanks.
Comment: Yes I understand thanks! I was wondering if that same constructor with only one field would be passed down to the subclass, but it isn't as you showed, we just need to make sure to call the superclass as you said. Thanks!


Cassandra consistency level and IF NOT EXISTS clause issue

Question: Cassandra 3.1
NodeJS driver: cassandra-driver 3.0.0
Keyspace is created using the following statement:
CREATE KEYSPACE IF NOT EXISTS xxxxxx
  WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 2 };
Even though the replication factor is 2 I am running only one instance for development purpose with consistency level set to ONE.
Here is the issue when I try to insert any record with IF NOT EXISTS clause I am getting consistency level error. But statements without IF NOT EXISTS work just fine. Here is the log from cqlsh:
<code>cqlsh:xxxxxx> CONSISTENCY;
Current consistency level is ONE.
cqlsh:xxxxxx> insert into accounts(account_id) values('test');
cqlsh:xxxxxx> insert into accounts(account_id) values('test1') if not exists;
Traceback (most recent call last): File "/usr/bin/cqlsh.py", line 1258, in perform_simple_statement result = future.result() File "/usr/share/cassandra/lib/cassandra-driver-internal-only-3.0.0-6af642d.zip/cassandra-driver-3.0.0-6af642d/cassandra/cluster.py", line 3122, in result raise self._final_exception Unavailable: code=1000 [Unavailable exception] message="Cannot achieve consistency level QUORUM" info={'required_replicas': 2, 'alive_replicas': 1, 'consistency': 'QUORUM'}
</code>
Answer: The "if not exists" clause for paxos uses a different consistency setting of "SERIAL CONSISTENCY", which can have the values SERIAL or LOCAL_SERIAL.
The SERIAL setting means it will need a quorum across all replicas, while the LOCAL_SERIAL means it will need a quorum in the local data center. With a replication factor of 2, a quorum is 2 replicas.
Unfortunately there is no LOCAL_ONE or ONE setting for "SERIAL CONSISTENCY", so in your case you would need two replicas to be alive for your insert if not exists to succeed.


Why Access don't update this?

Question: I have a table called Contacts with one field called Contacts.Title.
In MS-Access, If I do a query like this:
SELECT *
FROM Contacts
WHERE (((Contacts.Title) Like "%Boss%");

It works and found 70 rows. But if I try to do the next update, it doesn't find any row:
UPDATE Contacts
SET Contacts.Title = "Boss"
WHERE (((Contacts.Title) Like "%Boss%");

If I do the same query in the SQL Server (the table in Access is vinculated from a SQL Server) it works, changing the 70 rows. This question is not how to do that (because I just did in SQL Server without problems), is about why MS Access didn't find any row in the update?
I did something wrong? Or I'm  ignoring something?
Comment: Your brackets don't match. Is that just a typo?
Answer: I believe the MS Access wildcard is * not %
UPDATE Contacts
SET Contacts.Title = "Boss"
WHERE (((Contacts.Title) Like "*Boss*");

Comment: But in the Select, the rows appear, but not in the Update. Why?
Comment: It's certainly unexpected behaviour. So this is a table in MS Access right? what do you mean by 'vinculated'?

Why Access don't update this?


Linking SQL Server 2014 to Informix Database Results in Architecture Mismatch

Question: I am having quite an issue trying to create a linked server in SQL 2014 to Informix.  I have downloaded the IBM Informix SDK 4.10 FC2.  This allowed me to create a 32 bit ODBC in the 64 bit ODBC tool and I was able to register the ifxoledbc.dll with regsvr32.  However, I cannot get the ifxoledbc provider to show up under Server Objects -> Linked Servers -> Providers nor am I able to get the 64 bit ODBC set up under 64 bit.  Every time I try to set up a linked server to the 32 bit ODBC I get an architecture mismatch error which I expect.  I don't care whether I use the ifxoledbc driver directly for the linked server setup or use an ODBC connection for the linked server setup.  Either one will work for my purposes of reading from the Informix database, but I just can't seem to get past the 64 bit crap!
Has anyone been able to set up a linked server to Informix on a 64 bit server?
I realize the question has already been posed here almost a year ago: ODBC connection from 64-bit SQL Server to Informix data source
But the answers to that question were not specific enough to help me.  The guy who provided the screenshots did not say what he did to get the provider to show up.
I was going to post screenshots of the 64 bit ODBC showing that the DSN is 32 bit platform and a screenshot of the options I have when I try to add a new System DSN in the 64 bit version of ODBC (note that I cannot choose the IBM Informix ODBC Driver), but I don't have enough reputation points.
Comment: Actually, I misspoke.  I downloaded the IBM Informix SDK 4.10 FC5 developer edition located here: http://www14.software.ibm.com/webapp/download/preconfig.jsp?id=2011-04-06+21%3A07%3A01.344156R&S_TACT=&S_CMP=
Comment: it would be better to include that comment in your post: you can always edit your own posts. It would also be good to accept your own answer (click the V).
Answer: I finally fixed my own problem.  The trick was to run the 64 bit SDK installer in compatibility mode on the server (by right-clicking on the installer and selecting "Troubleshoot Compatibility").  The installer then runs in Windows 7 mode and installs the ODBC drivers correctly.  I did nothing to make the ifxoledbc provider show up under Linked Servers in SSMS.  Once the ODBC was set up, I used that DSN to connect to the Cisco Informix database.  I did not use the driver directly.


Is there a way to see the pokestops and gyms on a map?

Question: I'm on vacation on a pretty rural area and there is only 3 pokestops and a gym around me. I wonder how many pokestops and gyms are near my house in another city.
Is there a way to see pokestops and gyms in other places in a map (preferably online)?

There seems so be loads of websites linked. While posting your own website is allowed (as long as it answers the question properly) please keep in mind that stating your affiliation is required (Add something like "Disclaimer: I own this website" to the end of your answer) in order to avoid being spam flagged.
Comment: @ardaozkal a mosque, then?
Comment: You can always go look for a church ;)
Comment: I think ingress' intel page might work, but I'd need to download ingress to my phone first- would prefer downloading when I find out if it is required or not as my phone's storage is pretty full.
Comment: There isn't currently an official map, but someone has created a community Google Map to crowd source locations. You can get the link on the /r/pokemon Subreddit [here](https://www.reddit.com/r/pokemongo/comments/4rmu0d/so_someone_created_a_map_where_you_can_add_gyms/).
Comment: @Nolonar living in an islamic country unfortunately :(
Comment: @scenia I checked - 3 mosques near here, none has pokestops.
Answer: As I mentioned in this article, the portals from this game and Ingress do appear to be identical, with many portals being pokestops and mission portals being gyms. However, they do seem to have a limitation on the density of portals, so not portal has been converted.
Therefore, using the ingress intel map will provide you with your Pokémon Go map. I haven't found an official map yet, but this has served me will so far.
Or just look for any of the following, as they are typically great hubs:

Shopping centers
Parks
Museums
Churches
City Landmarks (city hall etc)
Historical Landmarks (statues etc)
College Campuses
Any other tourist-y location

Ingress portals are based upon notable looking landmarks. If you know any place that fits the categories above, it's probably a pokestop.
UPDATE:
Some pokestops have been removed from the game due to complaints, such as some in residential areas or ones around Police Stations etc. I have not checked if this change has been reflected in Ingress, but it has affected Pokémon Go.
Comment: The well in this town is literally a gym. I guess that is touristy.
Comment: In the nearby village, there are three Ingress portals; none of them has a mission. One is a gym, an other a pokestop, and the third is NOT in Pokemon Go at all. That said, Ingress is a good starting point; they probably didn't include the third because two were enough, but I doubt they would omit an isolated portal.
Comment: @SnoringFrog I should have chosen my wording more carefully, but if you read the second thread I linked, I do mention the limitations of density. "However, they do seem to have a limitation on the density of portals" Additionally, they have been removing pokestops (i'm not sure about portals since I haven't checked recently) due to complains etc. I shall update my answer to reflect this information.
Comment: @ardaozkal well if you have a city hall or park or anything "city" related, it tends to have poke stops. Unless you literally only have a gym. Then you MAYYYYY want to invest in a good car. Or just pay for pokeballs. Best of luck!
Comment: There are thankfully 3 pokestops here, one is a park, one is a statue (Might want to consider adding this to your list as it might be common) and the other is a mosque so your list seems pretty good.
Comment: @ardaozkal that was supposed to be included under museum but that didn't really make sense. I've added it as well. Thank you!
Comment: "all portals being pokestops and mission portals being gyms" This is not the case. As you can see [here](http://imgur.com/gallery/Tj1Jv), there are several Ingress portals that do not have corresponding Pokestops
Answer: Here is an alternative. You can use the existing map from Ingress and then with an additional plugin you can see the POGO stops and gyms. Article says it all.
https://www.reddit.com/r/pokemongo/comments/4rm9rt/faq_here_is_how_niantic_knew_about_that_local/
Comment: I'm using this right now and it works pretty well. (not accepting as answer as the other one has more content and answers in other ways (in case website goes down etc) too)
Comment: Servers for that are pretty much dead. (The IITC plugin connects to external servers)
Answer: there are some differences to the ingress map, but people have started mapping out the points themselves on this public map, so you can go and help there if you wish c: https://www.google.com/maps/d/edit?mid=1fYglPQeuhN4VcYCa_BD53eIAlpw
Answer: all those google maps end up sabotaged.
this is a custom map where data is stored in private database so people cannot sabotage it.
http://map.pokego.no/
enjoy
Answer: Literally any place 'important' is a pokestop (every church, community center/park or shopping center in my area) but some of the gyms are in super random places.
Answer: Take a look at pokiego.com it looks like they only have gyms for Australia and NZ though.
Comment: @Damek If the question is asking for a website, why is an answer that gives a website a bad thing?
Comment: The site seems to be down


Want to know if we can make the window size of a bay window larger?

Question: I'm not sure if enough of the framing has been exposed in these photos to answer this question, but thought I would give it a try. I have more photos I can add, but I can only seem to put one in?
We have one last window to replace in our home, the front room bay window. We would like to make any of these three windows wider if possible, particularly the two smaller side windows.
On the side of every window there is a double set of 2 x 4's.
We are wondering where there is 2 on each side of the small windows and then another two on the side of the large window, can any of those be changed to just one 2x4 so the window could be a bit wider? Or does each one need to be there for strength and support? It doesn't look like there are individual headers above each window.
If you look in the photo showing the exposed framing in the top left corner of the smaller window you can see at the king stud and two jack studs and the large header. That header runs right across the entire set of windows. The house was built 30 years ago if that helps with the answer.
Thanks!
Comment: Jack: sorry, horrible response.  You've just endorsed removing structure.
Comment: Based on what I see in the picture offered, yes you can. But more pictures need to be included with the drywall removed over the window and ceiling of the bay to give certainty.
Comment: No, just moving over a jack stud. The main header that carries the roof of the main building is concealed in the bulkhead of the bay window, that is the main structure, that is not fiddled with and will not need to be, with the question that is asked. The reason I asked to add more pictures is to see the headers that carry the weight of the very small roof that is over the bay windows. If that header carries over to meet the main header, if so then it is a matter of moving the jack stud (marked with the "X" on a continuous plate) over the 2" or so to get the bigger opening he needs
Comment: That is, if the header over the bay windows are sized heavy enough to carry the extra span by moving the jack stud. Again, that is why I asked about the extra pics. The header I expect to see should be above the continuous plate above the windows.
Answer: No, no and again NO.  Not the way you suggest it, anyway.
This is an exterior wall.  It is therefore a load bearing wall.  Those two 2x4s (called jack studs) support the header over the window.

The weight of the rest of the house above the window is protected by the header, which in turn transfers the force to the two jack studs (as in they jack up the house) carry that weight to the underlying structure.  If you remove one of the jack studs, too much force may be transferred to the other one, causing it to bow or even possibly fail.  Either scenario translates to having weight of the wall above the house coming to rest on the window itself - and that is a BAD THING (TM).
If you wish to restructure for a larger opening properly, you must open the wall up further and relocate the king and jack studs, and install a longer (and possibly wider) header as well.  Otherwise you can cause many tens of thousands of dollars of damage to your house.
Do not fiddle lightly with structure.
Comment: I don't think that is the part that the OP is wanting to move. You may be thinking the OP wants to enlarge the main opening the whole bay window is set into. He only wants to open up the RO of both small angled windows, the part that has only a tiny roof over it, at least it should be tiny in all of the bay windows I have seen. BUT the structure over those still need to be exposed to see what can be done.
Comment: I think Jack has the right visualization of the structure.  What we don't know is what's on top of the bay, outside.
Answer: Since I can't post pictures in comments I will clarify what I think the structure looks like if the walls were opened up, as well as the remedy... That is if the framing is the same as the sketch I have.

The remedy for a larger RO??
Comment: DO NOT DO THIS!  At least not until we get an exterior picture.  At this point, we have no idea what's on top of that window.  This answer MAY end up being correct, but it's premature.
Comment: These remedies are all depending on the exposure of the remaining framing. I thought I was making it pretty clear on all my postings....


Convert color image to black and white in Base64 format ( typescript )

Question: I'm trying to turn a color image into black and white. I googled and came up with some code in JavaScript and converted it to TypeScript. But the code does not return all the photos and part of the photo becomes black and white.
For example, I receive the following input and output:

My code is like this:
GrayScale() {
    const www = this;
    const myimage = new Image();
    myimage.src = this.croppedImage.src;
    myimage.onload = function () {
        const cnv = document.createElement('canvas');
        const cnx = cnv.getContext('2d');
        cnx.drawImage(myimage, 0, 0);
        const width = myimage.width;
        const height = myimage.height;
        const imgPixels = cnx.getImageData(0, 0, width, height);

        for (let y = 0; y < height; y++) {
            for (let x = 0; x < width; x++) {
                const i = (y * 4) * width + x * 4;
                const avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                imgPixels.data[i] = avg;
                imgPixels.data[i + 1] = avg;
                imgPixels.data[i + 2] = avg;
            }
        }

        cnx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
        www.croppedImage.src = cnx.canvas.toDataURL();
    };
}

Does anyone know what the reason is ? Thank you for your help
Comment: Output image is cropped because you need to set canvas's width and height to be equal to image size. `cnv.width = myimage.width; cnv.height = myimage.height;`. Do this before drawing on canvas. Does this solve your problem?
Comment: Your title suggests you want to convert an image to black and white (greyscale), but your pictures and code suggest you are already doing that. So what is the problem?
Comment: The problem is that the black and white photo is not the full size of the original photo. Part of it has turned black and white.
Comment: Arty OneSoul -  No, it did not solve the problem. The image got bigger but the same part of the photo was still black and white and the rest was white.
Comment: Then your issue is that the image is being cropped and has nothing to do with the part of your code that converts the image to greyscale. It begs the question, then, why you have an object named `croppedImage` in your code, since that's probably where the "problem" is.
Comment: The problem has nothing to do with that part. This is a method of a module. One thing you do not pay attention to is that I passed the croppedImage of myself to this part. I posted the original photo. The problem is when the whole photo should be black and white
Comment: @ArtyOneSoul - Oh sorry. Your solution worked. I put your code in the wrong place. thank you
Comment: I'll post my comment then as answer so that question is answered.
Comment: @mahdiaghasi You posted an image that is a cropped portion of the original image, and the entire cropped image is successfully converted to greyscale. If only part of the image is being converted, that would mean the entire image was being rendered correctly but only a part of it was being converted. If that's the issue, post the entire image. But the solution posted by Arty suggests that I am right - your issue has nothing to do with the greyscale conversion and everything to do with your output image being cropped.
Answer: After creating canvas you need to set its width and height. Otherwise it gets some default size not equal to image size, and resulting image is cropped. I.e.:
cnv.width = myimage.width;
cnv.height = myimage.height;


how unique is my random number

Question: We use a random number generator to create numbers in the format of {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}. where the X represents a digit which is base 16 (hexadecimal). that's 0-9,A-F
The hexadecimal digits are grouped in a format that is 36 characters long -- 32 hexadecimal characters grouped as 8-4-4-4-12 and separated by four hyphens: {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}.
So right now the permutations of the number are 16^32 (thanks @henry) - right?
We generated 2000 of these numbers.
What I want do is just take the last 12 digits from each number and I need them to be unique. (the last part after the hyphen)
what's the probability that there would be collisions (or repeats) between those 2000 numbers?
Comment: Your 32^16 should be $16^{32}$.  Your question is about the probability of a collision with $2000$ samples from a uniform distribution over $16^{12}$ numbers, and this will be very small - possibly (not checked) about $7 \times 10^{-9}$
Comment: Relevant: [universally unique identifiers on wikipedia](https://en.wikipedia.org/wiki/Universally_unique_identifier)
Answer: There are $N=16^{12}$ possibilities for the last number. Conversely, each number has a probability $p=\frac 1N = 16^{-12}$ of being picked. Let $P_n$ denote the probability that there are no collisions between $n$ numbers sampled this way.
Imagine generating the $2000$ samples sequentially:

Having picked the first number, the probability of a collision of the $2$rd number with the first one is $p$. Thus, $P_2=1-p$.
Having picked the first two numbers without a collision, the probability of a collision of the $3$rd number with the first $2$ numbers is $2p$. Thus, $P_3=P_2(1-2p)=(1-p)(1-2p)$.
Having picked the first $i$ numbers without a collision, the probability of a collision of the $i+1$ number with the first $i$ numbers is $ip$. Thus, $P_{i+1}=(1-ip)P_i=\prod_{j=1}^i (1-jp)$.

Thus, the probability of having some repeats in $2000$ samples is given by $1-P_{2000}$, i.e. $$1-\prod_{j=1}^{1999} (1-jp)$$
(Edit: See comments to my answer for an approximation to this expression.)
Also, see Collisions in a sample of uniform distribution.
Comment: I think this answer is correct but if $p\ll 1$ that product will turn out to be $\approx pn(n-1)/2$ approximately and it will be easier to calculate without multiplying lots of tiny fractions.
Comment: Because $(1-p)(1-2p)(1-3p)...(1-np)=(1-(1+2+3+....)p+O(p^2)\approx 1-pn(n-1)/2$
Comment: Should it not be $N=16^{12}$?
Comment: @A.M. You are right, I corrected my answer.

how unique is my random number


What is the best way to communicate a required selection within in data table?

Question: Currently in our (enterprise) UI, there are tables that have required selections. Typically, these tables have hundreds to thousands of objects. In one case an action is to be performed against these specific objects, and the user is required to select, at least one, in order to perform the action.
There is required asterisk next to the name of the table within the field header. Within the within the form nav itself, if a required field has not been met in that part of the form, it also indicates in the tab, with a red bar, there is an error within the category (tabs are a vertical stepper-list, the highlighted element indicates that portion of the form is active and in view).
The main difference in the design system is when a required input, or selection has not been met or contains an error, the input highlights red, and an error message appears. This pattern is less direct, and less clear for a selection in an entire table to be in error. Potentially this could be a red outline around the data table, however, I can't find a pattern like this online, or within our design system.
Another externality of calling this object table: In order to fetch the data, the user would have to have entered a URL, and a user and pw, and then the connection would have to be valid before fetching the table data. Automatically selecting the first leaf is a bit problematic as the nodes are only called and reveled when the user selects that object.
Comment: Can you share some visual mocks of your efforts so far? Visuals help to quick grok the problem and the context, and make the question (and its answers) more valuable for the community at large.
Comment: Updated the question as a question to help clarify. Added an image to communicate what required patterns already exist in the design.
Answer: On first glance, I wonder if the asterisk might be missed due to the massive amount of content that could populate in the table.
What if you would swap the Asterisk to something like this:
SELECT ITEMS (0) (Required)   <--- Text being red and bold.
SELECT ITEMS (0) (REQUIRED)   <--- Text being red and bold.
This way it's a bit larger than a single symbol and depending on the color of the red, can be a lot more noticeable. Personally I would try a slightly darker shade of red for the text though, but it depends on how it looks overall.


How to make Author mode component annotations visible in CQ5/AEM5.6.1?

Question: In AEM 5.6.1, if I add annotation to the component it works just fine while I'm editing the page but disappears after page is reloaded.

There is no difference if it is custom or out-of-the-box component, if page was activated or not, annotation is just not loading.
CRXDE Lite shows that cq:annotations node has been successfully created

Is there any configuration switch which should be turned on in order to load annotations?
Answer: After debugging CQ/ExtJS scripts it turned out that PageInfo provider is not returning .annotations property and condition on line #396 of /libs/cq/ui/widgets/source/widgets/wcm/EditBase.js was always false. Further debugging showed that our custom overlay of foundation/components/page lacked proper node type and it was the reason for omission of the annotations InfoProvider polling. Strange enough it didn't affect any other info provider (languages, msm, workflows, ...), just annotations.
More info: https://docs.adobe.com/docs/en/cq/5-6-1/developing/pageinfo.html
Answer: I saw similar - copying the cq:InfoProviders node from libs/foundation/components/page to the same node as my custom page node corrected it.


Can I log in from an Android phone without using the phone's google account?

Question: I've got a pokemon go game started with my google account and have been playing with my son.  My wife wants to put the game on her phone too so she can play with him during the week.  But on her phone (Google Android), it seems to force login with her own google account set up on her phone.
On mine (iOS), after hitting Sign In, it actually gives me a login box to enter email, and then password.  On hers, it seems to be an automatic login and goes immediately to the new game setup.  We can't find any option to say which account I want to log in with.
Any options?
Answer: Android phones do that when they only have 1 google account in them. If you have multiple accounts on a phone, a screen will pop up asking which account to login with.

So to solve this problem, just add any other google account from here:-
Answer: Since she's using an Android phone, I believe that she would have to log out of her google account on the entire phone in order to prevent an auto-login for the game. Most apps on Android phones have this behavior. But logging out of her google account on her phone would cause her to have to log into it on every app she uses every single time she opens them, which may not be worth the trouble. I can't make that determination, that would have to be something she decided.


Overflow right column to fill remaining height

Question: I have a layout where the top header should have 100%, and content has two content columns. Left column should take up remaining vertical space, and right column will overflow however the height should also take up remaining vertical space (same as the left element).
html:

            header

left

right

--            omitted a lot of repeating rows here which are needed to create overflow

right

right

right

css:
    html, body {
      height: 100%
    }

    .wrap {
      display: flex;
      flex-flow: column;
      height: 100%;
    }

    .header {
      background-color: blue;
      width: 100%;
    }

    .content {
      height: 100%;
      display: flex;
      justify-content: space-between;
    }

    .left {
      height: 100%;
      width: 50%;
      background-color: #d5f4e6;
    }

    .right {
      height: 100%;
      width: 50%;
      background-color: #d504e6;
      position: absolute;
      left: 50%;
      overflow: auto;
    }

I have it mostly working, but the right column height is slightly taller than the left element (by the height of the header for some reason). Open my codepen https://codepen.io/ilikepure/pen/MWajBYY
 link and scroll the bottom right i-frame all the way down to see the weird effect.
How can I fix this? Thanks!
Comment: remove position: absolute and left: 50%
Answer: It's because you have position: absolute on the .right element. Not sure why you have that in a flex layout:

html,
body {
  height: 100%
}

.wrap {
  display: flex;
  flex-flow: column;
  height: 100%;
}

.header {
  background-color: blue;
  width: 100%;
}

.content {
  height: 100%;
  display: flex;
  justify-content: space-between;
}

.left {
  height: 100%;
  width: 50%;
  background-color: #d5f4e6;
}

.right {
  height: 100%;
  width: 50%;
  background-color: #d504e6;
  overflow: auto;
}

    header

left

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right

right


What's the meaning of all this?

Question: While playing Arkham Origins, I stumbled on this code.  Unfortunately, I have completely forgotten where I was at in the game so I cannot provide the location that this screenshot was taken at.
Answer: When translated to ASCII characters, the hexadecimal shown in that screenshot translates to:

Joining the GCPD was the easiest thing I ever did. I will find out all of their dirty little secrets. By the time they know what I know, it will be too late. This is only the beginning.

Sources: [1], [2]
Comment: I figured it was HEX values, so I went through and decoded while waiting for an answer.  My output matches this one.  Thanks for the links.

What's the meaning of all this?


Syntax for Templated Member Functions

Question: Consider the following code:
template <typename Datatype>
class MyClass
{
    void doStuff();

    template <typename AnotherDatatype>
    void doTemplateStuff(AnotherDatatype Argument);
};

template <typename Datatype>
void MyClass<Datatype>::doStuff()
{
    // ...
}

template <typename Datatype>
template <typename AnotherDatatype>
void MyClass<Datatype>::doTemplateStuff(AnotherDatatype Argument)
{
    // ...
}

The implementation for the second member function, doTemplateStuff, will not compile if I condense it like this:
template <typename Datatype, typename AnotherDatatype>
void MyClass<Datatype>::doTemplateStuff(AnotherDatatype Argument)
{
    // ...
}

Why is this?  Shouldn't separating template information by commas have the same effect as putting each typename on its own line?  Or is there some subtle difference I'm not aware of...?
(Also, if someone can think of a better title please let me know.)
Answer: This is an excellent question.  I don't know the specific reason that the standards committee decided to design templates this way, but I think it's a callback to lambda calculus and type theory.  Mathematically speaking, there is an isomorphism between any function that takes two arguments and returns a value and a function that takes in a single argument, then returns a function that takes in yet another argument and then returns a value.  For example:
λx. λy. x + y
is isomorphic with (but not identical to)
λ(x, y).  x + y
where (x, y) is a single object representing the pair of x and y.
With C++ member function templates, C++ chose to use the first of these systems.  You have to specify all the arguments for the outermost function, then, separately, all of the arguments for the innermost function.  Mathematically this is equivalent to specifying all of the arguments at the same time in one argument list, but C++ didn't choose to do this.
Now, a really good question is why they didn't do this.  I'm not fully sure of the rationale, but if I had to guess it's because of weird interactions with template specialization.  If I can think of something specific I'll update this post.
Comment: This isomorphism is called Currying (see http://en.wikipedia.org/wiki/Currying). It's one of the building bricks of the Haskell programming language, for example.
Answer: Putting comma's between the template declaration tells the compiler to expect two template parameters.  In your case, because the object is a template object when you declare the function as you do you're violating your own declaration.  It's looking for that second template in the MyClass object, referencing the actual class declaration and realizing that it's an error.
Hence,
template<typename T, typename V>
struct Foo{
    void bar();
};

template<typename T, typename V>
void Foo<T,V>::bar(){...}

is what it's expecting to see.
template<typename T>
struct Foo{
    void bar();
}

template<typename T, typename V>
void Foo<T>::bar(){...}

is an error.  It's wondering where that other template parameter came from.
If you want to do this you'll need to write the function right there:
template<typename T>
struct Foo{
    template<typename V>
    void bar(const V& _anInputValue){
        cout << _anInputValue;
    }

    void baz();
};

template<typename T>
void Foo<T>::baz(){
    cout << "Another function.";
}

Syntax for Templated Member Functions


figuring out this Javascript code

Question: I am trying to figure out how the get the featured area
at http://blueoceanportfolios.com to link to webpages rather than displaying it within the featured box on the left .
This area is using JS file to display the videos on content in the featured box when different items on the menu are clicked, here is the working example :
http://www.blueoceanportfolios.com/company/
Okay ,
The problem: Loading a new webpage rather than displaying the content at featured box at the homepage of above website
Tried solutions: linking to javascript functions like onclick="window.location="http://someplace.com";" etc but still the content loads up in the featured box ,
try clicking on 2) it displays stackoverflow.com rather than loading new page.
Any suggestions ?
Answer: This:

... is not the way to add event handlers to an element.  If you want those anchors to link to a web page, put the URL in the href attribute like any normal link:
Link text

figuring out this Javascript code


Function to get item from list

Question: Is there a function for getting an item from a list? e.g. getitem(list, index)
Comment: *function*.  I said it twice.
Comment: Thanks JBernardo.  Would you like to add the answer?
Answer: Use operator.getitem:
import operator
operator.getitem(l, index)

Example:
>>> operator.getitem([1,2,3], 1)
2

Comment: Great answer, but I accepted g.d.d.c's for his/her cognizance.
Answer: I believe, though the other answers are correct, that he's probably needing to retrieve them using a callable.  To that end, this works:
>>> from operator import itemgetter
>>> get1 = itemgetter(1)
>>> get1([0,1,2,3,4,5])
1
>>> get1('abcdefg')
'b'

Comment: I applaude your intuition; that is indeed my use case.
Answer: You don't need it use this:
lVals[index]

Or do it yourself:
def itemAtPos(lVals, idx):
    if ifx < len(lVals):
        return lVals[idx]

Function to get item from list