How transition smoothly multiple guitar recordings?

Question: I play folk music with my guitar and I am trying to record some tracks.
In these songs there are many chords progression so my first attempt was to record them separately and then recreate the right sequence.
My problem is that you can hear like a "break" between the single recordings, they don't match up properly and you can definitely recognize they are not played in just one take.
For instance, how did he record a song like this?

Only one take or there's some trick I am not aware of?
Comment: Are you recording each attempt to a new track? If so you can usually cut or cross-fade at the transition point later. One trick is to not make the edits at the transition between chords - get the transition clean, even if you have to play just half a bar before, then make the chord change. You can then make your edit a bit earlier… where no-one will hear it.
Comment: Did you try to export the tracks when you got the "breaks"? I think if you place it right and record it in the same environment, you'll get it right after you export it.
Comment: I am not talking about connecting separate tracks, the problem is about different parts of the same song, like transit from the verse to the chorus section. Of course I am recording with the same settings and the same environment.
Comment: It would be a lot easier to help if we had an example of a recording that you have made where you can let us hear the problem, instead of a recording of what you're trying to achieve. Are you able to play the whole piece through live even if you make a mistake or three? If not then you might need more practice with it before you try to record it.
Comment: Are you recording to a metronome click-track that you listen to in your headphones while you play your guitar into the microphone? Recording each phrase to the same rigid tempo with a click track will be essential.
Comment: I listened to the recording you included in your post.  It sure sounds like he just played the whole thing through, as one would do in a concert performance.
Answer: There are two ways:

Play it in one take.  I won't get into your own abilities, or why you need to record sections separately, however for thousands of years musicians have played (and still play!) full, complete pieces without needing to stop and change.  It happens more than you think in modern music styles, and some artists pride themselves on playing their instrument and songs.
Edit sections.  Up until 35 or so years ago you couldn't do this.  I've done it recently, and it is simple to do within a DAW environment.  It is possible to create a composite, but your editing skills may not be sufficient to produce what you want.  It takes a little bit of effort and practice, and there will be plenty of web resources to help you out.  Making sure you play to a metronome may help you, but it's by no means obligatory.

Though, what I will say is that if your music is just designed to be recording only then composite building is fine, however if you are looking for you or someone else to play live, then really you need to put in the practice to learn to play start to finish.  Your ability, and your recordings, will be much better off.


How to animate RecyclerView like vertical Viewpager transforms

Question: I have used Vertical Viewpager in my project.
But there are some issues,

when the page has lots of onclick() events, the scrolling is too hard
fling event doesn't change the page
I tried to use gesture detector, but it changed pages too fast without transitions (without invoking transformPage())
when I scroll the page, Sometimes onclick() events also get triggered

So I decided to use  Recyclerview as Viewpager with the help of PagerSnapHelper.
It works fine. But the problem is ,

how to do the transition or animation when the item is changed (like I
  did in ViewPager)

For example, Zoomout transition or stack transition in Viewpager.
I tried stackLayoutManager but it takes more time to scroll and tried this related link .It doesn't work.
I researched for both issues How to reduce scroll speed for viewpager and how to do animations in recyclerview. I didn't get solution for it.
Can anyone help me!!! is it possible or I need to use any other widgets.
Edit
I tried #ADM's suggestion, it works fine but doesn't support PagerSnapHelper.
I have changed stacklayout manager in the above link but it doesn't support scrollToPosition() and PagerSnapHelper.
Code:
public class StackLayoutManager  extends LinearLayoutManager {

    private static final String TAG = "StackLayoutManager";

    //the space unit for the stacked item
    private int mSpace = 0;
    /**
     * the offset unit,deciding current position(the sum of  {@link #mItemWidth} and {@link #mSpace})
     */
    private int mUnit;
    //item width
    private int mItemWidth;
    private int mItemHeight;
    //the counting variable ,record the total offset including parallex
    private int mTotalOffset;
    //record the total offset without parallex
    private int mRealOffset;
    private ObjectAnimator animator;
    private int animateValue;
    private RecyclerView.Recycler recycler;
    private int lastAnimateValue;
    private int initialOffset;
    private boolean initial;
    private int mMinVelocityX;
    private VelocityTracker mVelocityTracker = VelocityTracker.obtain();
    private int pointerId;
    private Method sSetScrollState;
    RecyclerView recyclerView;

    public StackLayoutManager(Context context) {
        super(context, VERTICAL, false);
        setAutoMeasureEnabled(true);

    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        this.recycler = recycler;
        detachAndScrapAttachedViews(recycler);
        //got the mUnit basing on the first child,of course we assume that  all the item has the same size
        View anchorView = recycler.getViewForPosition(0);
        measureChildWithMargins(anchorView, View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        mItemWidth = anchorView.getMeasuredWidth();
        mItemHeight = getDecoratedMeasuredHeight(anchorView);

        mUnit = mItemHeight;
        //because this method will be called twice
        initialOffset = mUnit;
        mMinVelocityX = ViewConfiguration.get(anchorView.getContext()).getScaledMinimumFlingVelocity();
        fill(recycler, 0);

    }

    @Override
    public void onLayoutCompleted(RecyclerView.State state) {
        super.onLayoutCompleted(state);
        if (!initial) {
            fill(recycler, initialOffset, false);
            initial = true;
        }
    }

    @Override
    public void onAdapterChanged(RecyclerView.Adapter oldAdapter, RecyclerView.Adapter newAdapter) {
        initial = false;
        mTotalOffset = mRealOffset = 0;
    }

    private int fill(RecyclerView.Recycler recycler, int dy, boolean apply) {
        return fillFromTop(recycler, dy);
    }

    public int fill(RecyclerView.Recycler recycler, int dy) {
        return fill(recycler, dy, true);
    }

    private int fillFromTop(RecyclerView.Recycler recycler, int dy) {
        if (mTotalOffset + dy < 0 || (mTotalOffset + dy + 0f) / mUnit > getItemCount() - 1)
            return 0;
        detachAndScrapAttachedViews(recycler);
        mTotalOffset += dy;
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (recycleVertically(child, dy))
                removeAndRecycleView(child, recycler);
        }
        int curPos = mTotalOffset / mUnit;
        int leavingSpace = getHeight() - (left(curPos) + mUnit);
        int itemCountAfterBaseItem = leavingSpace / mUnit + 2;
        int e = curPos + itemCountAfterBaseItem;

        int start = curPos - 1 >= 0 ? curPos - 1 : 0;
        int end = e >= getItemCount() ? getItemCount() - 1 : e;

        int left = getWidth() / 2 - mItemWidth / 2;
        //layout views
        for (int i = start; i <= end; i++) {
            View view = recycler.getViewForPosition(i);

            float alpha = alpha(i);

            addView(view);
            measureChildWithMargins(view, 0, 0);
            int top =  (left(i) /* - ( 1 - scale ) * view.getMeasuredHeight() */ );
            int right = view.getMeasuredWidth() + left;
            int bottom = view.getMeasuredHeight() + top;
            layoutDecoratedWithMargins(view, left, top, right, bottom);
            view.setAlpha(alpha);
            view.setScaleY(1);
            view.setScaleX(1);
        }

        return dy;
    }

    private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            mVelocityTracker.addMovement(event);
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (animator != null && animator.isRunning())
                    animator.cancel();
                pointerId = event.getPointerId(0);

            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (v.isPressed())
                    v.performClick();
                mVelocityTracker.computeCurrentVelocity(1000, 14000);
                float xVelocity = mVelocityTracker.getYVelocity(pointerId);
                int o = mTotalOffset % mUnit;
                int scrollX;
                if (Math.abs(xVelocity) < mMinVelocityX && o != 0) {
                    if (o >= mUnit / 2)
                        scrollX = mUnit - o;
                    else
                        scrollX = -o;
                    Log.d("scrollx","from scroll");

                    Log.d("scrollx", "" + scrollX);
                    brewAndStartAnimator(300, (int) (scrollX));
                }
            }
            return false;
        }

    };

    private RecyclerView.OnFlingListener mOnFlingListener = new RecyclerView.OnFlingListener() {
        @Override
        public boolean onFling(int velocityX, int velocityY) {
            int o = mTotalOffset % mUnit;
            int s = mUnit - o;
            int scrollX;
            int vel = absMax(velocityX, velocityY);
            if (vel  > 0) {
                scrollX = s;
            } else
                scrollX = -o;
            Log.d("scrollx","from fling");
            Log.d("scrollx",""+scrollX);
            brewAndStartAnimator(100, scrollX);
          //  setScrollStateIdle();
            return true;
        }
    };

    private int absMax(int a, int b) {
        if (Math.abs(a) > Math.abs(b))
            return a;
        else return b;
    }

    @Override
    public void onAttachedToWindow(RecyclerView view) {
        super.onAttachedToWindow(view);
        this.recyclerView=view;
        view.setOnTouchListener(mTouchListener);
        view.setOnFlingListener(mOnFlingListener);
    }

    private void brewAndStartAnimator(int dur, int finalX) {
        animator = ObjectAnimator.ofInt(StackLayoutManager.this, "animateValue", 0, finalX);
        animator.setDuration(dur);
        animator.start();
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                lastAnimateValue = 0;
                recyclerView.scrollToPosition(findFirstCompletelyVisibleItemPosition());

            }

            @Override
            public void onAnimationCancel(Animator animation) {
                lastAnimateValue = 0;
                recyclerView.smoothScrollToPosition(findFirstCompletelyVisibleItemPosition());
            }
        });

    }

    private float alpha(int position) {
        float alpha;
        int curPos = mTotalOffset / mUnit;
        float n = (mTotalOffset + .0f) / mUnit;
        if (position > curPos)
            alpha = 1.0f;
        else {
            alpha = 1 - (n - position) / 1;
        }
        return alpha <= 0.001f ? 0 : alpha;
    }

    @Override
    public void scrollToPosition(int pos)
    {
          scrollToPositionWithOffset(pos, 0);
    }

    private int left(int position) {

        int curPos = mTotalOffset / mUnit;
        int tail = mTotalOffset % mUnit;
        float n = (mTotalOffset + .0f) / mUnit;
        float x = n - curPos;

        return ltr(position, curPos, tail, x);

    }

    private int ltr(int position, int curPos, int tail, float x) {
        int left;
        if (position <= curPos) {
            if (position == curPos) {
                left = (int) (mSpace * (1 - x));
            } else {
                left = (int) (mSpace * (1 - x - (curPos - position)));

            }
        } else {
            if (position == curPos + 1)
                left = mSpace + mUnit - tail;
            else {

                int baseStart = (int) (mUnit +  mUnit);
                left = (int) (baseStart + (position - curPos - 2) * mUnit - (position - curPos - 2) * (mUnit));
                if (BuildConfig.DEBUG)
                    Log.i(TAG, "ltr: curPos " + curPos + "  pos:" + position + "  left:" + left + "   baseStart" + baseStart + " curPos+1:" + left(curPos + 1));
            }
            left = left <= 0 ? 0 : left;
        }
        return left;
    }

    @SuppressWarnings("unused")
    public void setAnimateValue(int animateValue) {
        this.animateValue = animateValue;
        int dy = this.animateValue - lastAnimateValue;
        fill(recycler, dy, false);
        lastAnimateValue = animateValue;
    }

    @SuppressWarnings("unused")
    public int getAnimateValue() {
        return animateValue;
    }

    private boolean recycleVertically(View view, int dy) {
        return view != null && (view.getTop() - dy < 0 || view.getBottom() - dy > getHeight());
    }

    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        return fill(recycler, dy);
    }

    @Override
    public boolean canScrollHorizontally() {
        return false;
    }

    @Override
    public boolean canScrollVertically() {
        return true;
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT);
    }

    @SuppressWarnings("unused")
    public interface CallBack {

        float scale(int totalOffset, int position);

        float alpha(int totalOffset, int position);

        float left(int totalOffset, int position);
    }
}

