text:
Q: Custom dynamic graph in Android [UPDATE]
To conclude this question, I implemented my graph using the following two methods (see below).  drawCurve() receives a Canvas and an array of float.  The array is properly filled (timestamps are assumed by the value index in the array) and varies from 0.0 to 1.0.  The array is sent to prepareWindowArray() that takes a chunk of the array from position windowStart for windowSize-values, in a circular manner.
The array used by the GraphView and by the data provider (a Bluetooth device) is the same.  A Class in the middle ensures that GraphView  is not reading data that are being written by the Bluetooth device.  Since the GraphView always loop thru the array and redraw it at every iteration, it will update according to the data written by the Bluetooth device, and by forcing the write frequency of the Bluetooth device to the refresh frequency of the Graph, I obtain a smooth animation of my signal.
The GraphView's invalidate() method is called by the Activity, which run a Timer to refresh the graph at every x milliseconds.  The frequency at which the graph is refreshed is dynamically set, so that it adapt to the flow of data from the Bluetooth device (which specify the frequency of its signal in the header of its packet).
Find the complete code of my GraphView in the answer I wrote below (in the answer section).  If you guys find errors or way to optimize it, please let me know; it would be greatly appreciated!
/**
 * Read a buffer array of size greater than "windowSize" and create a window array out of it.
 * A curve is then drawn from this array using "windowSize" points, from left
 * to right.
 * @param canvas is a Canvas object on which the curve will be drawn.  Ensure the canvas is the
 * later drawn object at its position or you will not see your curve.
 * @param data is a float array of length > windowSize.  The floats must range between 0.0 and 1.0.
 * A value of 0.0 will be drawn at the bottom of the graph, while a value of 1.0 will be drawn at
 * the top of the graph.  The range is not tested, so you must ensure to pass proper values, or your
 * graph will look terrible.
 *      0.0  : draw at the bottom of the graph
 *      0.5  : draw in the middle of the graph
 *      1.0  : draw at the top of the graph
 */
private void drawCurve(Canvas canvas, float[] data){

    // Create a reference value to determine the stepping between each points to be drawn
    float incrementX = (mRightSide-mLeftSide)/(float) windowSize;

    float incrementY = (mBottomSide - mTopSide);

    // Prepare the array for the graph
    float[] source = prepareWindowArray(data);

    // Prepare the curve Path
    curve = new Path();
    // Move at the first point.
    curve.moveTo(mLeftSide, source[0]*incrementY);
    // Draw the remaining points of the curve
    for(int i = 1; i < windowSize; i++){
        curve.lineTo(mLeftSide + (i*incrementX), source[i] * incrementY);
    }

    canvas.drawPath(curve, curvePaint);

}

The prepareWindowArray() method that implement the circular behavior of the array:
/**
 * Extract a window array from the data array, and reposition the windowStart
 * index for next iteration
 * @param data the array of data from which we get the window
 * @return an array of float that represent the window
 */
private float[] prepareWindowArray(float[] data){
    // Prepare the source array for the graph.
    float[] source = new float[windowSize];

    // Copy the window from the data array into the source array
    for(int i = 0; i < windowSize; i++){
        if(windowStart+i < data.length)                         // If the windows holds within the data array
            source[i] = data[windowStart + i];                  // Simply copy the value in the source array
        else{                                                   // If the window goes beyond the data array
            source[i] = data[(windowStart + 1)%data.length];    // Loop at the beginning of the data array and copy from there
        }
    }
    // Reposition the buffer index
    windowStart = windowStart + windowSize;
    // If the index is beyond the end of the array
    if(windowStart >= data.length){
        windowStart = windowStart % data.length;
    }

    return source;
}

[/UPDATE]
I'm making an app that read data from a Bluetooth device at a fixed rate.  Everytime that I have new data, I want them to be plotted on the graph to the right, and to translate the remainder of the graph to the left in realtime.  Basically, like an oscilloscope would do.
So I made a custom View, with xy axis, a title and units.  To do this, I simply draw those things on the View canvas.  Now I want to draw the curve.  I manage to draw a static curve from an already filled array using this method:
public void drawCurve(Canvas canvas){

    int left = getPaddingLeft();
    int bottom = getHeight()-getPaddingTop();
    int middle = (bottom-10)/2 - 10;

    curvePaint = new Paint();
    curvePaint.setColor(Color.GREEN);
    curvePaint.setStrokeWidth(1f);
    curvePaint.setDither(true);
    curvePaint.setStyle(Paint.Style.STROKE);
    curvePaint.setStrokeJoin(Paint.Join.ROUND);
    curvePaint.setStrokeCap(Paint.Cap.ROUND);
    curvePaint.setPathEffect(new CornerPathEffect(10) );
    curvePaint.setAntiAlias(true);

    mCurve = new Path();
    mCurve.moveTo(left, middle);
    for(int i = 0; i < mData[0].length; i++)
        mCurve.lineTo(left + ((float)mData[0][i] * 5), middle-((float)mData[1][i] * 20));

    canvas.drawPath(mCurve, curvePaint);
}

It gives me something like this.

There are still things to fix on my graph (the sub-axis are not properly scaling), but these are details I can fix later.
Now I want to change this static graph (that receives a non-dynamic matrice of values) with something dynamic that would redraw the curve every 40ms, pushing the old data to the left and plotting the new data to the right, so I could visualise in real time the information provided by the Bluetooth device.
I know there are some graphing package that exists already, but I'm kinda noob with these things and I'd like to pratice by implementing this graph myself.  Also, most of my GraphView class is done, except for the curve part.
Second question, I'm wondering how I should send the new values to the graph.  Should I use something like a FIFO stack, or can I achieve what I want with a simple matrice of doubles?
On a side note, the 4 fields at the bottom are already dynamically updated.  Well, they are kind of faking the "dynamic", they loop thru the same double matrice again and again, they don't actually take fresh values.
Thanks for your time!  If something's unclear about my question, let me know and I'll update it with more details.

A: As mentioned in my question, here's the class that I designed to solve my problems.
/**
 * A View implementation that displays a scatter graph with
 * automatic unit scaling.
 *
 * Call the setupGraph() method to modify the graph's
 * properties.
 * @author Antoine Grondin
 *
 */

public class GraphView extends View {

    //////////////////////////////////////////////////////////////////
    // Configuration
    //////////////////////////////////////////////////////////////////

    // Set to true to impose the graph properties
    private static final boolean TEST = false;

    // Scale configuration
    private float minX = 0;         // When TEST is true, these values are used to
    private float maxX = 50;        // Draw the graph
    private float minY = 0;
    private float maxY = 100;

    private String titleText = "A Graph...";
    private String xUnitText = "s";
    private String yUnitText = "Volts";

    // Debugging variables
    private boolean D = true;
    private String TAG = "GraphView";

    //////////////////////////////////////////////////////////////////
    // Member fields
    //////////////////////////////////////////////////////////////////

    // Represent the borders of the View
    private int mTopSide = 0;
    private int mLeftSide = 0;
    private int mRightSide = 0;
    private int mBottomSide = 0;
    private int mMiddleX = 0;
    // Size of a DensityIndependentPixel
    private float mDips = 0;

    // Hold the position of the axis in regard to the range of values
    private int positionOfX = 0;
    private int positionOfY = 0;

    // Index for the graph array window, and size of the window
    private int windowStart = 0;
    private int windowSize = 128;
    private float[] dataSource;

    // Painting tools
    private Paint xAxisPaint;
    private Paint yAxisPaint;
    private Paint tickPaint;
    private Paint curvePaint;
    private Paint backgroundPaint;

    private TextPaint unitTextPaint;
    private TextPaint titleTextPaint;

    // Object to be drawn

    private Path curve;
    private Bitmap background;

    ///////////////////////////////////////////////////////////////////////////////
    // Constructors
    ///////////////////////////////////////////////////////////////////////////////

    public GraphView(Context context) {
        super(context);
        init();
    }

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

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

    ///////////////////////////////////////////////////////////////////////////////
    // Configuration methods
    ///////////////////////////////////////////////////////////////////////////////

    public void setupGraph(String title, String nameOfX, float min_X, float max_X, String nameOfY, float min_Y, float max_Y){
        if(!TEST){
            titleText = title;
            xUnitText = nameOfX;
            yUnitText = nameOfY;
            minX = min_X;
            maxX = max_X;
            minY = min_Y;
            maxY = max_Y;
        }
    }

    /**
     * Set the array this GraphView is to work with.
     * @param data is a float array of length > windowSize.  The floats must range between 0.0 and 1.0.
     * A value of 0.0 will be drawn at the bottom of the graph, while a value of 1.0 will be drawn at
     * the top of the graph.  The range is not tested, so you must ensure to pass proper values, or your
     * graph will look terrible.
     *      0.0  : draw at the bottom of the graph
     *      0.5  : draw in the middle of the graph
     *      1.0  : draw at the top of the graph
     */
    public void setDataSource(float[] data){
        this.dataSource = data;
    }

    ///////////////////////////////////////////////////////////////////////////////
    // Initialization methods
    ///////////////////////////////////////////////////////////////////////////////

    private void init(){
        initDrawingTools();
    }

    private void initConstants(){
        mDips = getResources().getDisplayMetrics().density;
        mTopSide = (int) (getTop() + 10*mDips);
        mLeftSide = (int) (getLeft() + 10*mDips);
        mRightSide = (int) (getMeasuredWidth() - 10*mDips);
        mBottomSide = (int) (getMeasuredHeight() - 10*mDips);
        mMiddleX = (mRightSide - mLeftSide)/2 + mLeftSide;
    }

    private void initWindowSetting() throws IllegalArgumentException {

        // Don't do anything if the given values make no sense
        if(maxX < minX || maxY < minY ||
                maxX == minX || maxY == minY){
            throw new IllegalArgumentException("Max and min values make no sense");
        }
        // Transform the values in scanable items
        float[][] maxAndMin = new float[][]{
                {minX, maxX},
                {minY, maxY}};
        int[] positions = new int[]{positionOfY, positionOfX};

        // Place the X and Y axis in regard to the given max and min
        for(int i = 0; i<2; i++){
            if(maxAndMin[i][0] < 0f){
                if(maxAndMin[i][1] < 0f){
                    positions[i] = (int) maxAndMin[i][0];
                } else{
                    positions[i] = 0;
                }
            } else if (maxAndMin[i][0] > 0f){
                positions[i] = (int) maxAndMin[i][0];
            } else {
                positions[i] = 0;
            }
        }

        // Put the values back in their right place
        minX = maxAndMin[0][0];
        maxX = maxAndMin[0][1];
        minY = maxAndMin[1][0];
        maxY = maxAndMin[1][1];

        positionOfY = mLeftSide +  (int) (((positions[0] - minX)/(maxX-minX))*(mRightSide - mLeftSide));
        positionOfX = mBottomSide - (int) (((positions[1] - minY)/(maxY-minY))*(mBottomSide - mTopSide));
    }

