text:
Q: How to fit the Ringdroid waveform in full width according to width of mobile screen I want to implement the Ringdroid waveform in my android app.But for some songs,the waveform created after choosing the song is larger than the screen size and for songs the waveform width is smaller than the mobile screen width .
Plz suggest me the change in code of Ringdroid ,so that every time the waveform of song totally covers the width of screen.
This is the link of Ringdroid project
https://github.com/google/ringdroid

A: After a whole lot of searching and surfing about it. I tried it myself and got the desired output with it
This is the WaveformView class of Ringdroid
package com.ringdroid;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

import com.ringdroid.soundfile.SoundFile;

/**
 * WaveformView is an Android view that displays a visual representation
 * of an audio waveform.  It retrieves the frame gains from a CheapSoundFile
 * object and recomputes the shape contour at several zoom levels.
 *
 * This class doesn't handle selection or any of the touch interactions
 * directly, so it exposes a listener interface.  The class that embeds
 * this view should add itself as a listener and make the view scroll
 * and respond to other events appropriately.
 *
 * WaveformView doesn't actually handle selection, but it will just display
 * the selected part of the waveform in a different color.
 */
public class WaveformView extends View {
    public interface WaveformListener {
        public void waveformTouchStart(float x);
        public void waveformTouchMove(float x);
        public void waveformTouchEnd();
        public void waveformFling(float x);
        public void waveformDraw();
        public void waveformZoomIn();
        public void waveformZoomOut();
    };

    // Colors
    private Paint mGridPaint;
    private Paint mSelectedLinePaint;
    private Paint mUnselectedLinePaint;
    private Paint mUnselectedBkgndLinePaint;
    private Paint mBorderLinePaint;
    private Paint mPlaybackLinePaint;
    private Paint mTimecodePaint;

    private SoundFile mSoundFile;
    private int[] mLenByZoomLevel;
    private double[][] mValuesByZoomLevel;
    private double[] mZoomFactorByZoomLevel;
    private int[] mHeightsAtThisZoomLevel;
    private int mZoomLevel;
    private int mNumZoomLevels;
    private int mSampleRate;
    private int mSamplesPerFrame;
    private int mOffset;
    private int mSelectionStart;
    private int mSelectionEnd;
    private int mPlaybackPos;
    private float mDensity;
    private float mInitialScaleSpan;
    private WaveformListener mListener;
    private GestureDetector mGestureDetector;
    private ScaleGestureDetector mScaleGestureDetector;
    private boolean mInitialized;

    public WaveformView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // We don't want keys, the markers get these
        setFocusable(false);

        Resources res = getResources();
        mGridPaint = new Paint();
        mGridPaint.setAntiAlias(false);
        mGridPaint.setColor(res.getColor(R.color.grid_line));
        mSelectedLinePaint = new Paint();
        mSelectedLinePaint.setAntiAlias(false);
        mSelectedLinePaint.setColor(res.getColor(R.color.waveform_selected));
        mUnselectedLinePaint = new Paint();
        mUnselectedLinePaint.setAntiAlias(false);
        mUnselectedLinePaint.setColor(res.getColor(R.color.waveform_unselected));
        mUnselectedBkgndLinePaint = new Paint();
        mUnselectedBkgndLinePaint.setAntiAlias(false);
        mUnselectedBkgndLinePaint.setColor(res.getColor(R.color.waveform_unselected_bkgnd_overlay));
        mBorderLinePaint = new Paint();
        mBorderLinePaint.setAntiAlias(true);
        mBorderLinePaint.setStrokeWidth(1.5f);
        mBorderLinePaint.setPathEffect(new DashPathEffect(new float[] { 3.0f, 2.0f }, 0.0f));
        mBorderLinePaint.setColor(res.getColor(R.color.selection_border));
        mPlaybackLinePaint = new Paint();
        mPlaybackLinePaint.setAntiAlias(false);
        mPlaybackLinePaint.setColor(res.getColor(R.color.playback_indicator));
        mTimecodePaint = new Paint();
        mTimecodePaint.setTextSize(12);
        mTimecodePaint.setAntiAlias(true);
        mTimecodePaint.setColor(res.getColor(R.color.timecode));
        mTimecodePaint.setShadowLayer(2, 1, 1, res.getColor(R.color.timecode_shadow));

        mGestureDetector = new GestureDetector(
            context,
            new GestureDetector.SimpleOnGestureListener() {
                public boolean onFling(MotionEvent e1, MotionEvent e2, float vx, float vy) {
                    mListener.waveformFling(vx);
                    return true;
                }
            }
        );

        mScaleGestureDetector = new ScaleGestureDetector(
            context,
            new ScaleGestureDetector.SimpleOnScaleGestureListener() {
                public boolean onScaleBegin(ScaleGestureDetector d) {
                    Log.v("Ringdroid", "ScaleBegin " + d.getCurrentSpanX());
                    mInitialScaleSpan = Math.abs(d.getCurrentSpanX());
                    return true;
                }
                public boolean onScale(ScaleGestureDetector d) {
                    float scale = Math.abs(d.getCurrentSpanX());
                    Log.v("Ringdroid", "Scale " + (scale - mInitialScaleSpan));
                    if (scale - mInitialScaleSpan > 40) {
                        mListener.waveformZoomIn();
                        mInitialScaleSpan = scale;
                    }
                    if (scale - mInitialScaleSpan < -40) {
                        mListener.waveformZoomOut();
                        mInitialScaleSpan = scale;
                    }
                    return true;
                }
                public void onScaleEnd(ScaleGestureDetector d) {
                    Log.v("Ringdroid", "ScaleEnd " + d.getCurrentSpanX());
                }
            }
        );

        mSoundFile = null;
        mLenByZoomLevel = null;
        mValuesByZoomLevel = null;
        mHeightsAtThisZoomLevel = null;
        mOffset = 0;
        mPlaybackPos = -1;
        mSelectionStart = 0;
        mSelectionEnd = 0;
        mDensity = 1.0f;
        mInitialized = false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mScaleGestureDetector.onTouchEvent(event);
        if (mGestureDetector.onTouchEvent(event)) {
            return true;
        }

        switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mListener.waveformTouchStart(event.getX());
            break;
        case MotionEvent.ACTION_MOVE:
            mListener.waveformTouchMove(event.getX());
            break;
        case MotionEvent.ACTION_UP:
            mListener.waveformTouchEnd();
            break;
        }
        return true;
    }

    public boolean hasSoundFile() {
        return mSoundFile != null;
    }

    public void setSoundFile(SoundFile soundFile) {
        mSoundFile = soundFile;
        mSampleRate = mSoundFile.getSampleRate();
        mSamplesPerFrame = mSoundFile.getSamplesPerFrame();
        computeDoublesForAllZoomLevels();
        mHeightsAtThisZoomLevel = null;
    }

    public boolean isInitialized() {
        return mInitialized;
    }

    public int getZoomLevel() {
        return mZoomLevel;
    }

    public void setZoomLevel(int zoomLevel) {
        while (mZoomLevel > zoomLevel) {
            zoomIn();
        }
        while (mZoomLevel < zoomLevel) {
            zoomOut();
        }
    }

    public boolean canZoomIn() {
        return (mZoomLevel > 0);
    }

    public void zoomIn() {
        if (canZoomIn()) {
            mZoomLevel--;
            mSelectionStart *= 2;
            mSelectionEnd *= 2;
            mHeightsAtThisZoomLevel = null;
            int offsetCenter = mOffset + getMeasuredWidth() / 2;
            offsetCenter *= 2;
            mOffset = offsetCenter - getMeasuredWidth() / 2;
            if (mOffset < 0)
                mOffset = 0;
            invalidate();
        }
    }

    public boolean canZoomOut() {
        return (mZoomLevel < mNumZoomLevels - 1);
    }

    public void zoomOut() {
        if (canZoomOut()) {
            mZoomLevel++;
            mSelectionStart /= 2;
            mSelectionEnd /= 2;
            int offsetCenter = mOffset + getMeasuredWidth() / 2;
            offsetCenter /= 2;
            mOffset = offsetCenter - getMeasuredWidth() / 2;
            if (mOffset < 0)
                mOffset = 0;
            mHeightsAtThisZoomLevel = null;
            invalidate();
        }
    }

    public int maxPos() {
        return mLenByZoomLevel[mZoomLevel];
    }

    public int secondsToFrames(double seconds) {
        return (int)(1.0 * seconds * mSampleRate / mSamplesPerFrame + 0.5);
    }

    public int secondsToPixels(double seconds) {
        double z = mZoomFactorByZoomLevel[mZoomLevel];
        return (int)(z * seconds * mSampleRate / mSamplesPerFrame + 0.5);
    }

    public double pixelsToSeconds(int pixels) {
        double z = mZoomFactorByZoomLevel[mZoomLevel];
        return (pixels * (double)mSamplesPerFrame / (mSampleRate * z));
    }

    public int millisecsToPixels(int msecs) {
        double z = mZoomFactorByZoomLevel[mZoomLevel];
        return (int)((msecs * 1.0 * mSampleRate * z) /
                     (1000.0 * mSamplesPerFrame) + 0.5);
    }

    public int pixelsToMillisecs(int pixels) {
        double z = mZoomFactorByZoomLevel[mZoomLevel];
        return (int)(pixels * (1000.0 * mSamplesPerFrame) /
                     (mSampleRate * z) + 0.5);
    }

    public void setParameters(int start, int end, int offset) {
        mSelectionStart = start;
        mSelectionEnd = end;
        mOffset = offset;
    }

    public int getStart() {
        return mSelectionStart;
    }

    public int getEnd() {
        return mSelectionEnd;
    }

    public int getOffset() {
        return mOffset;
    }

    public void setPlayback(int pos) {
        mPlaybackPos = pos;
    }

    public void setListener(WaveformListener listener) {
        mListener = listener;
    }

    public void recomputeHeights(float density) {
        mHeightsAtThisZoomLevel = null;
        mDensity = density;
        mTimecodePaint.setTextSize((int)(12 * density));

        invalidate();
    }

    protected void drawWaveformLine(Canvas canvas,
                                    int x, int y0, int y1,
                                    Paint paint) {
        canvas.drawLine(x, y0, x, y1, paint);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mSoundFile == null)
            return;

        if (mHeightsAtThisZoomLevel == null)
            computeIntsForThisZoomLevel();

        // Draw waveform
        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        int start = mOffset;
        int width = mHeightsAtThisZoomLevel.length - start;
        int ctr = measuredHeight / 2;

        if (width > measuredWidth)
            width = measuredWidth;

        // Draw grid
        double onePixelInSecs = pixelsToSeconds(1);
        boolean onlyEveryFiveSecs = (onePixelInSecs > 1.0 / 50.0);
        double fractionalSecs = mOffset * onePixelInSecs;
        int integerSecs = (int) fractionalSecs;
        int i = 0;
        while (i < width) {
            i++;
            fractionalSecs += onePixelInSecs;
            int integerSecsNew = (int) fractionalSecs;
            if (integerSecsNew != integerSecs) {
                integerSecs = integerSecsNew;
                if (!onlyEveryFiveSecs || 0 == (integerSecs % 5)) {
                    canvas.drawLine(i, 0, i, measuredHeight, mGridPaint);
                }
            }
        }

        // Draw waveform
        for (i = 0; i < width; i++) {
            Paint paint;
            if (i + start >= mSelectionStart &&
                i + start < mSelectionEnd) {
                paint = mSelectedLinePaint;
            } else {
                drawWaveformLine(canvas, i, 0, measuredHeight,
                                 mUnselectedBkgndLinePaint);
                paint = mUnselectedLinePaint;
            }
            drawWaveformLine(
                canvas, i,
                ctr - mHeightsAtThisZoomLevel[start + i],
                ctr + 1 + mHeightsAtThisZoomLevel[start + i],
                paint);

            if (i + start == mPlaybackPos) {
                canvas.drawLine(i, 0, i, measuredHeight, mPlaybackLinePaint);
            }
        }

        // If we can see the right edge of the waveform, draw the
        // non-waveform area to the right as unselected
        for (i = width; i < measuredWidth; i++) {
            drawWaveformLine(canvas, i, 0, measuredHeight,
                             mUnselectedBkgndLinePaint);
        }

        // Draw borders
        canvas.drawLine(
            mSelectionStart - mOffset + 0.5f, 30,
            mSelectionStart - mOffset + 0.5f, measuredHeight,
            mBorderLinePaint);
        canvas.drawLine(
            mSelectionEnd - mOffset + 0.5f, 0,
            mSelectionEnd - mOffset + 0.5f, measuredHeight - 30,
            mBorderLinePaint);

        // Draw timecode
        double timecodeIntervalSecs = 1.0;
        if (timecodeIntervalSecs / onePixelInSecs < 50) {
            timecodeIntervalSecs = 5.0;
        }
        if (timecodeIntervalSecs / onePixelInSecs < 50) {
            timecodeIntervalSecs = 15.0;
        }

        // Draw grid
        fractionalSecs = mOffset * onePixelInSecs;
        int integerTimecode = (int) (fractionalSecs / timecodeIntervalSecs);
        i = 0;
        while (i < width) {
            i++;
            fractionalSecs += onePixelInSecs;
            integerSecs = (int) fractionalSecs;
            int integerTimecodeNew = (int) (fractionalSecs /
                                            timecodeIntervalSecs);
            if (integerTimecodeNew != integerTimecode) {
                integerTimecode = integerTimecodeNew;

                // Turn, e.g. 67 seconds into "1:07"
                String timecodeMinutes = "" + (integerSecs / 60);
                String timecodeSeconds = "" + (integerSecs % 60);
                if ((integerSecs % 60) < 10) {
                    timecodeSeconds = "0" + timecodeSeconds;
                }
                String timecodeStr = timecodeMinutes + ":" + timecodeSeconds;
                float offset = (float) (
                    0.5 * mTimecodePaint.measureText(timecodeStr));
                canvas.drawText(timecodeStr,
                                i - offset,
                                (int)(12 * mDensity),
                                mTimecodePaint);
            }
        }

        if (mListener != null) {
            mListener.waveformDraw();
        }
    }

    /**
     * Called once when a new sound file is added
     */
    private void computeDoublesForAllZoomLevels() {
        int numFrames = mSoundFile.getNumFrames();
        int[] frameGains = mSoundFile.getFrameGains();
        double[] smoothedGains = new double[numFrames];
        if (numFrames == 1) {
            smoothedGains[0] = frameGains[0];
        } else if (numFrames == 2) {
            smoothedGains[0] = frameGains[0];
            smoothedGains[1] = frameGains[1];
        } else if (numFrames > 2) {
            smoothedGains[0] = (double)(
                (frameGains[0] / 2.0) +
                (frameGains[1] / 2.0));
            for (int i = 1; i < numFrames - 1; i++) {
                smoothedGains[i] = (double)(
                    (frameGains[i - 1] / 3.0) +
                    (frameGains[i    ] / 3.0) +
                    (frameGains[i + 1] / 3.0));
            }
            smoothedGains[numFrames - 1] = (double)(
                (frameGains[numFrames - 2] / 2.0) +
                (frameGains[numFrames - 1] / 2.0));
        }

        // Make sure the range is no more than 0 - 255
        double maxGain = 1.0;
        for (int i = 0; i < numFrames; i++) {
            if (smoothedGains[i] > maxGain) {
                maxGain = smoothedGains[i];
            }
        }
        double scaleFactor = 1.0;
        if (maxGain > 255.0) {
            scaleFactor = 255 / maxGain;
        }

        // Build histogram of 256 bins and figure out the new scaled max
        maxGain = 0;
        int gainHist[] = new int[256];
        for (int i = 0; i < numFrames; i++) {
            int smoothedGain = (int)(smoothedGains[i] * scaleFactor);
            if (smoothedGain < 0)
                smoothedGain = 0;
            if (smoothedGain > 255)
                smoothedGain = 255;

            if (smoothedGain > maxGain)
                maxGain = smoothedGain;

            gainHist[smoothedGain]++;
        }

        // Re-calibrate the min to be 5%
        double minGain = 0;
        int sum = 0;
        while (minGain < 255 && sum < numFrames / 20) {
            sum += gainHist[(int)minGain];
            minGain++;
        }

        // Re-calibrate the max to be 99%
        sum = 0;
        while (maxGain > 2 && sum < numFrames / 100) {
            sum += gainHist[(int)maxGain];
            maxGain--;
        }

        // Compute the heights
        double[] heights = new double[numFrames];
        double range = maxGain - minGain;
        for (int i = 0; i < numFrames; i++) {
            double value = (smoothedGains[i] * scaleFactor - minGain) / range;
            if (value < 0.0)
                value = 0.0;
            if (value > 1.0)
                value = 1.0;
            heights[i] = value * value;
        }

        mNumZoomLevels = 5;
        mLenByZoomLevel = new int[5];
        mZoomFactorByZoomLevel = new double[5];
        mValuesByZoomLevel = new double[5][];

        // Level 0 is doubled, with interpolated values
        mLenByZoomLevel[0] = numFrames * 2;
        mZoomFactorByZoomLevel[0] = 2.0;
        mValuesByZoomLevel[0] = new double[mLenByZoomLevel[0]];
        if (numFrames > 0) {
            mValuesByZoomLevel[0][0] = 0.5 * heights[0];
            mValuesByZoomLevel[0][1] = heights[0];
        }
        for (int i = 1; i < numFrames; i++) {
            mValuesByZoomLevel[0][2 * i] = 0.5 * (heights[i - 1] + heights[i]);
            mValuesByZoomLevel[0][2 * i + 1] = heights[i];
        }

        // Level 1 is normal
        mLenByZoomLevel[1] = numFrames;
        mValuesByZoomLevel[1] = new double[mLenByZoomLevel[1]];
        mZoomFactorByZoomLevel[1] = 1.0;
        for (int i = 0; i < mLenByZoomLevel[1]; i++) {
            mValuesByZoomLevel[1][i] = heights[i];
        }

        // 3 more levels are each halved
        for (int j = 2; j < 5; j++) {
            mLenByZoomLevel[j] = mLenByZoomLevel[j - 1] / 2;
            mValuesByZoomLevel[j] = new double[mLenByZoomLevel[j]];
            mZoomFactorByZoomLevel[j] = mZoomFactorByZoomLevel[j - 1] / 2.0;
            for (int i = 0; i < mLenByZoomLevel[j]; i++) {
                mValuesByZoomLevel[j][i] =
                    0.5 * (mValuesByZoomLevel[j - 1][2 * i] +
                           mValuesByZoomLevel[j - 1][2 * i + 1]);
            }
        }

        if (numFrames > 5000) {
            mZoomLevel = 3;
        } else if (numFrames > 1000) {
            mZoomLevel = 2;
        } else if (numFrames > 300) {
            mZoomLevel = 1;
        } else {
            mZoomLevel = 0;
        }

        mInitialized = true;
    }

    /**
     * Called the first time we need to draw when the zoom level has changed
     * or the screen is resized
     */
    private void computeIntsForThisZoomLevel() {
        int halfHeight = (getMeasuredHeight() / 2) - 1;
        mHeightsAtThisZoomLevel = new int[mLenByZoomLevel[mZoomLevel]];
        for (int i = 0; i < mLenByZoomLevel[mZoomLevel]; i++) {
            mHeightsAtThisZoomLevel[i] =
                (int)(mValuesByZoomLevel[mZoomLevel][i] * halfHeight);
        }
    }
}

The change is here in this part of code
 DisplayMetrics displaymetrics = getContext().getResources().getDisplayMetrics();
 int ScreenWidth= displaymetrics.widthPixels;

