text:
Q: Pigeon hole principle to prove $a-b=9$ in subset. I have a set of numbers
$$
[n] = \{1,2,...,n\}
$$
in my special case $n = 100$, and I have a subset of $[100]$ with the following specification
$$
A\subseteq[100]
$$
and
$$
|A| >= 55
$$
now I should prove, that this statement is true for some
$$
a,b\in A: a-b=9
$$
I thought about the problem and I realised, that if I just take the numbers $1-55$ that there are a lot of pairs $a,b$ that match the condition.
So I tried to build a set in which no pair matches the condition. Therefore I just used the even numbers from $2-100$. Because even-even=even. But there are only $50$ even numbers in $[100]$, so I have to add at least $5$ odd numbers. So as soon as I add one odd number my set matches the condition.
Using the pigeonhole principle:
$$
n,m \in \mathbb{N}, f: [n] \to [m], |f^{-1}(j)|, j \in [m], \exists j^{*} \in [m], |f^{-1}|>=\lceil\frac{n}{m}\rceil
$$
I get, that there is at least
$$
\lceil\frac{100}{55}\rceil = 1
$$
solution to my problem.
But I think that I have to specify the function for the projection to prove the problem.
And I think that I can use the modulo operator to achieve my goal, but currently I am stuck.
Could someone please help me?

A: First consider partitioning [$100$] in following manner :
$$ \{1,2,\ldots,18 \} \, \{19,20,\ldots,36 \} \cdots \{73,74,\ldots,90 \} \, \{91,92,\ldots,100 \} $$
Now in each of first five sets we have $9$ pairs differing by $9$ like  $$ (1,10) , (2,11) , \ldots (9,18), \ldots, (89,90) $$
and in last, one pair $(91,100)$. Remaining are unpaired.
Can you complete?

We have $9\cdot5+1=46$ pairs. And $8$ : ${92,93,\ldots,99}$ are unpaired.

To make a set $A$ not having the property, choose one number from each pair and all the unpaired ones. But we can choose only $46+8=54$ such numbers. $55^{th}$ number belongs to one of previous pairs, so $a-b=9$ must satisfy.


text:
Q: How do I get the height and width of the Android Navigation Bar programmatically? The black navigation bar on the bottom of the screen is not easily removable in Android. It has been part of Android since 3.0 as a replacement for hardware buttons. Here is a picture:

How can I get the size of the width and the height of this UI element in pixels?

A: New answer in 2021 comes to the rescue

insipred from Egis's answer:
context.navigationBarHeight

where the extension getter is
val Context.navigationBarHeight: Int
get() {
    val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager

    return if (Build.VERSION.SDK_INT >= 30) {
        windowManager
                .currentWindowMetrics
                .windowInsets
                .getInsets(WindowInsets.Type.navigationBars())
                .bottom

    } else {
        val currentDisplay = try {
            display
        } catch (e: NoSuchMethodError) {
            windowManager.defaultDisplay
        }

        val appUsableSize = Point()
        val realScreenSize = Point()
        currentDisplay?.apply {
            getSize(appUsableSize)
            getRealSize(realScreenSize)
        }

        // navigation bar on the side
        if (appUsableSize.x < realScreenSize.x) {
            return realScreenSize.x - appUsableSize.x
        }

        // navigation bar at the bottom
        return if (appUsableSize.y < realScreenSize.y) {
            realScreenSize.y - appUsableSize.y
        } else 0
    }
}

tested on:

*

*emulators with navigation bars

*

*pixel 3a (api 30)

*pixel 2 (api 28)

*pixel 3 (api 25)

*pixel 2 (api 21)

*Xiaomi Poco f2 pro with & without navigation bar(full display)

A: This is my code to add paddingRight and paddingBottom to a View to dodge the Navigation Bar. I combined some of the answers here and made a special clause for landscape orientation together with isInMultiWindowMode. The key is to read navigation_bar_height, but also check config_showNavigationBar to make sure we should actually use the height.
None of the previous solutions worked for me. As of Android 7.0 you have to take Multi Window Mode into consideration. This breaks the implementations comparing display.realSize with display.size since realSize gives you the dimensions of the whole screen (both split windows) and size only gives you the dimensions of your App window. Setting padding to this difference will leave your whole view being padding.
/** Adds padding to a view to dodge the navigation bar.

    Unfortunately something like this needs to be done since there
    are no attr or dimens value available to get the navigation bar
    height (as of December 2016). */
public static void addNavigationBarPadding(Activity context, View v) {
    Resources resources = context.getResources();
    if (hasNavigationBar(resources)) {
        int orientation = resources.getConfiguration().orientation;
        int size = getNavigationBarSize(resources);
        switch (orientation) {
        case Configuration.ORIENTATION_LANDSCAPE:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N &&
                context.isInMultiWindowMode()) { break; }
            v.setPadding(v.getPaddingLeft(), v.getPaddingTop(),
                         v.getPaddingRight() + size, v.getPaddingBottom());
            break;
        case Configuration.ORIENTATION_PORTRAIT:
            v.setPadding(v.getPaddingLeft(), v.getPaddingTop(),
                         v.getPaddingRight(), v.getPaddingBottom() + size);
            break;
        }
    }
}

private static int getNavigationBarSize(Resources resources) {
    int resourceId = resources.getIdentifier("navigation_bar_height",
                                             "dimen", "android");
    return resourceId > 0 ? resources.getDimensionPixelSize(resourceId) : 0;
}

private static boolean hasNavigationBar(Resources resources) {
    int hasNavBarId = resources.getIdentifier("config_showNavigationBar",
                                              "bool", "android");
    return hasNavBarId > 0 && resources.getBoolean(hasNavBarId);
}

A: The NavigationBar height varies for some devices, but as well for some orientations. First you have to check if the device has a navbar, then if the device is a tablet or a not-tablet (phone) and finally you have to look at the orientation of the device in order to get the correct height.
public int getNavBarHeight(Context c) {
         int result = 0;
         boolean hasMenuKey = ViewConfiguration.get(c).hasPermanentMenuKey();
         boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);

         if(!hasMenuKey && !hasBackKey) {
             //The device has a navigation bar
             Resources resources = c.getResources();

             int orientation = resources.getConfiguration().orientation;
             int resourceId;
             if (isTablet(c)){
                 resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape", "dimen", "android");
             }  else {
                 resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_width", "dimen", "android");
             }

             if (resourceId > 0) {
                 return resources.getDimensionPixelSize(resourceId);
             }
         }
         return result;
}

private boolean isTablet(Context c) {
    return (c.getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK)
            >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}

A: Actually the navigation bar on tablets (at least Nexus 7) has different size in portrait and landscape so this function should look like this:
private int getNavigationBarHeight(Context context, int orientation) {
    Resources resources = context.getResources();

    int id = resources.getIdentifier(
            orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape",
            "dimen", "android");
    if (id > 0) {
        return resources.getDimensionPixelSize(id);
    }
    return 0;
}

and in Kotlin:
private fun getNavigationBarHeight(): Int {
    val resources: Resources = requireContext().resources

    val resName = if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
        "navigation_bar_height"
    } else {
        "navigation_bar_height_landscape"
    }

    val id: Int = resources.getIdentifier(resName, "dimen", "android")

    return if (id > 0) {
        resources.getDimensionPixelSize(id)
    } else {
        0
    }
}

A: I think better answer is here because it allows you to get even cutout height too.
Take your root view, and add setOnApplyWindowInsetsListener (or you can override onApplyWindowInsets from it), and take insets from it.
In my camera activity, i add padding equal to the systemBars.bottom to my bottom layout. And finally, it fix cutout issue.

with appcompat it is like this
ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
    val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
    binding.takePictureLayout.apply {
        setPaddingRelative(paddingStart, paddingTop, paddingEnd, systemBars.bottom)
    }
    return@setOnApplyWindowInsetsListener insets
}

without appcompat, this:
mCameraSourcePreview.setOnApplyWindowInsetsListener((v, insets) -> { ... })

A: Try below code:
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
    return resources.getDimensionPixelSize(resourceId);
}
return 0;

A: The solution proposed by Egidijus and works perfectly for Build.VERSION.SDK_INT >= 17
But I got "NoSuchMethodException" during execution of the following statement with Build.VERSION.SDK_INT < 17 on my device:
Display.class.getMethod("getRawHeight").invoke(display);

I have modified the method getRealScreenSize() for such cases:
else if(Build.VERSION.SDK_INT >= 14)
{
    View decorView = getActivity().getWindow().getDecorView();
    size.x = decorView.getWidth();
    size.y = decorView.getHeight();
}

A: I resolved this issue for all devices(including Nexus 5, Samsung Galaxy Nexus 6 edge+, Samsung S10, Samsung Note II etc.). I think this will help you to handle device dependant issues.
Here I am adding two types of codes,
Java Code(for Native Android):
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.ViewConfiguration;
import android.view.WindowManager;

public class DeviceSpec {

    private int resourceID = -1;
    private Display display = null;
    private DisplayMetrics displayMetrics = null;
    private DisplayMetrics realDisplayMetrics = null;
    private Resources resources = null;
    private WindowManager windowManager = null;

    public double GetNavigationBarHeight(Context context) {
        try {
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            display = windowManager.getDefaultDisplay();
            displayMetrics = new DisplayMetrics();
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                realDisplayMetrics = new DisplayMetrics();
                display.getMetrics(displayMetrics);
                display.getRealMetrics(realDisplayMetrics);
                if(displayMetrics.heightPixels != realDisplayMetrics.heightPixels) {
                    resources = context.getResources();
                    return GetNavigationBarSize(context);
                }
            }
            else {
                resources = context.getResources();
                resourceID = resources.getIdentifier("config_showNavigationBar", "bool", "android");
                if (resourceID > 0 && resources.getBoolean(resourceID))
                    return GetNavigationBarSize(context);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    private double GetNavigationBarSize(Context context) {
        resourceID = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceID > 0 && ViewConfiguration.get(context).hasPermanentMenuKey())
           return (resources.getDimensionPixelSize(resourceID) / displayMetrics.density);
        return 0;
    }
}

And C# code(for Xamarin Forms/Android)
int resourceId = -1;
        IWindowManager windowManager = null;
        Display defaultDisplay = null;
        DisplayMetrics displayMatrics = null;
        DisplayMetrics realMatrics = null;
        Resources resources = null;