    private void initDrawingTools(){

        xAxisPaint = new Paint();
        xAxisPaint.setColor(0xff888888);
        xAxisPaint.setStrokeWidth(1f*mDips);
        xAxisPaint.setAlpha(0xff);
        xAxisPaint.setAntiAlias(true);

        yAxisPaint = xAxisPaint;

        tickPaint = xAxisPaint;
        tickPaint.setColor(0xffaaaaaa);

        curvePaint = new Paint();
        curvePaint.setColor(0xff00ff00);
        curvePaint.setStrokeWidth(1f*mDips);
        curvePaint.setDither(true);
        curvePaint.setStyle(Paint.Style.STROKE);
        curvePaint.setStrokeJoin(Paint.Join.ROUND);
        curvePaint.setStrokeCap(Paint.Cap.ROUND);
        curvePaint.setPathEffect(new CornerPathEffect(10));
        curvePaint.setAntiAlias(true);

        backgroundPaint = new Paint();
        backgroundPaint.setFilterBitmap(true);

        titleTextPaint = new TextPaint();
        titleTextPaint.setAntiAlias(true);
        titleTextPaint.setColor(0xffffffff);
        titleTextPaint.setTextAlign(Align.CENTER);
        titleTextPaint.setTextSize(20f*mDips);
        titleTextPaint.setTypeface(Typeface.MONOSPACE);

        unitTextPaint = new TextPaint();
        unitTextPaint.setAntiAlias(true);
        unitTextPaint.setColor(0xff888888);
        unitTextPaint.setTextAlign(Align.CENTER);
        unitTextPaint.setTextSize(20f*mDips);
        unitTextPaint.setTypeface(Typeface.MONOSPACE);

    }

    ///////////////////////////////////////////////////////////////////////////////
    // Overridden methods
    ///////////////////////////////////////////////////////////////////////////////

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

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

    public void onDraw(Canvas canvas){
        drawBackground(canvas);
        if(dataSource != null)
            drawCurve(canvas, dataSource);
    }

    ///////////////////////////////////////////////////////////////////////////////
    // Drawing methods
    ///////////////////////////////////////////////////////////////////////////////

    private void drawX(Canvas canvas){
        canvas.drawLine(mLeftSide, positionOfX, mRightSide, positionOfX, xAxisPaint);
        canvas.drawText(xUnitText, mRightSide -  unitTextPaint.measureText(xUnitText)/2, positionOfX - unitTextPaint.getTextSize()/2, unitTextPaint);
    }

    private void drawY(Canvas canvas){
        canvas.drawLine(positionOfY, mTopSide, positionOfY, mBottomSide, yAxisPaint);
        canvas.drawText(yUnitText, positionOfY + unitTextPaint.measureText(yUnitText)/2 + 4*mDips, mTopSide + (int) (unitTextPaint.getTextSize()/2), unitTextPaint);
    }

    private void drawTick(Canvas canvas){
        // No tick at this time
        // TODO decide how I want to put those ticks, if I want them
    }

    private void drawTitle(Canvas canvas){
        canvas.drawText(titleText, mMiddleX, mTopSide + (int) (titleTextPaint.getTextSize()/2), titleTextPaint);
    }

    /**
     * Read a buffer array of size greater than "windowSize" and create a window array out of it.
     * A curve is then drawn from this array using "windowSize" points, from left
     * to right.
     * @param canvas is a Canvas object on which the curve will be drawn.  Ensure the canvas is the
     * later drawn object at its position or you will not see your curve.
     * @param data is a float array of length > windowSize.  The floats must range between 0.0 and 1.0.
     * A value of 0.0 will be drawn at the bottom of the graph, while a value of 1.0 will be drawn at
     * the top of the graph.  The range is not tested, so you must ensure to pass proper values, or your
     * graph will look terrible.
     *      0.0  : draw at the bottom of the graph
     *      0.5  : draw in the middle of the graph
     *      1.0  : draw at the top of the graph
     */
    private void drawCurve(Canvas canvas, float[] data){

        // Create a reference value to determine the stepping between each points to be drawn
        float incrementX = (mRightSide-mLeftSide)/(float) windowSize;

        float incrementY = mBottomSide - mTopSide;

        // Prepare the array for the graph
        float[] source = prepareWindowArray(data);

        // Prepare the curve Path
        curve = new Path();
        // Move at the first point.
        curve.moveTo(mLeftSide, source[0]*incrementY);
        // Draw the remaining points of the curve
        for(int i = 1; i < windowSize; i++){
            curve.lineTo(mLeftSide + (i*incrementX), source[i] * incrementY);
        }

        canvas.drawPath(curve, curvePaint);
    }

    ///////////////////////////////////////////////////////////////////////////////
    // Intimate methods
    ///////////////////////////////////////////////////////////////////////////////

    /**
     * When asked to draw the background, this method will verify if a bitmap of the
     * background is available.  If not, it will regenerate one.  Then, it will draw
     * the background using this bitmap.  The use of a bitmap to draw the background
     * is to avoid unnecessary processing for static parts of the view.
     */
    private void drawBackground(Canvas canvas){
        if(background == null){
            regenerateBackground();
        }
        canvas.drawBitmap(background, 0, 0, backgroundPaint);
    }

    /**
     * Call this method to force the GraphView to redraw the cache of it's background,
     * using new properties if you changed them with setupGraph().
     */
    public void regenerateBackground(){
        initConstants();
        try{
            initWindowSetting();
        } catch (IllegalArgumentException e){
            Log.e(TAG, "Could not initalize windows.", e);
            return;
        }
        if(background != null){
            background.recycle();
        }
        background = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas backgroundCanvas = new Canvas(background);

        drawX(backgroundCanvas);
        drawY(backgroundCanvas);
        drawTick(backgroundCanvas);
        drawTitle(backgroundCanvas);

    }

    /**
     * Extract a window array from the data array, and reposition the windowStart
     * index for next iteration
     * @param data the array of data from which we get the window
     * @return an array of float that represent the window
     */
    private float[] prepareWindowArray(float[] data){
        // Prepare the source array for the graph.
        float[] source = new float[windowSize];

        // Copy the window from the data array into the source array
        for(int i = 0; i < windowSize; i++){
            if(windowStart+i < data.length)                         // If the windows holds within the data array
                source[i] = data[windowStart + i];                  // Simply copy the value in the source array
            else{                                                   // If the window goes beyond the data array
                source[i] = data[(windowStart + 1)%data.length];    // Loop at the beginning of the data array and copy from there
            }
        }
        // Reposition the buffer index
        windowStart = windowStart + windowSize;
        // If the index is beyond the end of the array
        if(windowStart >= data.length){
            windowStart = windowStart % data.length;
        }

        return source;
    }
}

A: Well I would start by just trying to redraw it all with the code you have and real dynalic data.  Only if that is not quick enough do you need to try anything fancy like scrolling...
If you need fancy I would try somthing like this.
I would draw the dynamic part of the graph into a secondary Bitmap that you keep between frames rather than directly to the canves.  I would have the background none dynamic part of the graph in another bitmap that only gets drawen on rescale etc.
In this secondary dynamic bitmap when ploting new data you first need to clear the old data you are replacing you do this by drawing the apropriate slice of the static background bitmap over the top of the stale data, thus clearing it and geting the background nice and fresh again.  You then just need to draw your new bit of dynamic data.  The trick is that You draw into this second bitmap left to right then just wrap back to the left at the end and start over.
To get from the soncodary bitmap to your cancas draw the bitmap to the canvas in two parts.  The older data to the right of what you just added needs to be drawn onto the left part of your final canvas and the new data needs to be drawn imediatly to the right of it.
For sending the data a circular buffer would be the normal thing for this sort of data where once it's off the graph you don't care about it.


text:
Q: "Derivations" and Runge's theorem I am trying to show that for a given region $\Omega\subset\mathbb{C}$ and a continous linear operator $D\in\mathcal{C}(\mathcal{H}(\Omega))$ satisfying Leibniz's rule
$$D(fg)=fD(g)+D(f)g, \qquad\forall f,g\in\mathcal{H}(\Omega),$$
there exists an holomorphic function $h\in\mathcal{H}(\Omega)$, such that
for any $f\in\mathcal{H}(\Omega)$
$$D(f)=f'\cdot h.$$
The problem says that I should use Runge's theorem, but I don't see how. By now, I have taken a compact disk $\overline{D}:=\overline{D(a,R)}\subset\Omega$ and used the analytic expression of $f$ over $D$ to obtain
$$\Phi(f)=\Phi\left(\sum_{n=1}^\infty a_n\frac{(z-a)^n}{n!}\right)=\sum_{n=1}^\infty\frac{a_n}{n!}\Phi((z-a)^n)=\sum_{n=1}^\infty\frac{a_n}{n!}n(z-a)^{n-1}\Phi(z-a)=$$
$$=\Phi(z-a)\sum_{n=1}^\infty\frac{a_n}{n-1!}(z-a)^{n-1}=\Phi(z-a)\cdot f'.$$
Since $\Phi(z-a)\in\mathcal{H}(D)$ and $f\in\mathcal{H}(\Omega)$, all that we have to do is apply the analytic continuation theorem and we obtain the result. What is wrong with my proof?

A: Hint. By virtue of Runge's Theorem, it suffices to show that, there exists an $h\in\mathcal H(\Omega)$, such that
$$
D(z^n)=nz^{n-1}h(z)\quad\text{and} \quad D\left(\frac{1}{(z-a)^n}\right) =-\frac{nh(z)}{(z-a)^{n+1}},
$$
for all $a\ne\in\Omega$.
Set first, $h(z)=D(z)$. Clearly, $D(z^n)=nz^{n-1}h(z)$, inductively, and
$$
0=D\left((z-a)\cdot\frac{1}{z-a}\right)=(z-a)h(z)\cdot\frac{1}{z-a}+D\left(\frac{1}{z-a}\right),
$$
and hence
$$
D\left(\frac{1}{z-a}\right) =-\frac{h(z)}{(z-a)^2}.
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding the common increase term in a non-constant sequence I have a sequence which I can't seem to properly map.
$a \; ; \;a +\frac{1}{2} a \; ; \; a + \frac{1}{2} a +\frac{1}{4} a$ + ...
I'm basically trying to write an R function that will calculate the result for any step in the sequence. I understand that the change is essentially $\frac{1}{2^n}$, but I haven't managed to factor it in so that I can get the result instead of just the change at every step.
For example, if $a = 100$, and I run the sequence 3 times, I would like to obtain a formula that yields: $100\; ; \;150 \; ; \;175$
Any idea how I can obtain the general formula for this?

