How to make a vertical SeekBar in Android?

Question: Can a SeekBar be vertical? I am not very good at UI design, so how can I make the  SeekBar more beautiful, please give me some templates and examples.
Comment: You have to roll your own implementation. An unfinished version is linked [here](http://stackoverflow.com/questions/631238/modifying-the-android-seekbar-widget-to-operate-vertically) and another [here](http://groups.google.com/group/android-developers/browse_thread/thread/bec05b0368c20e03)
Comment: I recently needed to implement it. Check [this](https://github.com/chanjungkim/VerticalSeekbar) out.
Answer:
For API 11 and later, can use seekbar's XML attributes(android:rotation="270") for vertical effect.
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rotation="270"/>

For older API level (ex API10), only use Selva's answer:
https://github.com/AndroSelva/Vertical-SeekBar-Android
Comment: Solution 1 - rotated SeekBar doesn't work properly. Thumb is drawn away, size and position can't be properly set (at least inside of RelativeLayout).
Comment: Ah, I upvoted you too fast. This hardly works. The slider internally uses the width/height before rotation, so everything is awkwardly positioned and sized.
Comment: It does work, however, you have to keep in mind that dimentions gets swapped, so what used to be width becomes height and so on. So when you increase the height you are actually stretching it that is why the thumb is drawn away, and that happens even with regular seekbar if you stretched the width.

Rotation is annoying, so I think it it easier if you place the seekbar inside a layout and size it correctly then rotate the layout and resize it to fit your main layout.
Comment: It is very annoying: you set the actual height of the SeekBar with the width attribute, but in the remainder of the layout this is still the width of the SeekBar element. If you then give the width attribute of the outer element a smaller value (since you only need a small width for a vertical element), the vertical line of the SeekBar is shortened corresponding to that width. This can be solved by introducing an additional wrapper that still has a large width attribute within the outer container with the small width attribute. But then there is indeed still the thumb offset. I gave up :-p
Comment: This won't work since the slider uses the width for determining the length of the bar!
Comment: please provide link to Selva's answer.
Comment: @Nikhil,Selva's answer is the one accepted by asker above. I think Selva own implement is simple and good !
Comment: I thinked of a an answer from an different post.
Comment: This is a very problematic hack, but I've had success setting the SeekBar's width and height to the desired height, and then setting the left and right margins as negative values to compensate for the excess width in my layout.
Comment: I'm so smart I just can say about rotation 270 without thinking about size and thumb
Answer: Here is a very good implementation of vertical seekbar.
Have a look.
http://560b.sakura.ne.jp/android/VerticalSlidebarExample.zip
And Here is my own implementation for Vertical and Inverted Seekbar based on this
https://github.com/AndroSelva/Vertical-SeekBar-Android
protected void onDraw(Canvas c) {
    c.rotate(-90);
    c.translate(-getHeight(),0);

    super.onDraw(c);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (!isEnabled()) {
        return false;
    }

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
            int i=0;
            i=getMax() - (int) ((getMax()-getMin()) * event.getY() / getHeight());
            setProgress(i);
            Log.i("Progress",getProgress()+"");
            onSizeChanged(getWidth(), getHeight(), 0, 0);
            break;

        case MotionEvent.ACTION_CANCEL:
            break;
    }
    return true;
}

Comment: hey there. I've tried the code you posted as .zip and it works great.. except for one issue: the SeekBar still draws its progress from left to right and not from bottom to top. Haven't found where it's coded. Do you have any suggestions for me? thx
Comment: hi! Love your verticalScrollbar Inverted, I was trying to create one but had a lot of difficulty finding the right rotation and translation. There's one small bug I found anyways: If MAX is not 100, the progress is not calculated correctly. To fix it you have to change (100-i) to (getMax()-i). This way it works perfect for any range.
Comment: @AndroSelva seekbar.setprogress(position) doesnt move vertical seekbar thumb to desired position. ....why so ?
Comment: apparently, i can be negative and larger than max as well here, so I changed it into `Math.max(0, Math.min(getMax(), i)`
Comment: THUMB DOESN'T WORK
Comment: this VerticalScrollBar is drawn incorrectly when put into LinearLayout with weight - but it could be solved by enclosing it with a FrameLayout
Answer: Working example
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class VerticalSeekBar extends SeekBar {

    public VerticalSeekBar(Context context) {
        super(context);
    }

    public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public VerticalSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(h, w, oldh, oldw);
    }

   @Override
   public synchronized void setProgress(int progress)  // it is necessary for calling setProgress on click of a button
   {
    super.setProgress(progress);
    onSizeChanged(getWidth(), getHeight(), 0, 0);
   }
    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    protected void onDraw(Canvas c) {
        c.rotate(-90);
        c.translate(-getHeight(), 0);

        super.onDraw(c);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                setProgress(getMax() - (int) (getMax() * event.getY() / getHeight()));
                onSizeChanged(getWidth(), getHeight(), 0, 0);
                break;

            case MotionEvent.ACTION_CANCEL:
                break;
        }
        return true;
    }
}

There, paste the code and save it. Now use it in your XML layout:
<android.widget.VerticalSeekBar
  android:id="@+id/seekBar1"
  android:layout_width="wrap_content"
  android:layout_height="200dp"
  />

Make sure to create a package android.widget and create VerticalSeekBar.java under this package
Comment: Works perfect! Thanks!
Comment: this isn't giving thumb but just the slider
Comment: try setting your own thumb using android:thumb="@drawable/thumb_image" . But I don't face the issue. http://stackoverflow.com/a/18559778/3496570
Comment: I also have an issue with the thumb with this solution. It is displayed but does not animate (its size does not increase) when moving it as the normal one does.
Comment: @XarEAhmer, Do you know how I can support bidirectional languages like `Arabic` as this `Vertical SeekBar` became upside down and the slider gives false progress direction?
Comment: @XarEAhmer is this from github or did you write it yourself? I'm looking for the license to implement it in my project
Comment: It is somewhere from github .
Answer: Try:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<SeekBar
    android:id="@+id/seekBar1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:rotation="270"
    />

</RelativeLayout>

Comment: Setting rotation rotates the slider but not the layout.  layout_width still controls the length of the slider.  As such the layouts still think it is width not height.  This makes it fun to correctly insert into a design.  I still have not figured out how to put a rotated seek bar on a GridLayout.
Comment: @Mahmoud By adding android:rotation="270"
Answer: I used Selva's solution but had two kinds of issues:

OnSeekbarChangeListener did not work properly
Setting progress programmatically did not work properly.

I fixed these two issues. You can find the solution (within my own project package) at
https://github.com/jeisfeld/Augendiagnose/blob/master/AugendiagnoseIdea/augendiagnoseLib/src/main/java/de/jeisfeld/augendiagnoselib/components/VerticalSeekBar.java
Comment: Works fine, thank you. You should also add a null check for the mOnSeekBarChangeListener variable.
Comment: @JörgEisfeld setting thumb and progressDrawab le failed for me
Comment: @JörgEisfeld, Do you know how I can support bidirectional languages like `Arabic` as this `Vertical SeekBar` became upside down and the slider gives false progress direction?
Comment: @blueware: Play with the lines `c.rotate(-90);` and `c.translate(-getHeight(),0);` - the second line flips it vertically. Try to rotated it +90 or 270 instead of -90 etc. and get ride of the flipping translation.
Answer: We made a vertical SeekBar by using android:rotation="270":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SurfaceView
        android:id="@+id/camera_sv_preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:id="@+id/camera_lv_expose"
        android:layout_width="32dp"
        android:layout_height="200dp"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_marginRight="15dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/camera_tv_expose"
            android:layout_width="32dp"
            android:layout_height="20dp"
            android:textColor="#FFFFFF"
            android:textSize="15sp"
            android:gravity="center"/>

        <FrameLayout
            android:layout_width="32dp"
            android:layout_height="180dp"
            android:orientation="vertical">

            <SeekBar
                android:id="@+id/camera_sb_expose"
                android:layout_width="180dp"
                android:layout_height="32dp"
                android:layout_gravity="center"
                android:rotation="270"/>

        </FrameLayout>

    </LinearLayout>

    <TextView
        android:id="@+id/camera_tv_help"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:text="@string/camera_tv"
        android:textColor="#FFFFFF" />

</RelativeLayout>

Screenshot for camera exposure compensation:
Comment: thanks for the pointer!  the trick is setting the height.... otherwise the framelayout uses the width of the seeker prior to the rotation
Comment: Not working....
Answer: This worked for me, just put it into any layout you want to.
<FrameLayout
    android:layout_width="32dp"
    android:layout_height="192dp">

    <SeekBar
        android:layout_width="192dp"
        android:layout_height="32dp"
        android:layout_gravity="center"
        android:rotation="270" />

</FrameLayout>