And If it is not possible with recyclerview, Please help me what to do with that VerticalViewPager. I have tried setting the field values, But it doesn't work.
    try {
        Class cls = this.getClass().getSuperclass();
        Field distanceField = cls.getDeclaredField("mFlingDistance");
        distanceField.setAccessible(true);
        distanceField.setInt(this, distanceField.getInt(this)/2);
    }catch (Exception ignored) {
        Log.d("error", ignored.toString());
    }

    try {
        Class cls = this.getClass().getSuperclass();
        Field minVelocityField = cls.getDeclaredField("mMinimumVelocity");
        minVelocityField.setAccessible(true);
        minVelocityField.setInt(this, minVelocityField.getInt(this) /2);
    } catch (Exception ignored) {
        Log.d("error", ignored.toString());
    }

    try {
        Class cls = this.getClass().getSuperclass();
        Field maxVelocityField = cls.getDeclaredField("mMaximumVelocity");
        maxVelocityField.setAccessible(true);
        maxVelocityField.setInt(this, maxVelocityField.getInt(this)/2);
    }catch (Exception ignored) {
        Log.d("error", ignored.toString());
    }

Comment: If understood correctly . You need snap with zoom out animation. Just for reference you can have a look at [this](https://github.com/xmuSistone/VegaLayoutManager) .
Comment: @ADM Thanks! let me try it :)
Comment: http://www.devexchanges.info/2015/11/making-carousel-layout-in-android.html
Comment: @NileshRathod Thanks!!! but I don't want to use third party libraries
Comment: @ADM I tried it. I did some changes but the code is complicated to understand for me.
Comment: @JyotiJK can u share your exact required output with question
Comment: @NileshRathod need a viewgroup like viewpager which scrolls vertically.
Comment: @JyotiJK did u check this http://www.devexchanges.info/2016/06/carousel-layout-with-viewpager-in.html
Comment: @NileshRathod I have tried viewpager with modifications . But it has some problems as I listed in question.
Comment: @JyotiJK check this also https://github.com/PuniCharana/Carousel-Demo
Comment: @NileshRathod simply I need [this kind of view](https://developer.android.com/training/animation/screen-slide)  vertically
Answer: Try this
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import android.support.animation.DynamicAnimation;
import android.support.animation.FlingAnimation;

public class MainActivity extends AppCompatActivity {

    CustomVerticalViewPager viewPager;
    ArrayList<DataModel> arrayList = new ArrayList<>();

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

        initArray();

        viewPager = findViewById(R.id.viewPager);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            FlingAnimation fling = new FlingAnimation(viewPager, DynamicAnimation.SCROLL_X);
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

        CustomAdapter adapter = new CustomAdapter(this, arrayList);
        viewPager.setAdapter(adapter);
    }

    private void initArray() {
        for (int i = 0; i < 10; i++) {
            DataModel dataModel = new DataModel();
            dataModel.setTitle("Title item No :- " + i);
            dataModel.setContent(" Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras auctor blandit dignissim. Suspendisse id lorem nulla. Proin urna lacus, posuere sed lacus a, dapibus consectetur neque. Donec in metus sagittis, consequat tellus eget, consequat ex. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec dui nisi, scelerisque eu nunc id, aliquet sagittis leo. Nunc ac ornare diam. Vestibulum sed elit euismod, ornare metus a, convallis ipsum. Nulla aliquam mi enim, porttitor commodo lacus dictum cursus. Phasellus sed eros sagittis, feugiat sapien ac, accumsan odio. In posuere congue lorem, quis pharetra mi tincidunt et. Nam tincidunt erat eu dapibus faucibus.\n" +
                    "\n");

            arrayList.add(dataModel);
        }

    }

}

LAYOUT

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.example.nilesh.testapp.CustomVerticalViewPager
        android:layout_width="match_parent"
        android:id="@+id/viewPager"
        android:layout_height="match_parent" />

</LinearLayout>

CustomVerticalViewPager

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class CustomVerticalViewPager extends ViewPager {
    private GestureDetector gestureDetector;
    public boolean isScrollEvent;
    public CustomVerticalViewPager(Context context) {
        super(context);
        init();
    }

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

    private void init() {
        gestureDetector=new GestureDetector(getContext(),new GestureListener());
        setPageTransformer(true, new VerticalPageTransformer());
        setOverScrollMode(OVER_SCROLL_NEVER);
        try {
            Field mScroller;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            FixedSpeedScroller scroller = new FixedSpeedScroller(getContext(), new DecelerateInterpolator());
            scroller.setScrollDuration(250);
            mScroller.set(this, scroller);
        } catch (Exception e) {}
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return gestureDetector.onTouchEvent((ev));

    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        boolean res= gestureDetector.onTouchEvent((ev));
        if((ev.getAction() == MotionEvent.ACTION_CANCEL ||ev.getAction()==MotionEvent.ACTION_UP)) {
            if(isScrollEvent) {
                try {
                    endFakeDrag();
                } catch (Exception e) {}
            }
            return true;
        }
       // Log.d("event", "ontouch      " + res);
        return res;
    }

    private class FixedSpeedScroller extends Scroller {

        private int mDuration = 500;

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

        public FixedSpeedScroller(Context context, Interpolator interpolator) {
            super(context, interpolator);
        }

        public FixedSpeedScroller(Context context, Interpolator interpolator, boolean flywheel) {
            super(context, interpolator, flywheel);
        }

        public void setScrollDuration(int duration) {
            mDuration = duration;
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }
    }

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            isScrollEvent=false;
          // Log.d("touch","singletap");
            return false;
        }
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        //   Log.d("touch","fling");
            isScrollEvent=false;
            try {
                float diffY = e2.getY() - e1.getY();
                if (diffY > 20) {
                    onSwipeDown();
                    return  false;
                } else if(diffY<-20){
                    onSwipeUp();
                    return  false;
                }
                else
                {
                    endFakeDrag();
                }

            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return false;

        }
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
        // Log.d("touch", "scroll" + " " + distanceX);
            beginFakeDrag();
            fakeDragBy(-distanceY);
            isScrollEvent=true;
            return true;

        }
    }
    public void onSwipeUp() {
        setCurrentItem(getCurrentItem() + 1);
    }
    public void onSwipeDown() {
        setCurrentItem(getCurrentItem() - 1);

    }
}

CustomAdapter

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;

public class CustomAdapter extends PagerAdapter {
    Context context;
    ArrayList<DataModel> arrayList = new ArrayList<>();

    LayoutInflater mLayoutInflater;

    public CustomAdapter(Context context, ArrayList<DataModel> arrayList) {
        this.context = context;
        this.arrayList = arrayList;
        mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((LinearLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        View itemView = mLayoutInflater.inflate(R.layout.custom_layout, container, false);

        TextView tvTitle = itemView.findViewById(R.id.tvTitle);
        TextView tvContent = itemView.findViewById(R.id.tvContent);

        tvContent.setText(arrayList.get(position).getContent());
        tvTitle.setText(arrayList.get(position).getTitle());

        tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "clicked position :" + position + " " + arrayList.get(position).getTitle(), Toast.LENGTH_SHORT).show();
            }
        });

        container.addView(itemView);

        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }
}

DataModel