A: For any step
$$s_n=s_{n-1}+\frac{1}{2^{n-1}}a$$
So that
$$s_n=\left(\sum_{k=1}^n\frac{1}{2^{k-1}}\right)a$$
Let $S:= \sum_{k=1}^n\frac{1}{2^{k-1}}= \sum_{k=0}^{n-1}\frac{1}{2^{k}}$. Observe that this is the geometric series of reason $q=\frac{1}{2}$. Then
$S=1+\frac{1}{2}(S-\frac{1}{2^{n-1}})$
$\frac{1}{2}S=1-\frac{1}{2^{n}}$
so
$S=2(1-\frac{1}{2^n})$
Then
$$s_n= 2(1-\frac{1}{2^n})a$$


text:
Q: Time measurement in C I'm trying to measure the time it takes my program to perform multiple operations in a loop and the entire program is written in C. I'm using the method from this post:
C# vs C - Big performance difference
However, when I try doing that method, on the declaration line for clock(), I get an error: Improper use of typedef symbol in function main.
The header file is included and does not cause any errors. This is a 16-bit C program written in the TurboC compiler for MS-DOS. I'm not sure which version of C it's using, but I think it's most likely C89 or one of the earlier versions of C. I don't know if that causes any syntax differences or not?
Here's the code I'm using:
clock_t start = clock();
while(count < 10000)
{
     count++;
}
printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);

And the error is exactly as I mentioned above.

A: In old-timey 16-bit C, you probably should use time_t and the time() function. They've been used for this purpose since approximately when email was invented.
Your code will die a horrible death sometime in 2038 if you do this.  http://en.wikipedia.org/wiki/Year_2038_problem
 #include <time.h>
 time_t start = time();
 /* do a bunch of stuff */
 time_t stop = time();
 unsigned long int elapsedSeconds = stop - start;

If something goes wrong with using time_t declarations, try unsigned long int instead.


text:
Q: Terraform detects changes to availability domain on data lookup Terraform detects changes to availability_domain and forces a replacement when no change has taken place.
When I run terraform apply a second time with no changes made, terraform forces a replacement of my instance, this is due to the availability_domain lookup, is this a bug, or is my lookup incorrect?
  # module.services.oci_core_volume must be replaced