        public double NavigationBarHeight
        {
            get
            {
                try
                {
                    windowManager = Forms.Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
                    defaultDisplay = windowManager.DefaultDisplay;
                    displayMatrics = new DisplayMetrics();
                    if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr2)
                    {
                        realMatrics = new DisplayMetrics();
                        defaultDisplay.GetMetrics(displayMatrics);
                        defaultDisplay.GetRealMetrics(realMatrics);
                        if (displayMatrics.HeightPixels != realMatrics.HeightPixels)
                        {
                            resources = Forms.Context.Resources;
                            return GetHeightOfNivigationBar();
                        }
                    }
                    else {
                        resources = Forms.Context.Resources;
                        resourceId = resources.GetIdentifier("config_showNavigationBar", "bool", "android");
                        if (resourceId > 0 && resources.GetBoolean(resourceId))
                            return GetHeightOfNivigationBar();
                    }
                }
                catch (Exception e) { }
                return 0;
            }
        }

        private double GetHeightOfNivigationBar()
        {
            resourceId = resources.GetIdentifier("navigation_bar_height", "dimen", "android");
            if (!ViewConfiguration.Get(Forms.Context).HasPermanentMenuKey && resourceId > 0)
            {
                return resources.GetDimensionPixelSize(resourceId) / displayMatrics.Density;
            }
            return 0;
        }

A: Tested code for getting height of navigation bar (in pixels):
public static int getNavBarHeight(Context c) {
    int resourceId = c.getResources()
                      .getIdentifier("navigation_bar_height", "dimen", "android");
    if (resourceId > 0) {
        return c.getResources().getDimensionPixelSize(resourceId);
    }
    return 0;
}

Tested code for getting height of status bar (in pixels):
public static int getStatusBarHeight(Context c) {
    int resourceId = c.getResources()
                      .getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        return c.getResources().getDimensionPixelSize(resourceId);
    }
    return 0;
}

Converting pixels to dp:
public static int pxToDp(int px) {
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}

A: How to get the height of the navigation bar and status bar. This code works for me on some Huawei devices and Samsung devices.
Egis's solution above is good, however, it is still incorrect on some devices. So, I improved it.
This is code to get the height of status bar
private fun getStatusBarHeight(resources: Resources): Int {
        var result = 0
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = resources.getDimensionPixelSize(resourceId)
        }
        return result
    }

This method always returns the height of navigation bar even when the navigation bar is hidden.
private fun getNavigationBarHeight(resources: Resources): Int {
    val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
    return if (resourceId > 0) {
        resources.getDimensionPixelSize(resourceId)
    } else 0
}

NOTE: on Samsung A70, this method returns the height of the status bar + height of the navigation bar.
On other devices (Huawei), it only returns the height of the Navigation bar and returns 0 when the navigation bar is hidden.
private fun getNavigationBarHeight(): Int {
        val display = activity?.windowManager?.defaultDisplay
        return if (display == null) {
            0
        } else {
            val realMetrics = DisplayMetrics()
            display.getRealMetrics(realMetrics)
            val metrics = DisplayMetrics()
            display.getMetrics(metrics)
            realMetrics.heightPixels - metrics.heightPixels
        }
    }

This is code to get height of navigation bar and status bar
val metrics = DisplayMetrics()
        activity?.windowManager?.defaultDisplay?.getRealMetrics(metrics)

        //resources is got from activity

        //NOTE: on SamSung A70, this height = height of status bar + height of Navigation bar
        //On other devices (Huawei), this height = height of Navigation bar
        val navigationBarHeightOrNavigationBarPlusStatusBarHeight = getNavigationBarHeight()

        val statusBarHeight = getStatusBarHeight(resources)
        //The method will always return the height of navigation bar even when the navigation bar was hidden.
        val realNavigationBarHeight = getNavigationBarHeight(resources)

        val realHeightOfStatusBarAndNavigationBar =
                if (navigationBarHeightOrNavigationBarPlusStatusBarHeight == 0 || navigationBarHeightOrNavigationBarPlusStatusBarHeight < statusBarHeight) {
                    //Huawei: navigation bar is hidden
                    statusBarHeight
                } else if (navigationBarHeightOrNavigationBarPlusStatusBarHeight == realNavigationBarHeight) {
                    //Huawei: navigation bar is visible
                    statusBarHeight + realNavigationBarHeight
                } else if (navigationBarHeightOrNavigationBarPlusStatusBarHeight < realNavigationBarHeight) {
                    //SamSung A70: navigation bar is still visible but it only displays as a under line
                    //navigationBarHeightOrNavigationBarPlusStatusBarHeight = navigationBarHeight'(under line) + statusBarHeight
                    navigationBarHeightOrNavigationBarPlusStatusBarHeight
                } else {
                    //SamSung A70: navigation bar is visible
                    //navigationBarHeightOrNavigationBarPlusStatusBarHeight == statusBarHeight + realNavigationBarHeight
                    navigationBarHeightOrNavigationBarPlusStatusBarHeight
                }

A:
I've done this, it works on every device I tested, and even on emulators:
// Return the NavigationBar height in pixels if it is present, otherwise return 0
public static int getNavigationBarHeight(Activity activity) {
    Rect rectangle = new Rect();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rectangle);
    activity.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
    return displayMetrics.heightPixels - (rectangle.top + rectangle.height());
}

A: I hope this helps you
public int getStatusBarHeight() {
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}

public int getNavigationBarHeight()
{
    boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
    int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
    if (resourceId > 0 && !hasMenuKey)
    {
        return getResources().getDimensionPixelSize(resourceId);
    }
    return 0;
}

A: I get navigation bar size by comparing app-usable screen size with real screen size. I assume that navigation bar is present when app-usable screen size is smaller than real screen size. Then I calculate navigation bar size. This method works with API 14 and up.
public static Point getNavigationBarSize(Context context) {
    Point appUsableSize = getAppUsableScreenSize(context);
    Point realScreenSize = getRealScreenSize(context);

    // navigation bar on the side
    if (appUsableSize.x < realScreenSize.x) {
        return new Point(realScreenSize.x - appUsableSize.x, appUsableSize.y);
    }

    // navigation bar at the bottom
    if (appUsableSize.y < realScreenSize.y) {
        return new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y);
    }

    // navigation bar is not present
    return new Point();
}

public static Point getAppUsableScreenSize(Context context) {
    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = windowManager.getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    return size;
}

public static Point getRealScreenSize(Context context) {
    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = windowManager.getDefaultDisplay();
    Point size = new Point();

    if (Build.VERSION.SDK_INT >= 17) {
        display.getRealSize(size);
    } else if (Build.VERSION.SDK_INT >= 14) {
        try {
            size.x = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
            size.y = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
        } catch (IllegalAccessException e) {} catch (InvocationTargetException e) {} catch (NoSuchMethodException e) {}
    }

    return size;
}

UPDATE
For a solution that takes into account display cutouts please check John's answer.

A: Combining the answer from @egis and others - this works well on a variety of devices, tested on Pixel EMU, Samsung S6, Sony Z3, Nexus 4. This code uses the display dimensions to test for availability of nav bar and then uses the actual system nav bar size if present.

/**
 * Calculates the system navigation bar size.
 */

public final class NavigationBarSize {

 private final int systemNavBarHeight;
 @NonNull
 private final Point navBarSize;

 public NavigationBarSize(@NonNull Context context) {
  Resources resources = context.getResources();
  int displayOrientation = resources.getConfiguration().orientation;
  final String name;
  switch (displayOrientation) {
   case Configuration.ORIENTATION_PORTRAIT:
    name = "navigation_bar_height";
    break;
   default:
    name = "navigation_bar_height_landscape";
  }
  int id = resources.getIdentifier(name, "dimen", "android");
  systemNavBarHeight = id > 0 ? resources.getDimensionPixelSize(id) : 0;
  navBarSize = getNavigationBarSize(context);
 }

 public void adjustBottomPadding(@NonNull View view, @DimenRes int defaultHeight) {
  int height = 0;
  if (navBarSize.y > 0) {
   // the device has a nav bar, get the correct size from the system
   height = systemNavBarHeight;
  }
  if (height == 0) {
   // fallback to default
   height = view.getContext().getResources().getDimensionPixelSize(defaultHeight);
  }
  view.setPadding(0, 0, 0, height);
 }

 @NonNull
 private static Point getNavigationBarSize(@NonNull Context context) {
  Point appUsableSize = new Point();
  Point realScreenSize = new Point();
  WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
  if (windowManager != null) {
   Display display = windowManager.getDefaultDisplay();
   display.getSize(appUsableSize);
   display.getRealSize(realScreenSize);
  }
  return new Point(realScreenSize.x - appUsableSize.x, realScreenSize.y - appUsableSize.y);
 }

}

A:
Simple One-line Solution

As suggested in many of above answers, for example

*

*https://stackoverflow.com/a/29938139/9640177

*https://stackoverflow.com/a/26118045/9640177

*https://stackoverflow.com/a/50775459/9640177

*https://stackoverflow.com/a/41057024/9640177
Simply getting navigation bar height may not be enough. We need to consider whether 1. navigation bar exists, 2. is it on the bottom, or right or left, 3. is app open in multi-window mode.
Fortunately you can easily bypass all the long coding by simply setting android:fitsSystemWindows="true" in your root layout. Android system will automatically take care of adding necessary padding to the root layout to make sure that the child views don't get into the navigation bar or statusbar regions.
There is a simple one line solution
android:fitsSystemWindows="true"

or programatically
findViewById(R.id.your_root_view).setFitsSystemWindows(true);

you may also get root view by
findViewById(android.R.id.content).getRootView();
or
getWindow().getDecorView().findViewById(android.R.id.content)

For more details on getting root-view refer - https://stackoverflow.com/a/4488149/9640177

A: The height of the bottom Navigation bar is 48dp (in both portrait and landscape mode) and is 42dp when the bar is placed vertically.

A: Here is how I solved this. I made a hideable bottom bar which needed padding depending on if there was a navigation bar or not (capacitive, on-screen or just pre lollipop).

View
setPadding(0, 0, 0, Utils.hasNavBar(getContext()) ? 30 : 0);

Utils.java
public static boolean hasNavBar(Context context) {
    // Kitkat and less shows container above nav bar
    if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
        return false;
    }
    // Emulator
    if (Build.FINGERPRINT.startsWith("generic")) {
        return true;
    }
    boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
    boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
    boolean hasNoCapacitiveKeys = !hasMenuKey && !hasBackKey;
    Resources resources = context.getResources();
    int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
    boolean hasOnScreenNavBar = id > 0 && resources.getBoolean(id);
    return hasOnScreenNavBar || hasNoCapacitiveKeys || getNavigationBarHeight(context, true) > 0;
}