// Draw waveform
        for ( i = 0; i < width; i++) {
            Paint paint;

            if (i + start >= mSelectionStart &&
                    i + start < mSelectionEnd) {
                paint = mSelectedLinePaint;
            } else {
                drawWaveformLine(canvas, ((ScreenWidth/width)*i), 0, measuredHeight,
                        mUnselectedBkgndLinePaint);
                paint = mUnselectedLinePaint;
            }
            drawWaveformLine(
                    canvas, ((ScreenWidth/width)*i),
                    ctr - mHeightsAtThisZoomLevel[start + i],
                    ctr + 1 + mHeightsAtThisZoomLevel[start + i],
                    paint);

you have to change the x-axis of draw line method according to your screen size

A: import java.util.LinkedList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceView;

/**
 * A view that displays audio data on the screen as a waveform.
 */
public class WaveformView extends SurfaceView {

  // The number of buffer frames to keep around (for a nice fade-out
  // visualization.
  private static final int HISTORY_SIZE = 6;

  // To make quieter sounds still show up well on the display, we use
  // +/- 8192 as the amplitude that reaches the top/bottom of the view
  // instead of +/- 32767. Any samples that have magnitude higher than this
  // limit will simply be clipped during drawing.
  private static final float MAX_AMPLITUDE_TO_DRAW = 8192.0f;

  // The queue that will hold historical audio data.
  private LinkedList<short[]> mAudioData;
  private Paint mPaint;

  public WaveformView(Context context) {
    this(context, null, 0);
  }

  public WaveformView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

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

    mAudioData = new LinkedList<short[]>();

    mPaint = new Paint();
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setColor(Color.WHITE);
    mPaint.setStrokeWidth(0);
    mPaint.setAntiAlias(true);
  }

  /**
   * Updates the waveform view with a new "frame" of samples and renders it.
   * The new frame gets added to the front of the rendering queue, pushing the
   * previous frames back, causing them to be faded out visually.
   *
   * @param buffer the most recent buffer of audio samples.
   */
  public synchronized void updateAudioData(short[] buffer) {
    short[] newBuffer;

    // We want to keep a small amount of history in the view to provide a nice
    // fading effect. We use a linked list that we treat as a queue for this.
    if (mAudioData.size() == HISTORY_SIZE) {
      newBuffer = mAudioData.removeFirst();
      System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
    } else {
      newBuffer = buffer.clone();
    }

    mAudioData.addLast(newBuffer);

    // Update the display.
    Canvas canvas = getHolder().lockCanvas();
    if (canvas != null) {
      drawWaveform(canvas);
      getHolder().unlockCanvasAndPost(canvas);
    }
  }

  /**
   * Repaints the view's surface.
   *
   * @param canvas the {@link Canvas} object on which to draw.
   */
  private void drawWaveform(Canvas canvas) {
    // Clear the screen each time because SurfaceView won't do this for us.
    canvas.drawColor(Color.BLACK);

    float width = getWidth();
    float height = getHeight();
    float centerY = height / 2;

    // We draw the history from oldest to newest so that the older audio
    // data is further back and darker than the most recent data.
    int colorDelta = 255 / (HISTORY_SIZE + 1);
    int brightness = colorDelta;

    for (short[] buffer : mAudioData) {
      mPaint.setColor(Color.argb(brightness, 128, 255, 192));

      float lastX = -1;
      float lastY = -1;

      // For efficiency, we don't draw all of the samples in the buffer,
      // but only the ones that align with pixel boundaries.
      for (int x = 0; x < width; x++) {
        int index = (int) ((x / width) * buffer.length);
        short sample = buffer[index];
        float y = (sample / MAX_AMPLITUDE_TO_DRAW) * centerY + centerY;

        if (lastX != -1) {
          canvas.drawLine(lastX, lastY, x, y, mPaint);
        }

        lastX = x;
        lastY = y;
      }

      brightness += colorDelta;
    }
  }
}


text:
Q: how do I prove this matrix result? How do I prove that if A and B are lower triangular matrices, then AB is also a lower triangular?

A: If $A$ and $B$ are lower triangular, then:
$$A = \begin{bmatrix} C & 0 \\ X & D \end{bmatrix}$$
$$B = \begin{bmatrix} E & 0 \\ Y & F \end{bmatrix}$$
Where $C$, $D$, $E$, and $F$ are lower triangular matrices.  What does $AB$ look like in terms of $C$, $D$, $E$, $F$, $X$, and $Y$?
Hint:

 You can make the inductive assumption that $CE$ and $DF$ are lower triangular because they are smaller than $A$ and $B$

A: For a lower triangular matrix $A = (a_{ij})$ we have the property $a_{ij} = 0$ for $i < j$.
E.g.
$$
\left(
\begin{matrix}
a_{11} & a_{12} & a_{13} \\
a_{21} & a_{22} & a_{23} \\
a_{31} & a_{32} & a_{33} \\
\end{matrix}
\right)
=
\left(
\begin{matrix}
a_{11} & 0 & 0 \\
a_{21} & a_{22} & 0 \\
a_{31} & a_{32} & a_{33} \\
\end{matrix}
\right)
$$
If we matrix multiply two lower triangular matrices $A B=C$ then by definition of the matrix product we have
$$
c_{ij} = \sum_{k=1}^n a_{ik} b_{kj}
$$
If $i < j$ $(*)$ then we split the sum into two sums and observe
$$
c_{ij} =
\sum_{k=1}^i a_{ik} \underbrace{b_{kj}}_{k\le i <j} +
\sum_{k=i+1}^n \underbrace{a_{ik}}_{i<k} b_{kj} = 0 \quad (**)
$$
During the first summation the summation index $k$ takes values between $1$ and $i$, thus $k$ stays less equal $i$ which is less than $j$ by assumption $(*)$ thus $k < j$ and $b_{kj}$ vanishes because $B$ is lower triangular having zero components if the first index is smaller than the second index, which is true in the upper triangular area above the matrix diagonal.
During the second sum the summation index $k$ takes values from $i+1$ to $n$. So $k$ being the second index for the $a_{ik}$ is larger than the first index $i$.
Because $A$ is lower triangular, such an $a_{ik}$ is zero.
$(**)$ means $C$ is lower triangular too.
Note: Such a split into two sums is always possible because $1 \le i < j \le n$, so each sum has at least one summand.
Example:
$$
\left(
\begin{matrix}
c_{11} & \fbox{$c_{12}$} & c_{13} \\
c_{21} & c_{22} & c_{23} \\
c_{31} & c_{32} & c_{33} \\
\end{matrix}
\right)
=
\left(
\begin{array}{ccc}
\hline
a_{11} & 0 & 0 \\
\hline
a_{21} & a_{22} & 0 \\
a_{31} & a_{32} & a_{33} \\
\end{array}
\right)
\left(
\begin{array}{c|c|c}
b_{11} & 0 & 0 \\
b_{21} & b_{22} & 0 \\
b_{31} & b_{32} & b_{33} \\
\end{array}
\right)
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Merge subarray and get random values from result array I am trying to create a string permutation for an array of values or for a single string and this is how I am doing:
function aliasName($string)
{
    $names = [];

    if (is_array($string)) {
        foreach ($string as $str) {
            $names[] = internalProcessing($str);
        }
    } else {
        $names[] = internalProcessing($string);
    }

    return $names[array_rand($names)];
}

function internalProcessing($str)
{
    $names = [];

    $input = strtolower($str);
    $length = strlen($input);
    $counter = pow(2, $length);

    for ($i = 0; $i < $counter; ++$i) {
        $binaryStr = str_pad(decbin($i), $length, '0', STR_PAD_LEFT);

        $variant = '';
        for ($j = 0; $j < $length; ++$j) {
            $variant .= ($binaryStr[$j] == '1') ? strtoupper($input[$j]) : $input[$j];
        }

        $names[] = $variant;
    }

    return $names;
}

$test1 = ['Mami', 'Abonis', 'Acierto', 'Alison', 'Bato', 'Chiste', 'Amada', 'Calor', 'Dato', 'Fiera', 'Exito'];
$test2 = 'mamI';

$test1Result = aliasName($test1);
$test2Result = aliasName($test2);

echo "\n test1 -------------------------------- \n";
var_export($test1Result);
echo "\n test2 -------------------------------- \n";
var_export($test2Result);

The code works good but I have a few issues and I need some help. If you run the code above in a console script you should see an output like the one below:
# php test.php

 test1 --------------------------------
array (
  0 => 'abonis',
  1 => 'aboniS',
  2 => 'abonIs',
  3 => 'abonIS',
  4 => 'aboNis',
  5 => 'aboNiS',
  6 => 'aboNIs',
  7 => 'aboNIS',
  8 => 'abOnis',
  9 => 'abOniS',
  10 => 'abOnIs',
  ...
)

 test2 --------------------------------
array (
  0 => 'mami',
  1 => 'mamI',
  2 => 'maMi',
  3 => 'maMI',
  4 => 'mAmi',
  5 => 'mAmI',
  6 => 'mAMi',
  7 => 'mAMI',
  8 => 'Mami',
  9 => 'MamI',
  10 => 'MaMi',
  ...
)

test2 output is just fine, but test1 is not. If you dump the content of $names at internalProcessing() (just before the return) you'll get something like:
// var_export($names);
// return $names;

# php test.php
array (
  0 => 'mami',
  1 => 'mamI',
  ...
)array (
  0 => 'abonis',
  1 => 'aboniS',
  ...
)array (
  0 => 'acierto',
  1 => 'aciertO',
  ...
)array (
  0 => 'alison',
  1 => 'alisoN',
  ...
)array (
  0 => 'bato',
  1 => 'batO',
  ...
)array (
  0 => 'chiste',
  1 => 'chistE',
  ...
)array (
  0 => 'amada',
  1 => 'amadA',
  ...
)array (
  0 => 'calor',
  1 => 'caloR',
  ...
)array (
  0 => 'dato',
  1 => 'datO',
  ...
)array (
  0 => 'fiera',
  1 => 'fierA',
  ...
)array (
  0 => 'exito',
  1 => 'exitO',
  ...
)array (
  0 => 'mami',
  1 => 'mamI',
  ...
)

I need to transform that output to something like:
$result_array = array (
    0 => 'mami',
    1 => 'mamI',
    ...,
    0 => 'abonis',
    1 => 'aboniS',
    ...,
    0 => 'acierto',
    1 => 'aciertO',
    ...,
    0 => 'alison',
    1 => 'alisoN',
    ...,
    0 => 'bato',
    1 => 'batO',
    ...,
    0 => 'chiste',
    1 => 'chistE',
    ...,
    0 => 'amada',
    1 => 'amadA',
    ...,
    0 => 'calor',
    1 => 'caloR',
    ...,
    0 => 'dato',
    1 => 'datO',
    ...,
    0 => 'fiera',
    1 => 'fierA',
    ...,
    0 => 'exito',
    1 => 'exitO',
    ...,
    0 => 'mami',
    1 => 'mamI',
    ...
  )

And finally if the input is an array of values then I should return any random values between 0 and count($result_array). I have tried array_merge() but didn't works for me since I got wrong result. Can any give me some push here?

A: You have indeed arrays of arrays, as internalProcessing returns an array, and you put that result as an array element in a wrapping array with this:
 $names[] = internalProcessing(...);

Instead you should store the result of internalProcessing as follows (in both occurrences):
 $names = array_merge($names, internalProcessing(...));

That does the trick as you can see in this fiddle.


text:
Q: Show only selected row in table and other row will hide on same time use Javascript It is a room type selection. Here I want to select room type on this selection I want to show only that row which I was selected from dropdown and other row should be hide at same time.
<select onChange="onSelect(this)" class="col-Room" name="ACRoom">
  <option value="optionAC" >AC-Room</option>
  <option value="optionNAC">Non AC-Room</option>