-/+ resource "oci_core_volume" "disk_res_instance[" {
      + auto_tuned_vpus_per_gb = (known after apply)
      ~ availability_domain    = "REGION" -> (known after apply) # forces replacement
      + backup_policy_id       = (known after apply)
      ~ freeform_tags          = {} -> (known after apply)
      ~ id                     = "ocid1.volume.oc1.me-jeddah-1.abc" -> (known after apply)
      ~ is_auto_tune_enabled   = false -> (known after apply)
      ~ is_hydrated            = true -> (known after apply)
      + kms_key_id             = (known after apply)
      ~ size_in_mbs            = "51200" -> (known after apply)

If I'm reading this correctly, it seems that the replacement is forced by the availability_domain, however, this remains unchanged.
resource "oci_core_volume" "diskinstance" {
  count               = 1
  availability_domain = data.oci_identity_availability_domains.ad_list.availability_domains[0]["name"]
...

data
data "oci_identity_availability_domains" "ad_list" {
  compartment_id = var.compartment_id
}

Is it that each time the data look-up on the availability domains is being done it forces it to be replaced, or something else?

A: It can be due to Image as well. Check if you are pulling latest Image.
This would not be case if you are doing planning immediately
Note: once Instance is launched AD will not be changed for an instance.


text:
Q: hcitool lescan Set scan parameters failed: Input/output error the following command
sudo hcitool lescan

throws the following error:
Set scan parameters failed: Input/output error

I have tried
hciconfig hci0 down
hciconfig hci0 up

and then
service bluetooth restart
service dbus restart

and tried againg. still didnt work.
OS: Ubuntu 18.04
bluez version: 5.48


text:
Q: Configuring a picklist in CRM Online 2015 We currently have a CRM Dynamics 4.0 system and as part of our Account Entity we have a field new_accountstatus with the following set up:
Schema

*

*Display Name: Account Status

*Name: new_accountstatus

*Requirement Level: No Constraint

*Searchable: Yes

*Description: "V1.0"

Type

*

*Type: Picklist

*
*

*Overdiew  2. Active  3. Suspended  4.De-Energise  5.Terminated  6.Inactive

*Default Value: Unassigned Value

We are contemplating upgrading and moving to CRM Online 2015 and have created an online trial and as part of the initial configuration we are trying to set up account model and the picklist with similar values and layout.
On creating a new field in CRM 2015 online I can see that the Data Type fields have completely changed. And from the available list Option Set was seemed the most relevant for my needs.
Can anyone explain to me what the Field Type of Simple and Calculated is all about? Also if I try to enter the same values as was in our old system of between 1-6 I get the message:
"The option value you specified does not use this solution's option value prefix (10,000). You should enter a number between 100,000,000 and 100,009,999"
If I enter this as 10,000,001 will this then be read as 1 from the option set as would have been the case in dynamics 4.0 picklist?

A: The type you need for your picklist is Option Set.
From CRM 2011 you can choose between local and global (existing) Option Set. If your picklist is used only inside account entity you can create it as local, if it is used in more than one entity (or you plan in the future that this is a possibility) you can create it as global, in order to be reused.
The difference between Simple and Calculated is a feature introduced with CRM 2015, in your case you need Simple (Calculated is in case the value becomes from a calculation, more details here: http://blogs.technet.com/b/lystavlen/archive/2014/11/20/calculated-fields-new-in-crm-2015.aspx)
Regarding the value (1-6). CRM 2011 introduced the concept of Solutions and Publishers, each Publisher can have an Option Set prefix (10000 is the value for the Default Publisher) in order to differentiate Option Set coming from different solutions.
You can still override the prefix, so you can put the values 1-6 if you prefer, the use of the prefix is suggested but not mandatory. the value 100,000,001 is different from 1, so (considering backward compatibility with external system) you should put 1 as value.


text:
Q: numpy: finding all pairs of numbers in a matrix that suffice on neighboring condition Suppose you have a matrix:
import numpy as np
mat = np.array([[0, 0, 1], [2, 0, 1], [1, 0, 3]])

and you want to retrieve all pairs of numbers in this matrix that are neighboring each other, not equal and ignoring zero. In this case this would be 3 & 1 and 2 & 1, but I want to be able to apply this to a very large matrix. Any help greatly appreciated, thanks!

A: This should do the trick, though admittedly, it's not the most elegant; I tested it on a 1000x1000 matrix of random integers, and it was pretty fast (just over a second). I'm not sure how you are thinking about the output, so I put it into a list called res.
import numpy as np
# To test on larger array
mat = np.array(np.random.random_integers(0, 9, 1000 * 1000)).reshape(1000, 1000)
res = []

for a in mat:
    # Take out the zeros
    no_zeros = a[a!=0]
    if len(no_zeros) > 1:
        for i in range(len(no_zeros) - 1):
            # Only append pairs of non-equal neighbours
            if no_zeros[i] != no_zeros[i+1]:
                res.append((no_zeros[i], no_zeros[i+1]))


text:
Q: Domain Restriction for ListPlot I constructed a table (here called 'distanceplot') with a set domain (from 0 to 100). I wish to keep this domain for the table constant. However, I shall be making multiple plots, each using a different subset of the domain. For example, I shall be making a plot which used only data from 0 to 10. Is there a way for ListPlot to restrict the domain already given to a table? I attempted to use the command DataRange, but it didn't change anything.
I tried the following

ListPlot[distanceplot,DataRange->{0,10}]

I know how to do this for Plot, but ListPlot I am not sure.

A: It may depend on what you would like to achieve visually with your plot.
I'll create some fake data to represent yours:
distanceplot = Table[{x, 2 x}, {x, 0, 100, 1}];

Here are two ways to achieve what you asked, which lead to somewhat different results
The first example, which I suggested in the comments, provides an explicit limit for the horizontal plot range. The vertical plot range is determined automatically by ListPlot, taking into consideration all your data:
ListPlot[distanceplot, PlotRange -> {{0, 10}, Automatic}, PlotRangePadding -> Scaled[0.05]]

As you can see, the vertical range goes all the way to 200, because that is the range encompassed by the full dataset. If this behavior is undesirable, you could a) give an explicit value for the $y$ range as well, or b) pre-select the data that you feed to ListPlot with e.g. Cases:
ListPlot[Cases[distanceplot, {x_, y_} /; 0 <= x <= 10], PlotRangePadding -> Scaled[0.05]]

In this case, we don't need to fiddle with the PlotRange at all: we simply feed only the data to be plotted to ListPlot, and let it do its internal magic to determine the appropriate PlotRange for this subset.
Note that, using this approach, you can filter your data any way you want. Suppose that you wanted only those points $10\le x \le 45$ for which $x$ is a prime number; you could then write:
ListPlot[
 Cases[distanceplot, {x_, y_} /; 10 <= x <= 45 && PrimeQ[x]],
 PlotRangePadding -> Scaled[0.05], AxesOrigin -> {0, 0}
]


text:
Q: Review reopen post queue suddenly increase I usually observe other than close votes all review queue has small numbers but today reopen post also have 3 figure number. Is queue was blocked due to some bug?

A: The latest build fixed a long-standing bug in the Reopen Queue (~500 questions), as well as adding a few hundred "popularly" closed questions for your attention.
Popularity in this case means lots of views plus a great question score plus a great average answer score - the community team will be tweaking these values in the coming days and will discuss them.


text:
Q: Reactjs Ajax returns first empty array while getting json object I have a problem. I am learning React js and I have a template which i must edit. I need to add some ajax methods for getting and sending info. I manage to do some of those actions but now I have a problem.
I have php scripts which is getting me json_encode.
getCategories: function() {
$.ajax({
  url: '#########my_url#########',
  dataType: 'json',
  success: function(data) {
    this.setState({datas: data});
  }.bind(this)
});
},

and I have this
getInitialState: function() {
  return {datas: []};
},

The problem is I always get firstly the empty array and then the result. And when I try to work with it, it gets me error because it tries to map the empty array. This is the console.log before I try to play with the object.
[HMR] Waiting for update signal from WDS...

[]

[WDS] Hot Module Replacement enabled
[Object, Object, Object, Object]

How can I make it to work after the object is full?

A: First option: render your view on ajax call success
Second option: anticipate the case your state.datas is still empty
for example if you're working in your render function try:
   { this.state.datas ? <div> Loading </div> : <....

Above is JSX syntax
Hope it helps
EDIT:
if(this.state.datas.length == 0) {
    var mycomponent =<div> Loading ... </div>;
} else {
   var mycomponent = this.state.datas;
}

Basically this should work.


text:
Q: Can't use functions exported from .bashrc in a bash script My .bashrc file exports a function called lookup:
lookup() {
  grep -r -ne "$1" * | grep -v "TAGS:" | grep -v "tags:"
}
export -f lookup

I can use that function in a shell.  But if I put it in a script like this:
#!/bin/bash
lookup "foo"

and run the script then bash reports "command not found" for lookup.  This used to work some time ago.  I strongly suspect this is stopped working after a security update of bash on my system (possibly related to shellshock/bashdoor?) My bash version is 4.1.10(1) on openSUSE 11.4

A: Check http://www.gnu.org/software/bash/manual/bashref.html#Bash-Startup-Files

Invoked non-interactively
When Bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute.

Specifically, none of the ~/.bashrc, ~/.profile, ~/.bash_profile are NOT sourced. ~/.bashrc is only invoked if the shell is an interactive shell.
You have a couple of options:

*

*source your .bashrc explicitly
#!/bin/bash
. ~/.bashrc
lookup "foo"

*start bash with the interactive flag
#!/bin/bash -i
lookup "foo"

*set the BASH_ENV variable when you start your script:
BASH_ENV=$HOME/.bashrc /path/to/my/script


text:
Q: if one field doesn't exist in the sent object it fails give this error "[parsing_exception] no text specified for text query" function getConversations(filter,res){
  client.search({
    index: "conversations",
    type: "docs",
    body: {
      "query": {
        "bool": {
          "should": [{
              "range": {
                "followers_count": {
                  "gte": filter.followers_count_range.gte,
                  "lte": filter.followers_count_range.lte
                }
              }
            },
            {
              "match": {
                "user_gender": filter.gender
              }
            },
            {
              "match": {
                "dialect": filter.dialect
              }
            },
            {
              "match": {
                "lang": filter.language
              }
            }

          ],

          "minimum_should_match":1

        }
      }

    }

  }, function(err, resp, status) {
    if (err) {
      console.log(err);
      res.status(400).send({
        message: "Not Found"
      });
    } else {
      //console.log("--- Response ---");
      console.log(resp);
      console.log("--- Hits ---");
      resp.hits.hits.forEach(function(hit) {
        console.log(hit._source);
      });
      res.status(200).send({
        message: "Done"
      });
    }
  });
}

I am new to elastic search and need more understanding and help.
if one field of the match doesn't exist in the send object it gives an error why, how can I fix that
if my filter has only a name property  it doesn't work all property must be in the filter obj
another question
if I want to say that if a language is a specific value I choose to neglect to match the dialect

A: You can check for the existence of a given filter before passing it to the ES request body with a ternary operator. If it's falsy, use the match_all query which is essentially the Elasticsearch equivalent a no-operation:
{
  query: {
    bool: {
      should: [
        {
          range: {
            followers_count: {
              gte: filter.followers_count_range.gte,
              lte: filter.followers_count_range.lte
            }
          }
        },
        filter.gender
          ? {
              match: {
                user_gender: filter.gender
              }
            }
          : {
              match_all: {}
            },
        filter.dialect
          ? {
              match: {
                dialect: filter.dialect
              }
            }
          : {
              match_all: {}
            },
        filter.language
          ? {
              match: {
                lang: filter.language
              }
            }
          : { match_all: {} }
      ],

      minimum_should_match: 1
    }
  }
};


text:
Q: Rewrite a piecewise function into a single expression Consider a piecewise function . I want a general way to rewrite it , into the single expression . I know that for sign function there is a single expression but I'm looking for solve it generally.

A: It is not always possible, and many of the times it is possible, it's only because we're hiding the piecewise definition behind a dedicated piece of notation. For instance, the function $f(x)=|x|$ is really the function
$$
f(x)=\cases{x&if $x\geq0$\\-x&if $x<0$}
$$It's just that this particular piecewise function is so common that we have established a specific piece of notation to make writing the function easier.

A: In one of your comments, you asked for a function, defined for all $x \in \mathbb{R},\,$ such that
$$
f(x)=\cases{
0 &\text{if}\; x < 0\\[3pt]
1 &\text{if}\; x > 0
}
$$
Here's one trick which will bury the cases . . .
$$f(x)=\left\lfloor{\max\left(0\,,\frac{1+x}{1+|x|}\right)}\right\rfloor$$


text:
Q: No network loopback device after security update ubuntu 12.04 I've had Ubuntu 12.04 on a server for the last several months, with everything working fine.  Last night I did an aptitude update && aptitude safe-upgrade to bring in all the latest security changes, and now when I boot the server no lo device is created.
It brings up the physical ethernet interfaces correctly, and I can ping in and out of the machine on those interfaces, but nothing can connect to anything on either localhost or 127.0.0.1.
ifconfig lists only eth0 and eth1.
No lo at all.
Here are the contents of /etc/network/interfaces:
# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto eth0
#NetworkManager#iface eth0 inet dhcp

Where should I be looking to diagnose and fix?
Thanks!

A: I have had similar problem.
My lo didn't start automatically at boot (after turning off IPv6 via sysctl and rebooting the server).
My first workaround was to start it manually with ifup --force lo. But after that I had to restart most of my services as they didn't work properly without loopback.
Finally this old forum post helped me to find out the proper and permanent solution:

*

*sudo rm -rf /var/run/network/*

*sudo reboot
(Apparently there was some old .lock file there that prevented the loopback to start properly.)

A: If lo can be brought up manually with ifup lo but isn't brought up automatically, you should be able to put the command ifup lo in /etc/rc.local so it will start at each boot.  Not an elegant solution but it should be a permanent solution.


text:
Q: Will the size of web.config effect the speed website? In my ASP.NET website, in order to block some countries to visit my website, I add many IP items to web.config file.
The size of the file web.config reach 1 MB, will it cause my website to be slow?

A: Web.config file gets loaded, when ASP.NET run time bootstraps your web site. This is one-time activity, when the web site is restarted. So, the size of 1 MB should not make your website slow.
However, basic question is: at what point you are matching the IP Address of web site? if not already doing, will advise to restrict the access via HTTP module and put it in ASP.NET pipeline towards the start.
There might be another way to block the countries - e.g. at the network layer. You should have a hole in your organisation fire wall to expose the website. You can try to coordinate with your network infrastructure, to block it at the firewall level only, thus avoiding any incoming traffic from blocked countries.


text:
Q: Entropy of discrete and continuous uniform distributions Despite a similar post here, I read that the entropy of a uniformly distributed discrete random variable is always log base $2$ of the number of observations in the dataset, $H(X) = \log(N)$. Is this also true for a uniformly distributed continuous r.v.?

A: Think about it.
A real number between $0$ and $1$ is able to contain infinite information. Just encode any symbol of the alphabet with the decimal representation 3 digit ascii symbols for example.
Entropy of continous distribution means how much information you need to store just for the shape of the distribution. You will need to add as many extra bits for whatever precision you will want.


text:
Q: Making all members of the C# class public for test I have a class with multiple protected methods, properties and fields. Let's say this is the class:
    public class UntestedClass
    {
        protected int field;
        protected int Method() => field + 5;
    }

I want to test the class but I have to make all members of that class accessible to my test methods. There are two ways that I know of:

*

*Subclass UntestedClass, override protected methods with public ones and add methods or properties to access protected fields. I do not like this way as it is too much tedious work.

    public class MyTestedClass : UntestedClass
    {
        public int Field {get => base.field; set => base.field = value; } // Now accessible as public
        public new int Method() => base.Method();                         // Now accessible as public
    }

*Inherit UntestedClass in my Unit test class. This approach takes care of tedious work but it makes it impossible to test different constructors.

    [TestClass]
    public class TestsOfTests : UntestedClass
    {
        [TestMethod]
        public void MethodTest()
        {
            base.field = 1;            // Assign to protected field
            var result = base.Method();// Invoke protected method
            .... and so on ...

Is there a better way? Ideally, I would love to have something like this:
   var testable = new MakeEverythingPublic<UntestedClass>();
   testable.field = 42;

I do not believe this is possible but maybe there is a third way that is better than the two choices I listed above?


text:
Q: How to append new fabric.Canvas to existing canvas element? new fabric.Canvas is replacing existing canvas element I am wanting to use fabric.js freeDraw. I want to append or add the fabric.Canvas on top of an existing canvas element that also has interactivity. However, when I use new fabric.Canvas it is replacing the existing canvas.
My existing canvas looks like this in the body:
<canvas id="canvas" width="2160" height="1440" style="background-color:#FFFFFF"></canvas>

I am trying to add the new fabric.Canvas on top by saying:
var canvasDraw = new fabric.Canvas('canvasDraw', { width:500, height:500, isDrawingMode: true});

So in short, I want to be able to freeDraw on the existing canvas by using fabric.js however that is possible. Either by inserting the new fabric.Canvas on top of the existing one or however it should be done.
Thank you,
Eric


text:
Q: Communication between main thread and worker threads in android In my very first android project, I do some data manipulation, so I use multi-threading approach.
In MainActivity, I created multiple Runnable object and use ExecutorService to run all the threads. As my understanding, all threads are put in message queue and executed in turn. And the because the main thread is already in the queue, it will be executed before starting other threads. Is there any way that I can make the main thread wait for other threads to finish and then continue?
   @Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //call MyFunction here
}
private List<Pair[]> myFunction(int dataInput) throws InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(12);
    MyTask MyTask = new MyTask();
    for (int i = 0; i < gallerySize; ++i) {
        final int index = i;
        Runnable runnable = MyTask.runLongOperationWithThread(new MyTask.DataCallback(){
            @Override
            public void onSuccess(double[] scores) {
                // get data back to main thread
            }

            @Override
            public void onError(Exception ex) {
                //TODO: log this error out to file
            }
        });
        executorService.execute(runnable);
    }

    // try to get back all data from multi threading and do some operations
    return returnList;
}

Do Looper and Handler help in this case?
And please correct me if I have any misunderstanding in android concept and threading.
Thanks.

A: In Android, stopping main thread is discouraged. The system will tell the user that the app is not responding. However, you can "notify" the main thread that the background thread has finished its work. Once the main thread knows this, it will do something. It is common in Android, it is what AsyncTask for.
However, AsyncTask is used for a simple one thread. In your case, one of the solution is to combine ExecutorService and AsyncTask. In doInBackground method of AsyncTask instance you make, use ExecutorService like usual, and wait it to finish by either shutdown(); awaitTermination() or invokeAll(). Read this question/answer for more information about how to wait ExecutorService to finish.
private class WrappingTask extends AsyncTask<Void, Void, Exception> {
    protected Exception doInBackground(Void... args) {
        ExecutorService taskExecutor = Executors.newFixedThreadPool(12);
        for (. . .) {
            taskExecutor.execute(new MyTask(. . .));
        }
        taskExecutor.shutdown();
        try {
            taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            . . .
            return e;
        }
        return null;
    }

    protected void onPostExecute(Exception error) {
        // Notify the user that the task has finished or do anything else
        // and handle error
    }
 }

In case of long running task
AsyncTask is a handy class to make threading and communicating (to main thread) easier. The problem for long running task is that the user can leave the Activity (and then come again), or there is an incoming call, etc. If you don't handle this Activity lifecycle with care, it is so "dangerous", AsyncTask does not handle this.
Long running task should be run in a Service. Note that Service is also run in the main thread, so the approach would be the same, unless you use IntentService. In case of IntentService, just execute all of the threads (formerly in doInBackground) in the onHandleIntent method and wait it there, this method is called on a worker thread.
Communicating Service with Activity and maintaining consistency of Activity's state through its lifecycle is a long story. You better read the documentation in "a full concentration" with a cup of coffee :D. This might helps:

*

*Managing the Activity Lifecycle

*Best Practices for Background Jobs


text:
Q: Python FastAPI security dependencies cleaner way to have power user I'm working on a FastAPI project where endpoinds can be accessed with multiple scopes. But some scopes give more permission than other. I made a simplify example of what I've made so far. The first layer of security (get_session) return a session object from a token and the second layer(is_authorized) define if the user should be considered has a power user.
I don't like this solution because I have to repeate on each endpoints a if statement.
I sure it's possible to do it only with FastAPI dependencies, but I haven't found any a clean solution to do this.
The main problem is that the argument can sometimes be in the path or the query. It must also be tested lower case.
If anyone has a cleaner solution to this case, please let me know. Thanks
from fastapi import Depends, FastAPI, HTTPException, Query, Path, Security
from fastapi.security import SecurityScopes

COMMON_PROPERTY = {}

app = FastAPI()

async def get_session():
    return {"user": "toto", "scopes": ["weak_user"]}

async def is_authorized(scope_required: SecurityScopes, session = Depends(get_session)):
    for power_user_scope in scope_required.scopes:
        if power_user_scope in session["scopes"]:
            return True
    return False

@app.get("/route1/{argument}")
async def route1(
    argument: str = Path(**COMMON_PROPERTY),
    session: dict = Security(get_session, scopes=["power_user", "weak_user"]),
    power_user: bool = Security(is_authorized, scopes=["power_user"]),
    ):

    if not power_user and argument.lower() != session["user"]:
        return "weak user data"

    return "power user data"

@app.get("/route2")
async def route2(
    argument: str = Query(**COMMON_PROPERTY),
    session: dict = Security(get_session, scopes=["power_user", "weak_user"]),
    power_user = Security(is_authorized, scopes=["power_user"]),
    ):

    if not power_user and argument.lower() != session["user"]:
        return "weak user data"

    return "power user data"


text:
Q: Difference between cv2, scipy.misc and skimage What is the main difference between

*

*cv2.imread / resize/ imwrite

*scipy.misc.imread / imresize/ imsave

*skimage.io.imread / skimage.transform.resize / skimage.io.imsave
and how to decide which one to use?
I know cv2 and skimage have different encoder, and cv2 use 'BGR' not 'RGB' in default. But sometimes a script might use them together, for example main.py, where it uses scipy.misc.imread, cv2.imresize and cv2.imwrite. I am wondering the reason to do so.

A: The scipy.misc module exists historically as a place to gather functions that do not fit easily into the other SciPy submodules.  It is slated for deprecation and should not be used.
In the Python ecosystem, I'd recommend imageio for reading images (or matplotlib.pyplot.imread, if you already are using matplotlib).
Scikit-image provides a convenient wrapper around all of these I/O libraries as skimage.io (it should pick up whatever is installed on your system already).  It also ensures that images are converted to the correct data type and range formats for use with other skimage functions (see http://scikit-image.org/docs/dev/user_guide/data_types.html).
cv2.imread et al. operate on OpenCV image objects and, as you've already observed, those images are typically stored in BGR memory layout.  But for loading PNGs and JPGs, most of these libraries listed above all wrap the same underlying C libraries, perhaps with slightly different parameters for compression etc.
I'd recommend that you use whichever functions minimize the dependency footprint of your script / package.


text:
Q: Подскажите как передать данные через Intent? public class MarkerList{

    public MarkerList(int capacity) {
        super(capacity);
    }

    public MarkerList() {
    }

    public MarkerList(Collection collection) {
        super(collection);
    }

    ArrayList<String> lat=new ArrayList<>();
    ArrayList<String> lng=new ArrayList<>();
    ArrayList<String> name=new ArrayList<>();
    ArrayList<String> type_2=new ArrayList<>();//Type_2

    public int getSize(){
        return name.size();
    }

    public ArrayList<String> getLat() {
        return lat;
    }

    public void setLat(ArrayList<String> lat) {
        this.lat = lat;
    }

    public ArrayList<String> getLng() {
        return lng;
    }

    public void setLng(ArrayList<String> lng) {
        this.lng = lng;
    }

    public ArrayList<String> getName() {
        return name;
    }

    public void setName(ArrayList<String> name) {
        this.name = name;
    }

    public ArrayList<String> getType_2() {
        return type_2;
    }

    public void setType_2(ArrayList<String> type_2) {
        this.type_2 = type_2;
    }
}

У меня есть такой класс. Я не могу передавать через PutExtras. Подскажите как передать мой класс?

A: Есть такая замечательная страничка на котрой можно без проблем сделать Parcelable: http://www.parcelabler.com/
Вот ваш Parcelable класс:
public class MarkerList implements Parcelable {

public MarkerList(int capacity) {
    super(capacity);
}

public MarkerList() {
}

public MarkerList(Collection collection) {
    super(collection);
}

ArrayList<String> lat=new ArrayList<>();
ArrayList<String> lng=new ArrayList<>();
ArrayList<String> name=new ArrayList<>();
ArrayList<String> type_2=new ArrayList<>();//Type_2

public int getSize(){
    return name.size();
}

public ArrayList<String> getLat() {
    return lat;
}

public void setLat(ArrayList<String> lat) {
    this.lat = lat;
}

public ArrayList<String> getLng() {
    return lng;
}

public void setLng(ArrayList<String> lng) {
    this.lng = lng;
}

public ArrayList<String> getName() {
    return name;
}

public void setName(ArrayList<String> name) {
    this.name = name;
}

public ArrayList<String> getType_2() {
    return type_2;
}

public void setType_2(ArrayList<String> type_2) {
    this.type_2 = type_2;
}

protected MarkerList(Parcel in) {
    if (in.readByte() == 0x01) {
        lat = new ArrayList<String>();
        in.readList(lat, String.class.getClassLoader());
    } else {
        lat = null;
    }
    if (in.readByte() == 0x01) {
        lng = new ArrayList<String>();
        in.readList(lng, String.class.getClassLoader());
    } else {
        lng = null;
    }
    if (in.readByte() == 0x01) {
        name = new ArrayList<String>();
        in.readList(name, String.class.getClassLoader());
    } else {
        name = null;
    }
    if (in.readByte() == 0x01) {
        type_2 = new ArrayList<String>();
        in.readList(type_2, String.class.getClassLoader());
    } else {
        type_2 = null;
    }
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    if (lat == null) {
        dest.writeByte((byte) (0x00));
    } else {
        dest.writeByte((byte) (0x01));
        dest.writeList(lat);
    }
    if (lng == null) {
        dest.writeByte((byte) (0x00));
    } else {
        dest.writeByte((byte) (0x01));
        dest.writeList(lng);
    }
    if (name == null) {
        dest.writeByte((byte) (0x00));
    } else {
        dest.writeByte((byte) (0x01));
        dest.writeList(name);
    }
    if (type_2 == null) {
        dest.writeByte((byte) (0x00));
    } else {
        dest.writeByte((byte) (0x01));
        dest.writeList(type_2);
    }
}

@SuppressWarnings("unused")
public static final Parcelable.Creator<MarkerList> CREATOR = new Parcelable.Creator<MarkerList>() {
    @Override
    public MarkerList createFromParcel(Parcel in) {
        return new MarkerList(in);
    }

    @Override
    public MarkerList[] newArray(int size) {
        return new MarkerList[size];
    }
};
}

A: Вам надо у вашего класса реализовать интерфейс Parcelable. Вот примерный класс, со списком методов и их реализацией - отредактируйте его под ваш класс по аналогии:
public class Model implements Parcelable {
    private String title;
    private String text;

    /**
     * Parcel implementation
     */
    private Model(Parcel in) {
        this.title = in.readString();
        this.text = in.readString();
    }

    /**
     * Parcel implementation
     */
    @Override
    public int describeContents() {
        return 0;
    }

    /**
     * Parcel implementation
     */
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(title);
        dest.writeString(text);
    }

    /**
     * Parcel implementation
     */
    public static final Parcelable.Creator<Model> CREATOR = new Parcelable.Creator<Model>() {
        @Override
        public Model createFromParcel(Parcel source) {
            return new Model(source);
        }

        @Override
        public Model[] newArray(int size) {
            return new Model[size];
        }
    };
}