public static int getNavigationBarHeight(Context context, boolean skipRequirement) {
    int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
    if (resourceId > 0 && (skipRequirement || hasNavBar(context))) {
        return context.getResources().getDimensionPixelSize(resourceId);
    }
    return 0;
}

A: In my case where I wanted to have something like this:

I had to follow the same thing as suggested by @Mdlc but probably slightly simpler (targeting only >= 21):
    //kotlin
    val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val realSize = Point()
    windowManager.defaultDisplay.getRealSize(realSize);
    val usableRect = Rect()
    windowManager.defaultDisplay.getRectSize(usableRect)
    Toast.makeText(this, "Usable Screen: " + usableRect + " real:"+realSize, Toast.LENGTH_LONG).show()

    window.decorView.setPadding(usableRect.left, usableRect.top, realSize.x - usableRect.right, realSize.y - usableRect.bottom)

It works on landscape too:

Edit
The above solution does not work correctly in multi-window mode where the usable rectangle is not smaller just due to the navigation bar but also because of custom window size.
One thing that I noticed is that in multi-window the navigation bar is not hovering over the app so even with no changes to DecorView padding we have the correct behaviour:

Note the difference between how navigation bar is hovering over the bottom of the app in these to scenarios.
Fortunately, this is easy to fix. We can check if app is multi window. The code below also includes the part to calculate and adjust the position of toolbar (full solution: https://stackoverflow.com/a/14213035/477790)
    // kotlin
    // Let the window flow into where window decorations are
    window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN)
    window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)

    // calculate where the bottom of the page should end up, considering the navigation bar (back buttons, ...)
    val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val realSize = Point()
    windowManager.defaultDisplay.getRealSize(realSize);
    val usableRect = Rect()
    windowManager.defaultDisplay.getRectSize(usableRect)
    Toast.makeText(this, "Usable Screen: " + usableRect + " real:" + realSize, Toast.LENGTH_LONG).show()

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N || !isInMultiWindowMode) {
        window.decorView.setPadding(usableRect.left, usableRect.top, realSize.x - usableRect.right, realSize.y - usableRect.bottom)
        // move toolbar/appbar further down to where it should be and not to overlap with status bar
        val layoutParams = ConstraintLayout.LayoutParams(appBarLayout.layoutParams as ConstraintLayout.LayoutParams)
        layoutParams.topMargin = getSystemSize(Constants.statusBarHeightKey)
        appBarLayout.layoutParams = layoutParams
    }

Result on Samsung popup mode:

A: In case of Samsung S8 none of the above provided methods were giving proper height of navigation bar so I used the KeyboardHeightProvider keyboard height provider android. And it gave me height in negative values and for my layout positioning I adjusted that value in calculations.
Here is KeyboardHeightProvider.java :
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager.LayoutParams;
import android.widget.PopupWindow;

/**
 * The keyboard height provider, this class uses a PopupWindow
 * to calculate the window height when the floating keyboard is opened and closed.
 */
public class KeyboardHeightProvider extends PopupWindow {

    /** The tag for logging purposes */
    private final static String TAG = "sample_KeyboardHeightProvider";

    /** The keyboard height observer */
    private KeyboardHeightObserver observer;

    /** The cached landscape height of the keyboard */
    private int keyboardLandscapeHeight;

    /** The cached portrait height of the keyboard */
    private int keyboardPortraitHeight;

    /** The view that is used to calculate the keyboard height */
    private View popupView;

    /** The parent view */
    private View parentView;

    /** The root activity that uses this KeyboardHeightProvider */
    private Activity activity;

    /**
     * Construct a new KeyboardHeightProvider
     *
     * @param activity The parent activity
     */
    public KeyboardHeightProvider(Activity activity) {
        super(activity);
        this.activity = activity;

        LayoutInflater inflator = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        this.popupView = inflator.inflate(R.layout.popupwindow, null, false);
        setContentView(popupView);

        setSoftInputMode(LayoutParams.SOFT_INPUT_ADJUST_RESIZE | LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);

        parentView = activity.findViewById(android.R.id.content);

        setWidth(0);
        setHeight(LayoutParams.MATCH_PARENT);

        popupView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

                @Override
                public void onGlobalLayout() {
                    if (popupView != null) {
                        handleOnGlobalLayout();
                    }
                }
            });
    }

    /**
     * Start the KeyboardHeightProvider, this must be called after the onResume of the Activity.
     * PopupWindows are not allowed to be registered before the onResume has finished
     * of the Activity.
     */
    public void start() {

        if (!isShowing() && parentView.getWindowToken() != null) {
            setBackgroundDrawable(new ColorDrawable(0));
            showAtLocation(parentView, Gravity.NO_GRAVITY, 0, 0);
        }
    }

    /**
     * Close the keyboard height provider,
     * this provider will not be used anymore.
     */
    public void close() {
        this.observer = null;
        dismiss();
    }

    /**
     * Set the keyboard height observer to this provider. The
     * observer will be notified when the keyboard height has changed.
     * For example when the keyboard is opened or closed.
     *
     * @param observer The observer to be added to this provider.
     */
    public void setKeyboardHeightObserver(KeyboardHeightObserver observer) {
        this.observer = observer;
    }

    /**
     * Get the screen orientation
     *
     * @return the screen orientation
     */
    private int getScreenOrientation() {
        return activity.getResources().getConfiguration().orientation;
    }

    /**
     * Popup window itself is as big as the window of the Activity.
     * The keyboard can then be calculated by extracting the popup view bottom
     * from the activity window height.
     */
    private void handleOnGlobalLayout() {

        Point screenSize = new Point();
        activity.getWindowManager().getDefaultDisplay().getSize(screenSize);

        Rect rect = new Rect();
        popupView.getWindowVisibleDisplayFrame(rect);

        // REMIND, you may like to change this using the fullscreen size of the phone
        // and also using the status bar and navigation bar heights of the phone to calculate
        // the keyboard height. But this worked fine on a Nexus.
        int orientation = getScreenOrientation();
        int keyboardHeight = screenSize.y - rect.bottom;

        if (keyboardHeight == 0) {
            notifyKeyboardHeightChanged(0, orientation);
        }
        else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            this.keyboardPortraitHeight = keyboardHeight;
            notifyKeyboardHeightChanged(keyboardPortraitHeight, orientation);
        }
        else {
            this.keyboardLandscapeHeight = keyboardHeight;
            notifyKeyboardHeightChanged(keyboardLandscapeHeight, orientation);
        }
    }

    /**
     *
     */
    private void notifyKeyboardHeightChanged(int height, int orientation) {
        if (observer != null) {
            observer.onKeyboardHeightChanged(height, orientation);
        }
    }

    public interface KeyboardHeightObserver {
        void onKeyboardHeightChanged(int height, int orientation);
    }
}

popupwindow.xml :
<?xml version="1.0" encoding="utf-8"?>
<View
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/popuplayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="horizontal"/>

Usage in MainActivity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

/**
 * Created by nileshdeokar on 22/02/2018.
 */
class MainActivity : AppCompatActivity() , KeyboardHeightProvider.KeyboardHeightObserver  {

    private lateinit var keyboardHeightProvider : KeyboardHeightProvider

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        keyboardHeightProvider = KeyboardHeightProvider(this)
        parentActivityView.post { keyboardHeightProvider?.start() }
    }

    override fun onKeyboardHeightChanged(height: Int, orientation: Int) {
        // In case of 18:9 - e.g. Samsung S8
        // here you get the height of the navigation bar as negative value when keyboard is closed.
        // and some positive integer when keyboard is opened.
    }

    public override fun onPause() {
        super.onPause()
        keyboardHeightProvider?.setKeyboardHeightObserver(null)
    }

    public override fun onResume() {
        super.onResume()
        keyboardHeightProvider?.setKeyboardHeightObserver(this)
    }

    public override fun onDestroy() {
        super.onDestroy()
        keyboardHeightProvider?.close()
    }
}

For any further help you can have a look at advanced usage of this here.

A: My version to handle cutouts + navigation bar
fun View.getCutoutRect(): Rect {
    return when {
        isInEditMode -> {
            val cutout = context.dpToPx(16f).roundToInt()
            Rect(cutout, cutout, cutout, cutout)
        }
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {
            val windowInsets = (context as? AppCompatActivity)?.window?.decorView?.rootWindowInsets ?: run {
                requestLayout()
                return Rect()
            }
            val cutout = WindowInsetsCompat.toWindowInsetsCompat(windowInsets).displayCutout
            val systemBars = WindowInsetsCompat.toWindowInsetsCompat(windowInsets).getInsets(WindowInsetsCompat.Type.systemBars())

            Rect(
                maxOf(cutout?.safeInsetLeft ?: 0, systemBars.left),
                maxOf(cutout?.safeInsetTop ?: 0, systemBars.top),
                maxOf(cutout?.safeInsetRight ?: 0, systemBars.right),
                maxOf(cutout?.safeInsetBottom ?: 0, systemBars.bottom),
            )
        }
        else -> {
            val savedRect = (this.getTag(R.id.view_insets_tag_id) as? Rect) ?: Rect()
            ViewCompat.setOnApplyWindowInsetsListener(this) { v, insets ->
                val cutout = insets.displayCutout
                val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
                val rect = Rect(
                    maxOf(cutout?.safeInsetLeft ?: 0, systemBars.left),
                    maxOf(cutout?.safeInsetTop ?: 0, systemBars.top),
                    maxOf(cutout?.safeInsetRight ?: 0, systemBars.right),
                    maxOf(cutout?.safeInsetBottom ?: 0, systemBars.bottom),
                )
                this.setTag(R.id.view_insets_tag_id, rect)
                if (savedRect != rect) {
                    requestLayout()
                }
                return@setOnApplyWindowInsetsListener insets
            }
            this.requestApplyInsets()
            savedRect
        }
    }
}

A: I suggest using the two Context extensions for getting status bar height in px and bottom navigation bar height in dp
Status bar height in dp
val Context.statusBarHeightInDp
    get() = run {
        val resourceId = this.resources.getIdentifier(
            "status_bar_height",
            "dimen",
            "android"
        )
        this.resources.getDimensionPixelSize(resourceId) / this.resources.displayMetrics.density
    }