Comment: the trick is setting the height.... otherwise the framelayout uses the width of the seeker prior to the rotation
Comment: is this the same answer made earlier by Maxim Mikhisor?
Comment: Not working.....
Answer: Note, it appears to me that if you change the width the thumb width does not change correctly.
I didn't take the time to fix it right, i just fixed it for my case. Here is what i did.
Couldn't figure out how to contact the original creator.
public void setThumb(Drawable thumb) {
    if (thumb != null) {
        thumb.setCallback(this);

        // Assuming the thumb drawable is symmetric, set the thumb offset
        // such that the thumb will hang halfway off either edge of the
        // progress bar.
        //This was orginally divided by 2, seems you have to adjust here when you adjust width.
        mThumbOffset = (int)thumb.getIntrinsicHeight();
    }

Answer: Wrap it inside a FrameLayout so that there is no Size issue.
  <FrameLayout
                android:layout_width="@dimen/_20dp"
                android:layout_marginStart="@dimen/_15dp"
                android:layout_marginEnd="@dimen/_15dp"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <SeekBar
                    android:layout_width="150dp"
                    android:layout_height="30dp"
                    android:layout_gravity="center"
                    android:rotation="270" />
  </FrameLayout>

Comment: best solution so far!
Comment: Not working.....
Answer: When moving the thumb with an EditText, the Vertical Seekbar setProgress may not work. The following code can help:
    @Override
public synchronized void setProgress(int progress) {
    super.setProgress(progress);
    updateThumb();
}

private void updateThumb() {
    onSizeChanged(getWidth(), getHeight(), 0, 0);
}

This snippet code found here:
https://stackoverflow.com/a/33064140/2447726
Answer: Try this
import android.content.Context;
import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.SeekBar;

/**
 * Implementation of an easy vertical SeekBar, based on the normal SeekBar.
 */
public class VerticalSeekBar extends SeekBar {
    /**
     * The angle by which the SeekBar view should be rotated.
     */
    private static final int ROTATION_ANGLE = -90;

    /**
     * A change listener registrating start and stop of tracking. Need an own listener because the listener in SeekBar
     * is private.
     */
    private OnSeekBarChangeListener mOnSeekBarChangeListener;

    /**
     * Standard constructor to be implemented for all views.
     *
     * @param context The Context the view is running in, through which it can access the current theme, resources, etc.
     * @see android.view.View#View(Context)
     */
    public VerticalSeekBar(final Context context) {
        super(context);
    }

    /**
     * Standard constructor to be implemented for all views.
     *
     * @param context The Context the view is running in, through which it can access the current theme, resources, etc.
     * @param attrs   The attributes of the XML tag that is inflating the view.
     * @see android.view.View#View(Context, AttributeSet)
     */
    public VerticalSeekBar(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * Standard constructor to be implemented for all views.
     *
     * @param context  The Context the view is running in, through which it can access the current theme, resources, etc.
     * @param attrs    The attributes of the XML tag that is inflating the view.
     * @param defStyle An attribute in the current theme that contains a reference to a style resource that supplies default
     *                 values for the view. Can be 0 to not look for defaults.
     * @see android.view.View#View(Context, AttributeSet, int)
     */
    public VerticalSeekBar(final Context context, final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);
    }

    /*
     * (non-Javadoc) ${see_to_overridden}
     */
    @Override
    protected final void onSizeChanged(final int width, final int height, final int oldWidth, final int oldHeight) {
        super.onSizeChanged(height, width, oldHeight, oldWidth);
    }

    /*
     * (non-Javadoc) ${see_to_overridden}
     */
    @Override
    protected final synchronized void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    /*
     * (non-Javadoc) ${see_to_overridden}
     */
    @Override
    protected final void onDraw(@NonNull final Canvas c) {
        c.rotate(ROTATION_ANGLE);
        c.translate(-getHeight(), 0);

        super.onDraw(c);
    }

    /*
     * (non-Javadoc) ${see_to_overridden}
     */
    @Override
    public final void setOnSeekBarChangeListener(final OnSeekBarChangeListener listener) {
        // Do not use super for the listener, as this would not set the fromUser flag properly
        mOnSeekBarChangeListener = listener;
    }

    /*
     * (non-Javadoc) ${see_to_overridden}
     */
    @Override
    public final boolean onTouchEvent(@NonNull final MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }

        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            setProgressInternally(getMax() - (int) (getMax() * event.getY() / getHeight()), true);
            if (mOnSeekBarChangeListener != null) {
                mOnSeekBarChangeListener.onStartTrackingTouch(this);
            }
            break;

        case MotionEvent.ACTION_MOVE:
            setProgressInternally(getMax() - (int) (getMax() * event.getY() / getHeight()), true);
            break;

        case MotionEvent.ACTION_UP:
            setProgressInternally(getMax() - (int) (getMax() * event.getY() / getHeight()), true);
            if (mOnSeekBarChangeListener != null) {
                mOnSeekBarChangeListener.onStopTrackingTouch(this);
            }
            break;

        case MotionEvent.ACTION_CANCEL:
            if (mOnSeekBarChangeListener != null) {
                mOnSeekBarChangeListener.onStopTrackingTouch(this);
            }
            break;

        default:
            break;
        }

        return true;
    }

    /**
     * Set the progress by the user. (Unfortunately, Seekbar.setProgressInternally(int, boolean) is not accessible.)
     *
     * @param progress the progress.
     * @param fromUser flag indicating if the change was done by the user.
     */
    public final void setProgressInternally(final int progress, final boolean fromUser) {
        if (progress != getProgress()) {
            super.setProgress(progress);
            if (mOnSeekBarChangeListener != null) {
                mOnSeekBarChangeListener.onProgressChanged(this, progress, fromUser);
            }
        }
        onSizeChanged(getWidth(), getHeight(), 0, 0);
    }

    /*
     * (non-Javadoc) ${see_to_overridden}
     */
    @Override
    public final void setProgress(final int progress) {
        setProgressInternally(progress, false);
    }
}

Comment: This approach has a flaw - reported `progress` can become less than min or max value if user continues to drag the thumb outside the bounds of the view.
Comment: Yes, i See the issue when we rapid to move the Seek thumb.
Answer: I tried in many different ways, but the one which worked for me was.
Use Seekbar inside FrameLayout
<FrameLayout
    android:id="@+id/VolumeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/MuteButton"
    android:layout_below="@id/volumeText"
    android:layout_centerInParent="true">
        <SeekBar
        android:id="@+id/volume"
        android:layout_width="500dp"
        android:layout_height="60dp"
        android:layout_gravity="center"
        android:progress="50"
        android:secondaryProgress="40"
        android:progressDrawable="@drawable/seekbar_volume"
        android:secondaryProgressTint="@color/tint_neutral"
        android:thumbTint="@color/tint_neutral"
    />

And in Code.
Setup Pre Draw callback on Seekbar, Where you can change the Width and height of the Seekbar
I did this part in c#, so Code i used was
            var volumeSlider = view.FindViewById<SeekBar>(Resource.Id.home_link_volume);

            var volumeFrameLayout = view.FindViewById<FrameLayout>(Resource.Id.linkVolumeFrameLayout);

            void OnPreDrawVolume(object sender, ViewTreeObserver.PreDrawEventArgs e)
            {
                volumeSlider.ViewTreeObserver.PreDraw -= OnPreDrawVolume;
                var h = volumeFrameLayout.Height;
                volumeSlider.Rotation = 270.0f;
                volumeSlider.LayoutParameters.Width = h;
                volumeSlider.RequestLayout();
            }

            volumeSlider.ViewTreeObserver.PreDraw += OnPreDrawVolume;

Here i Add listener to PreDraw Event and when its triggered, I remove the PreDraw so that it doesnt go into Infinite loop.
So when Pre Draw gets executed, I fetch the Height of FrameLayout and assign it to Seekbar. And set the rotation of seekbar to 270.
As my seekbar is inside frame Layout and its Gravity is set as Center. I dont need to worry about the Translation. As Seekbar always stay in middle of Frame Layout.
Reason i remove EventHandler is because seekbar.RequestLayout(); Will make this event to be executed again.
Answer: By using RotateLayout, having vertical SeekBar is a breeze. Just wrap that horrible SeekBar into it and Bob is your uncle:
<com.github.rongi.rotate_layout.layout.RotateLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:angle="-90"
    >

        <androidx.appcompat.widget.AppCompatSeekBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
        />

</com.github.rongi.rotate_layout.layout.RotateLayout>

https://github.com/rongi/rotate-layout
Answer: Getting started
Add these lines to build.gradle.
dependencies {
    compile 'com.h6ah4i.android.widget.verticalseekbar:verticalseekbar:0.7.2'
}

Usage
Java code
public class TestVerticalSeekbar extends AppCompatActivity {
    private SeekBar volumeControl = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_vertical_seekbar);

        volumeControl = (SeekBar) findViewById(R.id.mySeekBar);

        volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int progressChanged = 0;

            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progressChanged = progress;
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                Toast.makeText(getApplicationContext(), "seek bar progress:" + progressChanged,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

}

Layout XML

<com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBarWrapper
    android:layout_width="wrap_content"
    android:layout_height="150dp">
    <com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBar
        android:id="@+id/mySeekBar"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:max="100"
        android:progress="0"
        android:splitTrack="false"
        app:seekBarRotation="CW90" />
</com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBarWrapper>

NOTE: android:splitTrack="false" is required for Android N+.
Answer: In my case, I used an ordinary seekBar and just flipped out the layout.
seekbark_layout.xml - my layout that containts seekbar which we need to make vertical.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"/>

</RelativeLayout>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.vgfit.seekbarexample.MainActivity">

<View
    android:id="@+id/headerView"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:background="@color/colorAccent"/>

<View
    android:id="@+id/bottomView"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_alignParentBottom="true"
    android:background="@color/colorAccent"/>

<include
    layout="@layout/seekbar_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/bottomView"
    android:layout_below="@id/headerView"/>

 </RelativeLayout>

And in MainActivity I rotate seekbar_layout:
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.RelativeLayout
import kotlinx.android.synthetic.main.seekbar_layout.*

class MainActivity : AppCompatActivity() {

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

    rootView.post {
        val w = rootView.width
        val h = rootView.height

        rootView.rotation = 270.0f
        rootView.translationX = ((w - h) / 2).toFloat()
        rootView.translationY = ((h - w) / 2).toFloat()

        val lp = rootView.layoutParams as RelativeLayout.LayoutParams
        lp.height = w
        lp.width = h
        rootView.requestLayout()
    }
}
}

As a result we have necessary vertical seekbar:
Answer: You can do it by yourself -  it's now so difficult.
Here is an example from my project: https://github.com/AlShevelev/WizardCamera
Let start from settings (attrs.xml).
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ExpositionBar">
        <attr name="button_icon" format="reference" />
        <attr name="button_icon_size" format="dimension" />

        <attr name="stroke_width" format="dimension" />

        <attr name="stroke_color" format="color" />
        <attr name="button_color" format="color" />
        <attr name="button_color_pressed" format="color" />

        <attr name="min_value" format="float" />
        <attr name="max_value" format="float" />
    </declare-styleable>
</resources>

Here is a couple of utility functions:
fun <T: Comparable<T>>T.fitInRange(range: Range<T>): T =
    when {
        this < range.lower -> range.lower
        this > range.upper -> range.upper
        else -> this
    }

fun Float.reduceToRange(rangeFrom: Range<Float>, rangeTo: Range<Float>): Float =
    when {
        this == rangeFrom.lower -> rangeTo.lower
        this == rangeFrom.upper -> rangeTo.upper
        else -> {
            val placeInRange = (this - rangeFrom.lower) / (rangeFrom.upper - rangeFrom.lower)
            ((rangeTo.upper - rangeTo.lower) * placeInRange) + rangeTo.lower
        }
    }