</select>

This is javascript code which I am using for selection. But it is not working properly. Only second option is working on select and first option is not working properly on selection.
Please help me out.

A: You should hide other rows while showing some particular rows. While selecting first option, you are not hiding nonac rows. Also I suggest you to use classs names instead of ID, since table can have multiple ac/non-ac rows. The below code could help you.
<!DOCTYPE html>

            Rooms

            AC room

            Non Ac room

            AC room

            Non Ac room

<select onChange="onSelect(this)">
    <option value="ac">AC</option>
    <option value="nonac">NON AC</option>
</select>


text:
Q: Configure Spring Security to return JSON response after authentication I have a legacy application that is in spring 4 with UI as JSP. Need move the presentation layer from spring to react app. When I call /login with parameters it gives me an HTML, How do I change my existing spring security logic so that it returns a json response.
Here is the code snippet
protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().maximumSessions(1).and().invalidSessionUrl(URLConstants.LOGIN_URL);
        http.csrf().disable();
        http.anonymous().disable()
                .authorizeRequests().antMatchers("/")
                .access("hasRole('USER') or hasRole('ADMIN') or hasRole('DC MANAGER')")
.and().formLogin()          .loginProcessingUrl(URLConstants.LOGIN_URL).usernameParameter("ssoId").passwordParameter("password").and()
.rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)               .tokenValiditySeconds(18400).and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }

A: Write a custom AuthenticationSuccessHandler that writes your JSON and plug it into your formLogin().
.formLogin().successHandler(yourSucessHandlerBean);

Your handler could roughly look like this:
@Component
public class Securityhandler implements AuthenticationSuccessHandler {

 public void onAuthenticationSuccess(HttpServletRequest request,   HttpServletResponse response, Authentication authentication) throws IOException  {
    // write your JSON here, directly to the HttpServletResponse
 }

}


text:
Q: Express - Separating route handler logic into controllers I have seen examples of separating out Express router logic into controller files such as meanJS
E.g.
var express = require('express'),
  router = express.Router(),
  catalogues = require('../controllers/catalogues');

router.route('/catalogues')
  .get(catalogues.apiGET)
  .post(catalogues.apiPOST);

../controllers/catalogues
var request = require('request');

exports.apiGET = function(req, res) {
  var options = prepareCataloguesAPIHeaders(req);
  request(options, function(err, response, body){
    res.send(body);
  });
};

exports.apiPOST = function(req, res) {
  var options = prepareCataloguesAPIHeaders(req);
  options.json = true;
  options.body = stripBody(req.body);
  request(options, function(err, response, body){
    res.send(body);
  });
};

I have not seen any mention of this in the Express docs, so is this just a new way of thinking in terms of keeping the logic separate from the route definitions?
Are there any performance or other other gains achieved by using this approach?

A: MEAN.js tries to follow the MVC pattern (Model-View-Controller) in the server side and the result is the logic division between mongoose models, server templates, and controllers.
As a way to improve code organization it is common to separate routes and controllers to their own files as well. In a huge app it helps developers to maintain the code.
Regarding performance, I don't believe there's any improvement.


text:
Q: How do I set columns/members in Kohana ORM v3 class Model_User extends ORM {
  // columns: UserID, Name
  // public $Name ; // this didn't work
}

Currently I create an object:
$user = new Model_User() ;
and access columns like:
 $user->Name = 'My Name';

I'd like to have my IDE show me all the columns in the data model to avoid misspellings and to now right away what fields I can use.
How do I update my model to give my IDE the list of possible columns/properties? I tried adding the properties to the class but that broke the ORM() and no longer allowed saving. I must have overridden some base class property that gets set after reading in the column names from the database.

A: Use phpDoc's @property tag:
/**
   @property  string   Name     username
   @property  int      UserID   user ID (primary key)
 */
class Model_User extends ORM {
// ...
}

A: Got it working, have to proceed property names with $
/**
  *   @property string $Name
  *   @property int $UserID
  */


text:
Q: how to delete this json data before it loaded, this is a html canvas using konva library.
var json = 'http://pastebin.com/Qv1HAUmY' this is my json data,
then before i get the value of "json" all item like this are deleted
{
            "attrs": {
                "stroke": "#666",
                "fill": "#ddd",
                "radius": 8,
                "name": "topLeft anchor",
                "draggable": true,
                "dragOnTop": false,
                "visible": false,
                "id": "ResizeAnchor"
            },
            "className": "Circle"
        }, {
            "attrs": {
                "x": 93,
                "stroke": "#666",
                "fill": "#ddd",
                "radius": 8,
                "name": "topRight anchor",
                "draggable": true,
                "dragOnTop": false,
                "visible": false,
                "id": "ResizeAnchor"
            },
            "className": "Circle"
        }, {
            "attrs": {
                "x": 93,
                "y": 104,
                "stroke": "#666",
                "fill": "#ddd",
                "radius": 8,
                "name": "bottomRight anchor",
                "draggable": true,
                "dragOnTop": false,
                "visible": false,
                "id": "ResizeAnchor"
            },
            "className": "Circle"
        }, {
            "attrs": {
                "y": 104,
                "stroke": "#666",
                "fill": "#ddd",
                "radius": 8,
                "name": "bottomLeft anchor",
                "draggable": true,
                "dragOnTop": false,
                "visible": false,
                "id": "ResizeAnchor"
            },
            "className": "Circle"
        }

i want to remove all anchor using JavaScript if possible.

A: At first i think it is a shame that peoples questions get downvoted because the average user of stackoverflow can't see the problem in less than 5 seconds...
Anyway i think what you want to say you have a var called "json" which holds the json data from the link. Now you want to delete all anchors from the data.
The only problem i have with your question is that i can't see what in your json is an anchor and what is not, but here is a little snippet that might help you:
var json = '.......'; // your json data
var jsObj = eval('(' + json + ')'); // eval the json to an object
for (var property in jsObj) // iterate through all members of the object
{
    if (property == 'anchor') // when you got your anchor
    {
        delete jsObj[property]; // delete the property
    }
}

This is just an example how you can clean your json. Now you should be able to clean it under the conditions you need.


text:
Q: Find $\dim(W_{1} \cap W_{2} \cap W_{3})$ If $$W_{1}=\{(x,y,z)| x+y-z=0\}$$; $$W_{2}=\{(x,y,z)| 3x+y-2z=0\}$$; $$W_{3}=\{(x,y,z)| x-7y+3z=0\}$$
Find the $\dim(W_{1}\cap W_{2}\cap W_{3}).$
My solution- I know how to find $\dim(W_{1}\cap W_{2})=\dim W_{1} + \dim W_{2}-\dim(W_{1}+W_{2}).$ But can we extend this further or is there any simpler way to find this.

A: The intersection is the solution space of
$$
\begin{cases}
x+y-z=0\\
3x+y-2z=0\\
x-7y+3z=0
\end{cases}
$$
that is, the null space of the matrix
$$
\begin{bmatrix}
1 & 1 & -1 \\
3 & 1 & -2 \\
1 & -7 & 3
\end{bmatrix}
$$
which has rank $2$, as an easy elimination will prove. The rank-nullity theorem now helps.


text:
Q: How can I create a view that has different displays according to the role the user is in? I want to create a view that has different displays according to the role the user is in.
Should I create a different view for different roles or should I check the roles on the Veiw page itself rather than in the actions?
How would I check the role on the view page?

A: If the display changes based on the role -- and the change is small -- then I would do the check in the view.  If certain views are restricted based on the role, then I would do the check in the controller.  If the views are completely different (this would be hard to imagine), then separate views per role may be appropriate.
You may want to abstract out certain role-specific view components into partial views to simplify your view logic -- basically you only have to check to include the partial or not based on the role.
Also, other than to check for "IsAuthenticated", I would move the role checking logic to the controller and pass (as data) to the view information on which elements to include/exclude based on role.  This keeps the actual business logic from bleeding into your view.

A: If you are using MVC the whole point of development is to keep the logic out of the view and in the controller. It seems to me like you'd be better off on a WebForms development track than an MVC track.
All that being said, I do an Admin check on a lot of my pages by using a check like this:
<% if ((bool)ViewData["Admin"]) { %>

<% } %>

But if you are attempting to build actual logic into the View then you need to figure out what you can push back to the controller to do the work and have the view be as dumb as possible, acting on flags sent to it.

A:
Or should i use check the roles on the
  Veiw page its self rather than on
  actions, if so can someone plz show me
  how do check that on view page

You need to do both. Check roles on actions as a security measure and check roles on views to enable/disable specific controls.
Within your view page the long form of checking a role is
HttpContext.Current.User.IsInRole("Administrator")

many developers will create page helper methods so you can end up with something more concise for your application like
public static bool IsAdmin(this ViewUserControl pg)
{
    return pg.Page.User.IsInRole("Administrator")
}

then in your view you can just use this.IsAdmin()
To keep your view clutter down look into using partial views
<% if (IsAdmin())
   {
      Html.RenderPartial("AdminPanel");
   }
   else
   {
      Html.RenderPartial("UserPanel");
   }
%>

A: without researching the exact mechanism asp.net mvc uses for roles i would scream no for putting any of your  business logic in the view which is what you are doing if you are checking roles in the view

A: Yeah that was something that was bothering me as well ... but at the same time it seems  ridiculous to load whole different view for such a small change.
btw
how did you set this up in your controller.
Right now, my controller looks something like the code below, which I don't think is correct.
[Authorize(Roles = "Admin, Member")]
public ActionResult RegistrationInformation()
{

    return View();
}