public class DataModel {
    String title, content;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

custom_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="Nilesh"
        android:textColor="#000"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tvContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Hope this helps
EDIT
For fling effect use Move views using a fling animation

Fling-based animation uses a friction force that is proportional to an object's velocity. Use it to animate a property of an object and want to end the animation gradually. It has an initial momentum, which is mostly received from the gesture velocity, and gradually slows down. The animation comes to an end when the velocity of the animation is low enough that it makes no visible change on the device screen.
Comment: I have solved the problem by changing some code in Vertical ViewPager . Thanks for your answer
Comment: Please check my question. I have already tried vertical viewpager . In my case, scrolling to next page is too hard and fling is not supported
Comment: @JyotiJK can u share any gif or image of required fling effect more idea
Comment: @JyotiJK also check this **[Move views using a fling animation](https://developer.android.com/guide/topics/graphics/fling-animation)**
Comment: I will try and will let you know if any issue
Comment: @JyotiJK happy to hear that


Fazer uma consultar com base externa no Zend Framework

Question: Model
  public function excluirFiliadosNaoEnviados($base)
{

      $sql = "SELECT FROM " . $base . ".debito_automatico";
      $acao = $this->conexao->prepare($sql);
      if($acao->execute()){
        return true;
      }else{
        return false;
      }

}

Controle
public function prepararfiliadosAction()
{

    $base = DATABASE_GERAL;

    if($this->repositorio->excluirFiliadosNaoEnviados($base)) {
        echo $this->repositorio->prepararFiliados($this->getMesCompetencia()) ? 'true' : 'false';
    }

    $this->_helper->layout->disableLayout();
    $this->_helper->viewRenderer->setNoRender(TRUE);
}

A consulta não esta funcionando sempre retornando false.
Answer: Crie um model
<?php
class Application_Model_Inusuarios extends Zend_Db_Table_Abstract
{
    protected $_name    = 'in_usuarios';
    protected $_primary = array('id');
    protected $_dependentTables = array(
        "Application_Model_Inordem",
    );

    protected $_referenceMap = array(

        'Inloja' => array(
            'refTableClass'     => 'Application_Model_Inloja',
            'refColumns'        => 'id',
            'columns'           => 'loja_id'
        )
    );
}

Em seu action voce pode usar o model para montar sua query
public minhaAction(){

$modelUser = new Application_Model_Inusuarios();

$usuarioAtual = $modelUser->find($id)->current();

$sqlUsuariosAtivos   = $modelUser->select()->where("usuario_status = 'ativo'")->forceIndex("usuario_status");
$resultado = $modelUser->fetchAll($sqlUsuariosAtivos);
foreach ($resultado as $user){
    print_r($user);
}

}


Passing function pointer in place of slot function

Question: While trying to do something like this:
connect(process1, SIGNAL(waitForReadyRead()), this, SLOT(dataReceived_1()));

i have way too many processes for signals.
I have created a QList with all those processes (objects).
In order to simplify the code, i wanted to put this connect in a loop and perform this signal slot connection by iterating through the processList.
Something like this:
for(int i=0; i<procList.length(); ++i){
   connect(procList[i], SIGNAL(waitForReadyRead()), this, SLOT(data_rcvd[i]));
}

Here data_rcvd is a QList containing the slot functions.~
but unfortunately we can not add functions inside QList. So i want to know, is there a possibility to define function pointers to achieve this task???
Or you think, i create a new QProcess class (extend) and overload the function waitForReadyRead() to emit a pointer containing this specific information maybe?
Comment: How are slots differ for each process? Why don't you connect signals from all processes to a single slot?
Comment: Do you have a constant set of methods/functions that serve as slots? Is it always 1:1 relation? And how many are we talking about?
Comment: @tomdol yes they are 1-1 and about 20 of them.
Answer: A list may not contain functions but it may contain function pointers. So declare a list of function pointers . In expressions function designators implicitly are converted to pointers to the function types. Pointers are objects.
Here is a demonstrative program that uses the standard container std::list.
#include <iostream>
#include <list>

long long sum( int x, int y ) { return ( long long )x + y; }
long long multiply( int x, int y ) { return ( long long )x * y; }

int main()
{
    std::list<long long( * )( int, int )> lst = { sum, multiply };

    for ( const auto &p : lst ) std::cout << p( 10, 2 ) << '\n';
}

Its output is
12
20

Comment: Can you give an example for this?
Comment: thanks it works fine in general but when i define the function within a class (non static) then it does not compile. I always get this error: reference to non static member function must be called. I can not define function as slots if is declare them globally. Any idea?
Comment: @johnybravo Use instead template argument of the list like std::function.
Comment: Im still learning, could you give some idea? Although not perfect but one workaround as i see, if i declare the member function static it works. Since i will have only one instance of the class doing this, in worse case i will just use this technique then
Comment: @johnybravo As I already mentioned you can use std;:function.


Show that $\Vert v\Vert^2= \langle v,AA' v\rangle \iff AA'=I$

Question: Show that $\Vert v\Vert^2= \langle v,AA' v\rangle \iff AA'=I$.
My thoughts: let $AA'=M$. Then, the above implies
$$
\sum^n_{i=1}(1-M_{ii})v_i^2+\sum^n_{i=1}\sum^n_{j\neq i}v_iM_{ij}v_j=0.
$$
How would one go about showing $M_{ii}=1$ and $M_{ij}=0$?
Comment: $$||v||^2 = \langle v,v \rangle = \langle v, AA'v\rangle$$ helps you?
Comment: Use my hint and Luis hint. We get something like $\|Av\|^2 = \langle Av, Av \rangle = \langle v, v \rangle = \|v\|^2$ for all $v \in V$ (maybe need to move some primes around). What do we know about functions that preserve norms? (Hint: https://en.wikipedia.org/wiki/Isometry)
Comment: Is this over a real vector space and $A : V \rightarrow V$ is linear?
Comment: @User203940 yes, and A is a matrix.
Comment: Can you show $\langle Av, w \rangle = \langle v, A'w \rangle$?
Comment: Yes. $(Av)'w= v'A'w$.
Comment: I guess this boils down to how does one prove $\langle x,y\rangle= \langle x,z\rangle \iff y=z$
Answer: Let's prove $\|Av\| = \|v\|$ for all $v \in V$ iff $\langle Av, Aw\rangle = \langle v, w \rangle$ for all $v, w \in V$. This plus the hints should be enough for you to finish it.
If $\langle Av, Aw \rangle = \langle v, w \rangle $for all $v, w \in V$, then set $v = w$ to get $\|Av\|^2 = \langle Av, Av \rangle = \langle v, v \rangle = \|v\|^2$, so $\|Av\| = \|v\|.$
If $\|Av\| = \|v\|$ for all $v \in V$, then $\|A(v+w)\| = \|v+w\|$ for all $v, w \in V$. Notice
$$ \|A(v+w)\|^2= \langle A(v+w), A(v+w) \rangle = \langle Av + Aw, Av + Aw \rangle = \langle Av, Av\rangle + 2\langle Av, Aw \rangle + \langle Aw, Aw \rangle = \|v\|^2 + 2 \langle Av, Aw \rangle + \|w\|^2,$$
$$ \|v+w\|^2 = \langle v+w, v+w \rangle = \|v\|^2 + 2\langle v, w \rangle + \|w\|^2.$$
Setting these equal to each other and doing some algebra, we have
$$ 2 \langle Av, Aw \rangle = 2 \langle v, w \rangle \implies \langle Av, Aw \rangle = \langle v, w \rangle.$$
Edit: I'll also solve your problem in the comments. Fix $y$ and $z$. We claim $\langle x, y \rangle = \langle x, z \rangle$ for all $x$ iff $y = z$. The hard part is the implication, which we do now. If $\langle x, y \rangle = \langle x, z \rangle$, then $\langle x, y- z \rangle = 0$ for all $x$. In particular, $\langle y-z, y-z \rangle = \|y-z\|^2 = 0$. But recall $\|y-z\|^2 = 0$ if and only if $y - z =0$, or $y = z$.
Comment: Can I claim that by definition of isometry $A$ must be injective . Thus, $AA'w =w$ which then $ \implies AA'=I$?
Comment: This is proving that $A$ is an isometry, so you do need this step. Then if you know $A$ injective implies $AA'w = w$ you are done, but we haven't necessarily shown that yet. (It should be an easy step.)
Comment: Was the solution given in the edit a separate way to achieve the same goal; one without using the injectivity of $A$?
Comment: I just did it since you asked about it. You can probably use it.
Comment: This is a very enlightening post for me. I will accept the answer now.


Selecionar data a partir da data atual usando pickadate.js

Question: estou trabalhando em um projeto simples para um hostel, no site tem um pequeno formulário de solicitação de estádia. Nele tem dois campos para selecionar a data de entrada e outro para selecionar a data de saída.
Eu estou usando a biblioteca http://amsul.ca/pickadate.js/ pois já trabalho com ela a um bom tempo.
O problema é que não estou encontrando uma forma para que o segundo input onde irá carregar a data de saída, seja maior que a data selecionada no campo de chegada, igualmente tem nesses sites de compras de passagens. alguém me da uma luz?

$('.data1').pickadate({
  formatSubmit: 'yyyy/mm/dd',
  closeOnSelect: true,
  closeOnClear: true,
  monthsFull: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
  monthsShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
  weekdaysFull: ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'],
  weekdaysShort: ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sab'],
  today: 'hoje',
  clear: 'limpar',
  close: 'fechar',
  format: 'dd/mm/yyyy'
});

$('.data2').pickadate({
  formatSubmit: 'yyyy/mm/dd',
  closeOnSelect: true,
  closeOnClear: true,
  monthsFull: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
  monthsShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
  weekdaysFull: ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'],
  weekdaysShort: ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sab'],
  today: 'hoje',
  clear: 'limpar',
  close: 'fechar',
  format: 'dd/mm/yyyy'
});

<link href="https://parahybahostel.com.br/css/classic.css" rel="stylesheet" />
<link href="https://parahybahostel.com.br/css/classic.date.css" rel="stylesheet" />

<form method="POST">
  Entrada:
  <input type="text" name="chegada" class="data1" value="" />

 Saída:
  <input type="text" name="saida" class="data2" value="" />
</form>
Comment: está utilizando alguma linguagem bakc-end? pode incluir parte do código para testarmos ?
Comment: @JulioHenrique97 não estou usando não, eu inserir o código, como vc pode ver, a biblioteca já exibe todo o calendário
Comment: você quer que quando selecionar a primeira data a segunda não possa ser colocada caso seja selecionado uma data menor que a primeira ?
Comment: isso mesmo, igual neste exemplo aqui https://jqueryui.com/datepicker/#date-range
Comment: Nesse caso acho que minha resposta seria útil porem não do jeito que você queria, pera aê
Comment: Exato, funcionou, mas não da forma que eu queria rs, estou tentando aqui adaptar mas não consigo pegar o valor do ID data1 e usar no parâmetro min
Comment: ja desenvolvi o codigo pra vc, estou postando a resposta
Comment: ja postei uma solução
Answer: Utilize o min: new Date() no  formato YYYY/MM/DD
Consulte a documentação aqui e veja exemplos
$('.data1').pickadate({
  formatSubmit: 'yyyy/mm/dd',
  min: new Date(2017,11,28), // defina aqui adata de hoje
  closeOnSelect: true,
  closeOnClear: true,
  monthsFull: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
  monthsShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago',
 'Set', 'Out', 'Nov', 'Dez'],
  weekdaysFull: ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira',
 'quinta-feira', 'sexta-feira', 'sábado'],
  weekdaysShort: ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sab'],
  today: 'hoje',
  clear: 'limpar',
  close: 'fechar',
  format: 'dd/mm/yyyy'
});

Comment: O problema é que não seria a data de hoje, tem como jogar o valor da primeira data, que seria a data de chegada aí dentro? pois imagine que a pessoa selecione a data 20/12 ela não podere selecionar na data de sair uma data igual ou inferior a 20/12


ansible: Run role 'bar' against host 'B' when running role 'foo' against host 'A'

Question: Can I run a different role against a different host as a dependency of a role?
My use case for this is to reconfigure "postfwd" on my mail server when running the "postfix" role against a new server (which will relay all mail thru the mail server).
Answer: This is possible since ansible 1.3 using role dependencies and delegate_to
To run the postfwd role against host mail.example.com whenever the postfix role is run against any host, add the following to meta/main.yml within the postfix role:
dependencies:
  - role: postfwd
    delegate_to: mail.example.com


Why are these two functions equal?

Question: These functions are equal. But I don't understand why.
$$a \leftrightarrow f(x) =|\cos(2\pi x)|^2$$
$$b \leftrightarrow f(x) = \dfrac{\cos(4\pi x)}{2} + 0.5$$
Which results both in this plot:
Answer: They are the same because
$$|\cos(x)|^2=\cos^2(x)=\frac{1+\cos(2x)}{2}=\frac{\cos(2x)}{2}+\frac{1}{2}.$$
(Note that the absolute value doesn't do anything, because of the square; i.e., $x^2=|x|^2$ for any $x$.) See here. This can be derived as follows:
For any $x$ and $y$, we have
$$\cos(x+y)=\cos(x)\cos(y)-\sin(x)\sin(y).$$
Thus,
$$\cos(2x)=\cos^2(x)-\sin^2(x)$$
$$\cos(2x)=\cos^2(x)-(1-\cos^2(x))$$
$$\cos(2x)=2\cos^2(x)-1$$
and therefore
$$\cos^2(x)=\frac{1+\cos(2x)}{2}$$
Here is another, more direct derivation, using complex exponential definition of cosine:
$$\cos^2(x)=\left(\frac{e^{ix}+e^{-ix}}{2}\right)^2=\frac{(e^{ix})^2+2(e^{ix})(e^{-ix})+(e^{-ix})^2}{4}=$$
$$\frac{e^{i(2x)}+e^{-i(2x)}+2}{4}=\frac{\cos(2x)+1}{2}$$
Comment: Really strange, I restarted the browser already. I can't down vote as well (just to try ;)).
Comment: Thanks. I can accept, but not +1... "An error has occurred - please retry your request" I already tried 5 times.
Comment: @Martijn: Hmm, that's a bit odd. I guess try refreshing the page, or restarting your browser? If it doesn't work, don't worry about it, one upvote is not much in the grand scheme of things :)
Comment: Aha, succeeded. I logged out from the site, and logged in again. Now, I can see my upvote was registered, but I was unable to see it.
Comment: Another way to see they are equal is to consider the derivative of their difference. It's zero, so the difference is a constant, and the constant can be found by considering the difference at any convenient value such as x=0.

Why are these two functions equal?


Does nginx clear files in cache directory

Question: I have a few servers running nginx as a cache for larger static files.
Due to changes in disk space needed and so on, I've changed the size of the cache and also split it to multiple locations.
One question I do have though, will nginx clear any files in the cache directory if they are not used within the "inactive" time frame?
I basically want to know if I've made changes that will cause files in the cache location to not be updated by any requests, do I have to delete them myself to reclaim that space, or will nginx consider all files under any cache directory as candidates for eviction?
Answer: nginx documentation at http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache states

Cached data that are not accessed during the time specified by the inactive parameter get removed from the cache regardless of their freshness. By default, inactive is set to 10 minutes.

And

The special "cache manager" process monitors the maximum cache size set by the max_size parameter. When this size is exceeded, it removes the least recently used data. The data is removed in iterations configured by manager_files, manager_threshold, and manager_sleep parameters (1.11.5). During one iteration no more than manager_files items are deleted (by default, 100). The duration of one iteration is limited by the manager_threshold parameter (by default, 200 milliseconds). Between iterations, a pause configured by the manager_sleep parameter (by default, 50 milliseconds) is made.

Based on this information, nginx controls the disk space used.
If you are defining multiple proxy_cache_path entries with different keys_zone=name:size entries, each entry has its own declaration and counting of inactive time / maximum size of files.
So, if your keys_zone cache1 and keys_zone cache2 have max size 10 GB each, then your caches can take 20 GB in total.


Error is not catching properly

Question: I have a try... catch error handling while saving a custom form in the submit handler, but it is not going to the catch block nor throwing any error to the front end. Instead, it is throwing a fatal error and logging into the Apache error log. How could I force the error to appear on the front end?
   public function approve_button_handler(array &$form, FormStateInterface $form_state){
          $nid = $form_state->getValue('nid');
          try {
            $terra_node = Node::load($nid);
            $terra_node->set('field_number_of_cpu_s', $number_of_cpus);
            $terra_nodess->set('field_memory', $memory); //this is wrong
            //as i given $terra_nodess as the loaded entity type node,
            //or I could give a wrong field name.

            $terra_node->save();
          } catch (Exception $e) { //Not catching here
              drupal_set_message(t($e), 'error');
          }
    }

Comment: IMO don't do that - open terminal, `tail -f /var/log/apache2/error.log`, never close it :)
Comment: Yes, that should do thanks. But if something wrong happens in code, how could i know that without looking apache error log?
Comment: thanks, I am currently doing like that.
Answer: This is not a Drupal question, but a general PHP question. If your site is running PHP7, you can use the new Throwable instead of the Exception
   public function approve_button_handler(array &$form, FormStateInterface $form_state){
          $nid = $form_state->getValue('nid');
          try {
            $terra_node = Node::load($nid);
            $terra_node->set('field_number_of_cpu_s', $number_of_cpus);
            $terra_nodess->set('field_memory', $memory); //this is wrong

            $terra_node->save();
          } catch (Throwable $e) { // Use Throwable instead of Exception here
              drupal_set_message($e->getMessage(), 'error');
          }
    }

Remember, PHP7 only! And I fully agree with Clive's comment, showing Exceptions in the UI is a bad idea.
Comment: Yes, I realized that `showing Exceptions in the UI is a bad idea.` What all things fall in exceptions (Not fatal errors) that can show in the front end would be good to know.
Comment: Giving `Throwable` also falls into the `apache error log` not in front end. I have `PHP 7.3.0` running on CentOS-7

Error is not catching properly


Starting the script only once the "inventory" has reached a certan compacity in C#

Question: I'm writing a game in unity 3d and at one part of the game the player has too pick up the coins to unlock the door.
The inventory script
inventory script
I need my button script to know when there is 8 keys so it can unlock
button script
Any help would be super great.
Answer: You hold a reference to your InventoryScript inside your ButtonScript. Then your ButtonScript can ask your InventoryScript how many keys it has.


how to specify privacy settings( public , friends or only me) in Android Native Facebook login?

Question: I am searching for a long time and i was not successful yet .
Is there any method to specify the privacy setting while logging into the facebook itself through native login , so that whatever activities i do on facebook through app , posts in facebook with the specified privacy settings .
i am following the below link http://developers.facebook.com/docs/tutorials/androidsdk/3.0/scrumptious/authenticate/ for setting up the facebook native login .
while searching i found some codes for ios , they have something like

FBSessionDefaultAudienceEveryone
FBSessionDefaultAudienceALL_FRIENDS
FBSessionDefaultAudienceSELF

for privacy settings . But is there anything for android ?
i have added my code ,
<code>public class SplashFragment extends Fragment
{
    LoginButton authButton;
    //private static final List<String> PERMISSIONS = Arrays.asList("user_photos","email","user_status","friends_status","user_videos","user_checkins","friends_checkins","offline_access","user_actions.news","user_actions:parii_apps","user_events","friends_events");
    //private static final List<String> PERMISSION = Arrays.asList("publish_actions","publish_stream","publish_checkins","manage_pages","create_event","rsvp_event");

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.splash, container, false);

        authButton = (LoginButton) view.findViewById(R.id.fb_logIn_btn);
        authButton.setDefaultAudience(SessionDefaultAudience.ONLY_ME);
        Log.e(" setDefaultAudience ", " is "+authButton.getDefaultAudience());

        return view;
    }

}
</code>
this is not working for me
Any related answers are welcomed . Thanks in advance .
Answer: Yes.
Default audience only comes into play when you request for publish permissions, which you need to do through a session.requestForNewPublishPermissions() call with a NewPermissionsRequest object.
You can set a default audience on the NewPermissionsRequest object, see the javadocs here: https://developers.facebook.com/docs/reference/android/3.0/Session.NewPermissionsRequest
Comment: i went through the code but i could not get it clear . i added this line to LoginButton , LoginButton authButton.setDefaultAudience(SessionDefaultAudience.ONLY_ME);   But this does not do anything . Could you please explain briefly .
Comment: What permissions are you asking for? Default audience only applies to "publish" permissions like publish_stream, publish_actions, etc. Otherwise it's a no-op.
Comment: i want to set the privacy mode for the posts i do from my application . (i.e) If i specify ONLY_ME , then that particular post must me visible only to me and if EVERYONE , then the post must be shared as public ( visible to all ) . . . .
Comment: Please post the code on how you're doing this. I think we're speaking over each other at this point.
Comment: i have added the code to the question , please review it above .
Comment: Setting the default audience does not work globally, it only works for the particular permissions request you're making. So when you're asking for the [publish_actions, ...] permissions, that's when you need to set the default audience. Setting it just on the auth button doesn't do anything since that's not when you're asking for the publish permissions.