Важные моменты:

*

*Читать поля класса в методе-конструкторе (private Model(Parcel in)) надо в том же порядке, в коем они записаны в методе writeToParcel

*Читать строковые списки надо так: in.readList(mFotos, String.class.getClassLoader());

*Как читать/записывать вложенные объекты, реализующие Parcelable написано тут: Записать Parcelable в Parcelable
После этого передавать объект в Bundle Intent-a можно так:
Bundle b = new Bundle();
b.putParcelable(someParcelableObject);


text:
Q: How to fix this Binary Tree Deserialize problem? Where is the bug in this serialize() function
I wrote a function deserialize() in Swift to construct a binary tree from an array of optional Integer. I tested this function by comparing the output with the output of a tree constructed using manual method with same array. They look the same, which is good !
However, when I run another function isSameTree(), that is used to compare 2 trees (I am sure this function is working correctly), on deserialize()'s output and manual method's output, I have different results !
I assume deserialize() is not correct, but I could not find the bug!
// helper code
public class BinaryNode {
     public var value: Int
     public var left: BinaryNode?
     public var right: BinaryNode?
     public init(_ value: Int) {
         self.value = value
         self.left = nil
         self.right = nil
     }
 }

extension BinaryNode {
    public var description: String {
        return diagram(for: self)
    }
    private func diagram(for node: BinaryNode?,
                         _ top: String = "",
                         _ root: String = "",
                         _ bottom: String = "") -> String {
        guard let node = node else {
            return root + "nil\n"
        }
        if node.left == nil && node.right == nil {
            return root + "\(node.value)\n"
        }
        return diagram(for: node.right,
                       top + " ", top + "┌──", top + "│ ")
            + root + "\(node.value)\n"
            + diagram(for: node.left,
                      bottom + "│ ", bottom + "└──", bottom + " ")
    }
}

public func deserialize(_ array: inout [Int?]) -> BinaryNode? {
    guard !array.isEmpty, let value = array.removeFirst() else {
        return nil
    }
    let node = BinaryNode(value)
    node.left = deserialize(&array)
    node.right = deserialize(&array)
    return node
}