A: I'm not that familiar with ASP.NET MVC (yet) but can't you do some kind of conditional filter in the View?  If the Controller passes the role to the View, then you should be able to do a conditional filter and display a certain block of code if the user is an admin.  If you want to display a totally separate page, then you'd have a multiple Views, otherwise you can use one and do some conditional.
In Ruby on Rails it would be something like (sorry, I don't know ASP.NET MVC really yet):
<% if @user.admin? # is the user an admin %>

Admin Tools

<% end %>

Regular site content

In Rails you would load the extra content from partials; ASP.NET MVC has something similar but I forget what it's called.  Maybe look into that?
Sorry I can't be of more help -- like I said I haven't really gotten to play with ASP.NET MVC.

A: I have base model which from all others models extend. In this model i have loaded the user's roles. Its based on httpcontext.user.isinrole() method. All views are strong typed  expecting the base model type.
So i can always check in all views something like Model.CurrentUser.IsInRoles(Role1 | Role2). Not only in views of course, but in hole application.

A: I like to have full control over this in the view, and I find that:
<% if (User.IsInRole("Super User")) { %>

Hello world!

<% } %>

Works for most scenarios. It also allows you to easily do conditional formatting for other roles, e.g "Content Manager", "Registered", etc.
I do like Todd Smith's answer, because you might change the name of the Admin role, and that will require only one change, whereas, if you put the "Super User" or "Administrator" string directly in the view, you will have to change it wherever you've used the value.


text:
Q: BACnet Virtual Devices - never respond to a direct command Some background:
I'm attempting to create a virtual BACnet router with virtual devices behind it (see related post).  My test environment consists of a VM ( 10.2.0.15 ) running on my server with a BACnet explorer and Wireshark running on it.  I'm writing the code in VS2013 and also running wireshark on my local machine ( 192.168.56.1 ).
When I start the virtual router and send a who-is broadcast from the VM, I see the command and responses on the wireshark running on the vm.  On my local machine, I only see the command in wireshark, but not the responses going out.
All of this works fine.  However, the source address of the i-am responses ( according to wireshark on the VM as well as in the BACnet explorer details ) is that of the gateway (10.2.0.2) between the VM and my machine.
The Problem
Subsequent who-is commands targeting a specific virtual device never get to my local machine.  I can see the command being created using wireshark on the vm, but my code never sees the request nor does wireshark on my local machine see a new packet.
The Question
Should the source address of the initial i-am responses be the IP of my local machine or the IP address that I've assigned to the virtual device?  As stated above, the source address is currently that of the gateway between the VM and my machine.
Here is the code I'm using to construct the NPDU portion of the response to a who-is command - Hopefully someone can point out what I'm doing incorrectly.
        bytes[pos++] = BACnetEnums.BACNET_PROTOCOL_VERSION;

        //Control byte determines what fields exist in the rest of the NPDU record
        bytes[pos++] = this.AssembleControl();  //in the case, the response is 0x28

        //Destination Network Info
        //65535 - Broadcast
        bytes[pos++] = 0xff;  //DNET
        bytes[pos++] = 0xff;  //DNET

        //Destination
        bytes[pos++] = 0x00;  //DLEN
                              //DADDR
        //none since len = 0 and this is being broadcasted back

        bytes[pos++] = 0x00;  //SNET
        bytes[pos++] = 0x00;  //SNET

        bytes[pos++] = 0x06;  //SLEN

        //address should be 10.1.0.xxx, where x is the deviceid
        bytes[pos++] = this.SADR[0];  //10
        bytes[pos++] = this.SADR[1];  //1
        bytes[pos++] = this.SADR[2];  //0
        bytes[pos++] = this.SADR[3];  //varies based on the ID of the device - pulled from database
        bytes[pos++] = 0xBA;
        bytes[pos++] = 0xC0;

        //HopCount
        bytes[pos++] = 0xff;

A: Problem Solved
In case anyone else has the same problem, check your UDP sockets.  In my code, I  created a send socket and a receive socket and set one of them to non-exclusive.  Unfortunately, in doing so, the sending socket will block any packets coming in on the receive port -- however, it will let UDP broadcasts come through so that it appears to work part of the time.

A: One related comment worth making - for virtual devices; you might need to specify a DNET # & DADR - destination network number & destination (V-MAC) address.  And some devices can be fussy about having/receiving the DADR/MAC address as the right/specific length (of bytes, e.g. fussy about the number of left-hand/leading padding-zero bytes).


text:
Q: Apparent contradiction when using Mayer Vietoris I am using the Mayer Vietoris sequence to compute the de Rham cohomology of a twice punctured plane.
I computed it first by choosing my open cover to be $U=R^2-{pt}$ and $V=R^2-{pt}$ (the points are different) with $U\cup V = R^2$ and $U \cap V$ the double punctured plane. Everything worked as expected.
Then, I tried computing it another way. Assume the missing points are (0,1) and (0,-1). I take $U = [(x,y): y > -1/2] $ with (0,1) missing. Similarly, I take $V = [(x,y): y < 1/2] $ with (0,-1) missing. Then, $ U \cup V $ is the double punctured plane, and $ U \cap V $ is the convex strip $ [-1/2 < y < 1/2] $ . But $H^{0}(U) \oplus H^{0}(V) = H^{1}(U) \oplus H^{1}(V) = R^2$ while $H^{0}(U \cap V) = R$ and $H^{1}(U \cap V) = 0$, so that the sequence is not exact:
$ H^{0}(U \cap V) = R$ $\rightarrow$  $H^{1}(U \cup V)$ $\rightarrow$ $H^{1}(U) \oplus H^{1}(V) = R^2$ $\rightarrow$ $H^1(U \cap V) = 0$
What blunder am I making here?
Thanks

A: There's no blunder. The MV sequence says this (where $M = U \cup V$), and I'm gonna be sloppy about formatting:
$$
0 \to H^0M \to H^0 U + H^0 V \to H^0(U \cap V) \to \\
H^1 (M) \to H^1 U + H^1 V \to H^1(U \cap V) \to \ldots
$$
Let's fill in those groups:
$$
0 \to R \to R + R\to R\to \\
R+R \to R+R \to 0 \to \ldots
$$
The maps themselves look like this:
$$
0 \to R : 0 \mapsto 0\\
R \to R + R :t \mapsto (t, t)\\
R + R\to R : (u,v) \mapsto u - v \\
R \to R + R :t \mapsto 0\\
R+R \to R+R : (u, v) \mapsto (u, v) \\
R+R \to 0 : (u, v) \mapsto 0.
$$
That's exact at every step.
You might want to look at http://math.berkeley.edu/~jdahl/214/214MV.pdf as well.


text:
Q: React Extension Not working chrome extension I've installer react extension on react but not able to use it as i'm facing an error

DevTools failed to load SourceMap: Could not load content for chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/injectGlobalHook.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME


text:
Q: javascript jquery carrying html form POST data SO I have a form that look similar to
<form action="test.php" id="checksub"  method="post">
  <div>
    <select name="mydropdown">
      <option value="buy">buy</option>
      <option value="sell">sell</option>
    </select>
  </div>

  autocomplete text input that triggers "checksub"

  <input type="submit" id="checksub" name="checksub" style="visibility:hidden">
  <input type="submit" id="newsbutton" name="newsbutton">
</form>

<script type="text/javascript">
  $('#newbutton').click(function() {
    var newaction = "cantfinditems.php";
    $("#checksub").prop("action", newaction);
    $('#checksub').submit();
  });
</script>

Now the submit button is hidden because the autocomplete triggers it anyway,  but if the user cant find what they are looking for I want a button that says "cant find what your'e looking for?"
I want this button to have a different action to the form action, ie window.location = cantfinditems.php
but I also want to carry the POST data from the form ie  "mydropdown".
Thank you

A: Ok, so you need a second button, which calls a JavaScript function. In this function, you do a number of things:
Set the action attribute of the form to your alternate action (e.g. cantfinditems.php)
var newaction = "cantfinditems.php";
$("#form_id").prop("action", newaction);

Submit the form
$('#form_id').submit();

So a full example would be:
<script type="text/javascript">
$('#yourbuttonid').click(function() {
  var newaction = "cantfinditems.php";
  $("#form_id").prop("action", newaction);
  $('#form_id').submit();
});
</script>


text:
Q: Como hago para que no se pueda dividir por cero? Estoy realizando un proyecto en python el cual es una calculadora que hace las operaciones básicas de multiplicación, división, suma, y resta. El problema es que quiero evitar que se pueda dividir por cero, y con este código funciona, pero si introduces una letra y luego pones el cero la condición no se ha aplica y divide entre cero dando así error el programa. ¿Como podría solucionar esto?
resp="S"
while resp=="S":

  numero1=input("¿Que número eliges como primer número?")
  while not numero1.isdigit():
    print("Tienes que escribir un número")
    numero1=input("Que número eliges como primer número?")
  numero1=int(numero1)

  numero2=input("¿Que número eliges como segundo número?")
  while not numero2.isdigit():
    print("Tienes que escribir un número")
    numero2=input("¿Que número eliges como segundo número")
  numero2=int(numero2)

  op=input("¿Que tipo de operacion quieres realizar? (+ - / ó *)")
  while op not in ["+","-","/","*"]:
    print("Tienes que escribir + - / ó *")
    op=input("¿Que tipo de operacion quieres realizar? (+ - / ó *)")

  if op=="+":
    print(numero1+numero2)

  elif op=="-":
    print(numero1-numero2)

  elif op=="*":
    print(numero1*numero2)

  elif op=="/":
    while numero2==0:
      print("No se puede dividr por cero, elige otro número")
      numero2=input("¿Que número eliges como segundo número?")
      while not numero2.isdigit():
        print("Tienes que escribir un número")
        numero2=input("Que número eliges como segundo número?")
    numero2=int(numero2)
    print(numero1/numero2)

  resp=input("¿Quieres seguir jugando? (S/N)")
  while resp not in ["S","s","N","n"]:
      print("Tienes que escribir S o N")
      resp=input("¿Quieres seguir jugando? (S/N)")

A: Cuando ves repetirse las mismas líneas de código es hora de transformar eso en una función. En este caso, haremos una función que ingrese y valide un numero entero. Además tendrá un parámetro opcional que indique si se acepta el valor cero (es True por default).
def ingresar(lugar, admite_cero = True):
    valor = None
    while not valor:
        try:
            numero = input(f"¿Que número eliges como {lugar} número?")
            valor = int(numero)
            if valor == 0 and not admite_cero:
                print("Cero no es válido")
        except ValueError:
            print("Tienes que escribir un número")
    return valor

Para validar que sea un entero, usamos el truco de intentar convertirlo con int(), y si eso falla, atrapar la excepción y repetir el ingreso.
La función retorna el valor convertido a entero.
Luego, lo conveniente es pedir la operación primero y luego el segundo valor. Sabiendo la operación podemos pedir el segundo valor chequeando que sea distinto de cero en el caso de la división:
resp = "s"
while resp == "s":
    numero1 = ingresar("primer")
    op = input("¿Que tipo de operacion quieres realizar? (+ - / ó *)")
    while op not in ["+", "-", "/", "*"]:
        print("Tienes que escribir + - / ó *")
        op = input("¿Que tipo de operacion quieres realizar? (+ - / ó *)")
    numero2 = ingresar("segundo", op != "/")

    if op == "+":
        print(numero1 + numero2)
    elif op == "-":
        print(numero1 - numero2)
    elif op == "*":
        print(numero1 * numero2)
    elif op == "/":
        print(numero1 / numero2)

    resp = input("¿Quieres seguir jugando? (S/N)").lower()
    while resp not in 'sn':
        print("Tienes que escribir S o N")
        resp = input("¿Quieres seguir jugando? (S/N)")

produce:
¿Que número eliges como primer número?10
¿Que tipo de operacion quieres realizar? (+ - / ó *)+
¿Que número eliges como segundo número?4
14
¿Quieres seguir jugando? (S/N)n

Process finished with exit code 0


text:
Q: ASP .NET MVC: Html.Radiobutton onclick -- set ViewData[""] I'm new to ASP .NET MVC and to web programming in general.
I'm wondering if there is a way to set ViewData variables when a radiobutton is selected -- but before the page is submitted.
Maybe I'm barking up the wrong tree but what I'm trying to do is create a form where new fields are added based on which radio button is selected. So what I want to do is when a radiobutton is clicked it sets a ViewData variable and based on that ViewData variable a different partial view loads the appropriate fields below the current field.
I imagine there must be someway of doing a onclick="some C# function that sets ViewData(args)"
Thanks

A: ViewData only exists, and only exists server-side, for the lifetime of the request. So, once the page is rendered the object no longer exists.
Some alternate approaches you can take:
1 - Use client-side Javascript to add a form and inputs as necessary. More info here:
ASP.NET MVC & JQuery Dynamic Form Content
2 - Pre-render the new form, but hide it via CSS, and unhide it when the appropriate radio button is clicked. More info here:
expand collapse html field Firefox
3 - Use AJAX to render the new form when the appropriate radio button is clicked. More info here:
http://www.asp.net/learn/mvc/tutorial-32-cs.aspx

A: There are a couple of ways you could go about this.
1) You could have an Ajax form where through Javascript you post the form back and check to see if it's an Ajax Request, there by returning a partial view to a div that you specify.
2) Post the form as is and check server-side to see if the radio button was clicked, and thus redisplay the form with the new options visible.
If you take the first approach it would be easy enough to fall through to the second one for those without Javascript enabled.
There aren't really "onclick" events as I'm assuming you are used to from Webforms, you would basically have to roll your own Javascript to handle such things. Once you do a few, I think you'll find it's really not too bad, with the benefit that you'll have more control over what you're doing and through that gain a better understanding of the larger picture.