And at last, but not least - a class for vertical seek bar:
class ExpositionBar
@JvmOverloads
constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val drawingRect = RectF(0f, 0f, 0f, 0f)
    private val drawingPaint = Paint(Paint.ANTI_ALIAS_FLAG)

    private val strokeWidth: Float

    @ColorInt
    private val strokeColor: Int
    @ColorInt
    private val buttonFillColor: Int
    @ColorInt
    private val buttonFillColorPressed: Int

    private val icon: VectorDrawable

    private val valuesRange: Range<Float>

    private var centerX = 0f
    private var minY = 0f
    private var maxY = 0f

    private var buttonCenterY = 0f
    private var buttonRadiusExt = 0f
    private var buttonRadiusInt = 0f
    private var buttonMinY = 0f
    private var buttonMaxY = 0f
    private var buttonCenterBoundsRange = Range(0f, 0f)

    private var iconTranslationX = 0f
    private var iconTranslationY = 0f

    private var isInDragMode = false

    private var onValueChangeListener: ((Float) -> Unit)? = null

    private var oldOutputValue = Float.MIN_VALUE

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpositionBar)

        icon =  typedArray.getDrawable(R.styleable.ExpositionBar_button_icon) as VectorDrawable
        val iconSize = typedArray.getDimensionPixelSize(R.styleable.ExpositionBar_button_icon_size, 0)
        icon.setBounds(0, 0, iconSize, iconSize)

        strokeWidth = typedArray.getDimensionPixelSize(R.styleable.ExpositionBar_stroke_width, 0).toFloat()
        drawingPaint.strokeWidth = strokeWidth

        strokeColor = typedArray.getColor(R.styleable.ExpositionBar_stroke_color, Color.WHITE)
        buttonFillColor = typedArray.getColor(R.styleable.ExpositionBar_button_color, Color.BLACK)
        buttonFillColorPressed = typedArray.getColor(R.styleable.ExpositionBar_button_color_pressed, Color.BLUE)

        val minValue = typedArray.getFloat(R.styleable.ExpositionBar_min_value, 0f)
        val maxValue = typedArray.getFloat(R.styleable.ExpositionBar_max_value, 0f)
        valuesRange = Range(minValue, maxValue)

        typedArray.recycle()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        drawingRect.right = width.toFloat()
        drawingRect.bottom = height.toFloat()

        buttonCenterY = drawingRect.centerY()

        recalculateDrawingValues()
    }

    override fun onDraw(canvas: Canvas) {
        drawingPaint.color = strokeColor
        drawingPaint.style = Paint.Style.STROKE

        // Draw the center line
        canvas.drawLine(centerX, minY, centerX, buttonMinY, drawingPaint)
        canvas.drawLine(centerX, buttonMaxY, centerX, maxY, drawingPaint)

        // Draw the button
        canvas.drawCircle(centerX, buttonCenterY, buttonRadiusExt, drawingPaint)
        drawingPaint.style = Paint.Style.FILL
        drawingPaint.color = if(isInDragMode) buttonFillColorPressed else buttonFillColor
        canvas.drawCircle(centerX, buttonCenterY, buttonRadiusInt, drawingPaint)

        // Draw button icon
        canvas.translate(iconTranslationX, iconTranslationY)
        icon.draw(canvas)
        canvas.translate(-iconTranslationX, -iconTranslationY)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if(!isEnabled) {
            return false
        }

        when(event.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                if(isButtonHit(event.y)){
                    isInDragMode = true
                    invalidate()
                }
            }
            MotionEvent.ACTION_MOVE -> {
                if(isInDragMode) {
                    buttonCenterY = event.y.fitInRange(buttonCenterBoundsRange)
                    recalculateDrawingValues()
                    invalidate()

                    val outputValue = buttonCenterY.reduceToRange(buttonCenterBoundsRange, valuesRange)
                    if (outputValue != oldOutputValue) {
                        onValueChangeListener?.invoke(outputValue)
                        oldOutputValue = outputValue
                    }
                }
            }
            MotionEvent.ACTION_UP,
            MotionEvent.ACTION_CANCEL -> {
                isInDragMode = false
                invalidate()
            }
        }
        return true
    }

    fun setOnValueChangeListener(listener: ((Float) -> Unit)?) {
        onValueChangeListener = listener
    }

    private fun recalculateDrawingValues() {
        centerX = drawingRect.left + drawingRect.width()/2
        minY = drawingRect.top
        maxY = drawingRect.bottom

        buttonRadiusExt = drawingRect.width() / 2 - strokeWidth / 2
        buttonRadiusInt = buttonRadiusExt - strokeWidth / 2
        buttonMinY = buttonCenterY - buttonRadiusExt
        buttonMaxY = buttonCenterY + buttonRadiusExt

        val buttonCenterMinY = minY + buttonRadiusExt + strokeWidth / 2
        val buttonCenterMaxY = maxY - buttonRadiusExt - strokeWidth / 2
        buttonCenterBoundsRange = Range(buttonCenterMinY, buttonCenterMaxY)

        iconTranslationX = centerX - icon.bounds.width() / 2
        iconTranslationY = buttonCenterY - icon.bounds.height() / 2
    }

    private fun isButtonHit(y: Float): Boolean {
        return y >= buttonMinY && y <= buttonMaxY
    }
}

You can use it as shown here:
<com.shevelev.wizard_camera.main_activity.view.widgets.ExpositionBar
    android:id="@+id/expositionBar"
    android:layout_width="@dimen/mainButtonSize"
    android:layout_height="300dp"
    android:layout_gravity="end|center_vertical"

    android:layout_marginEnd="@dimen/marginNormal"
    android:layout_marginBottom="26dp"

    app:button_icon = "@drawable/ic_brightness"
    app:button_icon_size = "@dimen/toolButtonIconSize"
    app:stroke_width = "@dimen/strokeWidthNormal"
    app:stroke_color = "@color/mainButtonsForeground"
    app:button_color = "@color/mainButtonsBackground"
    app:button_color_pressed = "@color/mainButtonsBackgroundPressed"
    app:min_value="-100"
    app:max_value="100"
/>

Voila!
Answer: Hidden Vertical SeekBar

In a simpler way, you can make a SeekBar like this.
Like the way to increase or decrease the volume in video players. All
three Last attributes can be manipulated in the SeekBar.

<LinearLayout
        android:layout_width="@dimen/_40dp"
        android:layout_height="wrap_content"
        android:layout_marginVertical="100dp"
        android:gravity="center"
        android:orientation="vertical"
        >
        <SeekBar
            android:layout_width="500dp"
            android:layout_height="300dp"
            android:layout_gravity="center"
            android:rotation="270"
            android:secondaryProgress="6"
            android:progress="15"
            android:progressDrawable="@null"
            android:thumbTint="@null"
            android:secondaryProgressTint="@null"
            />
    </LinearLayout>

Answer: I made vertical seekbar library years ago for solve this see:

https://github.com/ASE55471/Android-VSlider

This library does not rotate original seekbar 90 or 270 degree, It's rewrite from scratch for resolve "Thumb not in the right place", "Can't set position from code", "Can't line up background drawable", "Touch position run away" etc. And also have some extra useful feature.
Answer: Simple answer
Instead of using android:rotation="270" inside of a seek bar, use it inside of a FrameLayout that wraps around it.
 <FrameLayout
    android:background="@color/gray"
    android:layout_width="300dp"
    android:layout_height="5dp"
    android:layout_marginEnd="-126dp"
    android:rotation="270"
    android:orientation="vertical"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent">
<SeekBar
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />
</FrameLayout>

To get my frame layout to be 24dp margin right I calculated width -150dp + 24dp because the frame layout is first drawn horizontally and then rotated vertically.
Comment: Not working....


website says connection insecure if typed without the protocol

Question: I have a website and when I type the url with 'https://' the browser shows the site normally, however if I do not include 'https://' in the url, the browser brings me to a page that says my connection is not secure.  I keep adding things to my htaccess but nothing seems to be working.
I think this issue is related to something missing from my htaccess file, but I do not know what to add.  Can someone please either tell me what to add and/or point me to a good resource? Thanks.
Comment: You might need to configure an HTTP to HTTPS redirect.
Comment: @Ace I keep trying that and it is not fixing anything.  What code should I use?
Comment: I made an answer post, easier to share code
Answer: Add this to your .htaccess (I'm assuming you use Apache)
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]

Also do an apache2ctl -k graceful after you changed the .htaccess
Comment: this appears to have fixed it on desktop but mobile still shows the same error.  That is to say, when I type the URL with no 'https://' in the beggining, on a desktop browser the site is shown normall but on an iPhone the browser shows a "connection inseccure" page.  It is a bit different now though: the url becomes the IP of the server.
Answer: I would not use a htaccess file to do this - I would create a virtualhost with a permanent redirect to achieve this:
<VirtualHost *:80>
        ServerName www.yourdomain.com
        ServerAdmin firstname.lastname@example.com
        Redirect /  https://www.yourdomain.com

        ErrorLog ${APACHE_LOG_DIR}/http_error.log
        CustomLog ${APACHE_LOG_DIR}/http_access.log combined
</VirtualHost>

Comment: I have not created a virtualhost before.  What file do I add this code to and are there any other steps?
Comment: this heavily depends on the OS / distribution you are using. In Ubuntu for example, you create a file ```http-redirect.conf``` inside the directory ```/etc/apache2/sites-available```, and afterwards, you execute ```a2ensite http-redirect``` to enable the virtualhost definition (this creates a link to the config inside the directory ```/etc/apache2/sites-enabled``` ). And of course, don't forget to reload / restart your apache2...
Comment: I shouldn't use the file already in that directory, 000-default.conf or default-ssl.conf?


How to define prior for beta-binomial A/B test

Question: I would like to run an A/B test using a Bayesian beta-binomial model whereby I would state probabilities such as $P(p_B>p_A)$ in place of using a traditional T-test. I've read that the prior should be constructed as $f(a,b) \sim (a+b)^{-\frac{5}{2}}$.  How exactly is this done?  I'm looking for an actual example of this step of the modeling process.
Here is my A/B test data by day formatted as: date, A enrollments, A conversions, B enrollments, B conversions.
<code>10/1/2015,150,16,148,17
10/2/2015,163,17,165,19
10/3/2015,155,14,157,18
10/4/2015,161,15,153,19
10/5/2015,148,14,150,16
</code>
Answer: I'm not sure what that prior represents, but from what you're looking to do, you should set up some Beta prior with your Bernoulli likelihood.
The posterior distribution of a Beta-Bernoulli is:
$$\sim Beta (a_0 + \sum{x_i} , b_0 + n - \sum{x_i})$$
where $\frac{a_0}{a_0 + b_0}$ is your prior conversion rate. The size of $a_{0}$ and $b_0$ represent the strength of belief in your prior. And $\sum{x_i}$ is the number of conversions you observe for a given day.
Now how you want to model it is up to you. You could model a conversion rate per day, or a cumulative conversion rate. You'll want to update the model for new data that comes in each day. You also must assume that each data point is independent of the others, which is a strong (perhaps invalid) assumption, especially if you have repeat visitors.
In the end you'll have a posterior distribution for $A$ and $B$. Then you could sample from those posteriors and count how many times $B > A$, which is your $P(B>A)$. You could also provide other posterior summaries, perhaps calculate a credible interval for $B - A$, or do any number of Bayesian posterior summaries. Also don't forget to calculate the power of the test to ensure you have a sufficient sample size.
Answer: In beta-binomial model beta distribution is a prior for binomial distribution. It is co-called conjugate prior, i.e. there exists closed form for beta-binomial distribution.
If you recall, Bayes theorem states that to obtain posterior we need likelihood function and a prior
$$ \underbrace{P(\theta|D)}_\text{posterior} \propto \underbrace{P(D|\theta)}_\text{likelihood} \times \underbrace{P(\theta)}_\text{prior} $$
then in beta-binomial model you use binomial distribution as a likelihood function and beta distribution as prior for $p$ parameter in binomial distribution, i.e.
$$ x_i \sim \mathrm{Binomial}(n, p) $$
$$ p \sim \mathrm{Beta}(\alpha, \beta) $$
where you need to assume some $\alpha$ and $\beta$ parameters for beta. If you want to assume that each value of $p$ has the same probability, i.e. you have no out-of-data (prior) information that you would like to include in your model, that you can set $\alpha = \beta = 1$, that is uniform for all the values of $p$ in $[0,1]$ interval. You can look at this thread for understanding beta distribution better, so it is easier for you to choose other values of $\alpha$ and $\beta$ if needed.
You can find code example of such A/B test, you cal look at this thread. If you are looking for examples, I would recommend this blog entry by Rasmus Bååth on binomial test implemented in Bayesian First Aid package for R. This topic is also covered in probably any handbook on Bayesian data analysis, e.g. Gelman eta al. (2004), or Kruschke (2010). Google search also reveals multiple worked examples of such model (e.g. this blog for introductory example).