func isSameTree(_ p: BinaryNode?, _ q: BinaryNode?) -> Bool {
        guard let p = p else {
            return q == nil
        }
        guard let q = q else {
            return p == nil
        }

        if p.value != q.value {
            return false
        }

        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
    }

// Using deserialize to construct trees
var a1: [Int?] = [1,nil,2,3]
var a2: [Int?] = [1,nil,2,nil,3]
if let tree = deserialize(&a1) {
    print(tree.description)
}

if let tree = deserialize(&a2) {
    print(tree.description)
}

// Using manual to construct trees
let a3: BinaryNode = {
    let one = BinaryNode(1)
    let two = BinaryNode(2)
    let three = BinaryNode(3)
    one.right = two
    two.left = three
    return one
}()
print(a3.description)
let a4: BinaryNode = {
    let one = BinaryNode(1)
    let two = BinaryNode(2)
    let three = BinaryNode(3)
    one.right = two
    two.right = three
    return one
}()
print(a4.description)

// The print statements above show similar trees are constructed
// However, below results are not same

isSameTree(deserialize(&a1), deserialize(&a2)) // true <- this is wrong
isSameTree(a3, a4) // false <--- this is correct

A: Seems you have forgotten that your deserialize(_:) is destructive for its parameter... Please remember why you need &.
//Re-load a1 & a2...
a1 = [1,nil,2,3]
a2 = [1,nil,2,nil,3]
print(isSameTree(deserialize(&a1), deserialize(&a2))) //-> false
print(isSameTree(a3, a4)) //-> false


text:
Q: Push and append an item into a linked list in C I have a weird problem. I have this piece of code, but it doesn't work. The weird part is that inside the function, the list is changed (printf commands indicate this), but when  call this function, nothing will be added to the list (my list is not empty).
void pushToList(node* list, int val) {
    node* newNode = (node*) malloc(sizeof(node));
    newNode->value=val;

    newNode->next = list;
    list = newNode;

    printf("here, list->value = %d \n", list->value);
    printf("here, list->next->value = %d \n", list->next->value);
}

// ----------------------------------
//    if (list==NULL) {
//        newNode->next = NULL;
//        list = newNode;
//    } else {
//        newNode->next = list;
//        list = newNode;
//    }

I call this function for example in my main function like this:
node* node1;
pushToList(node1, 1111);

And here is my struct and typedef in a separate header file (that I have included in my function file):
#ifndef STACKELEMENT_H
#define STACKELEMENT_H

struct stackElement {
    int value;
    struct stackElement* next;
};

typedef struct stackElement node;
#endif  /* STACKELEMENT_H */

Another weird behavior is that I have the following function for appending an item, and this function only works if my list is not empty:
int appendtoList(node* head, int val) {

    node* current = head;
    node* newNode = (node*) malloc(sizeof (node));

         if(newNode == NULL){
            fprintf(stderr, "Unable to allocate memory for the new node\n");
            exit(-1);
        }

    newNode->value = val;
    newNode->next = NULL;

    while (current->next) {
        current = current->next;
    }
    current->next = newNode;

    //    if (head->next == NULL) {
    //        head->next = newNode;
    //    } else {
    //        while (current->next != NULL) {
    //            current = current->next;
    //        }
    //        current->next = newNode;
    //    }
    //
        return 0;
}

A: use node**list as argument type in your function.
when u pass a pointer to a function like struct node *x to
 void max (struct node*p);
 the pointer is passed by value AND
if u want to really manipulate the contents to which x points to use struct node** as the argument type and pass &x to the function.
Same logic should apply to your problems.

A: The problem was with the return type, i.e. the scope of a variable which in this case is a pointer variable. mbratch also pointed out this, thank you very much, but actually before reading mbratch's comment, I suddenly remembered a point from a lecture note about "accessing an object outside of its lifetime" which I think is different from "call by value/call by reference" problem.
Just some clarifications for people who may run into this problem and may get confused:
since we are allocating memory for the struct newNode INSIDE the function pushToList (even though using dynamic memory allocation command), the memory assigned to this variable would be free/destroyed when the function ends and the control returns back to the callee function (in this case, main()). So you should set the return type of your function to node* (a pointer to a node struct) and in your function return the head. Like this:
node* pushToList(node* head, int val) {
    node* newNode = (node*) malloc(sizeof(node));
    newNode->value=val;
    newNode->next = head;
    head = newNode;
    return head;
}