text:
Q: Check if a Date field is greater than another Date field I am working on an issue tracking list and I added two custom fields of type Date/Time which allows date only, as follow:

*

*Plan start date.

*Plan end date.

How can I check that the start date is always less than or equal to end date?
I am seeking a way that will work inside the quick edit grid & inside the built-in create/edit forms ?

A: How you can do this:

*

*Open your list and open the list settings

*Select the column "Plan start date"

*Under Validation setting type in the below formula :

[Plan start date]<=[Plan end date]

This help you to validate your dates before saving them.
Hope this helps !


text:
Q: programmatically adding product to cart returns empty price i have been trying to programmatically add a product to cart using following lines of code, it seems to work and successfully adds product but for some reason, the price of newly added product always sets to zero.. how can i prevent this and let the actual price of product to be set for cart?
<?php

 error_reporting(E_ALL);
 ini_set('display_errors', 1);

require_once("app/Mage.php");
umask(0);
Mage::app('default');

 function mres($value)
{
    $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a");
    $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");

    return str_replace($search, $replace, $value);
}

echo "testing";
print_r($_POST);

$fname = mres( $_POST['fname'] );
$lname = mres( $_POST['lname'] );
$email = mres( $_POST['email'] );
$day = mres( $_POST['day'] );
$month = mres( $_POST['month'] );
$year = mres( $_POST['year'] );
$phone = mres( $_POST['phone'] );
$mobile = mres( $_POST['mobile'] );
$city = mres( $_POST['city'] );
$address = mres( $_POST['address'] );
$discount = mres( $_POST['discount'] );
$quantity = mres( $_POST['quantity'] );
$comments = mres( $_POST['comments'] );
$url = mres( $_POST['url'] );
$store = mres( $_POST['store'] );
$store_id = mres( $_POST['store_id'] );
$web_id = mres( $_POST['web_id'] );
$product_id = mres( $_POST['product_id'] );
$sku = mres( $_POST['sku'] );

setcookie('fname', $fname);
setcookie('lname', $lname);
setcookie('email', $email);
//setcookie('age', $age);
setcookie('phone', $phone);
setcookie('mobile', $mobile);
setcookie('city', $city);
setcookie('address', $address);

$customer = Mage::getModel('customer/customer');
//$customer  = new Mage_Customer_Model_Customer();
$password = substr(str_shuffle(md5(time())),0,8);;

$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);

//Zend_Debug::dump($customer->debug());

$isNew = 0;
if(!$customer->getId()) {
    $customer->setEmail($email);
    $customer->setFirstname($fname);
    $customer->setLastname($lname);
    $customer->setPassword($password);
    $isNew = 1;
}
try {
    $customer->save();
    $customer->setConfirmation(null);
    $customer->save();

    if($isNew)
    {
        $customer->sendNewAccountEmail();

        $ch = curl_init();

        //set the url, number of POST vars, POST data
        curl_setopt($ch,CURLOPT_URL, "//sameurl.php");
        curl_setopt($ch,CURLOPT_POST, count($_POST));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);

        //execute post
        $result = curl_exec($ch);

        //close connection
        curl_close($ch);

    }

    Mage::getSingleton('customer/session')->loginById($customer->getId());
}
catch (Exception $ex) {
    //Zend_Debug::dump($ex->getMessage());
}

//Build billing and shipping address for customer, for checkout
$_custom_address = array (
    'firstname' => $fname,
    'lastname' => $lname,
    'street' => array (
        '0' => $address,
        '1' => '',
    ),
    'city' => $city,
    'region_id' => '',
    'region' => '',
    'postcode' => '0000',
    'country_id' => 'PK',
    'telephone' => $phone . '-' . $mobile,
);
//$customAddress = Mage::getModel('customer/address')
$customAddress = new Mage_Customer_Model_Address();
$customAddress->setData($_custom_address)
            ->setCustomerId($customer->getId())
            ->setIsDefaultBilling('1')
            ->setIsDefaultShipping('1')
            ->setSaveInAddressBook('1');
try {
    $customAddress->save();

    Zend_Debug::dump($customAddress->debug());

}
catch (Exception $ex) {
    Zend_Debug::dump($ex->getMessage());
}
//Mage::getSingleton('checkout/session')->getQuote()->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));

Mage::getSingleton('checkout/session')->getQuote()
->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress)) ->setShippingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));

/*
$product = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('sku', $sku)
    ->addAttributeToSelect('*')
    ->getFirstItem();

$product->load($product_id);
$cart = Mage::getSingleton('checkout/cart');

$productInstance = Mage::getModel('catalog/product')->load($product_id);
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();
try {
    //$cart->addProduct($product, array('options'=> array('some-custom-option-id-here' => 'Some value goes here');
    //$cart->addProduct($product, array('price' => 5000));
    //$cart->addProduct($productInstance, $param);
    //$cart->save();

    $cart->init();
    $cart->addProduct($product, array('qty' => $qty));
    $cart->save();
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

}
catch (Exception $ex) {
    echo $ex->getMessage();
}
unset($product);
*/

$product = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('sku', $sku)
    ->addAttributeToSelect('*')
    ->getFirstItem();

$product->load($product_id);
$quote = Mage::getSingleton('checkout/session');
$quote->addProduct($product, $qty);

$quote->collectTotals()->save();

$storeId = $store_id;
$checkout = Mage::getSingleton('checkout/type_onepage');
$checkout->initCheckout();
$checkout->saveCheckoutMethod('register');
$checkout->saveShippingMethod('flatrate_flatrate');
$checkout->savePayment(array('method'=>'free'));

try {
    $checkout->saveOrder();
}
catch (Exception $ex) {
    echo $ex->getMessage();
}
/* Clear the cart */
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();
/* Logout the customer you created */
Mage::getSingleton('customer/session')->logout();

?>