Bottom nav bar height in dp
val Context.navBarHeightInDp
    get() = run {
        val resourceId = this.resources.getIdentifier(
            "navigation_bar_height",
            "dimen",
            "android"
        )
        this.resources.getDimensionPixelSize(resourceId) / this.resources.displayMetrics.density
    }

A: From Android R (SDK 30+), you can use this code to get size of status bar and navigation bar
WindowInsets insets = activity.getWindowManager().getCurrentWindowMetrics().getWindowInsets();
int statusBarHeight = insets.getInsets(WindowInsetsCompat.Type.statusBars()).top; //in pixels
int navigationBarHeight = insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom; //in pixels

A: To obtain the height in the layout XML itself (useful for the last element in a recycler view when clipToPadding is false) you can use the attribute actionBarSize:
android:paddingBottom="?attr/actionBarSize"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jenkins with Github Plugin build for EACH push I have Jenkins 1.629 with the Github Plugin configured to build for each push to my repository.
I have noticed that when I push multiple times during jenkins' quiet period (e.g. before the first jenkins job has begun but after it has been queued), that jenkins will simply build all of those commits as one build instead of building them separately.
How do I get jenkins to build each trigger separately? Is there any way using a parameterized build that I can achieve this?


text:
Q: Issues in the 'Fabcar' tutorial when bringing up a Kafka-based ordering service I've brought up a Kafka-based ordering service in the Fabcar network by modifying some docker composition/configuration files, which is one of the tutorials on Hyperledger Fabric readthedocs.
These are the issues I've suffered from. Could you please tell me how to resolve them or even one of them?

*

*I'd like to have containers start up in a specific order with 'wait-for-it.sh' script so that the orderer starts trying to connect to the Kafka cluster right after it is ready to perform commands. Do you happen to know how I should apply the script to my docker composition file?

*When I executed "enrollAdmin.js" file in order to register an admin account with node enrollAdmin.js on the network in the same way as I did on the unmodified network,
This error message is shown and it doesn't work:
~/fabric-samples/fabcar/node_nodules/fabric-
client/lib/Client.js:746
        async _createOrUpdateChannel(request, have_envelop) {
            ^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected Identifier
  at Object.exports.runInThisContext (vm.js:76:16)
  at Module._compile (module.js:542:28)
  at Object.Module._extensions..js (module.js:579:10)
  at Module.load (module.js:487:32)
  at tryModuleLoad (module.js:446:12)
  at Function.Module._load (module.js:438:3)
  at Module.require (module.js:497:17)
  at require (internal/module.js:20:19)
  at Object.<anonymous> (/home/~/fabric-samples/fabcar/node_modules/fabric-client/index.js:25:18)
  at Module._compile (module.js:570:32)

I took a look at Client.js file and was trying to understand how it works, but I have no idea what it is for and why it causes the issue.
Please help me resolve this issue if you know how.

A: Update Your nodejs .
check node version
node -v

It shoulb be greater than 8.0.0.


text:
Q: Building a Tesla Coil I want to have a go at building a Tesla Coil.
Has anybody here tried to build one before? How much do all the parts cost? Is it possible to make a small scale one? When can I get the plans, and what equipment/tools do I need?
UPDATE To make this question a little more specific...
There are a few parts of the general design of a Telsa coil that I'm unsure about.

*

*The HV transformer - I've seen that some plans say you can use a microwave oven transformer for this, and other plans say that you need to stack them by wiring the primarys in parallel and secondarys in series, but then you can get insulation breakdown. Is a MOT a good choice? If it's not good to use an MOT, then what?

*The tank cap - the general idea is to get a load of lower voltage caps and solder strings of them in series to get the voltage rating you need, then parallel the strings together to get the capacitance you need... but how do you stop it arcing across the leads?

*Whats an RF ground? Does it mean drive a stake into the ground and attach one side of the secondary to that?

*Finally, nearly every circuit I build fails to work the first time for one reason or another, and I use my meter and scope to work out whats wrong... How can I safely test parts of the circuit without being zapped with 20KV?

A: *

*The problem with MOTs is the voltage is too low to make a sparkgap work reliably. A pair is just-about doable but still not ideal. A neon-sign transformer is an easier and safer transformer for a first-time coil.

*Insulation and /or spacing

*A ground with a low inductance path, and one that will not damage anything if it sees a HV discharge to it. i.e.  not the ground pin on an AC outlet. Stake in the ground is ideal as long  as the cable length isn't very long.

*You won't need to do any measuraments on the HV side. You will know if there is HV present - corona hiss, ozone smell, arc-overs etc.

A: Lots of info to research can be found here.

A: I always thought about it but never did.  there is a chap in western australia who built some big ones and records videos and has a blog about it, not sure of the name now.
Good luck with it should be fun!  do be careful around it tough, cos they can generate some seriously high voltages :)