Gelman, A., Carlin, J.B., Stern, H.S., and Rubin, D.B. (2014). Bayesian data analysis. London: Chapman & Hall/CRC.
Kruschke, J. (2010). Doing Bayesian data analysis: A tutorial introduction with R. Academic Press.


What is the correct spelling and capitalization of "Naive Bayes"?

Question: I wonder which form(s) are correct amongst the following:

Naive Bayes (example: Tom Mitchell's chapter on Naive Bayes)
naive Bayes (example: the Wikipedia page on naive Bayes)

I have also read some documents that added a diaeresis on the i, i.e. Naïve Bayes or naïve Bayes, probably reflecting the French etymology of the adjective naive.
Answer: All the forms are commonly used:, it probably depends rather on each writer's personal style and on the style guide of the publisher of the text where the phrase appeared.
Bayes is always capitalized since it is a surname.
"naive" is or is not capitalized depending on a writer's style. It could be capitalized if a writer capitalizes all names of methods (e.g. Tom Michell, quoted by you, seems to capitalize also "Maximum a Posteriori", or "Maximum Likelihood Estimation"). It could be lowercase if all names are written lowercase (see similar example of distributions names). "Naïve" is just a alternative spelling for "naive" so it is just a question of spelling convention used by the writer.
See also https://english.stackexchange.com/questions/14/which-words-in-a-title-should-be-capitalized and https://english.stackexchange.com/questions/6560/when-should-you-use-title-case
Comment: I've edited for style. I've left unedited your comment on Bayes. Strictly, it's not correct that Bayes is **always** capitalized as I've often seen it all lower case. I agree personally that it's better to capitalize it. But words based on personal names can become accepted over time as all lower case. I'd not seen any one suggest that we are wrong to write "boycott".although the word comes from a person called Boycott.


Issues with saving an object in session

Question: In my project, I have this line, in the core file:
$LoggedIn = isset($_SESSION['User']) ? unserialize($_SESSION['User']) : false;

Core: http://pastebin.com/9HMP11bG
and under the login method, it has the corrosponding:
$_SESSION['User'] = serialize($User);

User Repo: http://pastebin.com/vNehc2Hm
User: http://pastebin.com/4UXT79MU
When I try to access the $LoggedIn object, it gives me an error like this:
Fatal error: Uncaught Error: Cannot use object of type __PHP_Incomplete_Class as array in C:\xampp\htdocs\jalawebs\dev\webcofounder\web\controller\index\index.php:14 Stack trace: #0 C:\xampp\htdocs\jalawebs\dev\webcofounder\config\core.php(111): require() #1 C:\xampp\htdocs\jalawebs\dev\webcofounder\index.php(9): require('C:\\xampp\\htdocs...') #2 {main} thrown in C:\xampp\htdocs\jalawebs\dev\webcofounder\web\controller\index\index.php on line 14

Answer: This happens when you call to a property of an unserialized object that is not defined in the script itself.
Creating a class like so new User() will invoke the autloader to load the script where unserialize() does not.
You could do the following:
$o = unserialize($yourstring);
if(is_object($o) && class_exists(get_class($o))){ // invoke the autoloader
  echo $o->LoggedIn;
}

Or just include the script directly with include_once() or require_once().
Comment: So it's not enough the script is being included in another file, which is included on the page?

Issues with saving an object in session


How do we make the "intuitive calculation" of conditional probability, rigorous?

Question: The definition of Conditional Probability for events $A$ and $B$ in sample space $S$ is $$\mathbb{P}(A|B)=\frac{\mathbb{P}(A\cap B)}{\mathbb{P}(B)}.$$
Sometimes, we use a rearranged version of this formula to calculate the probability of the intersection of events - called the multiplicative law of probability:
$$\mathbb{P}(A\cap B)=\mathbb{P}(A|B)\times \mathbb{P}(B)$$
When using this formula, how does one calculate $\mathbb{P}(A|B)?$ Since by definition the intersection is required to find the conditional probability? Is there an alternative definition/way to compute the conditional probability when you don't know the intersection?
I have calculated the conditional probability through intuition many times (E.g. picking Red/Blue marbles out of a bag, without replacement), but I was wondering if there was some sort of standard convention on how calculate the conditional probability when you don't know the intersection?
Example.
Say we have three people (Alex, Bob, Carol) with their three hats. Say I take all their hats, mix them up, and then return one to each person. What is the probability that person A and B get exactly their own hat back?
"Solution": The way I would think of it is: Let $E_A$ and $E_B$ be the events that Alex and Bob get their hats back respectively. Then,
$$\mathbb{P}(E_A\cap E_B)= \mathbb{P}(E_B)\times \mathbb{P}(E_A|E_B)$$
The probability of $E_B$ would be $\frac{1}{3}$. Now, the way I would calculate $\mathbb{P}(E_A|E_B) $ intuitively, even though I don't know what the intersection is (because that's what I'm trying to find), is "Since Bob has his hat, I have two hats left, which gives a probability of $\frac{1}{2}$ for Alex to get his hat back."
This intuitive logic of getting to the conditional probability directly, when I didn't use/bypassed the definition, is what I would like to clarify/formalise.
Comment: You might consider changing the title and editing the question body to emphasize that. Currently it sounds like you're just looking for any formula whatsoever that doesn't involve the intersection (which probably exists, but would be very context-specific, so that question would be too broad).
Comment: Are you asking if there's a formula which makes rigorous the kind of process you use to calculate the conditional probability "intuitively"?
Comment: Yes, @JackM, exactly right
Since it appears we are calculating it differently based on the worded intuition/idea of conditional probability being "given this happened, what is the chance this other thing happens" (even when the intersection might be unknown, or the thing we are exactly trying to calculate)
Comment: @JackM I've added an example and modified the title. Does this emphasize my question?
Comment: Yes. I wrote my answer before you added your example. I'll think about your example and see if I can address it specifically.
Comment: @JackM, Thanks! That's exactly what I was thinking about. If you could bridge your answer with this example, that would be really helpful (which maybe would surface some sort of pattern/process behind the intuition)
Answer: Say we have a bag with a red marble and two blue marbles. We draw two marbles. What is the probability they're both different colors? If we draw red on the first turn, we have a 100% chance of drawing different colors. If we draw blue, we have a 50% chance. So we have a $\frac23$ chance of drawing different overall. Clearly, I've used the conditional distribution of the event "drawing different colors" given the color of the first marble. How did I do it?
It turns out that formally, the answer is fairly boring. I did it by assuming that the conditional distributions are as I say they are in the very statement of the problem. When you talk about "drawing without replacement", you're basically saying the following:

There is a set $M=\{r, b_1, b_2\}$ of marbles.
There are two marble-valued random variables, $X_1$ and $X_2$.
$X_1$ is uniform on $M$.
$X_2$ is uniform on $M\setminus\{X_1\}$.

This isn't a proper mathematical description. The problem is point 4. When you describe a random variable as being "uniform on $A$", $A$ has to be a set. But $M\setminus\{X_1\}$ is not a set, it's a set-valued random variable. So how do I give a formal meaning to point 4? All I can really do is just directly assert that $X_2$ has the conditional distribution I expect it to have:

The conditional distribution of $X_2$ given $X_1=x$ is uniform on $M\setminus\{x\}$.
Answer: This doesn't answer the question exactly, but is a bit much for a comment:
Sometimes the conditional probability is already known. For example, let $\{X_n:n=0,1,2,\ldots\}$ be a Markov chain on the nonnegative integers with initial distribution $\alpha$ and transition matrix $P$, that is, for each nonnegative integer $i$ we have $\mathbb P(X_0=i)=\alpha_i$ and for each pair of nonnegative integers $i,j$ we have
$$
\mathbb P(X_{n+1} = j\mid X_n = i) = P_{ij},
$$
(the $(i,j)$-entry of $P$). Then, the distribution of $X_1$ would be given by
$$
\mathbb P(X_1 = j) = \sum_{i=0}^\infty \mathbb P(X_1 = j\mid X_0=i)\mathbb P(X_0=i) = \sum_{i=0}^\infty P_{ij}\alpha_i.
$$
Comment: Worth noting that our answers are basically the same. The kind of marble game I describe is basically an implicit description of a Markov chain.
Answer: There is not one formula, but there is a process.   You are using this process, and it is correct to do so when you can.
You should have some model for measuring your probability, and you might be able to adjust this model to evaluate a conditional probability.   If you can do so, then you may do so.
As long as your model is consistent, it will not matter which approach you take -- calculate the joint from the conditional and a marginal, or a conditional from the joint and a marginal -- though one route may seem easier than another … and that's why we often use Bayes' Rule after all.

For instance, in your bag of red and blue marbles example, your model is that each marble in the bag (at the time of drawing) is equally likely to be selected (that there is no bias), so you may therefore evaluate probabilities using the counts of marbles of each colour in the bag.
$$\textsf{The conditional probability that the second marble is red, when given that the first is blue,}\\\textsf{assuming that there were originally $m$ red and $n$ blue marbles in the bag, will be}\\\mathsf P(R_2\mid B_1)=\dfrac{m}{m+n-1}\\\textsf{The probability that we first draw a red marble and secondly a blue,}\\\textsf{ when drawing two marbles from the bag without replacement, is:}\\\mathsf P(B_1\cap R_2){=\dfrac{\binom n1\binom m1/2!}{\binom{m+n}{2}}\\=\dfrac{n\cdot m}{(m+n)(m+n-1)}}$$

Your hat example is similar, and your thinking is correct.   If Bob happens to have his hat when the hats were distributed without bias, then Alan either had his own hat or Carol's with equal probability.
Alternatively: When the hats are distributed without bias, there are six equally probable ways to do so, among which only one way will give Alan and Bob their own hats. However, there are two ways among the six that Bob could have his own hat back.$$\mathsf P(E_A\cap E_B)=\tfrac{1}{3!}\\\mathsf P(E_B)=\tfrac {2!}{3!}\\\therefore\quad\mathsf P(E_A\mid E_B)=\tfrac 1{2!}$$


Should fingers always play perpendicular to the keys?

Question: When looking at the reflection of the fallboard, I've noticed my fingers do not hit the keys straight from above. Instead, my hands are not fully pronated and fingers hit the keys at an angle of up to 45 degrees outwards.
Is this considered bad technique? Pronating my arms so that fingers play straight is possible, though it causes my elbows to go out to the side, which feels unnatural.
Comment: Have a good look at quite a few who play the piano really well. In different styles. You'll become aware that although purists will say there's a proper way to play, a lot of players do anything but, and still manage to do amazing things. There's an awful lot more than mere hand positioning. And, bear in mind we're all of different proportions so there isn't one perfect way to suit all.
Comment: I'm not sure you're using pronated and supinated correctly here, in terms of hands.
Comment: @Todd Wilcox You are right. I've replaced "supinated" with "not fully pronated". Just to be clear ; with pronation I mean rotating the right forearm anti clockwise.
Comment: That's how I was interpreting it also. Your hands should be more or less prone in a relaxed position. The knuckles for your index and middle fingers should be the highest point on the top of your hands. If you rest your hand on a flat surface, all of your fingers and the side of your thumb should be touching at about the same time. You should be able to achieve that with relaxed elbows. You might have to raise your seat until just before your knees hit the underside of the piano.
Comment: When you say "up to 45 degrees outwards", does that mean that when you play the highest note on the keyboard, your 3rd (middle) finger is at an angle of 45 degrees with respect to the keys? If so, that seems fine for single notes, but for chords I'd recommend *leaning* your body to the side to limit your angle away from the key orientation to about 20 degrees for the outer hand and maybe slightly more for the inner hand. (By "inner" here, I mean the one on the opposite side of the side you're leaning toward, so the left hand for high notes and the right hand for low notes.)
Answer: Your fingers shouldn't "hit" the keys, nor should they be little straight sticks.
Here are some bullet points to get you on track:

Back should be straight and tall with relaxed shoulders.
Distance from fallboard should have arms very nearly straight (not hyper-extended) when touching with closed fist. (When playing the keyboard, elbows should approximate a comfortable 90-degree angle.
Wrists should be level with ceiling.
Fingers should be gently curved (think capital "C" shape) and hand relaxed.
Keys pressed with pad of fingertip using firm fingers (i.e. not letting the first joint on your fingers pivot).

Hope that helps.
Comment: @StefanBroeder With relaxed shoulders, your elbows should fall more or less straight down. That means you may have to angle your lower arm outwards or inwards to reach the keys you want to play. As you go farther left or right, you may have to spread your elbows out, and even lean to one side or the other. You might watch some great pianists on YouTube to see how they do it, but take it with a grain of salt as many have unusual techniques that work for *them* but won't necessarily work for you.
Comment: No, my fingers are certainly curved. I'm talking about the lateral angle here. So imagine the right hand playing a C chord, but the forearm is rotated to the right.
Comment: Capital C sounds like **way** too much curvature.
Answer: One of my early teachers would place a pencil on the back of the hands, and then ask for a scale.  If you can do that you are probably OK.
What is perhaps more important from the stand point of avoiding Repetitive Stress Injury (Carpal Tunnel, etc. ) is the angle of the wrist - which should be fairly flat. The more bend in the wrist, up or down, the more chance of nerve damage and also the slower the fingers will move.


AWS Serverless Image Handler - Version 5 - Lambda running on Node.js 12 End of Life

Question: I've recently taken over a project that has AWS Serverless Image Handler version 5 implemented. And I've been sent various emails from the client they received about Node.js v12 hitting end of life and the Lambda functions needing to run on a new Node.js runtime.
Having a looking through the AWS account, I've seen I can just switch the runtime to Node.js v14 or v16, but do I need to do any code updates?
Sorry a complete noob to Lambda, and the CloudFormation stacks etc
Thought I would ask before I jump down the rabbit hole and look at setting up my own copy of Serverless Image Handler and doing some testing, or even trying to implement version 6.
Answer: This depends of the code / imported libraries in the Serverless Image Handler Lambda.
I would check if there are breaking changes in Node14, that could affect the code.
This does not have anything to do with Lambda / CF itself.


Passing pointer to array of objects into function

Question: When I run this code it crashes with out any errors. I have tried everything i know and done searches but i can figure this one out. It builds and runs fine and goes all the way to the cout in FleetCapacity and something about that line is making the code crash . When i commented out that line the code ran fine so im not sure as to why that line of code is causing my program to crash and burn.
#include <iostream>
#include <string>
using namespace std;

class Ship{
private:
    string shipName;
    string shipYear;
public:
    Ship(string sN,string sY){shipName=sN; shipYear=sY;}
    virtual void printInfo();
    void setShipName(string);
    virtual string getShipName();
    void setShipYear(string);
    string getShipYear();
};

class CruiseShip:public Ship{
private:
    int maxPass;
    int maxCrew;
public:
    CruiseShip(string sN,string sY, int mP,int mC):Ship(sN,sY){setShipName(sN);maxPass=mP; maxCrew=mC; }
    void printInfo();
    void setMaxPass(int);
    int getMaxPass();
    void setMaxCrew(int);
    int getMaxCrew();
};

class CargoShip:public Ship{
private:
    int cargoCap;
public:
    CargoShip(string sN,string sY,int cC):Ship(sN,sY){setShipName(sN);cargoCap=cC;}
    void printInfo();
    void setCargoCap(int);
    int getCargoCap();

};

void Ship::setShipName(string sN){shipName=sN;}
string Ship::getShipName(){return shipName;}
void Ship::setShipYear(string sN){shipYear=sN;}
string Ship::getShipYear(){return shipYear;}
void Ship::printInfo(){
cout<<"The ships name is "<<shipName<<endl;
cout<<"The ships year is "<<shipYear<<endl;
}

void CruiseShip::printInfo(){
cout<<"The ships name is "<<getShipName()<<endl;
cout<<"The ships maximum passangers is "<<maxPass<<endl;
}
void CruiseShip::setMaxPass(int mP){maxPass=mP;}
int CruiseShip::getMaxPass(){return maxPass;}
void CruiseShip::setMaxCrew(int mC){maxCrew=mC;}
int CruiseShip::getMaxCrew(){return maxCrew;}

void CargoShip::printInfo(){
cout<<"The ships name is "<<getShipName()<<endl;
cout<<"The ships cargo capacity is "<<cargoCap<<endl;
}
int CargoShip::getCargoCap(){return cargoCap;}
void CargoShip::setCargoCap(int cC){cargoCap=cC;}

void fleetCapacity(Ship** s ,int e){

    cout << "Name of ship: " << s[e]->getShipName() << endl;

}

int main()
{
    const int NUMSHIPS = 3;
    //int aSize = NUMSHIPS;
    // array of ship pointers initialized with addresses of dynamically allocated class objects.
    Ship *ships[NUMSHIPS] = {
                                         new Ship("The Dinghy Berry", "1982"),
                                         new CruiseShip("Disney Adventure Tours"," ",500,100),
                                         new CargoShip("The Sea Trucker"," ", 50)

                                       };

    for (int i = 0; i < NUMSHIPS; i++ )
    {
        ships[i]->printInfo();
    }

   cout << "The entire fleet capacity is: ";
   fleetCapacity(ships, NUMSHIPS);
    cout << " tons." << endl;
    return 0;
}

Comment: What does the debugger spit out on? Programs usually don't crash silently unless you specific did something to.
Answer: you are calling fleetCapacity(ships, NUMSHIPS); which is then accessing s[e] (ships[NUMSHIPS]) in the function. The valid indices are 0 through NUMSHIPS-1.
Comment: I might be the worst programmer ever.
Comment: Alright so could i use dynamic casting to determine if e[0] is a Ship, CruiseShip or CargoShip ? Or is there a better way to find that out?
Comment: I don't know what exactly you want the function to do, but you should use virtual functions to give each ship a different behavior depending on its class instead of using dynamic casts.


Tiebreakers for best loser in a single elimination playoff

Question: In an instance where three teams were beaten by 3:1, 4:2 and 5:3, which team qualifies as best losers?
Answer: In football, in case of equal goal differences, usually the goals scored are more important than the goals conceded. So, in your case the best loser will be the one who lost 3:5.
For instance, here you can take a look at tiebreakers used during the World Cup.


How to create a reverse proxy to host specified in url?

Question: I need to configure proxy with apache to proxy requests like
http://example.com/proxy/www.anothersite.com/[some-params]

to
http://www.anothersite.com/[some-params]

I tried to do this like that:
<LocationMatch ^/proxy/(.*)$>
    ProxyPassMatch http://$1
</LocationMatch>

But how can I make all redirects that sends to me remote host go via proxy? For example, if I go to url:
http://example.com/proxy/another-site.com

and another-site.com send me redirect to yet-another-site.com, it shall forward my browser to
http://example.com/proxy/yet-another-site.com

Comment: For more complex scenarios the `P` [mod_rewrite](https://httpd.apache.org/docs/2.4/rewrite/proxy.html) directive can also (reverse) proxy requests similar to what is offered by the ProxyPass* directives.
Answer: You can use Apache ProxyPassReverse directive for this. You can find its documentation in Apache documentation
Comment: Can I use ProxyPassReverse inside LocationMatch directive? Docs say that ProxyPassReverse will interpret the regexp literally as a path. So, I need to put ProxyPassReverse outside LocationMatch, but in that case I will lose remote host address, to which I am trying to proxy. :(
Answer: I would recommend not using Location or LocationMatch blocks, just use the 2 argument versions of ProxyPass and ProxyPassMatch. So in your case:
ProxyPassMatch ^/proxy/(.*)$ http://$1
However you cannot use Apache configuration to fix back end redirects as there is no corresponging ProxyPassReverseMatch directive (this directive simply cannot work this way). You would need to edit Location, Content-Location and URI headers using the Header directive (which duplicates what the the ProxyPassReverse directive does) and possibly use mod_sed/mod_substitute to fix and hard coded URLs in the HTML.
But it will be messy, very messy. The reason this sort of thing is not easy to do is that in general Apache is not an HTML content aware server, it's an HTTP aware server, two very different things.
It maybe slightly easier to upgrade to apache v2.4 so you can use mod_proxy_html (which is HTML aware) or write your own handler in mod_lua or similar.


Need help creating a power series for with specific condtions

Question: I needed to give an example of a power series that satisfies the following conditions: interval of convergence is [$e$,$\pi$)
I came up with this series: $$\sum_{n}^{\infty}\left(\frac{2}{\pi-e}\right)^n\left(x-\frac{1}{2}(e+\pi)\right)^n$$
However I'm pretty sure my series does not converge at $e$, i.e. my interval of convergence is ($e$,$\pi$) not [$e$,$\pi$)  . Any tips?
Answer: It looks like you tried to take the geometric series $p(x)=\sum_n x^n$ and shift/scale it so the interval of convergence matches up.  This won't work, unfortunately, because the interval of convergence of $p(x)$ is $(-1,1)$, and the sum does not converge on the boundary.  You'll need to start with a power series that converges on a half-open interval.  The easiest example is:
$$
h(x) = \sum_{n=1}^\infty\frac{x^n}{n}
$$
This series converges absolutely when $\vert x\vert<1$, and converges for $x=-1$, but fails to converge for $x=1$.  In other words, its interval of convergence is $[-1,1)$.  Now you can apply the appropriate scaling/shift to move this interval to $[e,\pi)$.  Enjoy!


How to notate a concatenation of a finite number of sequences?

Question: Say you have a time series sequence $A=(X_n)_{n \in I}$. There can be many subsequences of $A$, defined as follows:
$B = (X_n)_{n \in J}$ where $J \subseteq I$.
In other words, subsequence $B$ can be any of a finite number of subsequences within $A$, which we obtain by using possible subsets of the index set $I$, denoted with $J \subseteq I$.
How would one mathematically notate a new sequence that is a concatenation of all those possible subsequences that $B$ can be? This is easy enough to do with code but I don't know how to notate this correctly in mathematics.
Comment: The notion of a concatenation isn't really clear. Do you mean just sticking them end-to-end? If so, how are infinite sequences handled?
Comment: Yes, I am trying to simply stick them end to end in one large sequence. For now I would strictly be handling finite sequences, not infinite.
Answer: There's no standard notation for this, and you could basically define any notation you want as long as you say (with words) that this object is what you want it to be.
That said, here is one idea:
$$\prod_{J \subseteq I} A \upharpoonright J$$
Here $A \upharpoonright J$ is relatively standard notation for "the sequence you get when you restrict $I$ to $J$".
It is common to view sequences as a free monoid, and in this context concatenation is multiplication. This is why we use the symbol $\prod$.
One thing to keep in mind is that order matters, and the subsets of $I$ don't come equipped with a natural total ordering. This notation says that you're concatenating all the subsequences together, but it doesn't say what order you're concatenating them in.
So if you're going to use this, you'll want to specify how you're planning to order the subsets of $I$. If it doesn't matter for your purposes, you just want some sequence that contains every subsequence of $A$, then you can say that as well.

I hope this helps ^_^
Comment: Marked it as answered, the community cannot see my upvote since I am a new member. Thanks!
Comment: Thanks so much for the help! I appreciate the suggestion.
Comment: happy to help ^_^. If this answered your question, you should mark it as such so that other users know how to spend their time. Of course, you're asleep welcome to wait a while and see if other users put up suggestions too


Ito's formula to integrate Wiener (Brownian process)

Question: for the life of me I can't seem to figure out how to solve $\int_{0}^{t}W_{s}dW_{s}$. I know an Ito process $X$ is given by:
$$
X(t) = X(t_{0}) + \int_{0}^{t}bdt + \int_{0}^{t}\sigma dW_{t}
$$ and Ito's formula states that given a function $f(t, X)$, we have that:
$$
df(X_{t}) = (\partial _{t}f + \partial_{x}fb + \frac{1}{2}\partial_{xx}f\sigma)dt + \partial_{x}f\sigma dW_{t}
$$
In a book I'm reading it says suppose that $f(x) = x^{2}$ and apply Ito's formula to $f(W_{t})$, so we have that:
$$
\partial_{t}f = 0, \quad \partial_{x}f = 2x, \quad \partial_{xx}f = 2
$$
However, what are $b$ and $\sigma$? Through reading other stack exchange questions, other people define $b = 0$ and $\sigma = 1$, however, if this is the case, would it not be the case that $X_{t} = dW_{t}$? Also what is the solution to the above integral?
Comment: It is Wiener, not Weiner. And you can't have $t$ both in limit and $dt$ in integral
Answer: Yep, when you take $b=0$ and $\sigma=1$ you do indeed get $X_t = \int_0^t 1\,dW_t = W_t$ (not $dW_t$, that wouldn't make sense).  And applying Ito's formula to this with $f(x) = x^2$ tells you that
$$W_t^2 = 2 \int_0^t W_s\,dW_s + t$$
which rearranges to
$$\int_0^t W_s\,dW_s = \frac{1}{2}W_t^2 - \frac{1}{2}t$$
which is is presumably the answer you are looking for.
Comment: Thank you soo much. Really appreciate it!


Dynamically assign elements to object

Question: In R, I am trying to dynamically select columns of a data.frame called DF.  If
 cutOffYear=2014

and
forecast_years=3

Then this piece of code
paste0("DF$X",cutOffYear+1:forecast_years)

yields:
[1] "DF$X2015" "DF$X2016" "DF$X2017"

Assuming all three columns exist in DF how do I assign the column variables to the characters?
I have tried a lot of combinations of get, assign and paste0 but I am failing.
Comment: Do not use `$`, use `[[` or `[`
Answer: We can try with [ to select the columns.  It is often error prone when using $.  If we need to get the output as a data.frame with columns specified in the pasted combination of 'cutOffYear', 'forecast_years', then the below code should work fine
DF[paste0("X", cutOffYear+1:forecast_years)]

Comment: agreed ! @akrun
Comment: Thank you @akrun. This solves it and it is so much more efficient and neat.
Comment: @joel.wilson  I am not sure what the intention here is, Is it just to select the columns or do some operations?  If it is data.table, only a single column can be selected with `[[` (as it is the behavior of `[[`, otherwise, you have to add `with = FALSE` for subsetting

Dynamically assign elements to object


Expectation of a half- multivariate normal distribution

Question: I want to calculate the value of an expectation over a half- normal distribution. Attached please find something that has been in my mind until now. I think that it is not correct and also I don't know how I can get rid of dimension in the denominator.
Thank you very much in advance. My thought
Comment: It's not entirely clear to me what you're trying to calculate.  In the image linked to in your question, you appear to be trying to calculate $
\mathbb{E}\big(\mathbf{I}_{
\,b_k^TX\ge0}\,b_k^TX\big)\ $
where $\ \mathbf{I}_A\ $ is the indicator function of the event $\ A\ $, and $\ X\ $ is multivariate normal with mean $\ 0\ $ and covariance matrix $\ \Sigma\ $, while the question itself seems more to be asking about $\ \mathbb{E}\big(b_k^TX\,\big|\,b_k^TX\ge0\big)\ $ instead.  These aren't the same thing, so which is the one you actually want to calculate?
Comment: Hi lonza, thanks for your consideration. My question is the first argumen. I have also add another pic to be more clear what exactly I want to calculate.
Answer: If $\ X\ $ is multivariate normal with zero mean and covariance matrix $\ \Sigma\ $, then $\ Z=b_k^TX\ $ is a a normal variate with zero mean and variance $\ \sigma^2=$$\,\mathbb{E}\big(b_k^TXX^Tb_k\big)=$$\,b_k^T\mathbb{E}\big(XX^T\big)b_k=$$\ b_k^T\Sigma b_k\ \ $.  Therefore
\begin{align}
\mathbb{E}\big(\mathbf{I}_{b_k^TX\ge0}\ b_k^TX\big)&=\mathbb{E}\big(\mathbf{I}_{Z\ge0}\ Z\big)\\
&=\frac{1}{\sigma\sqrt{2\pi}}\int_0^\infty ze^\frac{-z^2}{2\sigma^2}dz\\
&=\frac{\sigma}{\sqrt{2\pi}}\int_0^\infty e^{-y}dy\\
&=\frac{\sigma}{\sqrt{2\pi}}\\
&=\sqrt{\frac{b_k^T\Sigma b_k}{2\pi}}\ .
\end{align}
Comment: Dear lonza, thank you very much. I am really appreciative of your help and guidance. The point is Z is a one dimensional random variable?
Comment: Yes.  Not merely one dimensional, however, but also *normally distributed*.


What's is the equivalent, by switching dydx to dxdy, of the following conditional probability integral of two continuous random variables?

Question: Given that $X$ and $Y$ are two continuous random variables and where $f_{Y|x}(x, y)$ is the conditional density function of the two variables when $\{x<y, 0<x<\infty, 0<y<\infty\}$, then:
$$P(0<Y<3|0<X<1)=\int_0^1\int_x^3f_{Y|X}(x,y)dydx$$
What would be the equivalent of the above with $dydx$ switched to be $dxdy$?
My attempt:
$$P(0<Y<3|0<X<1)=\int_0^3\int_0^yf_{Y|X}(x,y)dxdy$$
though this does not give the right answer (since I calculated with the actual function given in the problem).
Comment: My suggestion with these is always to sketch the area out. If you do, you'll see that those areas aren't equivalent. As a hint: you'll have to break the the $dxdy$ integral into a sum of two $dxdy$ integrals.
Comment: @NickKoprowicz Oh I see because for $y > 1$ it would not be from $0$ to $y$ since it stops at $x = 1$. Would it be $\int_0^1 \int_0^y f{Y|x}(x,y)dxdy+\int_1^3 \int_0^1 f{Y|x}(x,y)dxdy$?
Comment: Did you mean to say $0 < y < \infty$ instead of $0 < y < - \infty$?
Comment: @ericperkerson Oh yes, sorry about that.
Answer: The integral $\int_0^1 \int_x^3 f(x,y) dy dx$ corresponds to this picture, where we integrate along $y$ first from the values $y = x$ to the values $y = 3$.

The integral $\int_0^3 \int_0^{g(y)} f(x,y) dx dy$ where
$$
g(y) = \begin{cases}
x, & \text{ if } y < 1 \\
1, & \text{ if } y \ge 1
\end{cases}
$$
corresponds to this picture, where we integrate along $x$ first from the values $x = 0$ to the piecewise-defined values $x = g(y)$.

So you would have to break the integral into two pieces to do the second integral, viz.
$$
\begin{align}
\int_0^3 \int_0^{g(y)} f(x,y) dx dy & = \int_0^1 \int_0^{g(y)} f(x,y) dx dy + \int_1^3 \int_0^{g(y)} f(x,y) dx dy \\
& = \int_0^1 \int_0^{x} f(x,y) dx dy + \int_1^3 \int_0^{1} f(x,y) dx dy
\end{align}.
$$


ORM for python that does not require we to define all properties for classes for database tables

Question: I have access to a large database system. I would like to talk with it in an efficient manner.
Are there ORM framework like SQLAlchemy (I know SQLAlchemy) that does not require we to define all properties for classes for each database tables?
Because the database is already there, my aim is to avoid creating properties for classes.
Comment: How would an Object Relation Mapper work without objects?
Comment: @LarryLustig: I think OP wants a framework that will dynamically generate classes using database introspection.  OP did not say "does not require classes for each table", but "does not require *we define* classes for each table".
Comment: @LarryLustig - I believe the nuance here is that the OP would like not to have a calss _for each table_... Puzzling concept - but different than refusing the idea of objects altogether...
Comment: Still not sure what that means.  An ORM saves objects to a database, each object must be an instance of a class.  Do you think it means saving arbitrary objects not derived from an ORM class?  Or just skipping classes for the tables you don't want to use?  Such things could exist but I have no idea what the user is really asking.
Comment: @LarryLustig Sorry for confusion. I want to avoid coding all properties for classes manually, since the database have tables with more number of fields.  I have edited question to reflect this.
Answer: Using SQLAlchemy's introspection features you can easily enough have a metaclass that gives you a new mapped class given a table name.  The class still has to be defined, but you don't have to define it.
<code>def introspect(tablename, *mapper_args, **mapper_kwargs):
  u'given a table name and optional mapper arguments return an ORM class'
  global metadata  # or pass it in, or use OO, whatever
  global engine    # or pass it in, or use OO, whatever
  table = sqlalchemy.Table(tablename, metadata,
      autoload=True, autoload_with=engine)
  class DynamicClass: pass  # you can provide nice __init__, __str__ methods
  return sqlalchemy.orm.mapper(DynamicClass, table,
      *mapper_args, **mapper_kwargs)
</code>
Hibernate has a similar introspection feature, but it generates Java source files, and therefore is a build-time, not run-time, operation.


Exibir dados em Array

Question: Estou fazendo uma consulta em um banco de dados e preciso exibir as informações na tela, porém buscando de um em um. Tentei fazer por array, porém ele não está exibindo o vetor.
Código:
<?php
$a = $_GET['a'];
if($a == "buscar"){
  $id = $_POST['id'];
  $sql = ibase_query("SELECT NOME FROM TB_CLIENTE WHERE ID_CLIENTE LIKE '%".$id."%'");
  $row = ibase_fetch_row($sql);
  $vetorDados = array();
  $i=0;
  $vetorDados[$i]= ibase_fetch_row($sql);
  echo '
';
  echo '' . $vetorDados[$i] . '	';
  echo '' . $i . '	';
  echo '
';
  $i++;
}
?>

Answer: Faltou você criar um while para exibir dados, outro detalhe que ficou redundante foi você criar um array $vetorDados para imprimir o resultado do banco, sendo que a variável $row já é um array, abaixo segue o código para exibir os dados do banco.
<?php
$a = $_GET['a'];
if($a == "buscar"){
$id = $_POST['id'];
$sql = ibase_query("SELECT NOME FROM TB_CLIENTE WHERE ID_CLIENTE LIKE '%".$id."%'");
$i = 1;
while($row = ibase_fetch_row($sql)){
   echo "
";
   echo "{$row['NOME']}	";
   echo "{$i}	";
   echo "
";
   $i++;
   }
}
?>

A chave da variável $row é o nome da coluna do banco a qual você deseja imprimir a informação.
Comment: @ProgMen eu havia esquecido de fechar a `tag `
Comment: Entao, anteriormente eu estava fazendo assim, porem ai ele busca "todos" os nomes com aqele id, e se eu busco outro ele apaga o anterior, eu queria q ele fosse fazendo uma lista conforme iria adicionando
Comment: Veja se entendi, você que criar uma lista como se fosse um histórico dos ultimos registros buscados?
Comment: Isso,conforme vou dando mais ids eles vao aparecendo em ordem na tela, do jeito q estou fazendo, cada valor q eu entro ele apaga o anterior.
 `if($a == "buscar"){
                $id = $_POST['id'];
                $sql = ibase_query("SELECT NOME FROM TB_CLIENTE WHERE ID_CLIENTE = $id ");
                $row = ibase_fetch_row($sql);
                   echo '';
                   echo '' . $row[0] . '';
                   echo '';
              }`
Comment: @ProgMen entendi, mas dessa forma não é possível utilizando `php` para que ele funcione dessa forma precisa usar `jquery` ou  `javascript` que vai criando uma lista dinâmica no `innerHTML` dessa forma você deve concluir está pergunta e criar uma nova, solicitando auxilio quando a criar uma lista dinamica ordenada com dados de busca.
Comment: Perfeitamente, obrigado! Nao sabia haha, achava q php faria isso. obrigado.
Comment: Irei fazer a pergunta, pode me ajudar por la ?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/67249/discussion-between-wmomesso-and-progmen).

Exibir dados em Array


req.session em node.js

Question: Gostaria de saber como é o funcionamento básico da estrutura req.session do Node.js. Ela é nativa do Express ou do express-session? Por favor, me ajudem a entender mais sobre sessões.
Answer: ela é instalada à parte usando o comando "npm install express-session --save"
depois coloque isso no seu arquivo principal:
app.use(session({
    secret: '2C44-4D44-WppQ38S',
    resave: true,
    saveUninitialized: true
}));

E para criar um nova variável de sessão, segue o exemplo:
req.session.usuario = usuario;

E um middleware básico para autenticar seria:
module.exports = function(req, res, next) {
  if(!req.session.usuario) {
      return res.redirect('/');
  }
    return next();
};

Comment: Eu andei dando uma pesquisada e consegui entender, valeu pela ajuda!
Answer: Ela não é nativa do express, é necessário instalar ela pelo
NPM: npm i express-session
ou
Yarn: yarn add express-session
Até onde eu sei ela é uma forma mais segura de guardar informações que precisam ser protegidas, como um token gerado pelo jwt.
O express session é um middleware que precisa ser chamado no seu arquivo principal desta forma:
const serverSession = require('express-session')

.use(serverSession({ secret: sua-chave-secreta, resave: false, saveUninitialized:false }))

A sua chave secreta precisa ser gerada a md5 se não me engano e guardada de forma segura.
Leia a documentação pra entender de forma correta como a mesma funciona documentação
Espero ter ajudado.

req.session em node.js


Django + nginx + gunicorn not being able to serve static files

Question: I'm trying to deploy a django app in a EC2 instance but I'm currently having issues serving the static files of the app.
Currently, my nginx's conf file looks like this:
# Default server configuration
#
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_pass http://0.0.0.0:8000;
        }

        location /static/ {
                #autoindex on;
                root /home/ubuntu/some/folder/static/;
        }
}

Also in my settings.py file in my django project I have the following config related to my static files:
STATIC_URL = '/static/'
STATIC_ROOT = '/home/ubuntu/some/folder/static/'

and Gunicorn, I'm launching it as the following:
gunicorn3 --bind 0.0.0.0:8000 myproject.wsgi:application

And with that, if I access http://ec2-my-instanceI see the html content, but all my js and css files get error 404.
I'm kinda lost and I don't know what I'm missing to make it works, I already migrated the static content and I checked the folder which nginx is looking for the static files have them, but if I check the browser's console I see this kind of errors:
GET http://ec2-my-instance/static/somefile.js net::ERR_ABORTED 404 (Not Found)

Comment: You nginx server listens on port 80, you need to make the request to that port - `http://ec2-my-instance:80` or just `http://ec2-my-instance`. Nginx handles passing the request down to the app, you shouldn't access it directly
Comment: Check what port your apps nginx server config is listening on, you may have connected directly to your Django app instead of going through nginx. Can you show the rest of your config?
Comment: @IainShelvington I updated to question to put the whole nginx config file
Comment: @IainShelvington I treid it and I still don't get the static files served :(
Comment: ``DEBUG = False``
Answer: You want 'alias' not 'root':
location /static/ {
    alias /home/ubuntu/some/folder/static/;
}


Simultaneous equation help appreciated

Question: How do I solve this simultaneous equation? I know it has multiple solutions, but would anyone be able to show me the exact steps in working these out for future reference?
$$
\begin{cases}
2x +y = 4\\
-6x - 3y = -12
\end{cases}
$$
Thank you...
Comment: Basically, you want to get two of the variables to have the same number in front of them by multiplying or dividing the _whole_ equation by any number that will make it the same as any of the other equations as explained above. Then you want to subtract(or add) the two equations from each other to eliminate the variable you have chosen. You will just repeat this as well as use substitution to eventually find an answer.
Answer: As $2x+y=4-6x-3y=-12$
So, $2x+y=-12,y=-12-2x$
Putting $y=-12-2x$ in $4-6x-3y=-12$
$4-6x-3\{-12-2x\}=-12$
or $52=12$ which is impossible
So, the simultaneous equation will not have any solution
EDIT :
Due to the change in the question to $2x+y=4,-6x-3y=-12$
Again, from the 1st equation, $y=-12-2x$
Putting $y=-12-2x$ in $-6x-3y=-12$ we get, $12=12$ which is true for all values of $y$
So, $(x,-12-2x)$ will satisfy the given  simultaneous equation for all values of $x$
Comment: I think your solution is for a different system, perhaps prior to the edit. You  have not used equations $2x+y=4$ and $−6x−3y=−12$, as they are now.
Comment: @AméricoTavares, ya. Please find the original version.
Comment: It is "2x + y = 4 -6x - 3y = -12".
Comment: @AméricoTavares, Earlier I solved for that. Now edited the answer as the question is changed
Comment: Typo in "(...) from the 1st equation, $y=−12−2x$". Should be $y=4−2x$.
Answer: We have: $2x+y=4$ and $-6x-3y=-12$
Let's begin by solving each equation for $y$ and labelling them:
$\Rightarrow y=4-2x \hspace{80 mm}$ (i)
$\Rightarrow y=\dfrac{12-6x}{3}=4-2x \hspace{58.5 mm}$ (ii)
Graphically, these two lines overlap.
Therefore, the system of equations has an infinite number of solutions.

Simultaneous equation help appreciated


FreeIPA - ssh as root prompted for password

Question: I know the access via root won't work (client sshd_config and restricted account in FreeIPA). But is there a way to blacklist root either on the host or on FreeIPA so it's denied immediately rather than prompting for a password?
I'm wondering if I'm missing something... If not possible then I guess my next goal will be to log root attempts via FreeIPA and alert/report on them.
Answer: You should be able to do something like this in sshd_config:
Match User root
  AuthenticationMethods publickey

Match User *
  AuthenticationMethods publickey,password

Possibly add an AuthorizedKeysFile /dev/null to the root config as well.
Comment: can't you do `AuthenticationMethods none`
Comment: I don't think so: "none" (used for access to password-less accounts when PermitEmptyPasswords is enabled).
Comment: There's also `PermitRootLogin no` or `prohibit-password`


Programmatically scroll to a supplementary view within UICollectionView

Question: I am using UICollectionView to display photos in sections. Each section has a supplementary view as a header and is supplied via the method: viewForSupplementaryElementOfKind.
I have a scrubber on the side that allows the user to jump from section to section. For now I am scrolling to the first item in the section using scrollToItemAtIndexPath:atScrollPosition:animated:, but what I really want is to scroll the collectionView so that that section's header is at the top of the screen, not the first cell. I do not see an obvious method to do this with. Do any of you have a work around?
I suppose I could scroll to the first item of the section, and then offset that by the supplementary height plus the offset between the items and header if it comes down to that (there is a method for scrolling to point coordinates of the contentView). However if there is a simpler way, I'd like to know.
Thanks.
Comment: what's the problem about it? it should work nice since every supplementary view has its index path
Comment: Yes, they do indeed have indexPaths. I did a print out for both delegate methods that prep the cell and supplementary cell. The indexPaths are not mutually exclusive, rather they look like two distict sets with nonuniue indexPaths. This will probably not paste well here, but:
!!! Cell index path 0 0
!!! Supp index path 0 0
!!! Cell index path 0 1
!!! Cell index path 0 2
!!! Cell index path 0 3
!!! Cell index path 0 4
!!! Cell index path 0 5
!!! Cell index path 0 6
!!! Cell index path 0 7
!!! Cell index path 0 8
!!! Cell index path 0 9
!!! Cell index path 0 10
!!! Cell index path 0 11
Comment: I should state that I am printing out indexPath.section indexPath.item. Is there another property that I'm overlooking that would set these apart? You can see that [0 0] is in the cell view and supplementary view from what I have printed.
Answer: You can not use scrollToItemAtIndexPath:atScrollPosition:animated for this.
Hopefully, they will add a new method like scrollToSupplementaryElementOfKind:atIndexPath: in the future, but for now, the only way is to manipulate the contentOffset directly.
The code below shows how to scroll header to be on top vertically with FlowLayout. You can do the same for horizontal scrolling, or use this idea for other layout types.
NSIndexPath *indexPath = ... // indexPath of your header, item must be 0

CGFloat offsetY = [collectionView layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath].frame.origin.y;

CGFloat contentInsetY = self.contentInset.top;
CGFloat sectionInsetY = ((UICollectionViewFlowLayout *)collectionView.collectionViewLayout).sectionInset.top;

[collectionView setContentOffset:CGPointMake(collectionView.contentOffset.x, offsetY - contentInsetY - sectionInsetY) animated:YES];

Note that if you have non-zero contentInset (as in iOS 7, when scroll views expand below bars) you need to subtract it from the offsetY, as shown. Same for sectionInset.
Update:
The code assumes that the layout is in prepared, "valid" state because it uses it to calculate the offset. The layout is prepared when the collection view presents its content.
The call to [_collectionView.collectionViewLayout prepareLayout] before the code above may help when you need to scroll the collection view which is not yet presented (from viewDidLoad say). The call to layoutIfNeeded (as @Vrasidas suggested in comments) should work too because it also prepares the layout.
Comment: This does not work for me.
It crashes at layoutAttributes... with

 `Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'layout attributes for supplementary item at index path ([0, 0]) changed from
              index path: ([0, 0]); element kind: (UICollectionElementKindSectionHeader); frame = (0 0; 0 0);   to    index path: ([0, 0]); element kind: (UICollectionElementKindSectionHeader); frame = (0 0; 492 60);  without invalidating the layout'`

Any ideas?
Comment: And I found what was missing...
A call to [collectionView layoutIfNeeded]; before that fixes that problem and it works now!
Comment: One note.  When building the NSIndexPath be sure to set the 'item' to 0.  I just fixed a bug in my use of this where using a non-zero 'item' value caused the UICollectionView to request two supplementary cells when displaying it.  When you scroll that view off screen the collection view only removes one.
Comment: This will potentially scroll past the collectionView.contentSize boundary if your section is shorter than the height of the screen. I'll create variables called contentOffsetY and maxContentOffsetY:  `CGFloat contentOffsetY = offsetY - contentInsetY - sectionInsetY; CGFloat maxContentOffsetY = self.collectionView.contentSize.height - self.collectionView.frame.size.height;` Then you can alter your contentOffsetY: `if (maxContentOffsetY < 0) {maxContentOffsetY = 0;} if (contentOffsetY > maxContentOffsetY) { contentOffsetY = maxContentOffsetY;}`
Comment: I filed rdar://16572180 asking for this if anyone wants to dupe BTW
Answer: Solution in Swift,
let section: Int = 0 // Top

if let cv = self.collectionView {

    cv.layoutIfNeeded()

    let indexPath = IndexPath(row: 1, section: section)
    if let attributes =  cv.layoutAttributesForSupplementaryElement(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath) {

        let topOfHeader = CGPoint(x: 0, y: attributes.frame.origin.y - cv.contentInset.top)
        cv.setContentOffset(topOfHeader, animated: true)
    }
}

Props to Gene De Lisa: http://www.rockhoppertech.com/blog/scroll-to-uicollectionview-header/
Comment: This code works, but as the other solutions on this page suggested, you need to put a `cv.layoutIfNeeded()` function before you call `cv.layoutAttributesForSupplementaryElementOfKind` else this code will crash if the cv is not ready.
Answer: // scroll to selected index
NSIndexPath* cellIndexPath = [NSIndexPath indexPathForItem:0 inSection:sectionIndex];
UICollectionViewLayoutAttributes* attr = [self.collectionView.collectionViewLayout layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:cellIndexPath];
UIEdgeInsets insets = self.collectionView.scrollIndicatorInsets;

CGRect rect = attr.frame;
rect.size = self.collectionView.frame.size;
rect.size.height -= insets.top + insets.bottom;
CGFloat offset = (rect.origin.y + rect.size.height) - self.collectionView.contentSize.height;
if ( offset > 0.0 ) rect = CGRectOffset(rect, 0, -offset);

[self.collectionView scrollRectToVisible:rect animated:YES];

Answer: One thing the solutions don't manage is if you are pinning section headers. The methods work fine with unpinned headers, but if your headers are pinned, while scrolling to a section above the current section, it will stop once the section header appears (which will be for the bottom row of your section). That may be desirable in some cases but I think the goal is to put the top of the section at the top of the screen.
In which case you need to take the methods above and adjust them a bit. For instance:
UICollectionView *cv = self.collectionView;
CGFloat contentInsetY = cv.contentInset.top;
CGFloat offsetY = [cv layoutAttributesForItemAtIndexPath:ip].frame.origin.y;
CGFloat sectionHeight =
[cv layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionHeader atIndexPath:ip].frame.size.height;
[cv setContentOffset:CGPointMake(cv.contentOffset.x, offsetY - contentInsetY - sectionHeight) animated:YES];

Now you are basically scrolling the first row of your section to visible, less the height of its section header. This will put the section header on the top where you want it with pinned headers so the direction of the scroll won't matter anymore. I didn't test with section insets.


Adding javascript to module and access drupalSettings without jQuery

Question: I am trying to create a Drupal 8 version of the Mautic Drupal module. Currently I have just ported the Drupal 7 version as is, and the script for Mautic forms along with the tracking pixel is printed in a block. Mautic now uses a tracking script and I want to update the module to use it. The tracking script looks like this (notice the Mautic base url required):
js/mautic_drupal_tracking_code.js
(function(w,d,t,u,n,a,m){w['MauticTrackingObject']=n;
    w[n]=w[n]||function(){(w[n].q=w[n].q||[]).push(arguments)},a=d.createElement(t),
        m=d.getElementsByTagName(t)[0];a.async=1;a.src=u;m.parentNode.insertBefore(a,m)
})(window,document,'script', + drupalSettings.mautic_drupal.mautic_drupal_tracking_code.base_url + '/mtc.js','mt');

mt('send', 'pageview');

The script is showing on the page, but as I am trying to avoid jQuery, I can not find out how to access the drupalSettings variable.
My module code is updated and not in sync with the github repo. Here are a description of the files:
mautic_drupal.libraries.yml
mautic_drupal_tracking_code:
  version: VERSION
  js:
    js/mautic_drupal_tracking_code.js: {}
  dependencies:
    - core/drupalSettings

mautic_drupal.module
/**
 * Implements hook_page_attachments_alter().
 *
 * @param array $page
 */
function mautic_drupal_page_attachments_alter(array &$page) {
  $config = \Drupal::service('config.factory')->get('mautic_drupal.settings');
  $mautic_url = trim($config->get('base_url'), ' \t\n\r\0\x0B/');

  if ($mautic_url != '') {
    $page['#attached']['drupalSettings']['mautic_drupal']['mautic_drupal_tracking_code']['base_url'] = $mautic_url;
    $page['#attached']['library'][] = 'mautic_drupal/mautic_drupal_tracking_code';
  }
}

On the site, the script is showing, and the base url setting is set. But alas, I can not access the settings in my javascript, I can only find examples of how to do that in jQuery scripts.
Is this possible to do in pure javascript?
Answer: You can try to set a weight on the js file:
  js:
    js/mautic_drupal_tracking_code.js: { weight: -18 }

There is a core issue, that the dependencies don't get the correct priority. The weight is a workaround for this:
Replace custom weights with dependencies in library declarations
If you can't get drupalSettingsLoader.js running in the correct order, you can for testing purpose put the code to load the json array at the top of your custom js:
(function () {

  'use strict';

  var settingsElement = document.querySelector('head > script[type="application/json"][data-drupal-selector="drupal-settings-json"], body > script[type="application/json"][data-drupal-selector="drupal-settings-json"]');

  window.drupalSettings = {};

  if (settingsElement !== null) {
    window.drupalSettings = JSON.parse(settingsElement.textContent);
  }
})();

Comment: Unfortunately that did not work. Thanks for the tip thought, I did not know of this issue.
Comment: it should work without jquery, see the edited answer.


How can i access/download current application in AWS Elastic Beanstalk?

Question: i have a website where users can upload images.
my question is is there any simple way to access/download the current application i deployed in Elastic Beanstalk and access the files that the users uploaded?
because i can't keep "Upload & Deploy" each time i make changes in the code and loose all the images the users have uploaded.
please bare with me i'm a complete newbie with all this (explain briefly plzz).
Answer:
i make changes in the code and loose all the images the users have uploaded

This is bad practice leading to issues, one of which you are describing. If you want to follow good practices, you should keep your images outside of EB instance. Usually this is done by keeping them in S3 bucket or EFS filesystem.

my question is is there any simple way to access/download the current application i deployed in Elastic Beanstalk and access the files that the users uploaded?

But if you really want to store the images the way you do, then you have to SSH into your EB instance and copy the files to safe place (e.g. S3 bucket) manually. You application is located in /var/app/current.
You could also develop an automation for that, using .ebextentions scripts.
Nevertheless, your way of storing the images will only lead to issues in the long term. So maybe its good chance to re-architect your design now, before it will be too late.
Comment: Thank you SOO much this is the exact answer i needed ,  it's a simple school project for now, but i will consider what you said next time.