Proof by Induction: Solving $1+3+5+\cdots+(2n-1)$

Question: The question asks to verify that each equation is true for every positive integer n.
The question is as follows:
$$1+ 3 + 5 + \cdots + (2n - 1) = n^2$$
I have solved the base step which is where $n = 1$.
However now once I proceed to the inductive step, I get a little lost on where to go next:
<code>Assuming that k is true (k = n), solve for k+1:

(2k - 1) + (2(k+1) - 1)
(2k - 1) + (2k+2 - 1)
(2k - 1) + (2k + 1)
</code>
This is where I am stuck. Do I factor these further to obtain a polynomial of some sort? Or am I missing something?
Comment: "Solve for" is definitely the wrong term.  If I have the equation $x+y=5$ and I _solve for_ $y$, I get $y=5-x$.  That's how that term should be used.  If you write "Assuming that case $k$ is true, prove case $k+1$", then it would make sense.
Comment: I understand now. Next time I'll post the question with the correct terminology.
Answer: Assume true for $k$. Then consider the case $k+1$, you got $$1+3+\cdots+(2k-1)+(2(k+1)-1)$$ which is equal by inductive hypothesis $$k^2+(2k+1)=(k+1)^2$$ and this closes the induction.
Comment: As Michael Hardy said. You dont "solve". You do your base step, and then assume it holds for an arbitrary $k$, with this you have to show that $k+1$ holds as well.
Comment: So just to be clear, since I have proven that (2n - 1) is equivalent to n^2, I can just use n^2 + (2k + 1) and simplify to prove the next step in the induction case?
Comment: First of all $2n-1$ is not equivalent to $n^2$, the summation of odd numbers up to and including $2n-1$ equals to $n^2$, and the way induction works is: Prove it for a base case, then assume that it holds for an arbritrary number $n$, and then you have to use this to prove that the condition holds for $n+1$ as well.

Think of it as dominos. Your base case is saying "the first domino falls" and then your inductive step is saying, suppose one domino falls, (show some work) then the next domino falls. Hence, all dominos fall.
Comment: Thanks. I need to be more careful with how I word things. I understood that the summation of odd numbers up to and including 2n-1 was n^2, I just phrased it wrong. Thanks. I think the domino effect actually makes it much clearer to me. My main problem was figuring out how to finish the problem. You have really helped me a lot though. thank you!
Comment: This blog helped me also: https://perkss.github.io/#/MathFundamentals/MathPreliminaries#text-body
Answer: You have
$$
1+3+5+7+\cdots+(2k-1)\quad + \quad \Big( 2(k+1) - 1 \Big).
$$
This is equal to
$$
k^2 \quad + \quad \Big( 2(k+1) - 1\Big).
$$
Simplify:
$$
k^2 + 2k + 2 - 1
$$
$$
= k^2 + 2k + 1
$$
$$
= (k+1)^2.
$$
Answer: Even though there is an accepted answer, I feel compelled to give a "geometric proof," and by that, I mean a picture. This is in the spirit of discrete mathematics' counting in two ways.
The small blue squares of any individual larger square represent the last term of your sum. Here, I have shown $n=1,2,3,4$. Obviously, each large square has $n^2$ area.  Or you can see that it can also be thought of as adding up the "L" shaped additions.  Since both of these methods are counting the same thing, they must be the same number.