In appendToList function, in addition to this mistake, as mbracth pointed out, I was doing another mistake by checking head->next (although implicitly) rather than head itself (to see if it's NULL): if head is NULL, you can not access head->next. Indeed two answers marked as the correct answers in some other posts here on stackoverflow misleaded me to this mistake. Anyway, here is the correct way:
        if (head == NULL) {
            head = newNode;
        } else {
            while (current->next != NULL) {
                current = current->next;
            }
            current->next = newNode;
        }


text:
Q: Php ajax file upload error I want to upload file using ajax but i dont get data in php $_FILES and I get it in $_REQUEST. How do I do it. Below is my jquery code.Ajax is not working for file uploading so is there any code so that i can merge with existing code for file uploading process.
<script>
jQuery(function($){
    jQuery('#btn').click(function(){

        var data  = {},
            ticks = [];

        $('.ajax_elements').each(function(_, elem) {
            data[this.id] = this.value;

        });

        $.ajax({
            type  : 'POST',
            url   : 'app_process.php',
            data  : data,
            cache : false
        }).done(function(result) {
            alert(result);
        });
    });
});
</script>
<form name="frm" enctype="multipart/form-data">
    <input type="text" name="bb"  class="ajax_elements" id="one"/>
    <input type="file" class="ajax_elements" name="passport" id="passport" />
    <input type="button" name="bttn" id="btn"  />
    </form>

here is php file code
<?php
    if($_REQUEST['passport']!=''):
        $uploaddir = 'images/';
        move_uploaded_file($_FILES["file"]["tmp_name"], $uploaddir . str_replace(" ","_",$_REQUEST['passport']));
    endif;
?>

error message

Notice:  Undefined index: file in
  G:\xampp\htdocs\data_ajax\app_process.php on line 5

A: My advice would be to look at the XMLHttpRequest, FormData and File APIs. The Mozilla Developer Network have great documentation on all of these.
This needs testing and tweaking to be more robust in your development environment, but something along the lines of this could get you started...
<script>
$('#btn').click(function() {

    var xhr = new XMLHttpRequest();

    xhr.upload.addEventListener("load", function(e){
        // stuff to do when upload is complete
    }, false);

    xhr.upload.addEventListener("progress", function(e){
        // stuff here to handle progress bars, progress percentages etc.
    }, false);

    xhr.open('POST', 'app_process.php', true);

    var formdata = new FormData();
    var file = $('#passport').get(0).files[0];

    formdata.append('passport', file);

    xhr.send(formdata);

});
</script>

And the PHP...
<?php
if (isset($_FILES['passport'])) {
    $uploaddir = 'images/';
    $upload = move_uploaded_file($_FILES['passport']['tmp_name'], $uploaddir . str_replace(" ","_",$_FILES['passport']['name'])) or exit('Upload failed.');
} else {
    exit('File not found');
}
?>

Any additional information you want to send with the file needs to be added to the FormData object. These will appear in the PHP $_POST variable.
formdata.append('field', 'data');

Bear in mind that these APIs are not universally supported in browsers, so best practice is to include all the usual feature detection scripts before the user reaches this point.
You could also bind the upload function to the change event of the file input instead of asking for a button click...
$('#passport').change(function() { ...

Hope that helps.

A: There is 2 problems :
You need to add the attribute enctype="multipart/form-data" in the form tag if you want to upload files:
replace
<form name="frm">

by
<form name="frm" enctype="multipart/form-data" >

With ajax (and jquery), you cannot send file directly. But I suggest you that jquery form plugin who can help you with that


text:
Q: Play Framework Scala 2.2.2 store multiple values to session I would like to store user role to session. How I need to do this in play framework + scala?
My authentication method looks like this:
val loginForm = Form(
    tuple(
      "email" -> text,
      "password" -> text
    ) verifying ("Invalid username or password", result => result match {
      case (email, password) => User.authenticate(email, new sun.misc.BASE64Encoder().encode(md.digest(password.getBytes)).toString()).isDefined
    })
  )

 def authenticate = Action { implicit request =>
    loginForm.bindFromRequest.fold(
      formWithErrors => BadRequest(html.authentication.login(formWithErrors)),
      user => Redirect(routes.Application.index).withSession("username" -> user._1)
    )
  }

And my usermode looks like this:
  val simple = {
    get[Long]("user.id") ~
      get[String]("user.firstname") ~
      get[String]("user.lastname") ~
      get[String]("user.password") ~
      get[String]("user.email") ~
      get[Long] ("user.role") ~
      get[Long]("user.companyId") map {
      case id~firstname~lastname~password~email~role~companyId => User(id, firstname, lastname, password, email, role, companyId)
    }
  }


text:
Q: my docker-compose is failing on this line. Why? I need to copy a php.ini file that I have (with xdebug enabled) to /bitnami/php-fpm/conf/. I am using a bitnami docker container, and I want to use xdebug to debug the php code in my app. Therefore I must enable xdebug in the php.ini file. The /bitnami/php-fpm container on the repository had this comment added to it:
5.5.30-0-r01 (2015-11-10)
php.ini is now exposed in the volume mounted at /bitnami/php-fpm/conf/ allowing users to change the defaults as per their requirements.
So I am trying to copy my php.ini file to /bitnami/php-fpm/conf/php.ini in the docker-compose.yml. Here is the php-fpm section of the .yml:
  php-fpm:
    image: bitnami/php-fpm:5.5.26-3
  volumes:
     - ./app:/app
     - php.ini:/bitnami/php-fpm/conf
   networks:
      - net
volumes:
  database_data:
    driver: local
networks:
  net:

Here is the error I get: ERROR: Named volume "php.ini:/bitnami/php-fpm/conf:rw" is used in service "php-fpm" but no declaration was found in the volumes section.
Any idea how to fix this?

A: I will assume that your indentation is correct otherwise you probably wouldn't get that error. Always run your yaml's through a lint tool such as http://www.yamllint.com/.
In terms of your volume mount, the first one you have the correct syntax but the second you don't therefore Docker thinks it is a named volume.
Assuming php.ini is in the root directory next to your docker-compose.yml.
  volumes:
     - ./app:/app
     - ./php.ini:/bitnami/php-fpm/conf


text:
Q: What should be the next software version number? My current live app is 1.2.3.
Internally i have released up to 1.2.3.5 for testing. I now need to do an emergency fix on the production app. this version should ideally be 1.2.4 , but it would be confusing, as it should have all changes upto 1.2.3.5 and it would not.
I cant make the new production app 1.2.3.1 because that was already released internally.
what should be the new version number for my app?

A: I would recommend something akin to 1.2.3 Update 1. Or, 1.2.3.0.1, although I personally think more than four version numbers is ugly and would go with the former. FWIW, Java also uses similar wording.
The other logical options collide with existing versions and have a good probability of causing confusion, as you have already pointed out.

Ideally I would begun using 1.2.4.x internally as soon as 1.2.3 was released, thereby reserving the rest of 1.2.3.x for out-of-band updates to the current production version. You may wish to adopt something like this for the future to avoid similar collisions, but it is truly personal preference.


text:
Q: Why read-only transaction timeouts in Spanner? I am trying to run some complex SQL queries on Google Cloud Spanner to evaluate its analytical perfomance. I've been using command-line tool (gcloud spanner databases execute-sql) and python client library (specifically snapshot.execute_sql method), and in both cases I'm getting a timeout after around 25 minutes. In python case (which I'm more interested in) I am not even getting an error message - the CPU activity of an instance becomes 0, and client just hangs waiting for the result.
Spanner docs does not explicitly say that read-only transactions does not have timeout, but one stackoverflow answer claims it (Way to prevent transaction timeout?)
So, basically my question is: Is there really a timeout for SQL execution on the server side of a Spanner? If yes how to tune it, if no what can be the reason of the stated problem?

A: I think that this is due to Cloud Spanner's garbage collector that reclaims old versions of data by removing deleted or out of date data versions. According to the documentation, the garbage collector deletes versions older than 1 hour. This also means that a transaction can never read data versions older than 1 hour, effectively also putting a timeout of 1 hour on all (read-only) transactions.
See this part of the documentation: https://cloud.google.com/spanner/docs/reference/rest/v1/TransactionOptions, and then especially the Old sessions.read Timestamps and Garbage Collection part.

EDIT: Cloud Spanner now supports setting a version retention period that will allow you to query data with a staleness of more than 1 hour. See https://cloud.google.com/spanner/docs/timestamp-bounds#maximum_timestamp_staleness


text:
Q: AppService VNet integration fails I need to access a VM using an AppService. I'm getting this when i try to integrate with the VNET.

It just says VNet configuration failed and nothing more. AppService plan is in Premium.
What could be the cause of this?

A: You could scale up the app service plan to Standard or Premium V2. There are some limitations with using VNet Integration with VNets in the same region:

The feature is available from all App Service scale units in Premium
V2 and Premium V3. It is also available in Standard but only from
newer App Service scale units. If you are on an older scale unit you
can only use the feature from a Premium V2 App Service plan. If you
want to be certain of being able to use the feature in a Standard App
Service plan, create your app in a Premium V3 App Service plan. Those
plans are only supported on our newest scale units. You can scale down
if you desire after that.


text:
Q: How to edit fields in awk? for one of my university assignments I have to edit databases with POSIX utilities.
My problem is the following, I have been given a company import log and my professor wants me to get rid of the decimal seconds.
2018-04-12 17:03:45,547 INFO:twoex.db.record_administration.utilities:
I have tried using awk but since the timestamp is only one field, I am struggling to get rid of ,547
Does anyone have an idea how I could tackle this problem?
Thanks in advance.

A: Just remove the first comma and everything that comes after it until a space or a tab is found (it is not clear to me what is the field separator):
sed 's/,[^ \t]*//' file

Result:
2018-04-12 17:03:45 INFO:twoex.db.record_administration.utilities:      # old line
2018-04-12 17:03:45,547 INFO:twoex.db.record_administration.utilities:  # new line


text:
Q: Quartz-scheduler scheduling job every 2 weeks ignoring previous misfires I'm trying to schedule a job on a given day (user defined) on an interval of every 2 weeks and ignoring and previous misfires using Quartz-Scheduler.
For example:
If I set the start date to 7th Oct(Sunday) and today's date is 26th Oct, it should trigger on 4th Nov(Sunday), 18th Nov(Sunday)...
The only way I found to do this is using the WithCalendarIntervalSchedule extension with StartAt. The issue with this approach is that, if the start date is before today then all the misfires will be triggered when the trigger is being scheduled.
Cron expression and CronScheduleBuilder does not seem to allow this.
I cannot ignore misfires as i do not want triggers that failed to start on time for whatever reason to be ignored.
And i cannot force the start date to be after today.
Let me know if I'm missing anything, I've been looking for a solution to this for a couple of days now.

A: Turns out Quartz scheduler does not support schedule for every 2 weeks very well.
The trick to make it work is to set the start date to be the next DateTime that it should be triggered using the StartAt extension then use WithCalendarIntervalSchedule with WithIntervalInWeeks.


text:
Q: Unable to connect with https on EC2 with docker-compose I am unable to connect to my site via https though using http its working.
I used docker compose and build it on the ec2 machine. So in simple way i am not uploading any image to ecs/ecr, but pushing code to github and pulling to ec2 instance. Then i run it as i do locally. Every thing work fine except that i am unable to access it via https.
On aws , i have take following steps to configure https

*

*Create certificate via AWS certificate manager and verify it via DNS Create load balance

*Create new SG group having inbound rule for both http and https and source everywhere (0.0.0.0/0)

*Create a target group with http and connect it to my instance

*Add https listener and Select certificate from ACM for https listener

*check target group health and there is no issue

*Through my domain , ip, DNS name of load balance i can access website but not with https

Now i am not sure, where did i made the mistake, is the issue on docker site or on load balancer site. Though in terminal of EC2, i can see "ELB-HealthChecker/2.0" which mean the issue is not with ELB. It is with docker.
This is the docker-compose file i used
version: '3'

services:
  django_app: #can be any name, this name should match in default conf
    volumes:
      - static_vol:/app/sub_app/static
      - media_vol:/app/sub_app/media
    env_file:
      - .env
    build:
      context: .
    ports:
      - "8000:8000"
  nginx:
    build: ./nginx
    volumes:
      - static_vol:/app/sub_app/static
      - media_vol:/app/sub_app/media
    ports:
      - "80:80"
    depends_on:
      - django_app

volumes:
  static_vol:
  media_vol:

Now I have no clue where the things went wrong. Looking for help
EDIT. Attaching Images

SG for ELB

EDIT Console after ELB,
I can see ELB connected

As i am using nginx, may be there is some issue. Here is default.conf file
upstream django {
    server django_app:8000;
}

server {
    listen 80;

    location / {
        proxy_pass http://django;
    }

    location /static/ {
        alias /app/sub_app/static/;
    }

    location /media/ {
        alias /app/sub_app/media/;
    }
}

A: You need to configure the HTTPS listener on the load balancer to forward to port 80 on the target server. You shouldn't be opening port 443 in the docker-compose file, because you don't have an SSL certificate installed in the Nginx container. The SSL certificate you created is served by the load balancer, not Nginx.


text:
Q: What can we do about systemic lies regarding Monica's situation? Specifically, looking at this answer posted on:
What did Monica do to violate the CoC?
(Wayback Machine link for users without 10k)
It is accurate, contains references for all cited information, and is a true representation of what happened. The most up-voted answer is... Misleading at best.
This makes discussion and resolution of the issue impossible, because accurate information is systemically suppressed by users of Meta. Answers are voted down, questions and closed and even deleted.
What can be done to prevent this and get the facts out there for debate?

A: The linked answer has just been deleted, but can (currently) be viewed here https://web.archive.org/web/20191105085319/https://meta.stackexchange.com/questions/335373/what-did-monica-do-to-violate-the-coc#answer-337557. It contained:

*

*A quote from the article on The Register that repeated the statement made by the StackOverflow Inc. director who sacked Monica. This statement claimed Monica broke the CoC, but did not clearly explain in what way it was breached. The answer treated the director's statement as objective proof that the CoC was in fact breached.

*A quote from a Wikipedia page explaining what preferred gender pronouns are.

*Another quote from the Register article. The answer  claimed the quote, "there are multiple ways to avoid misgendering and we should not require a specific one", was from Monica and represented her position. The answer then claims that this quote demonstrates opposition to preferred gender pronouns. That claim appears to misrepresent Monica's position (she, like many professional writers, habitually avoids all pronouns in formal writing where possible, for clarity). It also misrepresents the current CoC, in which it is clarified that "You can often avoid using pronouns altogether" and that there is no rule against writing that naturally doesn't contain pronouns so long as it is not singling out particular users or groups, while moderators, who are held to a higher standard, are not allowed to "conspicuously" avoid using pronouns they "find uncomfortable".

*A long quote from some blogger completely unrelated to Monica or this situation, who was writing against preferred gender pronouns. It was strongly implied, without any evidence, that Monica was somehow in agreement with this completely unrelated blogger.

I didn't vote to delete the answer because I think it's useful to see concrete proof of how the unsubstantiated public allegations StackOverflow Inc have made are causing ongoing damage to Monica's reputation.
The user who posted the answer was active on many SE sites, with nearly 10k reputation here and nearly 40k on Stack Overflow. In the comments, the user said they trusted what was printed in The Register because it's a long-standing news site and has many Twitter followers.
The answer was clearly not what it's billed as in this question. It repeated an allegation, treating the allegation as proof of guilt, then appeared to try to tar Monica by association with completely unrelated individuals.

A: The same thing you do with answers containing misinformation:
You downvote it.
But what do we know? Who are we to say what is and isn't a lie, until all cards are put on the table? Who's to say things will be better if all cards are put on the table?
Stop speculating, and look at what we know.

A: What systemic lies are there that you think there should be done anything about? Everything the public knows is basically:

*

*Monica asked for clarification when a CoC update was being discussed in a private chatroom (TL)

*Monica was demodded.

*A SE employee talked to the press about it, and referenced her by name as having broken the CoC.

*Nobody bothered to tell Monica what she actually said that was supposed to break the CoC.

A:
What can we do about systemic lies regarding Monica's suspension?

She's not suspended. She was de-modded. Which I'm going to use to make a point instead of correcting it with an edit: We need to be careful what we say about this situation, the words we use, and the things we focus future discussion/debate/support efforts on.
I think Tim's answer on the question you're talking about sums it up pretty nicely: We don't discuss these things publicly. Many ships have sailed, including the one where SE kept their own advice and wouldn't have supplied comments to the press under this age old adage. But here we are.
There's a big part of this that's gone public, and that part consists of conflicting reports of the events (what SE so far has said publicly is contradicted by Monica). But we need to remember that even more may still be private, and falling under SE's policy of not discussing suspensions/demoddings publicly.

What can be done to prevent this and get the facts out there for debate?

What we can to to stop lies and misinformation from spreading further is to keep in mind the facts (that X was said by Monica or SE about the situation), and avoid putting our own interpretations of what was said over these, turning cold hard facts into subjective interpretations. We need to keep in mind that there's two conflicting reports out there already, and when talking about these things we should be careful to make sure our readers know both.
I feel bad about 'get the facts out there for debate'. Too much of this has already gone public and done (irreparable?) damage, and I hate to think what might happen in the future when we make 'getting the facts out there' the new standard in these situations. We're probably best off making do with the facts that are out there now, and respecting that parts are going to be kept private from now on. It's not ideal, it outright sucks (even for me, I'd love to know more too)... but it can at least give me some hope and a sense of security that if anything ever happens to me or others, we won't end up mangled by the MSE rumor mill.

A: There are two ways of upholding quality within any community on Stack Exchange Network:

*

*You use the existing means to give feedback. As in: you upvote "high quality" input, you down-, close-, delete-vote content you consider "low quality". Ideally, you leave the OP a comment telling them "what to improve". Sometimes you click on "flag" and report the corresponding post accordingly.

*When creating content yourself, you take a hard look before hitting the "submit" button. For example you avoid using loaded terms such as systematic lies. Because that term is your opinion, but you use it as if it were a fact.

Nonetheless, you are "correct" insofar that the voting system is far from perfect. Sometimes people vote without really reading everything, they see "something" in a post, and that results in a quick vote.
But the main point of this place is that quality is defined via consensus. Sometimes that is frustrating, but that is how things are here.
Finally note: answers with high vote counts often have high view counts. So, doing that downvote, and then writing fact based comments that outline the deficiencies of a bad post ... those comments will get many views, too. And when the comments are of high quality, they will get upvotes, too. Allowing you to "add" your counter arguments right next to the content you consider "low quality".


text:
Q: Pubnub real-time communication I am new to the socket communication concept and I have few basic questions.
We have server serving multiple clients WEB,MOBILE etc.. we want to implement real time changes in the web app (web app is consumer only)
Lets say that each user has it's own private channel and the channel name will be the UUID of the user.
How does the server side can keep track which users connected to their channel?
In our case there is no meaning to send message to a channel which no device is listning to.

*

*I saw presence feature but I am not sure that is the way it seems more appropriate for many users which can connect to a single channel and not 1-1

Basically when the server is handling somekind of user related operation I need a way to know if someone is listning to that user channel.
How it can be done with pubnub?
Lets say I am sending a message to a channel no one is listen/suscribed to

*

*if no one consuming the msg pubnub will consider it in the usage?

*once device will connected to that channel the message will be consumed?

A: How does the server side can keep track which users connected to their channel?
PubNub offers Presence "Connect WebHooks" which you can ask your Account Manager to enable for you.  Ask for "Presence Callback Active" and "Presence Callback Inactive" settings.  You'll want to setup a dev/prod key pair to point the WebHook URLs at different environments.

The HTTP callback URL that is triggered when a channel becomes active.


text:
Q: PHP APC CLI opcode cache has no effect i want to use apc as cli with opcode cache feature.
using apc.enable_cli to true. but noting happened in benchmark time and memory usage.
; php.ini
apc.enable_cli = 1

but in web based usage different. i see how work apc and do magic for running php scripts.
about half memory usage also about 0.01 faster than normal run php script.
but i think php dont use opcode cache during using apc in cli. how can i use it. is it possible?

A: I wouldn't expect apc to give any improvement in performance on the command line, because the apc cache is going to be dropped every run.


text:
Q: What's the difference between the following Func> async delegate approaches? If I have the following method:
public async Task<T> DoSomethingAsync<T>(Func<Task<T>> action)
{
   // bunch of async code..then "await action()"
}

What is the difference between the following two usages:
public async Task MethodOneAsync()
{
   return await DoSomethingAsync(async () => await SomeActionAsync());
}

public async Task MethodTwoAsync()
{
   return await DoSomethingAsync(() => SomeActionAsync());
}

Both compile, both work and there are no C# warnings.
What's the difference (if any)? Will both methods run true async if awaited by the caller?

A: There is no functional difference between the two. The only difference is if the Task from SomeActionAsync is returned directly or if it is awaited. Stephen Cleary has a good blog post about this, and recommends the second aproach for this trivial case.
The reason why the first approach is available is that you could have a non-trivial lambda expression like this:
public async Task MethodOneAsync()
{
    return await DoSomethingAsync(async () => {
        var i = _isItSunday ? 42 : 11;
        var someResult = await SomeActionAsync(i);
        return await AnotherActionAsync(someResult*i);
    });
}

So the difference is the same as the difference between a method whith this signature public async Task<int> MyMethod and this one public Task<int> MyMethod

A: Short Answer
MethodOneAsync() is truly Async, and shall be used, but MethodTwoAsync() is not truly Async, as it invokes Thread pool thread
Long Answer
For the purpose of testing and running I have simplified your code as follows:
Execution from the Main method of Linqpad as follows:
var resultTask = MethodOneAsync(); // Comment one the methods

resultTask.Result.Dump();

Actual Code
public async Task<int> DoSomethingAsync(Func<Task<int>> action)
{
    return await Task.FromResult<int>(3);
}

public async Task<int> MethodOneAsync()
{
    await Task.Delay(10);
    return await DoSomethingAsync(async () => await Task.FromResult<int>(3));
}

public async Task<int> MethodOneAsync()
{
    await Task.Delay(10);
    return await DoSomethingAsync(() => Task.FromResult<int>(3));
}

Now I reviewed the IL generated between the two calls and following is the most important difference:
First call with Async and Await inside DoSomethingAsync has following IL:
<>c.<MethodOneAsync>b__2_0:
IL_0000:  newobj      UserQuery+<>c+<<MethodOneAsync>b__2_0>d..ctor
IL_0005:  stloc.0
IL_0006:  ldloc.0
IL_0007:  ldarg.0
IL_0008:  stfld       UserQuery+<>c+<<MethodOneAsync>b__2_0>d.<>4__this
IL_000D:  ldloc.0
IL_000E:  call        System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Int32>.Create
IL_0013:  stfld       UserQuery+<>c+<<MethodOneAsync>b__2_0>d.<>t__builder
IL_0018:  ldloc.0
IL_0019:  ldc.i4.m1
IL_001A:  stfld       UserQuery+<>c+<<MethodOneAsync>b__2_0>d.<>1__state
IL_001F:  ldloc.0
IL_0020:  ldfld       UserQuery+<>c+<<MethodOneAsync>b__2_0>d.<>t__builder
IL_0025:  stloc.1
IL_0026:  ldloca.s    01
IL_0028:  ldloca.s    00
IL_002A:  call        System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Int32>.Start<<<MethodOneAsync>b__2_0>d>
IL_002F:  ldloc.0
IL_0030:  ldflda      UserQuery+<>c+<<MethodOneAsync>b__2_0>d.<>t__builder
IL_0035:  call        System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Int32>.get_Task
IL_003A:  ret

Second one without Async and Await has the following code:
<>c.<MethodOneAsync>b__2_0:
IL_0000:  ldc.i4.3
IL_0001:  call        System.Threading.Tasks.Task.FromResult<Int32>
IL_0006:  ret

Beside this the first one has the complete state machine code for extra async await call, which is expected.
Important points:

*

*For Async method call use async () => await SomeActionAsync(), as this is true Async execution and works on IO completion ports

*In other case it invokes a Threadpool thread for the Async method execution, which is not good for Asynchronous execution

I can paste the complete IL if required to understand the difference, but best is you evaluate the same in the Visual studio or LinqPad to understand the nuances

A: Firstly, your example doesn't make sense, you're either returning something, or not, returning the results of the awaited function without a return type would be a compiler error.
public async Task MethodOneAsync()
{
    return await DoSomethingAsync(() => SomeActionAsync());
}

Secondly, this has nothing to do with "true" async as that would be an implementation detail which is not shown
Thirdly, the only difference between either of the hypothetical examples
await DoSomethingAsync(async () => await SomeActionAsync());

and
await DoSomethingAsync(() =>  SomeActionAsync());

Given the definition of DoSomethingAsync, in the first example the compiler will create an extra IAsyncStateMachine implementation, instead of just forwarding the Task. I.e More compiled code, more IL, more instructions, and in this example seemingly redundant.
There are is a small caveat with exceptions when eliding tasks, however because this is just a simple pass through there is no other code which will throw, ergo the extra state-machine or try catch and Task.FromException is not needed.
The real appreciable differences would come if your signature was actually an Action instead of Func<Task> which would create an async void given an async lambda, however this is not case in your question.

A: Async/await construct inserts some infrastructure code which is only useful if there is some code after the "await".  Otherwise it essentially does nothing.  Your code is equivalent to
public Task MethodThreeAsync()
{
    return DoSomethingAsync(() => SomeActionAsync());
}

All of the three methods are "true async".


text:
Q: Why random prediction by kalman filter? I applied kalman filter where I lost the position of object while tracking. I have taken velocity model of kalman implementation (x,y,vx,vy).when detected object is lost in the frame, kalman prediction is started but it's predicting in random direction with high change in state(predicted box is not covering body part of object). What could be the reason for this?

Note: My detected box is random(at different part of body of object in
  random size ) as I'm using optical flow.

Using this I implemented the code for object tracking. But I took kalman-velocity model using this reference. While calculating velocity I took pixel change (centroid of object location) over processing frame difference (here not taking time due to some uncertainty in my case) assigning it to state vector and passing it to measurement with detected object centroid location (x,y)
I tried to tune the parameter of kalman (eg: processNoiseCovariance = 1e-5 and measurementNoiseCovariance = 1e-1) init value but still not getting proper result.
Can anyone suggest these value with explanation?
Second thing...how to handle the case when object is turning that time how can I use kalman for tracking because it's not working in this condition.
Any suggestion will be appreciated. Thanks in advance, :)


text:
Q: How addEventListener influences the onclick property of DOM element? element.onclick = function() { alert(1); }

alert(element.onclick);

The above code will output function () { alert(1); }
Then I continue to execute the following code:
element.addEventListener('click', function() { alert(2); }, false);
alert(element.onclick);

The output is still function () { alert(1); }
In fact when clicking on the element now, the code addEventListener('click', function() { alert(2); }, false); works, it means the new function alert(2) has written into the onclick property of this element. But why is the output still unchanged?
So, what I want to know is when executing addEventListener, how the onclick property changed?
Looking forward to your reply.

A: OnClick is a DOM Level 0 property.  AddEventListener is part of the DOM Level 2 definition.  Adding an event handler via the AddEventListener method does not change the OnClick property on the element, rather it adds the listener to a collection of event listeners on the element.  You can find out more about DOM Level 2 events at http://www.w3.org/TR/DOM-Level-2-Events/events.html.   There's also a nice article at http://en.wikipedia.org/wiki/DOM_events.

A: The "onfoo" attributes are independent of the event handler management system accessed via "addEventListener()".  It's best to use one or the other, not both, and the right choice is the more flexible and unintrusive "addEventListener()" (where available).