A: Here we add the product to cart using external script
<?php
include 'app/Mage.php';
Mage::app();
// Need for start the session
Mage::getSingleton('core/session', array('name' => 'frontend'));
try {
    $product_id = '52'; // Replace id with your product id
    $qty = '4'; // Replace qty with your qty
    $product = Mage::getModel('catalog/product')->load($product_id);
    $cart = Mage::getModel('checkout/cart');
    $cart->init();
    $cart->addProduct($product, array('qty' => $qty));
    $cart->save();
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
    Mage::getSingleton('core/session')->addSuccess('Product added successfully');
    header('Location: ' . 'index.php/checkout/cart/');
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

Note:- here 52 is the simple product-id and 4 is the quantity value, you can replace with your quantity.

A: There are many things wrong here and I feel compelled to do a code review with you. See the end for the correct approach.
Code review:

This line is loading a product with an undefined $sku var:
$product = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('sku', $sku)
    ->addAttributeToSelect('*')
    ->getFirstItem();

Now you're reloading the $product var with an undefined value, returns a blank model or null.
$product->load($product_id);

Getting the cart model (but not necessarily mine from my customer session):
$cart = Mage::getSingleton('checkout/cart');

Wait - now we're loading another instance of a blank object:
$productInstance = Mage::getModel('catalog/product')->load($product_id);

Clearing the brand new cart:
$cart->truncate();

Saving our empty cart:
$cart->save();

Getting all the items in our empty cart, clearing them, and saving again:
$cart->getItems()->clear()->save();

The right way:

All in all this code makes no sense. Some Google searching turns up the right way to add a product to the current user's cart with the correct price attached:
$quote = Mage::getSingleton('checkout/session')->getQuote();
$quote->addProduct($product, $qty);

$quote->collectTotals()->save();

Where $product and $qty are both defined, and $product is an instance of Mage_Catalog_Model_Product and $qty is an integer.

A: I had this problem before.
In my task, I needed to add product on specific quote.Below code helped me to accomplish this:
$quoteModel = Mage::getModel('sales/quote')->load($quoteId);
$cartModel = Mage::getModel('checkout/cart');
$cartModel->setData('quote', $quoteModel);
$cartModel->init();
$cartModel->addProduct(productId, array('qty'=>5));
$cartModel->save();

Hope that wil help you in this case.

A: Here is the easy way to add product to cart/quote:
$customer = Mage::getModel('customer/customer')->load($customerId);
$product = Mage::getModel('catalog/product')->load($productId);
// load quote by customer and store...
$quote = Mage::getModel('sales/quote')->setStore($storeId)->loadByCustomer($customerId);
$quote->addProduct($product, 1);
$quote->setIsActive(1);
$quote->collectTotals()->save();

A: Here is the working code to add product to Cart:
$customer = Mage::getModel('customer/customer')->load($customerId);
$product = Mage::getModel('catalog/product')->load($productId);
// load quote by customer and store...
$quote = Mage::getModel('sales/quote')->setStore($storeId)->loadByCustomer($customerId);
$quote->addProduct($product, 1);
$quote->setIsActive(1);
$quote->collectTotals()->save();


text:
Q: How to rapidly prototype an image recognition application using Machine learning & neural network? Known that I'm very new in Machine learning.

I was thinking about a real world example of using Machine Learning
  and Neural network in an application and I want to try it with a
  mobile application who can handle image recognition with the front
  camera after make an image of something(A cat for exemple).

I really need advice of tools to use to rapidly make a prototype of this application with a python backend that I will call via rest.
Thanks in advance.

A: You can follow PyImageSearch. It has lot of stuff related image processiong like face recognition and license Plate Recognition system. It also use  neural networks.

A: Use an image recognition API, like google vision.
It is easy and fast to put in an application, and a lot more effective if you do not have experience and ressources in ML

A: I suggest if you are new to the machine learning algorithms, that you use an API from Google or Microsoft and get in touch with the flow and how it works .. Once you understand what are the inputs and outputs, you can try to replace the API for you own neural net, try to train it properly and collect results ..
Machine learning is not an easy concept and if you start big, there is a good chance that you'll get discouraged before you finish building it ... The API will provide you with a functional prototype very quickly and thus help you stay motivated to pursue it more ..
But to answer your question more directly, TensorFlow by Google is probably the most sophisticated tool for machine learning in general right now..
There is an excellent course for deep learning with TensorFlow made by Google on Udacity ..

A: I have done something similar for our company website. It is based on caffe though.
You can go through the source code here
However, it is a segmentation demo. You need to modify it a little.


text:
Q: How can I get a specific variable reading the data atribute on element? I have some fields on my site, and they are the same, but each one of then should update some jquery variable with it's value.
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>

I need that depending on the data-atribute, they run the same function, but update the variable pointed in the atribute.
Example:
for = "0";
int = "0";
agi = "0";

$( "input" ).focusout(function() {
    data-atribute-of-the-element = $(this).val;
})

I have no know idea how to do this.
And seems stupid to create a different function for every input.
Thanks in advance!

A: Create an object which has a field which is your variable. Something like below.

var a={'for':'0','int':'0','agi':'0'}

$( "input" ).focusout(function() {
    a[$(this).attr('data-atribute')] = $(this).val();
    console.log(a.for);
    console.log(a.int);
    console.log(a.agi);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>

A: .attr() does work, but since you're using data attributes anyway, you may as well use the .data() function designed for them.
See comments in the code snippet for explanation:

/* Set up an object to contain the values you're capturing.
   This means we won't have to predefine all the variables or
   set them individually; it also means you can use reserved words
   like "for", which wouldn't work as variables on their own: */
var capturedValues = {};

$( "input" ).focusout(function() {

  // This gets the contents of the "data-atribute" attribute:
  var theName = $(this).data("atribute");

  // This captures the value of the current input field,
  // and puts it in the capturedValues object using theName as the key:
  capturedValues[theName] = $(this).val();
  // Later on you can reference these as e.g. capturedValues.agi

  // Show the results (just for demo):
  console.log(capturedValues);

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>

A: Use the .attr function of jQuery:
$( "input" ).focusout(function() {
    let data-atribute-of-the-element = $(this).attr('data-atribute');
})

A: How about:
var for = "0";
var int = "0";
var agi = "0";

$( "input" ).focusout(function(s) {
  switch ($(this).attr('data-attribute')) {
    case 'for':
      for = $(this).val();
      break;
    case 'int':
      int = $(this).val();
      break;
    case 'agi':
      agi = $(this).val();
      break;
  }

  //OR
  var t = $(this).attr('data-attribute');
  if (t == 'for') for = $(this).val();
  else if (t == 'int') int = $(this).val();
  else if (t == 'agi') agi = $(this).val();
})

PS: 'atribute' has 2 t's : attribute


text:
Q: Storing checkbox data I am currently writing a script whereby an array of checkboxes are displayed using:
<?
  while($i = mysqli_fetch_array($get_perms)){

  $pname = $i[pname];
  $id = $i[id];
?>
  <div>
    <input type="checkbox" tabindex="1" name="<? echo("$id");?>" value="1" <? if($permissionid[$id] == '1') {echo ' checked="checked" ';}?> /><?echo(" $pname");?>
  </div>
<? } ?>

However, I also have another part doing a similar thing, but for Sget_perms is a different sql to gain different data.
Now, obviously, when it comes to posting back the data to the form/script, there's going to be a problem between distinguishing the two databits in the form.
This is the SQL to update the data given from form:
$insert = mysql_query("UPDATE `perms` SET
    `title`='$_POST[title]',
    `1` ='$_POST[1]',
    `2` ='$_POST[2]',
    `3` ='$_POST[3]',
    `4` ='$_POST[4]',
    `5` ='$_POST[5]',
    `user` ='$_POST[username]'
     WHERE `userid` = '$valued_user_show[id]'
")

So how on earth do I correctly distinguish between the two, and there be able to correctly enter the SQL?
The schema of the table is basically:
7 columns, userid, user, 1, 2, 3, 4 ,6
userid is the userid of the user who has been posted to script before form. user is the name.
The numbers are the permission numbers.
$get_perm is the sql to load the current information about the user from the table in an array.

A: First: never include user-submitted data in a SQL statement without escaping it!  A malicious user could exploit that to clobber your data, retrieve data without authorization, and cause all manner of harm.  Always use mysql_real_escape_string() to escape submitted values going into a query.
On to your actual question: to distinguish your two similar sets of fields, just give them different names.  Perhaps the first would be called permsA and the second permsB.  You'd then get HTML like this:
<input type="checkbox" tabindex="1" name="permsA_<? echo $id;?>" value="1" <? if($permissionid[$id] == '1') {echo ' checked="checked" ';}?> /><?echo htmlspecialchars($pname);?>

Note that I also included a call to htmlspecialchars() to properly escape the $pname value for use in HTML, and I omitted the unnecessary quotes around "$id" (putting a variable in quotes like that just makes PHP do additional processing to parse the string; you can just echo the variable itself without quotes).
Then in your SQl statement:
$insert = mysql_query("UPDATE `perms` SET
    `title`='" . mysql_real_escape_string($_POST[title]) . "',
    `1` ='" . mysql_real_escape_string($_POST['permsA_1'] . "',
    `2` ='" . mysql_real_escape_string($_POST['permsA_2'] . "',
    `3` ='" . mysql_real_escape_string($_POST['permsA_3'] . "',
    `4` ='" . mysql_real_escape_string($_POST['permsA_4'] . "',
    `5` ='" . mysql_real_escape_string($_POST['permsA_5'] . "',
    `user` ='" . mysql_real_escape_string($_POST['username']) . "'
     WHERE `userid` = '$valued_user_show[id]'
")

Here the only change is to add the permsA_ prefix, and to properly escape all user-submitted values.

A: Create an array with your checkboxes:
<input type="checkbox" name="mycheckbox[]"/>

And "mycheckbox" will be available as an array in your _POST data.


text:
Q: One-to-many relationship I have the following situation and I do not know how to solve it. I have tried in different ways but with no avail.I don't even know if this is possible. I would like this to be done with a CouchDB View, with a map(or reduce) functions.  I want to implement a one to many relationship in CouchDB as per the below example:
{
      "_id": 1,
      "name" : "Me",
      "doctype" : "employee"
    },
    {
     "_id" : 2,
     "name" : "MeAgain",
     "doctype" : "employee"
    },
    {
     "_id" : 3,
     "doctype": "holidayrequest",
     "startdate": "01/25/2021",
     "requesterid": "1"
    },
    {
     "_id" : 4,
     "doctype": "holidayrequest",
     "startdate": "01/16/2021",
     "requesterid": "1"
    },
    {
     "_id" : 5,
     "doctype": "holidayrequest",
     "startdate": "04/16/2021",
     "requesterid": "2"
    },
    {
     "_id" : 6,
     "doctype": "holidayrequest",
     "startdate": "04/25/2021",
     "requesterid": "2"
    }

I would like the outcome to be :
{
 "_id": 1,
  "name" : "Me",
  "doctype" : "employee",
  "holidays":[
     {
        "_id" : 3,
        "doctype": "holidayrequest",
        "startdate": "01/25/2021",
        "requesterid": "1"
     },
     {
        "_id" : 4,
        "doctype": "holidayrequest",
        "startdate": "01/16/2021",
        "requesterid": "1"
     }
  ]
},
{
 "_id" : 2,
 "name" : "MeAgain",
 "doctype" : "employee",
 "holidays":[
     {
      "_id" : 5,
      "doctype": "holidayrequest",
      "startdate": "04/16/2021",
      "requesterid": "2"
    },
    {
      "_id" : 6,
      "doctype": "holidayrequest",
      "startdate": "04/25/2021",
      "requesterid": "2"
    }
 ]
}

Can this be done?


text:
Q: Fill C-Array with zeros, then copy data into it This is part of FTP client app that uses Sockets for network communication.
Before sending command to the FTP server, I want to initialize command buffer
to zeroes - no chance to mix new command with any old characters that may be
at the end of buffer (following the new command and '\0'.
//global buffers msg[1024] and cmd[16]
void sendCommand(int client_socket, char* command, size_t cmd_len) {
    int in, out;
    memset(&msg, 0, sizeof(msg));
    memset(&cmd, 0, sizeof(cmd));
    strncpy(cmd, command, cmd_len); //
    printf("Command: %s\n", cmd);   //debugging prompt
    out = send(client_socket, cmd, sizeof(cmd), 0);
    sleep(1);
    in = recv(client_socket, msg, sizeof(msg), 0);
    sleep(1);
    printf("received %d bytes: %s\n", in, msg);  //debugging prompt
}

Edit: Following is call of the function above:
sendCommand(client_socket, "USER anonymous\r\n", sizeof("USER anonymous\r\n"));
The problem is: The buffer really gets empty and then filled with the command
but server cannot recognize certain commands (e.g. PASV). The problem is in the
code because if I try to comment out memset(&cmd, 0, sizeof(cmd)); I get expected
result for current command plus error 500 Unknown command for the tails of buffer cmd
Here is example answer from the server:
Command: USER anonymous
received 720 bytes: 331 Please specify the password.
Command: PASS dummy
received 720 bytes: 230-FFFFF III TTTTTT  Welcome!
230 Login successful.
500 Unknown command.    //tail of old data
command: PASV
received 94 bytes: 227 Entering Passive Mode (147,229,9,30,40,184).
500 Unknown command.    //tail of old data
500 Unknown command.    //tail of old data
command: QUIT
received 14 bytes: 221 Goodbye.

Thanks in advance!

A: The error was incorrect string length.
1) No NULL at the end of string is needed.
2) The only correct end of line is CRLF for FTP
3) Now I use strlen instead of sizeof

A: are you putting the /r at the end of your command? and make sure in strncpy cmd_len will include the /r in the length


text:
Q: xades-t format with java xml signing api I would like to use java xml signing api for xades-t signature type. I need to do a canonical transform on signature value node, get a timestamp and insert the result under the object tag.
I can successfully use the api to do regular signing, but I am confused about getting one step further. any pointers are very much appreciated.
thanks

A: Try with jXAdES at xades.dev.java.net.
Here you have some sample tests:
https://xades.dev.java.net/source/browse/xades/trunk/jxades/src/main/java/net/java/xades/test/
Hope it helps :)
Regards,
  Ricardo


text:
Q: If $E(X|Y) = X$, what does this imply about the relationship between $X$ and $Y$? Let $Z, K, V$ denote random variables, where $Z$ is binary, $K$ is categorical from 1-10, and $V$ is continuous.
Let $X = P(Z = 1|V = v)$ and $Y_k = P(Z = 1|V = v, K = k)$. Now define $Y = (Y_1, \ldots, Y_{10})$. What is $E(X|Y)$? Is it equal to $X$ because $Y$ is a coarser (or finer) partition of $X$?
My thinking is:
\begin{align*}
E(X|Y) &= E(E(Z|V=v) | \{E(Z|V=v, K=1), \ldots, E(Z|V=v, K=10)\}\\
\end{align*}
But I'm not sure how exactly to show that $E(X|Y) = X$.

A: It's not true (in general) that $E[X|Y]=X$. Consider this example

*

*$X$ is sampled with equal probability from 11-30

*$Y$ is the units digit of $X$.

Then $Y$ is determined by $X$ so $E[Y|X]=Y$ but $E[X|Y]\neq X$. For example, if $Y=1$, $X$ could be 11 or 21 with equal probability, so $E[X|Y=1]=16$.
If $E[Y|X]=Y$ then $Y$ is (almost surely) a deterministic function of $X$. If that function is (almost surely) one:one then $X$ is also a deterministic function of $Y$ and $E[X|Y]=X$, but not otherwise.


text:
Q: JavaScript - Select radio button if any checkbox is checked I'm trying to write JavaScript code where a radio button should be populated if a checkbox is checked.
Following is the HTML code:
<form>

Radio Buttons

   <input type="radio" name="radio1" id="radio1"> Radio 1

   <input type="radio" name="radio2" id="radio2">Radio 2

Checkbox Groups

Group 1

PD

         <input id="pdcb" type="checkbox" name="G1PD1" onclick="validate()">G1 PD1

         <input id="pdcb" type="checkbox" name="G1PD2" onclick="validate()">G1 PD2

ID

         <input id="idcb" type="checkbox" name="G1ID1" onclick="validate()">G1 ID1

         <input id="idcb" type="checkbox" name="G1ID2" onclick="validate()">G1 ID2

Group 2

PD

         <input id="pdcb" type="checkbox" name="G2PD1" onclick="validate()">G2 PD1

         <input id="pdcb" type="checkbox" name="G2PD2" onclick="validate()">G2 PD2

ID

         <input id="idcb" type="checkbox" name="G2ID1" onclick="validate()">G2 ID1

         <input id="idcb" type="checkbox" name="G2ID2" onclick="validate()">G2 ID2

</form>

So here's what I want the JavaScript to do: If any of the PD checkboxes are selected, then the radio button Radio 1 should get selected. If none of the PD checkboxes are selected, then the radio button Radio 2 should get selected. Similarly, if none of the checkboxes are selected, then NONE of the radio buttons should get selected.
So far, I've written the following JS code:
function validate()
{
    if(document.getElementById("pdcb").checked) //if pdcb checkbox(es) is/are checked
  {
    document.getElementById("radio1").checked = true;
    document.getElementById("radio2").checked = false;
  }
  else if (!document.getElementById("pdcb").checked) //if none of the pdcb checkbox(es) is/are checked
  {
    document.getElementById("radio1").checked = false;
    document.getElementById("radio2").checked = true;
  }
  else //if no checkbox is checked, then don't populate any radio button
  {
    document.getElementById("radio1").checked = false;
    document.getElementById("radio2").checked = false;
  }

}

PS: I need the code to be in pure JavaScript. I can't use jQuery.
Edit
I apologize for getting my requirements wrong. But here's the correct requirement. If any of the PD checkboxes are selected, then the radio button Radio 1 should get selected. If none of the PD checkboxes are selected, then the radio button Radio 2 should get selected. Similarly, if none of the checkboxes are selected, then NONE of the radio buttons should get selected.

A: I want to first point out that if you were testing this in a JSFiddle, the LOAD TYPE needs to be set to "No Wrap-in " for your inline onclick events to work.
Now, to your code. Document elements can either be tied to a class or ID. Classes are for when you're using elements that share the same functionality, styling, etc.; ID's are for unique elements and unique elements only. For example, in your JavaScript, when you try to test for checked pdcb elements with
document.getElementById("pdcb").checked
JavaScript simply grabs the first element on the page with the ID of pdcb. You have four elements with this ID name; this means that the last three pdcb elements are ignored and never evaluated.
Instead, let's utilize
document.getElementsByClassName("pdcb")

Note the plural form of the word 'Element'. What this does is it returns an array of all elements with the class name of pdcb. We'll get to the fact that we're dealing with an array in a few minutes. First, let's change most of your HTML ID's to classes.

      <input class="pdcb" type="checkbox" name="G1PD1" onclick="validate()">G1 PD1

      <input class="pdcb" type="checkbox" name="G1PD2" onclick="validate()">G1 PD2

You're going to want to do this for all of your pdcb and idcb elements. Feel free to preserve radio1 and radio2 as ID's because they're unique elements, not reused like pdcb and idcb are.

Now we can address the JavaScript; you're HTML is fine from here assuming you've made the changes necessary from above. Since we changed things from ID's to classes, expressions like the following simply won't do.
document.getElementById("pdcb")
Recall the solution that I wrote earlier:
document.getElementsByClassName("pdcb")
Also recall that I said that this will return an array of elements; in your case, four pdcb elements.
One option that you have at your disposal for tackling this problem is that you can iterate through the array of elements returned by document.getElementsByClassName("pdcb") to evaluate whether any pdcb class has been checked. It'll look something like this:
var pdcbClass = document.getElementsByClassName("pdcb");

    //for each pdcb class on our HTML document
    for (var i = 0; i < pdcbClass.length; i++) {
       if (pdcbClass[i].checked == true) {
          //the next two lines are straight from your JavaScript code
          document.getElementById("radio1").checked = true;
          document.getElementById("radio2").checked = false;
        }
    }

As you can imagine, we can use the exact same idea for the idcb class elements on your page. By the time we're done, we should have something like what you see below.
function validate()
{
  var pdcbClass = document.getElementsByClassName("pdcb");
  var idcbClass = document.getElementsByClassName("idcb");
  console.log(this);
    for (var i = 0; i < pdcbClass.length; i++) {
    if (pdcbClass[i].checked == true) {
       document.getElementById("radio1").checked = true;
         document.getElementById("radio2").checked = false;
    }
  }

  for (var i = 0; i < idcbClass.length; i++) {
    if (idcbClass[i].checked == true) {
      document.getElementById("radio1").checked = false;
      document.getElementById("radio2").checked = true;
    }
  }
}

But there's a problem! No matter what check box fires off this validate() function, no check box is ever turned off. That means if we check a box with the  pdcb class and then check a box with the idcb class, the pdcb box still stays checked; we never said to uncheck it. What this means is that even though it was an idcb click that triggered validate(), all of the code in the function gets executed. Either you have to have the user manually uncheck the previous box before checking a new one, or you need to write some code that does this same thing. Specifically, when a new check box is checked, you need to clear the previous box(es) of their checked property.
That is an entirely different problem and merits a different question. Also consider that this isn't the only way to write this event/functionality, but you're making good progress.
Here's essentially the code you need to keep on going.
https://jsfiddle.net/a4k9xggu/


text:
Q: Condition formatting in Excel. Find non-matching values between columns I have two columns; quantity ordered and quantity shipped.
If and order is 100% filled those values should match on each row.
I want to write a conditional format that highlights quantity shipped if it is less than quantity ordered on the same row.
I can compare values between columns but have been unable to specify that the comparison is on the same row.


text:
Q: Setting HttpRequest request body for HttpContext.Current I am trying to unit test HttpContext in my test class as follows, but could not find the way how to set request body for this object.
Is there any way to do it? So HttpContext.Current.Request.GetBufferedInputStream(); will return the bytes of the body string I set.
   [TestMethod()]
    public void GetRequestStringTest2()
    {
        string filename = "";
        string url = "http://www.localhost.com";
        string queryString = "";
        HttpRequest request = new HttpRequest(filename, url, queryString);
        // TODO: set request body here
        // string requestBody = "request-test-123";
        StringBuilder sb = new StringBuilder("response-test-123");
        StringWriter writer = new StringWriter(sb);
        HttpResponse response = new HttpResponse(writer);
        HttpContext.Current = new HttpContext(request, response);
        string requestString = HttpUtilities.GetRequestString();
        Assert.IsNotNull(requestString);
        Assert.AreEqual("request-test-123", requestString);
    }

 public static string GetRequestString()
        {
            if (HttpContext.Current != null)
            {
                Stream stream = HttpContext.Current.Request.GetBufferedInputStream();
                new StreamReader(stream).ReadToEnd();
                StreamReader bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
                bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
                string requestString = bodyStream.ReadToEnd();
                return requestString;
            }

            throw new InvalidOperationException("HttpContext.Current is not available.");
        }

A: There is, but it will not be easy.
In order to do this you need to call the method internal void SetRawContent(HttpRawUploadedContent rawContent) from HttpRequest.
The problem is, you cannot call a internal method from a external assembly, however there is some ways to bypass this: C# - How to access internal class from external assembly.