If $\int^{\pi}_0 x f (\sin x) dx = k \int^{\pi/2}_0 f (\sin x) dx$, find $k$.

Question:
Problem : If $\int^{\pi}_0 x f (\sin x) dx = k \int^{\pi/2}_0 f (\sin x) dx$, find $k$.
Solution : Period of sine function is $2 \pi$

I don't know whether we can use the period of this function to solve this problem.
Comment: I didn't downvote you, but I imagine the person who did did it because your title contains all the relevant information about the question and the body of the post doesn't contribute much.
Comment: Why did this get a down vote?
Answer: Let $ I := \int\limits_0^\pi x f(\sin x)\ dx $. By the substitution $ u \mapsto \pi - x $, we arrive at $$I =  \int\limits_0^\pi \left(\pi - u\right) f\left(\sin\left(\pi - u\right)\right) \ du = \int\limits_0^\pi \left(\pi - u\right)f(\sin u)\ du $$Hence, $$ 2I = \int_0^\pi \left(u + \left(\pi - u\right)\right)f(\sin u) \ du = 2\pi \int_0^\frac{\pi}{2} f(\sin u) \ du $$ Hence, the answer is that $ k = \pi $.
Comment: $ \sin x $ is symmetric about $ \frac{\pi}{2} $ so the integral from $ 0 $ to $ \frac{\pi}{2} $ has the same value as the integral from $ \frac{\pi}{2} $ to $ \pi $.
Comment: Can we use $f(sin ({\pi/2}- x) = f (sin x)$. I think $sin ({\pi/2}- x)= cosx$
Comment: You're right. I'll fix the post.
Comment: Now u= $\pi -x $ when $x=0$ then $u= \pi$ and when $x= \pi$ then u should be $0$ also $du =- dx$ I get it
Comment: @JonClaus I have a question: in your final integral $2\pi \int_0^\frac{\pi}{2} f(\sin u) \ du$, how did you factor the $2$ out of the integral and make the upper bound of the integral $\pi/2$?
Comment: @JonClaus Ah that makes sense. Clever.
Comment: @rst, after the substitution the bottom limit becomes $ \pi $, the upper limit becomes $ 0 $, and $ dx $ becomes $ -du $. Then you can reverse the two limits by canceling the negation.
Comment: In general, $ \displaystyle \int_a^b f(x) \ dx = \int_a^b f(a + b - x) \ dx $ precisely by that logic.
Comment: @JonClaus Yeah, I realized it after posting the comment. Thats why  wrote"I get it"
Comment: We can also see last step by the formula $\int^{2a} _0 f dx=2\int^a _0 f dx$ if $f(2a-x)=f(x)$
Answer: Assume that the given equation is true regardless of the unknown function $f$. Then, to simplify calculations, choose a simple function such as $f(x)=1$. Then we obtain:
$$ \begin{align*}
\int_0^{\pi} x dx &=  k\int_0^{\pi/2} dx \\
\left[\dfrac{x^2}{2} \right]_0^{\pi} &=  k\left[x \right]_0^{\pi/2} \\
\dfrac{\pi^2}{2} &=  k\left[\dfrac{\pi}{2} \right] \\
k &= \pi
\end{align*} $$
Comment: This can be a useful strategy for multiple choice questions.
Comment: Depending on the context for the OP, that assumption for $f$ may require more justification.
Comment: @AndréNicolas A very helpful observation!
Comment: Well, above assumption is not necessary


Retain values during myform_validate()

Question: In Drupal 6, I have a custom form validation function, where:

I copy the value from field A to field B, if field B is empty.
I call form_set_error() when the field B contains more than X characters.

Validation works fine, and the error is set. The problem is that the value in field B is not retained when the form is rebuilt: field B remains empty. I want to keep the value in field B after validation (when the error is set) to make it easy for users to edit it down to the right length.
My validation function looks like this:
function myform_validate($form, &$form_state) {
  if (empty($form_state['values']['field_b']['0']['value'])) {
        $form_state['values']['field_b']['0']['value'] = $form_state['values']['field_a']['0']['value'];
      }
      if (strlen($form_state['values']['field_b']['0']['value']) > 260) {
        form_set_error('field_b', 'Text in field b is too long');
      }
    }
  }
}

Any suggestions on how to retain the value in field B when the form is rebuilt?
Answer: If you want to set a form value from within your validation callback you'll need to use something like form_set_value. Values that are assigned directly in the manner shown above will not be retained, but that function should do the trick! It's specifically intended for this purpose - setting a form value during the validation phase.
For example:
function myform_validate($form, &$form_state) {
  if (empty($form_state['values']['field_b'])) {
        // Note that the $form array - not $form_state - is used in the first parameter.
        // The second parameter is the value you are setting.
        // Third just pass the $form_state array itself, which will be altered by form_set_vaue().
        form_set_value($form['field_b'], $form_state['values']['field_a'], $form_state);
      }
      if (strlen($form_state['values']['field_b']) > 260) {
        form_set_error('field_b', 'Text in field b is too long');
      }
    }
  }
}

Comment: Thanks! `form_set_value()` is what I was looking for. I'm struggling to find the right value to replace, as it's part of a (CCK fieldset) array.

I understand I have to pass in an '#parents' array, but can't seem to find the correct key/array path.

The field itself is a textfield that's part of a fieldset, so I've tried mulitple variations of `array('#parents' => array('fieldset', 'field', '0', 'value')`. Anything obvious I'm doing wrong here?
Comment: Answering my own question: `form_set_value(array('#parents' => array('field_a', '0', 'value')), $form_state['values']['field_b'][0]['value'], $form_state);` seems the right way to get to the field's value.

Retain values during myform_validate()


Pinched/Palm Harmonics

Question: After playing with pinched harmonics for ages, I recently, completely by accident, found palm harmonics.
Pinched uses the edge of the thumb to produce the node, while palm uses the palm for the same purpose.
Is one better than the other - easier to use, more effective? I feel that for all harmonics, the closer to the bridge the string is plucked, the easier it is to make them, so possibly palm harmonics is the way to go. But very few players seem to use them, preferring pinched instead. Why?
Answer: Is this on the electric guitar? I use palm harmonics when playing slide guitar with a thumb pick, and I believe that lap steel players use them. They're not as accurate as pinch harmonics, I would guess.
Comment: Yes, electric..
Comment: True, lap steel players won't tend to use pinched harmonics, as the palm is more readily available.
Answer: I am sure I've tried palm harmonics, but I'm good with pinch harmonics because it's all done with a party of your body thats used to being used dexterously, the thumb. I'm sure many learn pinch harmonics by accident, with it being very close to how they normally pick.
Steel players usually have a bar in one hand and fingerpicks on the other, so the palm is the only skin available to get that effect.
Answer: It's all a matter of personal tastes, innate aptitudes, and reflexive habit.
To say one is better than the other would be to offer an opinion.
To say one is easier than the other is to share your personal experience.
And which one is more effective is completely up to the performer. (And the satisfied members of the audience as well, come to think of it.)
I think it's all a matter of how you were trained, or the culture in which you were raised.
The first few times I saw videos of Jeff Lynne (of ELO fame) playing guitar, I thought, "What the heck?".
He tends to play these interesting chords up the fret board wherein he hangs his fretting hand thumb up over the top to either barre the top string or two, or to achieve a muting effect.
The way most of us were raised, we would endeavor to achieve the same sounds using a conventional barre chord technique, using our fretting hand index finger as the movable nut.
Tomato-tomaahto.
Whatever works, that's what gets the job done.
Comment: Jeff hangs his thumb over to touch the bottom strings, not top. This hardly answers the question, and personal experience is what goes towards answering a lot of questions here, not a lot wrong in that.
Comment: I'm not asking about easier/harder. More *when* one is the better way to play each of those harmonics. One of my claims to fame is I used to teach Jeff's sister Andrea to play guitar! Weird!

Pinched/Palm Harmonics


Drupal Caching and hook_init

Question: So I was considering using hook_init() to do stuff but I'm not understanding what it means when it says that "This hook is not run on cached pages." Oh really?
So as an experiment I made sure caching was turned on for anonymous users, and went to the site in a browser window where I was not logged in. So I was definitely getting some cached pages, right? Then I added this to my module
function mymodule_init() {
  $num = rand(0,1000);
  drupal_set_message($num);
}

I figured if the hook wasn't being run, then I shouldn't get a random number each time I viewed the page. I wasn't sure if I should even get a message or not! But I am getting a different random number each time. So what exactly does it mean when it says that the hook isn't being run on cached pages? And when is it NOT ok to use this hook? Sorry if it's something obvious I don't know.
-- edit --
Thanks for the answer. I should have realized the drupal_set_message thing was causing the page not to be cached. So I went back and I also tried adding java script like this:
function mymodule_init() {
  $num = rand(0,1000);
  drupal_add_js(array('mymodule' => array('rand' => $num)), 'setting');

  $path = drupal_get_path('module', 'mymodule');
  drupal_add_js($path . '/js/mymodule.js');

  echo $num;
}

And in my javascript file:
(function ($) {
    Drupal.behaviors.mymodule = {
        attach: function(context,settings) {
            var num = Drupal.settings.mymodule.rand;

            alert(num);
        }
    }
})(jQuery)

It still seems to alert a random number every time. So is drupal_add_js also disabling the cache? I even tried using a simple echo statement in hook_init() and it still seemed to echo a random number. So are all these things causing the page not to be cached or does hook_init() still get run somehow?
Comment: Are you logged in?
Comment: I was not logged in on the browser I was using
Answer: A couple things here:

hook_init() will be run on the first hit on the page, eg, if it's not in cache already, it will be run and then the page will be cached.  But...
A page will not be cached if there are any drupal messages, so, when you call drupal_set_message() it sets drupal_page_is_cacheable(FALSE); and the page isn't cached.

ADDITION:
Regarding your additional code with respect to Javascript:  adding this code in verbatim here does not exhibit the random behavior you see on your site; eg; here the same number appears until the cache is refreshed.
Which made me think about this.  Check your cache times:

If the times are set to <none> I see the behavior you seem to experience, but when they are set to anything else, eg:

then I don't.

Drupal Caching and hook_init


Is it correct to say one 'estimates' or 'measures' r-squared?