text:
Q: Pass up child component's config to parent Normally, to define a grid type, I do something like this:
Ext.define('MyApp.view.MyGrid', {
  extend: 'Ext.grid.Panel',
  alias: 'widget.myGrid',
  store: 'MyStore',
  columns: [...],
}

and then I add it to a container or layout via its xtype, 'myGrid'.
What I want to do is define a reusable custom component that either extends Ext.grid.Panel or accepts the same configs (such as columns), but is really a container that contains a grid and other stuff.
Ext.define('MyApp.components.ContainedGrid', {
  extend: 'Ext.container.Container' //or Ext.grid.Panel, whatever works
  alias: 'widget.containedGrid',
  layout: 'card',
  items: [
    {someObject}, //doesn't matter what this is
    {aGrid}, //the grid that should receive the configs from the caller
  ],
}

Ideally, this component could be configured like a regular Ext.grid.Panel object, and those configurations should be really apply to the grid defined second in the items array.
In other words, something like the following should render a window containing a card layout, where the second card should be the grid, with the columns & store provided to the container.
Ext.create('Ext.window.Window',  {
  title: 'hi',
  layout: 'fit',
  items: {
    xtype: 'containedGrid',
    store: myStore,
    columns: [...],
  },
});

Logically, I just want to say that the configs provided to the container apply to one of its components, but I don't know how to execute that.  Any thoughts?
Edit:
To be succinct, what I'm trying to do is create a component that is configured just like a grid, but is really a container that includes a grid, along with some other stuff.  This component will be used several times, so I'd like to package it as a reusable component.

A: Override the initComponent method:
Ext.define('MyWindow', {
    extend: 'Ext.window.Window',
    layout: 'fit',
    title: 'Foo',

    initComponent: function(){
        this.items = {
            xtype: 'grid',
            store: this.store,
            columns: this.columns
        };
        this.callParent();
    }
});

Ext.onReady(function(){
    new MyWindow({
        width: 200,
        height: 200,
        autoShow: true,
        store: {
            fields: ['name'],
            data: [{
                name: 'Name 1'
            }]
        },
        columns: [{
            dataIndex: 'name',
            text: 'Name'
        }]
    });
});

A: Define a property for the gridconfig
Ext.define('MyApp.components.ContainedGrid', {
  extend: 'Ext.container.Container' //or Ext.grid.Panel, whatever works
  alias: 'widget.containedGrid',
  layout: 'card',
  /**
   * @cfg {object} gridCfg
   */

  initComponent: function(){
     var gridCfg = { xtype: 'grid' };
     if(this.gridCfg)
          gridCfg = Ext.apply(gridCfg ,this.gridCfg);
     if (this.items) // we assume if set it will be always array!
          this.items.push(gridCfg);
     else
          this.items = [gridCfg];
     delete this.gridCfg; // we no longer need this property here
     this.callParent(arguments);
  }
}

And the usecase:
Ext.create('Ext.window.Window',  {
  title: 'hi',
  layout: 'fit',
  items: {
    xtype: 'containedGrid',
    gridCfg: {
       store: myStore,
       columns: [...]
    }
  },
});

Update
I think I now understand what you are looking for. To register listeners directly onto the container you need to relay the events. I've made a example that at least relay the events of the view (which should be most). You will be able to relay also events of the table and the features (features first after rendering). Here's a JSFiddle that print all events from the container into the console.
Ext.define('Ext.ux.ContainedGrid', {
      extend: 'Ext.container.Container',
      alias: 'widget.containedGrid',
      layout: 'card',
      /**
       * @cfg {object} gridCfg
       */

      /**
       * @private {object} grid
       */
      initComponent: function(){
         var me = this,
             grid;
         // provide some default settings for the grid here,
         // which can be overriden by each instance
         var gridCfg = { }; // the defaulttype is defined on the componentmanager call
         me.gridCfg = me.gridCfg ? Ext.apply(gridCfg ,me.gridCfg) : gridCfg;

         me.grid = me.getGrid();

         if (me.items && Ext.isArray(me.items))
              me.items.push(me.grid);
         else if(me.items)
              me.items = [me.items, me.grid];
         else
              me.items = [me.grid];
         delete me.gridCfg; // we no longer need this property here
         // Relay events from the View whether it be a LockingView, or a regular GridView
         this.relayEvents(me.grid, [
                /**
                 * @event beforeitemmousedown
                 * @inheritdoc Ext.view.View#beforeitemmousedown
                 */
                'beforeitemmousedown',
                /**
                 * @event beforeitemmouseup
                 * @inheritdoc Ext.view.View#beforeitemmouseup
                 */
                'beforeitemmouseup',
                /**
                 * @event beforeitemmouseenter
                 * @inheritdoc Ext.view.View#beforeitemmouseenter
                 */
                'beforeitemmouseenter',
                /**
                 * @event beforeitemmouseleave
                 * @inheritdoc Ext.view.View#beforeitemmouseleave
                 */
                'beforeitemmouseleave',
                /**
                 * @event beforeitemclick
                 * @inheritdoc Ext.view.View#beforeitemclick
                 */
                'beforeitemclick',
                /**
                 * @event beforeitemdblclick
                 * @inheritdoc Ext.view.View#beforeitemdblclick
                 */
                'beforeitemdblclick',
                /**
                 * @event beforeitemcontextmenu
                 * @inheritdoc Ext.view.View#beforeitemcontextmenu
                 */
                'beforeitemcontextmenu',
                /**
                 * @event itemmousedown
                 * @inheritdoc Ext.view.View#itemmousedown
                 */
                'itemmousedown',
                /**
                 * @event itemmouseup
                 * @inheritdoc Ext.view.View#itemmouseup
                 */
                'itemmouseup',
                /**
                 * @event itemmouseenter
                 * @inheritdoc Ext.view.View#itemmouseenter
                 */
                'itemmouseenter',
                /**
                 * @event itemmouseleave
                 * @inheritdoc Ext.view.View#itemmouseleave
                 */
                'itemmouseleave',
                /**
                 * @event itemclick
                 * @inheritdoc Ext.view.View#itemclick
                 */
                'itemclick',
                /**
                 * @event itemdblclick
                 * @inheritdoc Ext.view.View#itemdblclick
                 */
                'itemdblclick',
                /**
                 * @event itemcontextmenu
                 * @inheritdoc Ext.view.View#itemcontextmenu
                 */
                'itemcontextmenu',
                /**
                 * @event beforecontainermousedown
                 * @inheritdoc Ext.view.View#beforecontainermousedown
                 */
                'beforecontainermousedown',
                /**
                 * @event beforecontainermouseup
                 * @inheritdoc Ext.view.View#beforecontainermouseup
                 */
                'beforecontainermouseup',
                /**
                 * @event beforecontainermouseover
                 * @inheritdoc Ext.view.View#beforecontainermouseover
                 */
                'beforecontainermouseover',
                /**
                 * @event beforecontainermouseout
                 * @inheritdoc Ext.view.View#beforecontainermouseout
                 */
                'beforecontainermouseout',
                /**
                 * @event beforecontainerclick
                 * @inheritdoc Ext.view.View#beforecontainerclick
                 */
                'beforecontainerclick',
                /**
                 * @event beforecontainerdblclick
                 * @inheritdoc Ext.view.View#beforecontainerdblclick
                 */
                'beforecontainerdblclick',
                /**
                 * @event beforecontainercontextmenu
                 * @inheritdoc Ext.view.View#beforecontainercontextmenu
                 */
                'beforecontainercontextmenu',
                /**
                 * @event containermouseup
                 * @inheritdoc Ext.view.View#containermouseup
                 */
                'containermouseup',
                /**
                 * @event containermouseover
                 * @inheritdoc Ext.view.View#containermouseover
                 */
                'containermouseover',
                /**
                 * @event containermouseout
                 * @inheritdoc Ext.view.View#containermouseout
                 */
                'containermouseout',
                /**
                 * @event containerclick
                 * @inheritdoc Ext.view.View#containerclick
                 */
                'containerclick',
                /**
                 * @event containerdblclick
                 * @inheritdoc Ext.view.View#containerdblclick
                 */
                'containerdblclick',
                /**
                 * @event containercontextmenu
                 * @inheritdoc Ext.view.View#containercontextmenu
                 */
                'containercontextmenu',
                /**
                 * @event selectionchange
                 * @inheritdoc Ext.selection.Model#selectionchange
                 */
                'selectionchange',
                /**
                 * @event beforeselect
                 * @inheritdoc Ext.selection.RowModel#beforeselect
                 */
                'beforeselect',
                /**
                 * @event select
                 * @inheritdoc Ext.selection.RowModel#select
                 */
                'select',
                /**
                 * @event beforedeselect
                 * @inheritdoc Ext.selection.RowModel#beforedeselect
                 */
                'beforedeselect',
                /**
                 * @event deselect
                 * @inheritdoc Ext.selection.RowModel#deselect
                 */
                'deselect'
            ]);
         me.callParent(arguments);
      },
      getGrid: function() {
         if(this.grid)
             return this.grid;
         return this.grid = Ext.ComponentManager.create(this.gridCfg,'grid');;
      }

});


text:
Q: How to find import name/key of pip3 installed module I am aware of how to install new python modules with pip. I have great success with that. But once the modules are installed, I have no idea how to import them.
For example, I may run
sudo pip3 install mysql-connector-python

I see all of the necessary install messages, and I am told that my brand spanking new module has been installed. I run pip3's list and freeze functions, and sure enough, it says that the modules are installed. My pip3 freeze output looks like...
mysql-connector-python==1.1.6

I then run python 3.xx and try
import mysql-connector-python

thinking that text listed in my pip3 freeze call is the import path, but I get an ImportError.
Is there a way to list the keys/keywords/strings that I need to use to properly import a new module? Clearly, mysql-connector-python is not the right key. That's really all I need, the keyword. After that, I can do the rest.

A: You can see the files an installed package contains using:
pip show --files packagename

The base directory that features prominently in that list will in most cases be the package name to import inside Python.


text:
Q: timer doesn't stop on buttonclick I have trouble with timer in button click. When i click button startpause() method is called there i set start timer and stop timer. It works fine when I click button normally(one click after sometime another click) but when I click the button again and again speedly the timer starts to jump with 2-3 secs. Seems like more than one timer is running.. Anyone have any idea....?? here time is my timer method
function startpause() {

    if(FLAG_CLICK) {
        setTimeout(tim,1000);
        FLAG_CLICK = false;
    }
    else {
        clearTimeout(ti);
        FLAG_CLICK = true;
    }
}

function tim() {

    time.innerHTML = t;
    t = t + 1;
    ti= setTimeout("tim()", 1000);
}

A: You need to store setTimeout somewhere in order to manipulate it later.
var myVar;

function myFunction()
{
  myVar=setTimeout(function(){alert("Hello")},3000);
}

function myStopFunction()
{
  clearTimeout(myVar);
}

ref http://www.w3schools.com/js/js_timing.asp

A: Maybe you must change this:
if(FLAG_CLICK) {
    setTimeout(tim,1000);
    FLAG_CLICK = false;
}

to:
if(FLAG_CLICK) {
    tim();
    FLAG_CLICK = false;
}

It seems works for me normally

A: Try this:
// assuming you declared ti and t out here, cuz I hope they're not global

var t = 0;
var ti;
var running = false;

function startpause() {

    clearTimeout(ti);
    if(!running) {
        ti = setTimeout(tim,1000);
        running = true;
    } else {
        running = false;
    }
}
function tim() {
    time.innerHTML = t;
    t = t + 1;
    ti = setTimeout(tim,1000);
}

You can read more about the .setTimeout() here: https://developer.mozilla.org/en/docs/DOM/window.setTimeout
Also, see the jsfiddle I just created: http://jsfiddle.net/4BMhd/


text:
Q: Как отправить голосовое сообщение через VK API .62? Единственная инфа, которая есть в интернете здесь.
По тому способу делаю голосовое сообщение из группы, но в ответ приходит именно документ. Естественно, в документации нечего нет на тему отправки голосовых сообщений. Метод должен работать, сам я подозреваю, что дело в формате файла (я использовал ogg).

A: Нет, дело было не в формате файла: просто этот метод, во-первых, не был в общем доступе, а во-вторых, с ним всё не так просто. Я описывал в статье тонкости этого процесса: нужно получить сервер для загрузки документа с ключом доступа пользователя, затем загрузить документ на сервер опять же с ключом доступа пользователя, и сохранять в свой список документов (видно его всё равно не будет) тоже с ключом доступа пользователя. А вот отправлять уже нужно будет с ключом доступа сообщества, причем если пользователь не был администратором сообщества, вместо голосового сообщения придут 3 точки.
Буквально пару дней назад выкатили обновление: теперь (во избежание капч и прочего) документы в диалогах загружаются как бы от имени адресата, и загружаются они прямо в диалог: https://vk.com/dev/docs.getMessagesUploadServer, и теперь оно должно работать нормально и с ключом доступа сообщества.


text:
Q: Get documentation from GitHub project as a single pdf I'm looking for a single pdf of the ErpNext and Frappe user manuals.
Documentation seems to be provided in html and the source is in markdown. I did find tools to convert markdown to html/pdf, but no reliable solution to generate a SINGLE pdf file keeping the structure as shown here:
Put more abstractly: How to transform GitHub markdown documentation (organized in subdirectories) into a single pdf file?
Could anyone help me out?
Any way of achieving this is welcome, thanks in advance!

A: You can convert markdown to PDF with Pandoc or similar tools.
You can fsearch the internet about how to concatenate files on your OS.
There are several (online) tools to merge multiple PDFs into one.
To create a single file you can either

*

*concatenate the markdown files into one big file, then convert to PDF, or

*convert all markdown files to PDF, then merge all PDF files into one big PDF.


text:
Q: Online php script runner I want to develop an online PHP script runner. I don't know how get started with it.  Any basic ideas will be appreciated.  Thanks.

A: In very simple form:
eval($_GET["code"]);

but you have to pay attention to the security risks of doing so.
It is highly recommended to filter some "evil code" like create/delete files on the webspace etc.


text:
Q: plotting time in hh:mm:ss format on the x axis I have an issue, which I feel should be really easy to solve, however I am unable to figure it out.
I have two arrays of equal length, one containing some measurement values and another one containing the time stamps of this measurements as strings in the form of hh:mm:ss (for example: time = ['09:17:12', '09:17:13', '09:17:17', ..., '12:49:02']. The time stamps are not equally separated in time, sometimes they differ by a second, sometimes by 5 seconds. Both arrays are very long - around 100 000 entries.
I would like to plot the measurement values on the y axis against the time stamp values on the x axis. Additionally I would like the formatter on the x axis to show the time every hour (or two hours) in order to avoid overlapping.
I've spent quite a long time trying to figure out how to do it, and I assume it should be fairly straightforward, however I am unable to do it. I guess it should involve datetime, date2num, as well as fiddling with the x axis formatter and locator. If anyone has any suggestions it would be greatly appreciated.


text:
Q: NullException error in MVC first code entity I have MVC first code project but I get below error

First code! So there is no default database.
Model class
public class Applicant
{
    public int ApplicantID { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public int PhoneNumber { get; set; }
}

Context class:
public class Context : DbContext
{
    public List<Applicant> Applicants { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Applicant>().Property(r => r.ApplicantID)
                     .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

Applicant repasority class:
public  Applicant Create(string username, string password, int phoneNumber, out int existResult)
{
    if (context.Applicants.Where(x => x.UserName == username).ToString() != null)
    {
        applicant = new Applicant()
        {
            UserName = username,
            Password = password,
            PhoneNumber = phoneNumber,
        };
        context.Applicants.Add(applicant);
        existResult = 1;
        return applicant;
    }
    existResult = 0;
    return applicant;
}

And I added below code to my web.config in my web solution:
  <connectionStrings>
    <add connectionString="Data Source=.;Catalog=Homi;Integrated Security=True" providerName="System.Data.SqlClient" name="Context" />
 </connectionStrings>
</configuration>

A: ok I find answer.
first I changed context class to this like below
add this part:
public Context()
    {
        base.Configuration.LazyLoadingEnabled = false;
        base.Configuration.ProxyCreationEnabled = false;
        base.Configuration.ValidateOnSaveEnabled = false;
    }

and changed string to DbSet:
    public DbSet<Applicant> Applicants { get; set; }

second
a cool mistake :D I forgot to do this:

Project –> Manage NuGet Packages…
Note: If you don't have the Manage NuGet Packages… option you should
  install the latest version of NuGet
Select the Online tab
Select the EntityFramework package
Click Install

after all for some place of code if above ways doesn't work try{}catch{}
was last solution!
and in end when I run my web nothing saved in my db :(
it was very important to put "context.SaveChanges();" in applicant repository after "context.Add(applicant);"
that's all
tnx


text:
Q: How to remove all characters after the last backslash in a path with Batch EDIT: The value of %%a is
<MachineEntry uuid="{awae1979-6512-4br8-acg5-3oe94f56712de}" src="C:\Users\John\VirtualBox VMs\VM\VM.vbox"/>

I'm trying to grab the folder of a VMWare Virtual Machine. Since the user can change where the folder is located, the path is never the exact same. I've created a script that grabs the path for any VMs on the system but the issue then is that I have a path that ends in a file. In the code I've provided I tried to use the existing findstr loop to remove the slash and trailing characters but it only removes the C:\. Here is an example of my current code:
(FOR /F "delims=" %%a in ('findstr /I /L "src" VirtualBox.xml') DO (
   SET "line=%%a"
   REM This is the term that the script searches for
   SET "line=!line:*src=!"
   REM This removes the excess characters from the grabbed string
   SET "line=!line:~2,-3!"
   SET "line=!line:*\=!"
   FOR /F "delims=<" %%b in ("!line!") DO ECHO !line!
))
PAUSE

In my example code it delivers Users\John\VirtualBox VMs\VM\VM.vbox. It ends up only cutting the C:\ off.  I want it to instead cut the last \ off giving me C:\Users\John\VirtualBox VMs\VM. Any ideas on how I could get the code to iterate from the end of the line instead of from the start? Any advice or suggestions are welcome!

A: Would it not be easier to use the doublequotes as delimiters?
@For /F Tokens^=4Delims^=^" %%A In ('Find "src="^<"VirtualBox.xml"')Do @Echo(%%A

or if you only wanted the path, not the full string:
@For /F Tokens^=4Delims^=^" %%A In ('Find "src="^<"VirtualBox.xml"')Do @Echo(%%~dpA

[Edit /]
Here's an alternative, batch-file solution based upon the location provided by LotPings, in their comment below, and leveraging powershell:
@For /F "Delims=" %%A In ('PowerShell -NoProfile -Command^
 "[XML]$VBoxes = Get-Content "$Env:UserProfile\.VirtualBox\VirtualBox.xml";"
 "$VBoxes.VirtualBox.Global.MachineRegistry.MachineEntry |"
 "ForEach-Object {Split-Path -Path "$_.src" -Resolve}" 2^>Nul'
)Do @Echo(%%A

This is a single line command, changed to multiline to improve readability. In it I have used Split-Path along with -Resolve so that only results which are currently available are output.

A: You could use = and / as delimiters to extract the quoted path and then let the ~ modifiers do their job:
for /F "tokens=3 delims==/" %%L in ('findstr /I "src=" "VirtualBox.xml"') do (
    echo Full path: %%~L
    echo File name: %%~nxL
    echo Dir. path: %%~dpL
)

A: My solution is using in batch file:
@echo off
for /F "tokens=3 delims=/=" %%I in ('%SystemRoot%\System32\findstr.exe /I /L "src" VirtualBox.xml') do set "VirtualBoxPath=%%~dpI"
echo Virtual box path is: "%VirtualBoxPath%"

FOR with option /F starts in this case a new command process in background with %ComSpec% /c and the command line between the two ' inside the round brackets appended resulting with Windows installed into C:\Windows in executing:
C:\Windows\System32\cmd.exe /c C:\Windows\System32\findstr.exe /I /L "src" VirtualBox.xml

FINDSTR searches case-insensitive for lines containing the literal string src in file VirtualBox.xml in current directory which can be also a directory different to the directory containing the batch file. In this case FINDSTR outputs to handle STDOUT of background command process the line:
<MachineEntry uuid="{awae1979-6512-4br8-acg5-3oe94f56712de}" src="C:\Users\John\VirtualBox VMs\VM\VM.vbox"/>

FOR captures everything output to handle STDOUT of started command process and processes the captured text line by line after started cmd.exe terminated itself.
FOR ignores always empty lines on processing the captured output.
FOR splits up by default each line into substrings using normal space and horizontal tab as delimiters and assigns just first space/tab delimited string to specified loop variable I. The line splitting behavior is modified for this task by specifying tokens=3 delims=/= on FOR command line after option /F.
The string delimiters are now the forward slash / and the equal sign = which means the XML line to process is split up into:

*

*<MachineEntry uuid

*"{awae1979-6512-4br8-acg5-3oe94f56712de}" src

*"C:\Users\John\VirtualBox VMs\VM\VM.vbox"

*>
Only the third string is of interest and is assigned to loop variable I because of tokens=3.
So loop variable I gets assigned the string:
"C:\Users\John\VirtualBox VMs\VM\VM.vbox"

FOR ignores by default also all lines starting with a semicolon because of eol=; is the default for end of line option. The end of line option must not be changed here because the XML line to process never starts with ;.
In real FOR first splits up the line using the specified or the default string delimiters and then checks if the first substring starts with the specified or default end of line character. So FOR would also ignore in this case a line starting for example with =/; because of = and / would be removed during line splitting and then first substring starts with ; although the line itself starts with = and for that reason the line is completely ignored although assigned to loop variable I should be the third and not the first substring.
The string assigned to loop variable I is referenced with %%~dp using three modifiers:

*

*The first one is ~ which results in removing surrounding " from string assigned to loop variable I.

*The second one is d which means drive letter with colon.

*The third one is p which means path without drive letter and colon.
The path is everything up to last backslash with including the last backslash.

Therefore the string C:\Users\John\VirtualBox VMs\VM\ is assigned to environment variable VirtualBoxPath.
In general it does not matter on applying the modifiers on string assigned to a loop variable if this string really references an existing file or folder. The modifiers are applied on the string itself if no file/folder can be found by FOR with the string assigned to referenced loop variable in file system. Of course the file/folder referenced by the string assigned to loop variable must exist if being incomplete like just a file name without file extension is assigned to loop variable and wanted is drive, path or file extension. In this case FOR accesses file system to get full qualified file name of incomplete file name string and tries its best to get the wanted data.


text:
Q: Why do child classes cast to parent type default to parent version of private instance methods, but not of other instance methods? It was my understanding that a child cast to the parent type (as in Super sc = new Child();) would call the parent class's static methods, and access the parent class's non-hidden fields, but would make use of the child class's instance methods.
This does not seem to hold true for the case of private instance methods (those in which overriding does not actually take place because the parent method is private.)
I understand that the fact that there is no overriding (private parent methods are not visible to the child, so they can only be hidden.) would mean that the child wouldn't look up the heirarchy to see the parent's version of the method when the instance method is invoked from the child.
However, the exact opposite of what I'd expect (the version present in the child being called) is occurring.  The parent version of the private method is invoked.
Why does this happen if the instance methods of the child are typically invoked, and within the child, there is a method with an identical signature (a perfect match for the invocation of method2() in this case) already present, hiding the same method in the parent class?
package whatever;

public class A {

    public void method1(){
        System.out.println("A method1().");
    }
    //using "final" here to emphasize that this is a hiding, not an override.
    private final void method2(){
        System.out.println("A private method2().");
    }

    public static void main(String[] args)
    {
        A a = new A().new B();
        a.method1(); //calls B  method 1
        ((A.B)a).method1(); //calls B method 1
        a.method2(); //calls A private method 2 **I expected it to call B private method 2
        ((A.B)a).method2(); //calls B private method 2

    }

    public class B extends A {

        public void method1(){
            System.out.println("B method1().");
        }
        private final void method2(){
            System.out.println("B private method2().");
        }
    }

}

A: First, B is actually a nested class and, oddly enough, the private members of nested classes can by accessed by the outer class. Otherwise, it wouldn't even be legal to do ((A.B)a).method2(); (The reverse is also true. B can access private members in A as well.)
That said, to answer your actual question, the reason a.method2(); calls the private method in A is that private methods are not virtual, as they cannot be overriden at all. (How could they be, if inheriting classes aren't supposed to even know about them?) As such, they are bound at compile time, which means using the declared type of the variable. A a is declared as A, but (A.B)a is cast at compile time to B. Thus, your first call uses the private method from A and your second call uses the private method from B.
It's quirky that the facts in those two paragraphs don't interact with each other. It might reasonable to expect that, since the nested class "knows" about the outer class's private members, an override might be possible. But it's not. Private functions never show up in the vTable and can never be overridden.

A: Short answer: because your B class is in the same file (.java) with the one that contains #main() method.

A: The reason that the private method of the parent class is visible to the child class is that the child class is an inner class of its parent class in your case.

Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private


text:
Q: Check if SSL Certificate is present or not in iOS? I have an API end point which has an SSL Certificate (secure https API). My iOS app bundle also includes that certificate so when I try to reach the API end point, objective C verifies if the certificate matches or not. My implementation of matching certificates works fine.
But I also need to verify if the API provides an SSL Certificate or not.
I am using AFNetworking for matching the certificates, and the place where it verifies the certificate: - (void)connection:(NSURLConnection *)connection
willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge does not even gets called when there is no certificate present. Hence the app doesn't verify anything.
I need something to verify in first place if the API has certificate or not, and if it doesn't then the app should not reach to the API end point.


text:
Q: Show that the Cantor set is totally disconnected So I'm trying to prove that the Cantor set $C$ is totally disconnected - that is, for any two points $x, y \in C$ there is a $z \notin C$ where either $x < z < y$ or $y < z < x$. I'd like to check if my argument proves this proposition.
First I assume without loss of generality that $x < y$.
Next, we fix $k \in \mathbb{N} \cup \{0\}$. If $|x - y| > 1/3^k$ we can easily argue that $x$ and $y$ are in two different subintervals of $C_k$ and choosing $z \notin C$ is straightforward.
If $|x - y| \leq 1/3^k$, then the two points are in the same subinterval of $C_k$. But since $x \neq y$, then we can choose a $1 \geq \delta > 0$ such that $|x - y| = \delta$. Now all we have to do is choose $n > 0$ such that $|x - y| = \delta > 1/3^{k + n}$. With some rearrangement we have $n > - k - \log_3(\delta)$ which means if we choose $n = -k + \lceil - \log_3(|x - y|)\rceil + 1$, then the set $C_{k + n} = C_{\lceil - \log_3(|x - y|)\rceil + 1}$ will result in $x$ and $y$ not being in the same subinterval. So there would exist a $z \notin C$ between $x$ and $y$.
How does my proof look?

A: Your proof is OK. It can be simplified as follows.
Suppose $y>x.\,$ Let $k\in \Bbb{N}\,$ be that $\,1/3^k<y-x<1/3^{k-1}.\,$ Then there is an interval $I=\left(l/3^{k+1}, (l+1)/3^{k+1}\right)\:(0\leqslant l<3^{k+1}-1)\:$ such that $I\subset(x,y)\,$ but $\,I\cap C=\varnothing.\,$ By choosing a $\,z\in I,\,$ we have $\,z\in (x,y)$ and $\,z\notin C$.

A: A minimal choice of $k$ exists because the sequence $3^{-k}$ converges to $0$, i.e., there is an integer $K$ such that for all $k\geq K$, we have $3^{-k}<|x-y|$. By choosing any such $k\geq K$, we can argue that $x$ and $y$ are in different sub-intervals without cases.


text:
Q: for loop output formatting: add newline with a description and space I'm running through a list of files to cat and redirecting all of the output to a single file using a for loop. My loop works but i'm looking for a way to add a descriptor line before each file's contents is dumped and add a space before each new file entry. Here is my script.
#!/bin/bash

files=$(ls -l /home/user/*.txt | awk 'NR>=2 {print $9}')

for i in $files; do /bin/cat "$i" >> "/home/user/catfiles.txt"
done

My output looks like this:
 spawn ssh user@x.x.x.x
 run $command
 quit
 spawn ssh user@x.x.x.x
 run $command
 quit

I would like for it to look like this:
 "Description for first file here"
 spawn ssh user@x.x.x.x
 run $command
 quit
 <space>
 "Description for second file here"
 spawn ssh user@x.x.x.x
 run $command
 quit
 <space>

UPDATE: The file description name would need to vary by file using the actual file name.
"This is $file1"
"This is $file2"
 etc,etc..

A: This will merge them as you require it:
for f in /home/user/*.txt;do
    echo "This is ${f##*/}" >> /home/user/catfiles.txt
    /bin/cat "${f}" >> /home/user/catfiles.txt
    echo >> /home/user/catfiles.txt
done

The file name is printed without its path. If you want the path printed, too, then simply replace ${f##*/} with ${f}.
Update
${variable##pattern} is called parameter substitution. Bash will search for pattern in variable and remove the longest match. In this case the variable is f and pattern is */ which matches any String that ends with a slash. The double hash ## indicates to remove the longest String in f that can be matched by */. Since f is a path it will match and remove everything up to and including the last /, thus leaving only the filename.
The Bash documentation has further and more detailed info on this subject. Alternatively, you can search in man bash for Parameter Expansion.

A: So you want this, and BTW your files=$(ls -l /home/user/*.txt | awk 'NR>=2 {print $9}') is wrong, don't parse ls output, jus use shell:
for i in /home/user/*.txt; do
    echo "Description for first file here $i" >> /home/user/catfiles.txt
    /bin/cat "$i" >> "/home/user/catfiles.txt"
    echo >> /home/user/catfiles.txt
done

A: This will resolve the issue:
for i in /home/user/*; do
echo "This is from $i" >> "/home/user/catfiles.txt"
/bin/cat "$i" >> "/home/user/catfiles.txt"
    echo >> "/home/user/catfiles.txt"
done

Since "i" represents each file in this case, $i in the second line starting with echo will give you the different filename.
If you want to exclude the file path so the line simply has the file name without the /home/user you can insert a sed statement after the 3rd line.
for i in /home/user/*; do
echo "This is from $i" >> "/home/user/catfiles.txt"
/bin/cat "$i" >> "/home/user/catfiles.txt"
/bin/sed -i -e 's/\/home\/user\///g' /home/user/catfiles.txt
    echo >> "/home/user/catfiles.txt"
done


text:
Q: How to get all data by `echo json_encode($data);` I want to update user wall by my below script if new data added in sql within last 15 second.
It's update fine if I just use only one data $data = $row['description']; in server.php file.
When I am going to array all data in server.php file to display full post and make my script as below, It's display [object Object] continuously.
So I want to display newly added full post with user img, name, detail etc.

But I have no idea about how to do it.

Please give me a guideline.
server.php

include("../db.php");
global $dbh;
header('Content-Type: application/json; charset=utf-8');
while (true) {
date_default_timezone_set('Asia/Dhaka');
//fetch data
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$results = mysqli_query($dbh,"SELECT * FROM comments WHERE qazi_id='1012' AND date >= '$datetime' ORDER BY date DESC LIMIT 1") or die(mysqli_error($dbh));
$rows =  mysqli_fetch_assoc($results);

$data = array();

$data['id'] = $rows['id'];
$data['qazi_id'] = $rows['qazi_id'];
$data['likes'] = $rows['likes'];
$data['username'] = $rows['username'];
$data['img'] = $rows['img'];
$data['description'] = $rows['description'];
$data['url'] = $rows['url'];
$data['parent_id'] = $rows['parent_id'];
$data['date'] = $rows['date'];

//has data
if (!empty($data)) {
    echo json_encode($data);
    flush();
    exit(0);
}
sleep(5);
}

JS Script:
function addmsg(type, msg){
    $("#messages").append(
        "
"+ msg +"
"
    );
}

function waitForMsg(){
    $.ajax({
        type: "GET",
        url: "server.php",
        async: true,
        cache: false,
        timeout:15000,
        success: function(data){
            addmsg("new", data);
            setTimeout(
                waitForMsg,
                1000
            );
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            setTimeout(
                waitForMsg,
                15000);
        }
    });
};

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

Html:

A: You must reference the properties of the object, not the object itself. For example, to show the description:
function addmsg(type, msg){
    $("#messages").append(
        "
"+ msg.description +"
"
    );
}

Alternatively, just pass the description to your function instead:
success: function(data){
            addmsg("new", data.description);
            setTimeout(
                waitForMsg,
                1000
            );
        },

A: In the "simple" example ($data = $row['description'];) your data is returned as a string, that's why it works. When you sent your object back to the page things get more difficult. You still try to print the object as a string (JavaScript translates and shows you [Object Object], saying that you actually retrieved an object). You need to supply the proper index/key to msg to retrieve the correct info.
For example: msg['description'] should return the description.
function addmsg(type, msg){
    $("#messages").append(
        "
"+ msg["description"] +"
"
    );
}

Basically your data is returned as this
msg = {
         "username" : "foo",
         "description" : "bar",
         etc....
      }

It's returned as a JavaScript object from which you can retrieve properties normally.

*

*msg.username or

*msg["username"]
To build your message you need to build your message object containing the various properties of msg (or data).
function addmsg(type, msg){
    $("#messages").append(
        "
User " + msg["username"] + "sent: " + msg["description"] +"
"
    );
}


text:
Q: Excel VBA translation date into another format Really new to the Excel VBA.
Been working on one task and tried to piece all different elements into one working macro.
Here is my goal
as you can see on the picture,
there is a list of ID and names who reported their leave during the month.
I would like to translate into below format
start date/  end date /hours taken
1 Tried the code to capture start date, but failed to resume the loop to capture the end date.
Sub FindMatchingValue()
    Dim i As Integer, intValueToFind As Integer
    intValueToFind = 8
    For i = 1 To 500    ' Revise the 500 to include all of your values
        If Cells(2, i).Value = intValueToFind Then
            MsgBox ("Found value on row " & i)
            Cells(2, 35).Value = Cells(1, i) 'copy the start date to same row column 35
            Exit Sub
        End If
    Next i

    ' This MsgBox will only show if the loop completes with no success
    MsgBox ("Value not found in the range!")
End Sub

2 End date would be the last day for employee who took leave in consecutive days.
Really appreciate help from our community.

A: Following code will return you the first set of consecutive leave for first ID (Row 2) with start date, end date and hours taken:
Sub FindMatchingValue()
    Dim i As Integer, intValueToFind As Integer, Found As Boolean, HoursTaken As Single
    intValueToFind = 8
    For i = 1 To 34    'Considering 34 is the max date column
        If Found Then
            If Cells(2, i).Value = "" Then
                MsgBox ("Last consecutive column " & i - 1)
                Cells(2, 36).Value = Cells(1, i - 1) 'copy the end date to same row column 36
                Cells(2, 37).Value = HoursTaken 'Hours taken to same row column 37
                Found = False
                Exit Sub 'Skip after first set of leave
            Else
                HoursTaken = HoursTaken + Cells(2, i)
            End If
        ElseIf Cells(2, i).Value = intValueToFind Then
            MsgBox ("Found value on column " & i)
            Cells(2, 35).Value = Cells(1, i) 'copy the start date to same row column 35
            Found = True
            HoursTaken = Cells(2, i)
        End If
    Next i

    'This MsgBox will only show if the loop completes with no success
    MsgBox ("Value not found in the range!")
End Sub

You have to think more on how will you capture the next sets of leave for the same person and run it for entire set of data row. Hope this will be help in solving your problem.


text:
Q: Expandable Recyclerview Android I tried to create recyclerview with its adapter, working fine but failed to create
child recyclerview on click of its parent Item.
Required this type of layout https://github.com/thoughtbot/expandable-recycler-view
but unfortunately failed to resolve AS dependency as it is too old.
I also tried to take recyclerview in parent adapter but its not working with wrap_content i have to specify length of Recycler which is not possible in my case i have to draw dynamic layout.


text:
Q: M.2 PCIe x2 and SATA connections and key/notch with SATA/PCIe x4 SSDs For my current project I am adding an M.2 slot for additional storage. Even though SATA data throughput is more than sufficient I would like to support both SATA and PCIe based SSDs, as I dont know what will be more/less available and affordable in future.
M.2 Keys
The M.2 connectors use keying notches in different positions, depending on the provided interfaces. Each key position is identified by a letter.

*

*Key B: SATA + PCIe x2 (+ others)

*Key M: SATA + PCIe x4

A quick search for M.2 SSDs on amazon showed that most NVMe/PCIe based SSDs use Key M, while SATA SSDs use a combined Key B and M. Therefore, for maximum compatibility, I need to use Key M.
Available System Interfaces
My system has one SATA and 2 PCIe lanes that may be connected to the M.2 receptacle, what is the requirement for Key B. I am missing 2 PCIe lanes for key M.
Plan
I plan to use the M key for maximum mechanical compatibility and would like to provide one SATA and 2 PCIe-Lanes on the M.2 connector.
Questions

*

*Do all NVMe/PCIe based SSDs work with 2 instead of 4 PCIe lanes?

*Is there a requirement on which PCIe lanes need to be used in this case?

*How may the two PCIe lanes that are not used be terminated?

A: A card that has B and M notches is generally SATA, although it could be NVMe x 2 if the CONFIGx pins are set to that mode.
An M-notch card as a practical matter is strictly NVMe, and can be x1, x2 or x4.
There's no issue with leaving PCIe lanes unconnected. The root complex will sense which ones are and power down the ones that aren't.
The PCIe lane width negotiation starts from the max number of lanes and works its way down. Lane counts are always a power of 2. So a x4 M.2 card would be lanes 3-2-1-0. x2 would be lanes 1-0. x1 would be lane 0.
PCIe / NVMe can work over 1, 2 or 4 lanes. So if the host only has 1 lane, you can use that to connect an M.2 card.


text:
Q: Twisting a tightly fitting rod Consider the task of extracting a cylindrical rod held by friction in a tightly fitting shaft. Instinctively one would tend to twist the rod around its axis while pulling. The question is,  what is the physical basis for this? Does applying a torque reduce the axial force required?

A: When you pull on the cylinder you apply a force $f_\mathrm{pull}$ between the rod and the shaft. When you twist you apply an additional force $f_\mathrm{twist}$ which acts perpendicularly to $f_\mathrm{pull}$. The total force acting between the rod and shaft is then $\sqrt{f_\mathrm{pull}^2+f_\mathrm{twist}^2}$ which is greater than $f_\mathrm{pull}$ alone.
Why does this help remove the rod? Because the larger force helps you overcome the stiction and thus enables the rod to move.

A: Can we assume that this a non-deformable problem? i.e. Are we talking about something like a metal rod inside a metal tube? If the materials are deformable - e.g. a wine cork in a bottle, then I think there are all sorts of factors to do with the elastic properties of the material that come into play.
So leaving that aside; applying a torque to the stuck item will provide a force that may be able to overcome the static friction, without applying a further normal force to the sides of the tube that might increase the total force required to get the thing out. The problem with just pulling is that inevitably the force is applied non-axially, or the tube is not precisely straight and so an additional, possibly very large, normal force is applied to points along the tube which in turn increases the force required to overcome static friction.

A: I agree with @lemon that the torque may help overcome static friction, however, his/her formula does not look convincing, as, if we applied both forces in the same direction, we would increase the magnitude of the total force.
My hypothesis is if you use axial force only, it is difficult to direct it exactly along the axis, and misalignment increases friction. When the rod starts rotating due to the torque, you only need to add small axial force to slowly extract the rod.


text:
Q: Download handler does not save file shiny R library(shiny)
library(plyr)

shinyServer(function(input, output){

  myfile<-reactive({
#reading 3 csv files and merging them into a dataframe
  })

  output$downloadData<-downloadHandler(

    filename = function(){

      paste("mergedfile","csv",sep='.')
    },

    content= function(file){
      write.csv(myfile(),file,sep=",")
    }
  )

})

I am reading 3-4 files reactively and then merging them. After that without displaying them I need to download the merged file.
I wrote the above code but a dialog box opens which asks me where to save but the file doesn't get saved. Am I doing something wrong with the download handler.
ui.R

downloadButton('downloadData','Download')

This is what I have in my main panel in ui.R file

A: Your probably using the Rstudio viewer to run the app? Open the app in your browser and your code will work
( click open in borwser or run runApp('/path/to/myApp',launch.browser=T) ).
See this link.
Also no need to set sep="," for write.csv since this is the default.


text:
Q: need to implement some route behavior, but don't know how I'm completelly newbie on react and react-native. So i ask to forgive me for possibly stupid question.
I use redux with react-native-router-flux.
First of all, let me describe the behavior what I want.
I have a scene that shows some info about video. The data is fetching from http page. The video have links to another videos - something like "related videos".
On the related video link clicked I need to open new similar scene but vith info of this new video. This vide have relateds too and so on.
So that's what I trying.
A have one scene with key=film. It renders all the info about video. The info fetchs from remote server. On fething it uses this.props.key to identificate the video page. On related video click I called Action.film({key: NEW_VIDEO_KEY}) and new scene opens, takes new data from fetch and shows new video info. And so on. I do this 5 times for example. So 6 scenes was opened (with the first one). But after pressing the BACK button all previous scenes shows the same info as the last one.
I think, it's because of react-router-flux does not remember scenes data but only the route. Each opened scene was modified props, so after the last scene it hase the last props.
I don't understand how to implement needed behavior as I describe at the beginning.
May be I need to add something like history object to the state and after each opened scene push video object to it and on pop scene pop the last video object from the history object... And return the previous object to the previous scene with Action.pop({video: VIDEO_OBJECT})...
But if I showing the related videos in listview I need to save the scroll position of each scene (( And what about hardware back button...
May be I understand something wrong and there is a more complex and simple way...

A: Ok. I found a problem. the problem was in my misunderstanding how all things works together. Now it works well as needed.


text:
Q: Div Lightbox JQueryPlug-in i am searching for a Div Lightbox JQuery Plugin that executes automatically when i enter the web page. Example :www.alljobs.co.il (like the popup div)

A: Any lightbox plugin should be fine, you'd just need run the call for the plugin in the:
$(document).ready(function(){
    // code here
});

Check out Thickbox and look at the "Inline" example down the page.


text:
Q: How do I stop ENTER from adding a newline to my textarea? While working on a chatting application, I've encountered the following problem:
For the user to write his messages, I have implemented a textarea through HTML, and when said user presses enter, it does indeed send the message, but it also adds a newline to said textarea. Can I add something to the end of my EventListener in order to remove the newline? Thanks. (Edit: I need to be able to send the messages with ENTER, but not have the effect of it on my textarea text). Here's my EventListener:
document.addEventListener('keydown', e => {
    if (e.key == "Enter"){
        send();
        //solution goes here...
    }
});

Setting the value of the textarea to "" doing TA.value = ""; didn't work.

A: Event.preventDefault()

document.querySelector('textarea').addEventListener('keydown', e => {
  if (e.key === 'Enter') {
    console.log('send')
    e.preventDefault()
  }
})
<textarea></textarea>


text:
Q: Ruby/Rails Way to Check if object in an Array exists in other Array Think of these lines of code :
@boss_locations = BossLocation.order('min_level asc').all
@discovered = current_user.discovered_locations.includes(:boss_location).all

The first one gets all available boss locations. The second one, gets all the discovered user locations(user_id, boss_location_id) and also includes the boss_location object.
Now, in my view, i want to present every boss location and a message like 'Discovered' or 'Not Discovered', based on whether a boss location exists on @discovered.
Now, my question is how can i feed my view with an easy way to do that. I could just traverse both arrays, but i'm pretty sure it's not the better way. Maybe there is a nice way to map all the boss locations based on the discovered boss locations for the user. How would you do it ?
EDIT - The variables have :
@boss_locations :
 => [#<BossLocation id: 670261930, name: "Fire Swamp", location_index: 1, min_level: 5, needed_gold_to_open: 500, created_at: "2011-05-18 05:35:48", updated_at: "2011-05-18 05:35:48">, #<BossLocation id: 723149845, name: "Rabbit Remains", location_index: 3, min_level: 15, needed_gold_to_open: 3000, created_at: "2011-05-18 05:35:48", updated_at: "2011-05-18 05:35:48">, #<BossLocation id: 81327760, name: "Grateful Plains", location_index: 2, min_level: 10, needed_gold_to_open: 1200, created_at: "2011-05-18 05:35:48", updated_at: "2011-05-18 05:35:48">]

@discovered :
 => [#<DiscoveredLocation id: 736487645, user_id: 986759322, boss_location_id: 670261930, created_at: "2011-05-22 05:37:01", updated_at: "2011-05-22 05:37:01">, #<DiscoveredLocation id: 736487646, user_id: 986759322, boss_location_id: 723149845, created_at: "2011-05-22 05:37:06", updated_at: "2011-05-22 05:37:06">, #<DiscoveredLocation id: 736487647, user_id: 986759322, boss_location_id: 81327760, created_at: "2011-05-22 06:01:35", updated_at: "2011-05-22 06:01:35">]

A: This is a lot of logic to put in a controller or view; consider creating a discovered? method on the BossLocation model. That way you could iterate through @boss_locations and call discovered? on each:
  <% @boss_locations.each do |bl| %>

      <%= "#{bl.name}: #{bl.discovered?(current_user)}" %>

  <% end %>

The method would probably look like this:
class BossLocation < ActiveRecord::Base
  def discovered?(user)
    user.discovered_locations.map(&:boss_location).include?(self)
  end
end

I commented above and you seemed to like the idea, so I wrote it out.

A: To encapsulate your data-model better, you'll want to modify your model class.
class BossLocation < ActiveRecord::Base
  has_many :discovered_locations
  has_many :users, :through => :discovered_locations

  def discovered_by?(user)
    self.users.include?(user)
  end
end

Then all you need in your controller is:
@boss_locations = BossLocation.order('min_level asc').all

And in your view:
<% @boss_locations.each do |boss_location| %>

    <%= boss_location.name %>:
    <%= boss_location.discovered_by?(current_user) ? 'Discovered' : 'Not Discovered' %>

<% end %>

A: As the objects in the two arrays are not identical, you might need to iterate in a custom way:
<% @boss_locations.each do |boss_location|

    <%= boss_location.name %>:
    <%= @discovered_boss_locations.inject('Not Discovered') { |result, element| result = 'Discovered' if element.boss_location_id ==  boss_location.id}

<% end %>