Question: I am writing a report and am unsure about whether is correct to say one 'measures' r-squared or whether one 'estimates' it. I know the two words have two different semantic meanings, probably related to whether you are identifying the 'true' value or not, but as a non-statistician I am finding it hard to decide which is more appropriate.
Or perhaps neither is suitable and a different word is better.
I have searched around a fair amount and couldn't find an obvious answer.
Comment: In practice, I doubt anyone will care. Use whichever one sounds best to you
Comment: If you did both, it might be up to you to choose. Which did you do… "estimate" or "measure" or both?
Answer: The coefficient of determination $R^2$ is the square of the multiple correlation coefficient (see this related answer), which is a function of the sample coefficients between the variables.  Consequently, it is something that you "measure" or "compute" from the data, rather than something you estimate.  However, it is possible to define an analogous value for the square of the true multiple correlation coefficient and treat the coefficient of determination as an estimate for this, so you could reasonably say that you "measure" the coefficient of determination, but you "estimate" the underlying value of the square of the true multiple correlation.

Here is a more formal version of this breakdown.  Suppose we first define the true correlation values and sample correlation values (using the Pearson coefficient) for all the variables in the problem.  We will label the true correlation values $\rho_i = \mathbb{Corr}(Y,X_i)$ and $\rho_{i,j} = \mathbb{Corr}(X_i,X_j)$ and the sample correlation values $r_i = \mathbb{Corr}(\mathbf{y},\mathbf{x}_i)$ and $r_{i,j} = \mathbb{Corr}(\mathbf{x}_i,\mathbf{x}_j)$, where the latter denote sample correlation between observed vectors of values.  Now define the true version and sample version of the goodness of fit vector and design correlation matrix respectively by:
$$\mathbf{GOF} \ \mathbf{vector} \quad \quad \quad \quad \quad \quad \quad \quad \quad \mathbf{DC} \ \mathbf{matrix} \quad \quad \quad \quad \\[12pt]
\boldsymbol{\rho}_{\mathbf{y},\mathbf{x}} = \begin{bmatrix} \rho_1 \\ \rho_2 \\ \vdots \\ \rho_m \end{bmatrix} \quad \quad \quad \boldsymbol{\rho}_{\mathbf{x},\mathbf{x}} = \begin{bmatrix}
\rho_{1,1} & \rho_{1,2} & \cdots & \rho_{1,m} \\
\rho_{2,1} & \rho_{2,2} & \cdots & \rho_{2,m} \\
\vdots  & \vdots  & \ddots & \vdots  \\
\rho_{m,1} & \rho_{m,2} & \cdots & \rho_{m,m} \\ \end{bmatrix}, \\[40pt]
\boldsymbol{r}_{\mathbf{y},\mathbf{x}} = \begin{bmatrix} r_1 \\ r_2 \\ \vdots \\ r_m \end{bmatrix} \quad \quad \quad \boldsymbol{r}_{\mathbf{x},\mathbf{x}} = \begin{bmatrix}
r_{1,1} & r_{1,2} & \cdots & r_{1,m} \\
r_{2,1} & r_{2,2} & \cdots & r_{2,m} \\
\vdots  & \vdots  & \ddots & \vdots  \\
r_{m,1} & r_{m,2} & \cdots & r_{m,m} \\ \end{bmatrix}.$$
The parameter version and sample version of the coefficient of determination are then given by:
$$\begin{matrix}
\text{Regression model parameter (unnamed)}
\quad \quad \quad \quad \quad
\phi^2 = \boldsymbol{\rho}_{\mathbf{y},\mathbf{x}}^\text{T} \boldsymbol{\rho}_{\mathbf{x},\mathbf{x}}^{-1} \boldsymbol{\rho}_{\mathbf{y},\mathbf{x}},  \\[6pt]
\text{Coefficient of Determination}
\quad \quad \quad \quad \quad \quad \quad \quad \quad \quad
R^2 = \boldsymbol{r}_{\mathbf{y},\mathbf{x}}^\text{T} \boldsymbol{r}_{\mathbf{x},\mathbf{x}}^{-1} \boldsymbol{r}_{\mathbf{y},\mathbf{x}}. \\[6pt]
\end{matrix}$$
Now, the value $R^2$ is a statistic that can be computed from the sample, whereas the parameter $\phi^2$ is an unobservable aspect of the regression model that can only be estimated.  We can of course use the coefficient of determination $R^2$ to estimate the unknown parameter $\phi^2$.
Comment: @Nick I see a very real difference: the "computation" is a statistic whereas the target of the "estimate" is a parameter of the model.  All three--the statistic, the statistic *qua* estimator, and the parameter--can be called a "coefficient of determination."  This is perfectly in keeping with the ambiguous use of other terms like "mean" and "standard deviation" in similar situations.
Comment: Just to elaborate slightly on @whuber s trichotomy: I'm more familiar with them being called estimates, estimators, and estimands, respectively.
Comment: @Firebug: I think the problem here is that capital-rho (in Greek) uses an identical symbol to capital-p (in English).  It is usual to use unambiguously Greek symbols for model parameters, so I have chosen to switch to $\phi^2$ for this purpose.  Capital-rho is also rather fraught with peril in a statistical context, since capital-p is often used to denote a probability value or probability measure.
Comment: I have added a new section to this answer to be more explicit about the parameter and statistic in the present case.
Comment: That's just me being pedantic :P. It's the same glyph, yes
Comment: This sounds like a distinction without a difference to me. Statistics is full of messy and inconsistent terminology. Are you describing it, defending it or both?
Comment: +1, though missed chance of defining the estimand ${\it Ρ}^2$ (capital $\rho$) instead of $\phi^2$ :)
Answer: Although some theory relates $R^2$ to a certain "true" value, it is mostly not used and interpreted as an estimator of that value, but rather as a characteristic of an empirical fit, and as such I'd say it is "computed" and not "estimated". I wouldn't say "measured" either (which goes against my intuition but I have difficulties explaining why), although one could probably defend both "measured" and "estimated" if necessary.
Comment: This seems to hinge on how words are used in practice, which is fine by me, but your opening also weakens your case.
Comment: I agree about "measured". Like "estimated" it suggests that there is something apart from the data that you are attempting to get at.
Answer: To me, "estimates" sounds weird because the r-squares is not a representation of some hidden object. "Measures" could be okay but I don't hear that so often. I would prefer "calculates" or "computes".
Comment: Sounds weird is not much of a reason.
Comment: Re "not a representation:" On the contrary, $R^2$ is a definite property of the underlying population or model.
Comment: @whuber: That assumes the distribution of predictors $X$ is part of the model. But a regression model is often taken as only specifying the conditional distribution of $Y\mid X$, and in that case $R^2$ is not a property of the model. So I would prefer to say "calculates"
Comment: @kjetil No such assumption is necessary.  Either the distribution of the regressors is part of the model or the regressors are *fixed.*  It doesn't matter: $R^2$ remains a property of the data generating function.


Email chegando em branco com PHP

Question: Fiz um pequeno formulário para testar a função mail, o e-mail está sendo enviado porém chega com os campos nome e mensagem em branco. Vi outros fóruns e eles indicam outras bibliotecas mas queria saber no que estou errando.
<form action="enviar.php" method="post">

    Nome:
    <input type="text" name="nome" required>

    Email:
    <input type="email" name="email" required>

    Mensagem:
    <textarea name="mensagem"></textarea>

    <input type="submit" name="enviar" value="Enviar">

</form>

PHP
<?php

$nome = $_POST['nome'];
$email = $_POST['email'];
$mensagem = $_POST['mensagem'];
$titulo = 'Email Curso PHP';
$dest = 'firstname.lastname@example.com';
$dados = 'Nome :'.$nome." Email: ".$email." Destinatário: ".$dest." Mensagem: ".$mensagem;

mail($dest, $titulo, $dados);

?>

Comment: Verificou se os valores estão chegando corretamente em `$_POST`?
Comment: Sim, mas consegui fazer funcionar colocando tudo get. Está correto desta forma?
Answer: <?php

$nome = $_REQUEST['nome'];
$email = $_REQUEST['email'];
$mensagem = $_REQUEST['mensagem'];
$titulo = 'Email Curso PHP';
$dest = 'firstname.lastname@example.com';
$dados = 'Nome :'.$nome." Email: ".$email." Destinatário: ".$dest." Mensagem: ".$mensagem;

mail($dest, $titulo, $dados);

se Estiver num ambiente Linux verificar se tem permissão de leitura/escrita
Comment: Sua resposta parece exatamente a mesma do autor da pergunta. Tente não postar apenas código, explique como resolver o problema.
Comment: resolve o probelma mudando o $_POST pro $_REQUEST,não expliquei pois acho que dá para entender a diferença

Email chegando em branco com PHP


Google GeoCoding service - Getting clean street name

Question: I'm working with Google GeoCoding service (using a get request from the browser) and try to get the clean street name (without the pre/post direction and the suffix)
for example: If my address is "3307 W Bertona St Apt 3 , Seattle , WA"
I want to get just the street name "Bertona".
My request url:
https://maps.googleapis.com/maps/api/geocode/json?address=3307%20W%20Bertona%20St%20Apt%203%20%2C%20Seattle%20%2C%20WA%20%2C%20&sensor=false&client={clientId}&signature={PrivateKey}
Is there any way to retrieve the clean street name from the service?
Answer: You can retrieve the street name from address_components array in the response:
{
   "results":[
   {
        "address_components":[
        {
          "long_name":"3",
          "short_name":"3",
          "types":[
             "subpremise"
          ]
        },
        {
          "long_name":"3307",
          "short_name":"3307",
          "types":[
             "street_number"
          ]
        },
        {
           "long_name":"West Bertona Street",
           "short_name":"W Bertona St",
           "types":[
              "route"
           ]
         },

The component of type route contains the long and short street names. This is the most clean name that you can get from Geocoding API request.


Why is pandas str.replace returning NaN?

Question: I am trying to remove the comma separator from values in a dataframe in Pandas to enable me to convert the to Integers. I have been using the following method:
df_orders['qty'] = df_orders['qty'].str.replace(',','')

However this seems to be returning NaN values for some numbers which did not originally contain ',' in their values. I have included a sample of my Input data and current output below:
Input:
         date      sku  qty
556603  2020-10-25  A   6
590904  2020-10-21  A   5
595307  2020-10-20  A   31
602678  2020-10-19  A   11
615022  2020-10-18  A   2
641077  2020-10-16  A   1
650203  2020-10-15  A   3
655363  2020-10-14  A   18
667919  2020-10-13  A   5
674990  2020-10-12  A   2
703901  2020-10-09  A   1
715411  2020-10-08  A   1
721557  2020-10-07  A   31
740515  2020-10-06  A   49
752670  2020-10-05  A   4
808426  2020-09-28  A   2
848057  2020-09-23  A   1
865751  2020-09-21  A   2
886630  2020-09-18  A   3
901095  2020-09-16  A   47
938648  2020-09-10  A   2
969909  2020-09-07  A   3
1021548 2020-08-31  A   2
1032254 2020-08-30  A   8
1077443 2020-08-25  A   5
1089670 2020-08-24  A   24
1098843 2020-08-23  A   16
1102025 2020-08-22  A   23
1179347 2020-08-12  A   1
1305700 2020-07-29  A   1
1316343 2020-07-28  A   1
1399930 2020-07-19  A   1
1451864 2020-07-15  A   1
1463195 2020-07-14  A   15
2129080 2020-05-19  A   1
2143468 2020-05-18  A   1

Current Output:
         date      sku  qty
556603  2020-10-25  A   6
590904  2020-10-21  A   5
595307  2020-10-20  A   31
602678  2020-10-19  A   11
615022  2020-10-18  A   2
641077  2020-10-16  A   1
650203  2020-10-15  A   3
655363  2020-10-14  A   NaN
667919  2020-10-13  A   NaN
674990  2020-10-12  A   NaN
703901  2020-10-09  A   NaN
715411  2020-10-08  A   NaN
721557  2020-10-07  A   NaN
740515  2020-10-06  A   NaN
752670  2020-10-05  A   NaN
808426  2020-09-28  A   2
848057  2020-09-23  A   1
865751  2020-09-21  A   2
886630  2020-09-18  A   3
901095  2020-09-16  A   47
938648  2020-09-10  A   NaN
969909  2020-09-07  A   NaN
1021548 2020-08-31  A   NaN
1032254 2020-08-30  A   NaN
1077443 2020-08-25  A   NaN
1089670 2020-08-24  A   NaN
1098843 2020-08-23  A   NaN
1102025 2020-08-22  A   NaN
1179347 2020-08-12  A   NaN
1305700 2020-07-29  A   NaN
1316343 2020-07-28  A   1
1399930 2020-07-19  A   1
1451864 2020-07-15  A   1
1463195 2020-07-14  A   15
2129080 2020-05-19  A   1
2143468 2020-05-18  A   1

I have had a look around but can't seem to find what is causing this error.
Comment: must be going blind but i can't see any commas in your input dataframe?
Answer: I was able to reproduce your issue:
# toy df
df

  qty
0   1
1  2,
2   3

df['qty'].str.replace(',', '')

0    NaN
1      2
2    NaN
Name: qty, dtype: object

I created df by doing this:
df = pd.DataFrame({'qty': [1, '2,', 3]})

In other words, your column has mixed data types - some values are integers while others are strings. So when you apply .str methods on mixed types, non str types are converted to NaN to indicate "hey it doesn't make sense to run a str method on an int".

You may fix this by converting the entire column to string, then back to int:
df['qty'].astype(str).str.replace(',', '').astype(int)

Or if you want something a litte more robust, try
df['qty'] = pd.to_numeric(
    df['qty'].astype(str).str.extract('(\d+)', expand=False), errors='coerce')


Is it possible to send a variable to a page via a header redirect?

Question: I have a small error handling function that informs should inform the user of the error whilst on a redirect.
At present, it either redirects but does not pass through the variables $error and $prize or I can echo out the $error from the function.
I need to be able to redirect the user and then on the new page echo out the variable. Can i do this?
function error($error, $prize)
 {

    header('Location: ' . $form);
    echo $error . '
';
    echo $prize;

exit;
} // end error handler

Answer: This problem is often solved using session variables that show the error on the next page after the redirect. Basically, just check for session messages/errors on every page - and then you can add messages/errors to the user's session any time you need too.
Most PHP frameworks have this listed as "flash variables" under their session handling section.
Answer: You could do it through GET:
$params = http_build_query(array('error'=> $error, 'prize'=>$prize));
header('Location: '.$form.'?'.$params);

destination page:
if($_GET) {
   $vars = $_GET;
   echo $vars['error'];
   echo $vars['prize'];
}


Using python modules like beautifulSoup and request in Visual Studio C#

Question: I am trying to run an external python script using c# in visual studio. I am using modules like BeautifulSoup and requests
But I am getting the following error
No module named requests

Earlier I was getting the same error for BeautifulSoup, I added the following line to my python script and the error was solved
sys.path.append("[Path to Python]\Python\Python35-32\Lib\site-packages")

I am using IronPython in the Visual Studio 2015. Is there anyway I can overcome this error? If it is not possible, is there any other way to run a python script (with the above mentioned modules) in a c# environment.
I tried using the solution given by denfromufa, but then I am getting the following error
This is my Python code
import sys
import requests
import re
import io
from bs4 import BeautifulSoup
from math import floor

r  = requests.get("https://www.google.com/")
data = r.text
soup = BeautifulSoup(data, 'html.parser')
result = []

for item in soup.find_all(attrs={'class' :'something'}):
        for m in item.select('a[href^="something"]'):

        m1 = m['href'].replace("something","",1)

        m2 = re.sub(r'&.*$', "", m1)

        m3 = re.sub(r'%3F.*$', "", m2)

        m4 = m3.replace("%2F","/")

        m5 = m4.replace("%3A",":")

        result.append(m5)
        result.append(m.get_text())

for image in item.find_all('img'):
    k1 = re.sub(r'&cfs.*$',"",image['src'])
    k2 = re.sub(r'^https://something.*$',"",k1)
    k3 = re.sub(r'.*url=',"",k2)
    k4 = re.sub(r'%3F.*$', "", k3)
    k5 = k4.replace("%2F","/")
    k6 = k5.replace("%3A",":")
    k7 = re.sub(r'.*\.gif',"",k6)
    result.append(k7)

seen = set()
result_final = []
for item in result:
    if item not in seen:
        seen.add(item)
        result_final.append(item)

result_final = list(result_final)

My c# code is the following
 using (Py.GIL())
                {
                    dynamic sys = Py.Import("sys");
                dynamic requests = Py.Import("requests");
                dynamic re = Py.Import("re");
                dynamic io = Py.Import("io");
                dynamic BeautifulSoup = Py.Import("bs4");
                dynamic math = Py.Import("math");
                Console.WriteLine(5);
                dynamic r = requests.get("https://www.google.com/");
                dynamic data = r.text;
                dynamic soup = BeautifulSoup.BeautifulSoup(data, "html.parser");
                }

I used
    var divExp = new { _class = "smoething" };
    var item = soup.find_all(Py.kw("class", divExp._class));

I am getting the result. But when I try to implement the select method on the item variable, I ma getting an error saying that Python Object doesn't contain a definition for 'select'
item.select("a[href^='https://www.google.com/']");

Final Answer
using (Py.GIL())
                {
                    dynamic sys = Py.Import("sys");
                    dynamic requests = Py.Import("requests");
                    dynamic re = Py.Import("re");
                    dynamic io = Py.Import("io");
                    dynamic BeautifulSoup = Py.Import("bs4");
                    dynamic math = Py.Import("math");
                    Console.WriteLine(5);
                    dynamic r = requests.get(url);
                    dynamic data = r.text;
                    dynamic soup = BeautifulSoup.BeautifulSoup(data, "html.parser");

                    var divExp = new { _class = "className" };
                    var item = soup.find_all(Py.kw("class", divExp._class));
                    dynamic tag = soup.select("a[href^='https://something.com/']");
                    for (var i = 1; i < item.Length(); i++)
                    {
                        // Extrxting the required info using regex

                        String input = Convert.ToString(item[i]);
                        string pattern_link = "(.*href=\"https:[\\/][\\/]something.com[\\/]a.php\\?u=)|(&.*)";
                        string replacement_link = " ";
                        Regex rgx_link = new Regex(pattern_link);
                        string result_link = rgx_link.Replace(input, replacement_link);

                        .
                        .
                        .
                        .
                        string pattern_link_1 = "(http|https)%.*";
                        Regex rgx_link_1 = new Regex(pattern_link_1);
                        Match result_link_1 = rgx_link_1.Match(result_link);
                        String input_1_1 = Convert.ToString(result_link_1.Value);

                        result_link_2 = result_link_2.Replace("%2F", "/").Replace("%3A", ":");

                    }

                }

Answer: Why not use HTML Agility Pack? It's the C# equivalent.
http://html-agility-pack.net/
You can import it into your solution.
For external python scripts see,
https://www.codeproject.com/articles/121374/step-by-step-guidance-of-calling-iron-python-funct
Answer:
install CPython, one of versions 2.7, 3.4+
pip install pythonnet
reference installed Python.Runtime.DLL in your .NET project
follow tutorial on www.python4.net, embedding section.

```
<code>> scriptcs (ctrl-c to exit or :help for help)

> #r "C:\Python\Anaconda3_64b\Lib\site-packages\Python.Runtime.dll"
> using Python.Runtime;
> dynamic bs4;
> using (Py.GIL()) {bs4=Py.Import("bs4");}
> bs4.__file__.ToString()
C:\Python\Anaconda3_64b\lib\site-packages\bs4\__init__.py
> dynamic rq;
> using (Py.GIL()) {rq=Py.Import("requests");}
> dynamic r=rq.get("https://www.google.com/")
> dynamic soup = bs4.BeautifulSoup(r.text,"html.parser");
> soup.ToString()
</code>
```
Comment: This might sound a bit silly. How do I execute the file once I import it using PythonEngine.ImportModule("filename.py")
Comment: Here is one simple example: https://github.com/pythonnet/pythonnet/blob/master/README.md
Comment: You can also look at the embedded tests and nPython console project
Comment: I tried doing it, but I am getting some errors. The error is when I use a function from the imported module. I have updated the question with the new results
Comment: You need to import bs4 not BeautifulSoup. See bs tutorial: https://www.crummy.com/software/BeautifulSoup/bs4/doc/
Comment: I tried that  then I got "'Python.Runtime.PyObject' does not contain a definition for 'func' " exception

Edit:- I had to use BeautifulSoup.BeautifulSoup(data, "html.parser"). Now it works. Thank You
Comment: Can you point me to the syntaxes for the 'nested for loops'. Using the python one is not working out
Comment: I updated my answer, you did not use correctly bs4 namespaces
Comment: I was able to implement your code. But I am having problems in translating my code from python, especially in translating the nested for loops and calling functions with attributes. Is there a proper documentation for this
Comment: Feel free to open other issues. But formulate them with code samples
Comment: `"{ 'class' :'something'}"` is not a Python dictionary, instead you are just passing a string. You need to build a Python dict.
Comment: I tried passing it as a dictionary, but I am still getting the empty result. I updated the question
Comment: I was able to solve the previous error. But now another function I could call on that variable in python is not working
Comment: The problem is that you used `var item` - this should be `dynamic item`. Please read more about dynamic and DLR.
Comment: Thank You very much. I was able to solve all the errors, by following your suggestions. I finished writing my python in c#. It was the first time I was working with c# and python, and your suggestions were really valuable. Once again thank you for all the suggestions.
Comment: @KennethRoy can you update your answer with final solution?
Comment: Sorry for the delay, I was busy the past week and didn't get the time to visit the stackoverflow. I have updated it.


Não consigo atualizar meu app na google play?

Question: sei que é necessário alterar o número da versão, porém quando faço a alteração e tento gerar um apk dá erro e me mostra uma mensagem...
Error:Versão XML "2.0" não suportada; somente XML 1.0 é suportada.
Comment: Everton, se a [resposta do Wakim](http://pt.stackoverflow.com/a/51571/6454) te ajudou, vote nela, se ela é a certa, marque-a como *aceita*, dê uma olhada aqui: http://meta.pt.stackoverflow.com/a/1079/6454
Answer: Acredito que você tenha alterado isso:
<?xml version="1.0" encoding="utf-8"?>

Para isso:
<?xml version="2.0" encoding="utf-8"?>

Não está correto, porque essa é a versão do XML que é usado no AndroidManifest. É necessário manter como está.

Para incrementar a versão do seu aplicativo você precisa definir e modificar duas propriedades, mas a forma como isso é feito depende de como está fazendo o build do aplicativo.
As duas propriedades que dizem a versão do seu aplicativo são android:versionCode e android:versionName.
VersionCode
O VersionCode é um inteiro que representa a versão do código do seu aplicativo, relativo a outras versões. Você pode até programaticamente gerar esse valor, ele é apenas um número que diz quando um aplicativo é mais recente que outro. Ele não tem relação com a versão que o usuário vê.
Ele é usado apenas pelo Google Play e outras lojas, para saber que houve uma atualização no apk que você enviou, assim fazendo a distribuição.
Você pode usar a regra que quiser, até tendo espaços entre versões. Por experiência própria eu sempre incremento em 1 a cada atualização. Se você subir uma versão já usada, o Google Play irá rejeitar seu upload.
VersionName
O VersionName é uma String que representa a versão do release do seu aplicativo. Você pode usar a notação comum de <major>.<minor>.<point> (e.g: 2.0.1) ou qualquer outra forma que achar conveniente. Por ser uma String você seguir a ordem que quiser, que não faz diferença (O único problema é confundir o usuário).
Essa é a versão que o usuário de fato observa nas lojas.

Como eu citei, a configuração vai depender de como você faz o build do seu apk.
Se você usa o ADT
Apenas modifique os atributos android:versionCode e android:versionName na sua tag manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.package.name"
    android:versionCode="2"
    android:versionName="1.1">

    <application android:icon="@drawable/icon" android:label="@string/app_name">
    ...
    </application>
</manifest>

Se você usa o Gradle
Com o Gradle, você pode configurar o versionCode e versionName no build.gradle, mas lembre-se que ele sempre sobreescreverá o valor da tag manifest. Caso contrário é o valor da tag manifest que prevalecerá.
Exemplo de configuração:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1        # Valor que as lojas usam para identificar que houve uma atualizacao
        versionName "1.0"    # Valor que aparece para o usuario
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

Vale a pena olhar as referências para um melhor entendimento.
Referências:

http://developer.android.com/tools/publishing/versioning.html
http://developer.android.com/tools/building/configuring-gradle.html
Comment: Consegui, muito obrigado!! @Wakim


Writing a function of many variables as a function of a vector?

Question: I have a function that looks like this
$$f(x,y,z_1,z_2,z_3,\dots ,z_k) \tag{1}$$
and I figured I could write it compactly as
$$f'(x,y,Z) \tag{2}$$
where $Z = [z_1,z_2,z_3,\dots,z_k]$, and $f'$ denotes that the function may need to be changed to accommodate taking a vector as an input instead of a series of variables (I'm not sure it needs to be changed, but I put the $'$ incase a change is necessary).
Are these equivalent? At first I thought they were but now I'm thinking that they may not be. That is, can i rewrite $(1)$ as $(2)$?
If the re-writing is indeed okay, how would I denote the partial derivative of $(2)$ w.r.t $z_i, 1\leq i \leq k$? Because if I use $(1)$ is is just $f_{i+2}(\cdot)$
I'm thinking now that it may be best to leave my function in the form of $(1)$, regardless of whether a transformation is possible...
Thanks.
Answer: A function $f:A^n\to\mathbb{R}$, where $A^n\subset \mathbb{R}^n$ can be expressed in any convenient way, either $f(x_1,...,x_n)$ or $f(\vec{x})$ where $\vec{x}=(x_1,...,x_n)$, that is $$
 f(\vec{x})\equiv f(x_1,...,x_n)$$ both notation are equivalent and commonly used. The gradient (a vector of partial derivatives) of both is
$$\vec{\nabla} f =\left(\frac{\partial f}{\partial x_1},...,\frac{\partial f}{\partial x_n}\right)$$


Best way to draw circle in C using letters

Question: I want to draw a circle using (ASCII) letters like +, - or *. What is best algorithm for this problem?
Comment: Did you try [Midpoint circle algorithm on wikipedia](http://en.wikipedia.org/wiki/Midpoint_circle_algorithm)
Answer: You can do something like this:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int main()
{
    int radius = 16;
    int i,j;
    for (i=0; i<=2*radius; i++)
    {
        for (j=0; j<=2*radius; j++)
        {
            double distance = sqrt((double)(i-radius)*(i-radius) + (j-radius)*(j-radius));
            if (distance>radius-0.5 && distance<radius+0.5)
            {
                printf("*");
            }
            else
            { printf(" ");}
        }
        printf("\n");
    }
    return 0;
}


How to align a dhtml button to the right

Question: I have this button:
{ type:"button", name:"map_button", value:"Show in Map", width: 100, enabled:false  },
what command can I use to align it to the right?  I have tried:
{ type:"button", name:"map_button", align:"right", value:"Show in Map", width: 100, enabled:false  },
and it doesn't work. I am not sure what else it could be
Comment: yes thank you! offsetLeft worked.
Answer: I believe you might be looking for the "offsetLeft" attribute:
{ type:"button", name:"map_button", offsetLeft:100, value:"Show in Map", width: 100, enabled:false }
Also, you might want to try playing with the "position" attribute as in this link:
http://docs.dhtmlx.com/form__positioning.html
Answer: You can use something like that:

{type:'block',name:'block_button',list:[
  {type:"button", name:"map_button",value:"Show in
  Map",width:100,enabled:false } ]}

And after declare the form:

name_form._getItemByName('block_button').style.float='right'


Is there a way to quickly disable caching for all views? (for dev work)

Question: Is there a variable/other way to quickly disable all views caching when working on a dev server?  I have a lot of views which have different caching settings, and there are times when I am doing testing that I would just like to turn all views caching off, similar to the way that you can turn CSS/JS aggregation off.
I found that the Views module itself has its own cache in the documentation, but this is not the caching for individual views-- and the caching for each individual view is what I want to turn off.
Comment: +1. Interesting question asked before: [How to disable/enable cache of all views programmatically?](http://drupal.stackexchange.com/questions/161408/how-to-disable-enable-cache-of-all-views-programmatically). What is described here [How to disable caching in Drupal 7 Views module](http://www.inmotionhosting.com/support/edu/drupal-7/views-module-tutorial/disable-view-cache) does not have the desired effect and what you refer to here [Disable Views caching](https://www.drupal.org/node/1917566) says that mentioned setting in Views only caches meta-data about Views or am I missing something?
Answer: If You ask about drupal 7 can use
cache_clear_all('*', 'cache_views', TRUE);
in template file.
Refreshing page that is using the file will clear all views cache.


List of medical terms

Question: Does anyone know where I might get my hands on a list of medical terms (diseases, etc.)? Diminutive forms are unnecessary. Crucially, the data cannot be dirty, and cannot contain words that are typically not used in a non-medical sense. The use of this list requires that false-positive identification of a medically relevant term be kept to a minimum. To this end it does not have to be exhaustive (precision vs recall).
I have found a number of lists on github. However ones like this have common first names included (such as Jacob, Jack, Marcus, Robin, etc.), meaning that all such terms would have to be manually weeded out before it could be used.
Comment: Diseases and their diagnoses for example are standardized as ICD - http://en.wikipedia.org/wiki/International_Statistical_Classification_of_Diseases_and_Related_Health_Problems. Refine the requirements. I guess you're looking for `English` but in Radiology and Pathology it is not uncommon that doctors use [Latin](http://en.wikipedia.org/wiki/Latin) as the finding-description language.
Comment: I'm voting to close this question as off-topic because it is not a specific programming problem.
Answer: Health.gov data sets have diagnosis codes used by Medicare

List of medical terms


Adding content type field value to a taxonomy term?

Question: What I'm trying to say at the title is, I have this Select List field that gets its values from a taxonomy called "Thing".
The taxonomy term are (Thing-1,Thing-2,Other).
When "Other" is selected a text field called "Specify" will appear. What I'm trying to do is when the user submits the form. Whatever he placed on the "Specify" field will be added as a "Thing" Taxonomy term.
So the terms will be (Thing-1,Thing-2,New Thing,Other).
I might be over explaining this, but I can't find anything on google.
Comment: You might need to add a custom submit handler for the form via form_alter hook, and in that submit (seeing as you are not using Autocomplete term widget (tagging)) you will check if taxonomy term selected is 'Other', then check if the value in 'Specify' is already a taxonomy terms via taxonomy_get_term_by_name(), and then depending on that create a new taxonomy term for the vocabulary and save it via taxonomy_term_save().
Comment: I'm very new to drupal and a little more details would be very appreciated, probably some code snippets perhaps? I completely understood your instructions but I'm not sure where to start?
Comment: possible duplicate of [Taxonomy vocabulary not showing up as existing field in new content type](http://drupal.stackexchange.com/questions/137100/taxonomy-vocabulary-not-showing-up-as-existing-field-in-new-content-type)
Comment: http://drupal.stackexchange.com/questions/137100/taxonomy-vocabulary-not-showing-up-as-existing-field-in-new-content-type/137122#137122 Please let me know if my answer to the linked question would help you. Thank you.
Answer: If you are using Select (or Other) module and it does not specifically need to be a taxonomy term, there is an option for exactly this:

On the field edit page, the "Other value as default value" allows you
to select how other will be handled:

Add the values to the other textfield-> store the value but don't
change the list

Append the values to the current list-> store the
value and add to the list attached to the node/user/entity

Append the values to the available options-> store the value and add the value to
the list so that it can be selected on other nodes/users/entities

Ignore the values-> do not store the value

EDIT (courtesy of DuaelFr)
You will need the 7.x-3.x-dev version to be able to use this module on a Taxonomy Reference Widget.