Programs & Examples On #Writexml

CSS 3 slide-in from left transition

I liked @mate64's answer so I am going to reuse that with slight modifications to create a slide down and up animations below:

_x000D_
_x000D_
var $slider = document.getElementById('slider');_x000D_
var $toggle = document.getElementById('toggle');_x000D_
_x000D_
$toggle.addEventListener('click', function() {_x000D_
    var isOpen = $slider.classList.contains('slide-in');_x000D_
_x000D_
    $slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');_x000D_
});
_x000D_
#slider {_x000D_
    position: absolute;_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background: blue;_x000D_
    transform: translateY(-100%);_x000D_
    -webkit-transform: translateY(-100%);_x000D_
}_x000D_
_x000D_
.slide-in {_x000D_
    animation: slide-in 0.5s forwards;_x000D_
    -webkit-animation: slide-in 0.5s forwards;_x000D_
}_x000D_
_x000D_
.slide-out {_x000D_
    animation: slide-out 0.5s forwards;_x000D_
    -webkit-animation: slide-out 0.5s forwards;_x000D_
}_x000D_
    _x000D_
@keyframes slide-in {_x000D_
    100% { transform: translateY(0%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-in {_x000D_
    100% { -webkit-transform: translateY(0%); }_x000D_
}_x000D_
    _x000D_
@keyframes slide-out {_x000D_
    0% { transform: translateY(0%); }_x000D_
    100% { transform: translateY(-100%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-out {_x000D_
    0% { -webkit-transform: translateY(0%); }_x000D_
    100% { -webkit-transform: translateY(-100%); }_x000D_
}
_x000D_
<div id="slider" class="slide-in">_x000D_
    <ul>_x000D_
        <li>Lorem</li>_x000D_
        <li>Ipsum</li>_x000D_
        <li>Dolor</li>_x000D_
    </ul>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
_x000D_
_x000D_

MySQL SELECT WHERE datetime matches day (and not necessarily time)

NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24' - it is a performance killer:

  • it will calculate DATE() for all rows, including those, that don't match
  • it will make it impossible to use an index for the query

It is much faster to use

SELECT * FROM tablename 
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'

as this will allow index use without calculation.

EDIT

As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read

SELECT * FROM tablename 
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'

The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.

How to sort alphabetically while ignoring case sensitive?

You can directly call the default sort method on the list like this:

myList.sort(String.CASE_INSENSITIVE_ORDER); // reads as the problem statement and cleaner

or:

myList.sort(String::compareToIgnoreCase);  // reads as the problem statement and cleaner

Creating a list of objects in Python

To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.

instancelist = [ MyClass() for i in range(29)]

and then access the instances through the index of the list.

instancelist[5].attr1 = 'whamma'

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

One more possible reason if you are using Tycho and Maven to build bundles, that you have wrong execution environment (Bundle-RequiredExecutionEnvironment) in the manifest file (manifest.mf) defined. For example:

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Engine Plug-in
Bundle-SymbolicName: com.foo.bar
Bundle-Version: 4.6.5.qualifier
Bundle-Activator: com.foo.bar.Activator
Bundle-Vendor: Foobar Technologies Ltd.
Require-Bundle: org.eclipse.core.runtime,
 org.jdom;bundle-version="1.0.0",
 org.apache.commons.codec;bundle-version="1.3.0",
 bcprov-ext;bundle-version="1.47.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.5
Export-Package: ...
...
Import-Package: ...
...

In my case everything else was ok. The compiler plugins (normal maven and tycho as well) were set correctly, still m2 generated old compliance level because of the manifest. I thought I share the experience.

'Incorrect SET Options' Error When Building Database Project

According to BOL:

Indexed views and indexes on computed columns store results in the database for later reference. The stored results are valid only if all connections referring to the indexed view or indexed computed column can generate the same result set as the connection that created the index.

In order to create a table with a persisted, computed column, the following connection settings must be enabled:

SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET NUMERIC_ROUNDABORT ON
SET QUOTED_IDENTIFIER ON

These values are set on the database level and can be viewed using:

SELECT 
    is_ansi_nulls_on,
    is_ansi_padding_on,
    is_ansi_warnings_on,
    is_arithabort_on,
    is_concat_null_yields_null_on,
    is_numeric_roundabort_on,
    is_quoted_identifier_on
FROM sys.databases

However, the SET options can also be set by the client application connecting to SQL Server.

A perfect example is SQL Server Management Studio which has the default values for SET ANSI_NULLS and SET QUOTED_IDENTIFIER both to ON. This is one of the reasons why I could not initially duplicate the error you posted.

Anyway, to duplicate the error, try this (this will override the SSMS default settings):

SET ANSI_NULLS ON
SET ANSI_PADDING OFF
SET ANSI_WARNINGS OFF
SET ARITHABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON 
SET NUMERIC_ROUNDABORT OFF
SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE T1 (
    ID INT NOT NULL,
    TypeVal AS ((1)) PERSISTED NOT NULL
) 

You can fix the test case above by using:

SET ANSI_PADDING ON
SET ANSI_WARNINGS ON

I would recommend tweaking these two settings in your script before the creation of the table and related indexes.

Vue.js dynamic images not working

Here is Very simple answer. :D

<div class="col-lg-2" v-for="pic in pics">
   <img :src="`../assets/${pic}.png`" :alt="pic">
</div>

Link to all Visual Studio $ variables

Anybody working on legacy software using Visual Studio 6.0 will find that $(Configuration) and $(ProjectDir) macro's are not defined. For post-build/pre-build events, give a relative path starting with the location of your .dsw file(workspace) as the starting point. In relative path dot represents the current directory and .. represents the parent directory. Give a relative path to the file that need to be processed. Example: ( copy /y .\..\..\Debug\mylib.dll .\..\MyProject\Debug\ )

Java - How to create a custom dialog box?

Well, you essentially create a JDialog, add your text components and make it visible. It might help if you narrow down which specific bit you're having trouble with.

Extract substring from a string

substring(int startIndex, int endIndex)

If you don't specify endIndex, the method will return all the characters from startIndex.

startIndex : starting index is inclusive

endIndex : ending index is exclusive

Example:

String str = "abcdefgh"

str.substring(0, 4) => abcd

str.substring(4, 6) => ef

str.substring(6) => gh

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

Draw in Canvas by finger, Android

Start By going through the Fingerpaint demo in the sdk sample.

Another Sample:

public class MainActivity extends Activity {

    DrawingView dv ;
    private Paint mPaint;    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dv = new DrawingView(this);
        setContentView(dv);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(Color.GREEN);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(12);
    }

    public class DrawingView extends View {

        public int width;
        public  int height;
        private Bitmap  mBitmap;
        private Canvas  mCanvas;
        private Path    mPath;
        private Paint   mBitmapPaint;
        Context context;
        private Paint circlePaint;
        private Path circlePath;

        public DrawingView(Context c) {
            super(c);
            context=c;
            mPath = new Path();
            mBitmapPaint = new Paint(Paint.DITHER_FLAG);
            circlePaint = new Paint();
            circlePath = new Path();
            circlePaint.setAntiAlias(true);
            circlePaint.setColor(Color.BLUE);
            circlePaint.setStyle(Paint.Style.STROKE);
            circlePaint.setStrokeJoin(Paint.Join.MITER);
            circlePaint.setStrokeWidth(4f);
        }

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

            mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            mCanvas = new Canvas(mBitmap);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            canvas.drawBitmap( mBitmap, 0, 0, mBitmapPaint);
            canvas.drawPath( mPath,  mPaint);
            canvas.drawPath( circlePath,  circlePaint);
        }

        private float mX, mY;
        private static final float TOUCH_TOLERANCE = 4;

        private void touch_start(float x, float y) {
            mPath.reset();
            mPath.moveTo(x, y);
            mX = x;
            mY = y;
        }

        private void touch_move(float x, float y) {
            float dx = Math.abs(x - mX);
            float dy = Math.abs(y - mY);
            if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
                mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
                mX = x;
                mY = y;

                circlePath.reset();
                circlePath.addCircle(mX, mY, 30, Path.Direction.CW);
            }
        }

        private void touch_up() {
            mPath.lineTo(mX, mY);
            circlePath.reset();
            // commit the path to our offscreen
            mCanvas.drawPath(mPath,  mPaint);
            // kill this so we don't double draw
            mPath.reset();
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float x = event.getX();
            float y = event.getY();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    touch_start(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_MOVE:
                    touch_move(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    touch_up();
                    invalidate();
                    break;
            }
            return true;
        }
    }
}

Snap shot

enter image description here

Explanation :

You are creating a view class then extends View. You override the onDraw(). You add the path of where finger touches and moves. You override the onTouch() of this purpose. In your onDraw() you draw the paths using the paint of your choice. You should call invalidate() to refresh the view.

To choose options you can click menu and choose the options.

The below can be used as a reference. You can modify the below according to your needs.

public class FingerPaintActivity extends Activity
        implements ColorPickerDialog.OnColorChangedListener {

    MyView mv;
    AlertDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mv= new MyView(this);
        mv.setDrawingCacheEnabled(true);
        mv.setBackgroundResource(R.drawable.afor);//set the back ground if you wish to
        setContentView(mv);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(0xFFFF0000);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(20);
        mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 },
                0.4f, 6, 3.5f);
        mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
    }

    private Paint       mPaint;
    private MaskFilter  mEmboss;
    private MaskFilter  mBlur;

    public void colorChanged(int color) {
        mPaint.setColor(color);
    }

    public class MyView extends View {

        private static final float MINP = 0.25f;
        private static final float MAXP = 0.75f;
        private Bitmap  mBitmap;
        private Canvas  mCanvas;
        private Path    mPath;
        private Paint   mBitmapPaint;
        Context context;

        public MyView(Context c) {
            super(c);
            context=c;
            mPath = new Path();
            mBitmapPaint = new Paint(Paint.DITHER_FLAG);

        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            mCanvas = new Canvas(mBitmap);

        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
            canvas.drawPath(mPath, mPaint);
        }

        private float mX, mY;
        private static final float TOUCH_TOLERANCE = 4;

        private void touch_start(float x, float y) {
            //showDialog(); 
            mPath.reset();
            mPath.moveTo(x, y);
            mX = x;
            mY = y;

        }
        private void touch_move(float x, float y) {
            float dx = Math.abs(x - mX);
            float dy = Math.abs(y - mY);
            if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
                mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
                mX = x;
                mY = y;
            }
        }

        private void touch_up() {
            mPath.lineTo(mX, mY);
            // commit the path to our offscreen
            mCanvas.drawPath(mPath, mPaint);
            // kill this so we don't double draw
            mPath.reset();
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
            //mPaint.setMaskFilter(null);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float x = event.getX();
            float y = event.getY();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    touch_start(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_MOVE:

                    touch_move(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    touch_up();
                    invalidate();
                    break;
            }
            return true;
        }
    }

    private static final int COLOR_MENU_ID = Menu.FIRST;
    private static final int EMBOSS_MENU_ID = Menu.FIRST + 1;
    private static final int BLUR_MENU_ID = Menu.FIRST + 2;
    private static final int ERASE_MENU_ID = Menu.FIRST + 3;
    private static final int SRCATOP_MENU_ID = Menu.FIRST + 4;
    private static final int Save = Menu.FIRST + 5;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(0, COLOR_MENU_ID, 0, "Color").setShortcut('3', 'c');
        menu.add(0, EMBOSS_MENU_ID, 0, "Emboss").setShortcut('4', 's');
        menu.add(0, BLUR_MENU_ID, 0, "Blur").setShortcut('5', 'z');
        menu.add(0, ERASE_MENU_ID, 0, "Erase").setShortcut('5', 'z');
        menu.add(0, SRCATOP_MENU_ID, 0, "SrcATop").setShortcut('5', 'z');
        menu.add(0, Save, 0, "Save").setShortcut('5', 'z');

        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        mPaint.setXfermode(null);
        mPaint.setAlpha(0xFF);

        switch (item.getItemId()) {
            case COLOR_MENU_ID:
                new ColorPickerDialog(this, this, mPaint.getColor()).show();
                return true;
            case EMBOSS_MENU_ID:
                if (mPaint.getMaskFilter() != mEmboss) {
                    mPaint.setMaskFilter(mEmboss);
                } else {
                    mPaint.setMaskFilter(null);
                }
                return true;
            case BLUR_MENU_ID:
                if (mPaint.getMaskFilter() != mBlur) {
                    mPaint.setMaskFilter(mBlur);
                } else {
                    mPaint.setMaskFilter(null);
                }
                return true;
            case ERASE_MENU_ID:
                mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
                mPaint.setAlpha(0x80);
                return true;
            case SRCATOP_MENU_ID:

                mPaint.setXfermode(new PorterDuffXfermode(
                        PorterDuff.Mode.SRC_ATOP));
                mPaint.setAlpha(0x80);
                return true;
            case Save:
                AlertDialog.Builder editalert = new AlertDialog.Builder(FingerPaintActivity.this);
                editalert.setTitle("Please Enter the name with which you want to Save");
                final EditText input = new EditText(FingerPaintActivity.this);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.FILL_PARENT,
                        LinearLayout.LayoutParams.FILL_PARENT);
                input.setLayoutParams(lp);
                editalert.setView(input);
                editalert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        String name= input.getText().toString();
                        Bitmap bitmap = mv.getDrawingCache();

                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        File file = new File("/sdcard/"+name+".png");
                        try
                        {
                            if(!file.exists())
                            {
                                file.createNewFile();
                            }
                            FileOutputStream ostream = new FileOutputStream(file);
                            bitmap.compress(CompressFormat.PNG, 10, ostream);
                            ostream.close();
                            mv.invalidate();
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }finally
                        {

                            mv.setDrawingCacheEnabled(false);
                        }
                    }
                });

                editalert.show();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Color Picker

public class ColorPickerDialog extends Dialog {

    public interface OnColorChangedListener {
        void colorChanged(int color);
    }

    private OnColorChangedListener mListener;
    private int mInitialColor;

    private static class ColorPickerView extends View {
        private Paint mPaint;
        private Paint mCenterPaint;
        private final int[] mColors;
        private OnColorChangedListener mListener;

        ColorPickerView(Context c, OnColorChangedListener l, int color) {
            super(c);
            mListener = l;
            mColors = new int[] {
                    0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00,
                    0xFFFFFF00, 0xFFFF0000
            };
            Shader s = new SweepGradient(0, 0, mColors, null);

            mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mPaint.setShader(s);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(32);

            mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mCenterPaint.setColor(color);
            mCenterPaint.setStrokeWidth(5);
        }

        private boolean mTrackingCenter;
        private boolean mHighlightCenter;

        @Override
        protected void onDraw(Canvas canvas) {
            float r = CENTER_X - mPaint.getStrokeWidth()*0.5f;

            canvas.translate(CENTER_X, CENTER_X);

            canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
            canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);

            if (mTrackingCenter) {
                int c = mCenterPaint.getColor();
                mCenterPaint.setStyle(Paint.Style.STROKE);

                if (mHighlightCenter) {
                    mCenterPaint.setAlpha(0xFF);
                } else {
                    mCenterPaint.setAlpha(0x80);
                }
                canvas.drawCircle(0, 0,
                        CENTER_RADIUS + mCenterPaint.getStrokeWidth(),
                        mCenterPaint);

                mCenterPaint.setStyle(Paint.Style.FILL);
                mCenterPaint.setColor(c);
            }
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            setMeasuredDimension(CENTER_X*2, CENTER_Y*2);
        }

        private static final int CENTER_X = 100;
        private static final int CENTER_Y = 100;
        private static final int CENTER_RADIUS = 32;

        private int floatToByte(float x) {
            int n = java.lang.Math.round(x);
            return n;
        }

        private int pinToByte(int n) {
            if (n < 0) {
                n = 0;
            } else if (n > 255) {
                n = 255;
            }
            return n;
        }

        private int ave(int s, int d, float p) {
            return s + java.lang.Math.round(p * (d - s));
        }

        private int interpColor(int colors[], float unit) {
            if (unit <= 0) {
                return colors[0];
            }
            if (unit >= 1) {
                return colors[colors.length - 1];
            }

            float p = unit * (colors.length - 1);
            int i = (int)p;
            p -= i;

            // now p is just the fractional part [0...1) and i is the index
            int c0 = colors[i];
            int c1 = colors[i+1];
            int a = ave(Color.alpha(c0), Color.alpha(c1), p);
            int r = ave(Color.red(c0), Color.red(c1), p);
            int g = ave(Color.green(c0), Color.green(c1), p);
            int b = ave(Color.blue(c0), Color.blue(c1), p);

            return Color.argb(a, r, g, b);
        }

        private int rotateColor(int color, float rad) {
            float deg = rad * 180 / 3.1415927f;
            int r = Color.red(color);
            int g = Color.green(color);
            int b = Color.blue(color);

            ColorMatrix cm = new ColorMatrix();
            ColorMatrix tmp = new ColorMatrix();

            cm.setRGB2YUV();
            tmp.setRotate(0, deg);
            cm.postConcat(tmp);
            tmp.setYUV2RGB();
            cm.postConcat(tmp);

            final float[] a = cm.getArray();

            int ir = floatToByte(a[0] * r +  a[1] * g +  a[2] * b);
            int ig = floatToByte(a[5] * r +  a[6] * g +  a[7] * b);
            int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);

            return Color.argb(Color.alpha(color), pinToByte(ir),
                    pinToByte(ig), pinToByte(ib));
        }

        private static final float PI = 3.1415926f;

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float x = event.getX() - CENTER_X;
            float y = event.getY() - CENTER_Y;
            boolean inCenter = java.lang.Math.sqrt(x*x + y*y) <= CENTER_RADIUS;

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mTrackingCenter = inCenter;
                    if (inCenter) {
                        mHighlightCenter = true;
                        invalidate();
                        break;
                    }
                case MotionEvent.ACTION_MOVE:
                    if (mTrackingCenter) {
                        if (mHighlightCenter != inCenter) {
                            mHighlightCenter = inCenter;
                            invalidate();
                        }
                    } else {
                        float angle = (float)java.lang.Math.atan2(y, x);
                        // need to turn angle [-PI ... PI] into unit [0....1]
                        float unit = angle/(2*PI);
                        if (unit < 0) {
                            unit += 1;
                        }
                        mCenterPaint.setColor(interpColor(mColors, unit));
                        invalidate();
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    if (mTrackingCenter) {
                        if (inCenter) {
                            mListener.colorChanged(mCenterPaint.getColor());
                        }
                        mTrackingCenter = false;    // so we draw w/o halo
                        invalidate();
                    }
                    break;
            }
            return true;
        }
    }

    public ColorPickerDialog(Context context,
                             OnColorChangedListener listener,
                             int initialColor) {
        super(context);

        mListener = listener;
        mInitialColor = initialColor;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        OnColorChangedListener l = new OnColorChangedListener() {
            public void colorChanged(int color) {
                mListener.colorChanged(color);
                dismiss();
            }
        };

        setContentView(new ColorPickerView(getContext(), l, mInitialColor));
        setTitle("Pick a Color");
    }
}

how to include js file in php?

I found a different solution that I like:

<script>
    <?php require_once("/path/to/file.js");?>
</script>

Also works with style-tags and .css-files in the same way.

Twitter Bootstrap modal: How to remove Slide down effect

Just remove the fade class and if you want more animations to be perform on the Modal just use animate.css classes in your Modal.

How to get first object out from List<Object> using Linq

I do so.

List<Object> list = new List<Object>();

if(list.Count>0){
  Object obj = list[0];
}

libxml install error using pip

All the answers above assume the user has access to a privileged/root account to install the required libraries. To install it locally you will need to do the following steps. Only showed the overview since the steps can get a little involved depending on the dependencies that you might be missing

1.Download and Compile libxml2-2.9.1 & libxslt-1.1.28(versions might change)

2.Configure each install path for both libxml and libxslt to be some local directory using configure. Ex. ./configure --prefix=/home_dir/dependencies/libxslt_path

3.Run make then make install

4.Download and compile lxml from source

Regex for parsing directory and filename

A very late answer, but hope this will help

^(.+?)/([\w]+\.log)$

This uses lazy check for /, and I just modified the accepted answer

http://regex101.com/r/gV2xB7/1

jQuery Ajax Request inside Ajax Request

$.ajax({
    url: "<?php echo site_url('upToWeb/ajax_edit/')?>/" + id,
    type: "GET",
    dataType: "JSON",
    success: function (data) {
        if (data.web == 0) {
            if (confirm('Data product upToWeb ?')) {
                $.ajax({
                    url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
                    type: "post",
                    dataType: "json",
                    data: {web: 1},
                    success: function (respons) {
                        location.href = location.pathname;
                    },
                    error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
                        alert(xhr.responseText); // munculkan alert
                    }
                });
            }
        }
        else {
            if (confirm('Data product DownFromWeb ?')) {
                $.ajax({
                    url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
                    type: "post",
                    dataType: "json",
                    data: {web: 0},
                    success: function (respons) {
                        location.href = location.pathname;
                    },
                    error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
                        alert(xhr.responseText); // munculkan alert
                    }
                });
            }
        }
    },

    error: function (jqXHR, textStatus, errorThrown) {
        alert('Error get data from ajax');
    }

});

Python reshape list to ndim array

You can think of reshaping that the new shape is filled row by row (last dimension varies fastest) from the flattened original list/array.

An easy solution is to shape the list into a (100, 28) array and then transpose it:

x = np.reshape(list_data, (100, 28)).T

Update regarding the updated example:

np.reshape([0, 0, 1, 1, 2, 2, 3, 3], (4, 2)).T
# array([[0, 1, 2, 3],
#        [0, 1, 2, 3]])

np.reshape([0, 0, 1, 1, 2, 2, 3, 3], (2, 4))
# array([[0, 0, 1, 1],
#        [2, 2, 3, 3]])

Making an API call in Python with an API that requires a bearer token

It just means it expects that as a key in your header data

import requests
endpoint = ".../api/ip"
data = {"ip": "1.1.2.3"}
headers = {"Authorization": "Bearer MYREALLYLONGTOKENIGOT"}

print(requests.post(endpoint, data=data, headers=headers).json())

How to link to part of the same document in Markdown?

Gitlab uses GitLab Flavored Markdown (GFM)

Here "all Markdown-rendered headers automatically get IDs"

One can use mouse to :

  • move mouse over header
  • move mouse over hover selector which becoms visible to the left from header
  • copy and save link using right mouse click

    For example in README.md file I have header:

## series expansion formula of the Boettcher function

which gives a link :

https://gitlab.com/adammajewski/parameter_external_angle/blob/master/README.md#series-expansion-formula-of-the-boettcher-function

Prefix can be removed so the link here is simply

file#header

which here means:

README.md#series-expansion-formula-of-the-boettcher-function

Now it can be used as :

[series expansion formula of the Boettcher function](README.md#series-expansion-formula-of-the-boettcher-function)

One can also do it manually: replace spaces with hyphen sign.

Live example is here

How do I escape ampersands in XML so they are rendered as entities in HTML?

When your XML contains &amp;amp;, this will result in the text &amp;.

When you use that in HTML, that will be rendered as &.

Set drawable size programmatically

To use

textView.setCompoundDrawablesWithIntrinsicBounds()

Your minSdkVersion should be 17 in build.gradle

    defaultConfig {
    applicationId "com.example..."
    minSdkVersion 17
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
}

To change drawable size:

    TextView v = (TextView)findViewById(email);
    Drawable dr = getResources().getDrawable(R.drawable.signup_mail);
    Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
    Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 80, 80, true));

    //setCompoundDrawablesWithIntrinsicBounds (image to left, top, right, bottom)
    v.setCompoundDrawablesWithIntrinsicBounds(d,null,null,null);

How to update a single pod without touching other dependencies

This is a bit of an outlier and not likely to be what the OP was dealing with, but pod update <podname> will not work in all cases if you are using a local pod on your computer.

In this situation, the only thing that will trigger pod update to work is if there is a change in the podspec file. However, making a change will also allow for pod install to work as well.

In this situation, you can just modify something minor such as the description or summary by one letter, and then you can run the install or update command successfully.

Error #2032: Stream Error

Just to clarify my comment (it's illegible in a single line)

I think the best answer is the comment by Mike Chambers in this link (http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/) by Hunter McMillen.

A note from Mike Chambers:

If you run into this using URLLoader, listen for the:

flash.events.HTTPStatusEvent.HTTP_STATUS

and in AIR :

flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUS

It should give you some more information (such as the status code being returned from the server).

Cause of a process being a deadlock victim

The answers here are worth a try, but you should also review your code. Specifically have a read of Polyfun's answer here: How to get rid of deadlock in a SQL Server 2005 and C# application?

It explains the concurrency issue, and how the usage of "with (updlock)" in your queries might correct your deadlock situation - depending really on exactly what your code is doing. If your code does follow this pattern, this is likely a better fix to make, before resorting to dirty reads, etc.

How to force a script reload and re-execute?

How about adding a new script tag to <head> with the script to (re)load? Something like below:

<script>
   function load_js()
   {
      var head= document.getElementsByTagName('head')[0];
      var script= document.createElement('script');
      script.src= 'source_file.js';
      head.appendChild(script);
   }
   load_js();
</script>

The main point is inserting a new script tag -- you can remove the old one without consequence. You may need to add a timestamp to the query string if you have caching issues.

How do I shutdown, restart, or log off Windows via a bat file?

No one has mentioned -m option for remote shutdown:

shutdown -r -f -m \\machinename

Also:

  • The -r parameter causes a reboot (which is usually what you want on a remote machine, since physically starting it might be difficult).
  • The -f parameter option forces the reboot.
  • You must have appropriate privileges to shut down the remote machine, of course.

Difference between == and ===

The logical right shift (v >>> n) returns a value in which the bits in v have been shifted to the right by n bit positions, and 0's are shifted in from the left side. Consider shifting 8-bit values, written in binary:

01111111 >>> 2 = 00011111
10000000 >>> 2 = 00100000

If we interpret the bits as an unsigned nonnegative integer, the logical right shift has the effect of dividing the number by the corresponding power of 2. However, if the number is in two's-complement representation, logical right shift does not correctly divide negative numbers. For example, the second right shift above shifts 128 to 32 when the bits are interpreted as unsigned numbers. But it shifts -128 to 32 when, as is typical in Java, the bits are interpreted in two's complement.

Therefore, if you are shifting in order to divide by a power of two, you want the arithmetic right shift (v >> n). It returns a value in which the bits in v have been shifted to the right by n bit positions, and copies of the leftmost bit of v are shifted in from the left side:

01111111 >> 2 = 00011111
10000000 >> 2 = 11100000

When the bits are a number in two's-complement representation, arithmetic right shift has the effect of dividing by a power of two. This works because the leftmost bit is the sign bit. Dividing by a power of two must keep the sign the same.

How to loop through files matching wildcard in batch file

There is a tool usually used in MS Servers (as far as I can remember) called forfiles:

The link above contains help as well as a link to the microsoft download page.

SVG gradient using CSS

2019 Answer

With brand new css properties you can have even more flexibility with variables aka custom properties

_x000D_
_x000D_
.shape {
  width:500px;
  height:200px;
}

.shape .gradient-bg {
  fill: url(#header-shape-gradient) #fff;
}

#header-shape-gradient {
  --color-stop: #f12c06;
  --color-bot: #faed34;
}
_x000D_
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" class="shape">
  <defs>
    <linearGradient id="header-shape-gradient" x2="0.35" y2="1">
        <stop offset="0%" stop-color="var(--color-stop)" />
        <stop offset="30%" stop-color="var(--color-stop)" />
        <stop offset="100%" stop-color="var(--color-bot)" />
      </linearGradient>
  </defs>
  <g>
    <polygon class="gradient-bg" points="0,0 100,0 0,66" />
  </g>
</svg>
_x000D_
_x000D_
_x000D_

Just set a named variable for each stop in gradient and then customize as you like in css. You can even change their values dynamically with javascript, like:

document.querySelector('#header-shape-gradient').style.setProperty('--color-stop', "#f5f7f9");

How to make rectangular image appear circular with CSS

Following worked for me:

CSS

.round {
  border-radius: 50%;
  overflow: hidden;
  width: 30px;
  height: 30px;
  background: no-repeat 50%;
  object-fit: cover;
}
.round img {
   display: block;
   height: 100%;
   width: 100%;
}

HTML

<div class="round">
   <img src="test.png" />
</div>

Use of 'prototype' vs. 'this' in JavaScript?

What's the difference? => A lot.

I think, the this version is used to enable encapsulation, i.e. data hiding. It helps to manipulate private variables.

Let us look at the following example:

var AdultPerson = function() {

  var age;

  this.setAge = function(val) {
    // some housekeeping
    age = val >= 18 && val;
  };

  this.getAge = function() {
    return age;
  };

  this.isValid = function() {
    return !!age;
  };
};

Now, the prototype structure can be applied as following:

Different adults have different ages, but all of the adults get the same rights.
So, we add it using prototype, rather than this.

AdultPerson.prototype.getRights = function() {
  // Should be valid
  return this.isValid() && ['Booze', 'Drive'];
};

Lets look at the implementation now.

var p1 = new AdultPerson;
p1.setAge(12); // ( age = false )
console.log(p1.getRights()); // false ( Kid alert! )
p1.setAge(19); // ( age = 19 )
console.log(p1.getRights()); // ['Booze', 'Drive'] ( Welcome AdultPerson )

var p2 = new AdultPerson;
p2.setAge(45);    
console.log(p2.getRights()); // The same getRights() method, *** not a new copy of it ***

Hope this helps.

Difference between static, auto, global and local variable in the context of c and c++

When a variable is declared static inside a class then it becomes a shared variable for all objects of that class which means that the variable is longer specific to any object. For example: -

#include<iostream.h>
#include<conio.h>
class test
{
    void fun()
    {
        static int a=0;
        a++;
        cout<<"Value of a = "<<a<<"\n";
    }
};
void main()
{
    clrscr();
    test obj1;
    test obj2;
    test obj3;
    obj1.fun();
    obj2.fun();
    obj3.fun();
    getch();
}

This program will generate the following output: -

Value of a = 1
Value of a = 2
Value of a = 3

The same goes for globally declared static variable. The above code will generate the same output if we declare the variable a outside function void fun()

Whereas if u remove the keyword static and declare a as a non-static local/global variable then the output will be as follows: -

Value of a = 1
Value of a = 1
Value of a = 1

JPA and Hibernate - Criteria vs. JPQL or HQL

Most the answers here are misleading and mention that Criteria Queries are slower than HQL, which is actually not the case.

If you delve deep and perform some tests you will see Criteria Queries perform much better that regular HQL.

And also with Criteria Query you get Object Oriented control which is not there with HQL.

For more information read this answer here.

How to run ssh-add on windows?

In order to run ssh-add on Windows one could install git using choco install git. The ssh-add command is recognized once C:\Program Files\Git\usr\bin has been added as a PATH variable and the command prompt has been restarted:

C:\Users\user\Desktop\repository>ssh-add .ssh/id_rsa
Enter passphrase for .ssh/id_rsa:
Identity added: .ssh/id_rsa (.ssh/id_rsa)

C:\Users\user\Desktop\repository> 

(Mac) -bash: __git_ps1: command not found

__git_ps1 for bash is now found in git-prompt.sh in /usr/local/etc/bash_completion.d on my brew installed git version 1.8.1.5

Find the index of a char in string?

The String class exposes some methods to enable this, such as IndexOf and LastIndexOf, so that you may do this:

Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then

End If

How and where to use ::ng-deep?

Just an update:

You should use ::ng-deep instead of /deep/ which seems to be deprecated.

Per documentation:

The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

You can find it here

How to have jQuery restrict file types on upload?

You can get the value of a file field just the same as any other field. You can't alter it, however.

So to superficially check if a file has the right extension, you could do something like this:

var ext = $('#my_file_field').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
    alert('invalid extension!');
}

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

What do you want to do with this unique ID? Maybe you can do what you want without this ID.

The MAC address maybe is one option but this is not an trusted unique ID because the user can change the MAC address of a computer.

To get the motherboard or processor ID check on this link.

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

Having included a dependency on spring-boot-configuration-processor in build.gradle:

annotationProcessor "org.springframework.boot:spring-boot-configuration-processor:2.4.1"

the only thing that worked for me, besides invalidating caches of IntelliJ and restarting, is

  1. Refresh button in side panel Reload All Gradle Projects
  2. Gradle task Clean
  3. Gradle task Build

Eclipse: How do you change the highlight color of the currently selected method/expression?

If you're using eclipse with PHP package and want to change highlighted colour then there is slight difference to above answer.

  1. Right click on highlighted word
  2. Select 'Preferences'
  3. Go to General > Editors > Text Editors > Annotations. Now look for "PHP elements 'read' occurrences" and "PHP elements 'write' occurrences". You can select your desired colour there.

Change Highlighted text colour in Eclips with PHP

converting json to string in python

There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

Doctrine and LIKE query

This is not possible with the magic methods, however you can achieve this using DQL (Doctrine Query Language). In your example, assuming you have entity named Orders with Product property, just go ahead and do the following:

$dql_query = $em->createQuery("
    SELECT o FROM AcmeCodeBundle:Orders o
    WHERE 
      o.OrderEmail = '[email protected]' AND
      o.Product LIKE 'My Products%'
");
$orders = $dql_query->getResult();

Should do exactly what you need.

How to get element by innerText

Simply pass your substring into the following line:

Outer HTML

document.documentElement.outerHTML.includes('substring')

Inner HTML

document.documentElement.innerHTML.includes('substring')

You can use these to search through the entire document and retrieve the tags that contain your search term:

function get_elements_by_inner(word) {
    res = []
    elems = [...document.getElementsByTagName('a')];
    elems.forEach((elem) => { 
        if(elem.outerHTML.includes(word)) {
            res.push(elem)
        }
    })
    return(res)
}

Usage:

How many times is the user "T3rm1" mentioned on this page?

get_elements_by_inner("T3rm1").length

1

How many times is jQuery mentioned?

get_elements_by_inner("jQuery").length

3

Get all elements containing the word "Cybernetic":

get_elements_by_inner("Cybernetic")

enter image description here

Getting values from query string in an url using AngularJS $location

Not sure if it has changed since the accepted answer was accepted, but it is possible.

$location.search() will return an object of key-value pairs, the same pairs as the query string. A key that has no value is just stored in the object as true. In this case, the object would be:

{"test_user_bLzgB": true}

You could access this value directly with $location.search().test_user_bLzgB

Example (with larger query string): http://fiddle.jshell.net/TheSharpieOne/yHv2p/4/show/?test_user_bLzgB&somethingElse&also&something=Somethingelse

Note: Due to hashes (as it will go to http://fiddle.jshell.net/#/url, which would create a new fiddle), this fiddle will not work in browsers that do not support js history (will not work in IE <10)

Edit:
As pointed out in the comments by @Naresh and @DavidTchepak, the $locationProvider also needs to be configured properly: https://code.angularjs.org/1.2.23/docs/guide/$location#-location-service-configuration

Redirecting to a new page after successful login

Try header("Location:home.php"); instead of showing $msg = 'Login Complete! Thanks'; Hope it'll help you.

How to get access to HTTP header information in Spring MVC REST controller?

You can use the @RequestHeader annotation with HttpHeaders method parameter to gain access to all request headers:

@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
    // Use headers to get the information about all the request headers
    long contentLength = headers.getContentLength();
    // ...
    StreamSource source = new StreamSource(new StringReader(body));
    YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
    // ...
}

Big-O summary for Java Collections Framework implementations?

The guy above gave comparison for HashMap / HashSet vs. TreeMap / TreeSet.

I will talk about ArrayList vs. LinkedList:

ArrayList:

  • O(1) get()
  • amortized O(1) add()
  • if you insert or delete an element in the middle using ListIterator.add() or Iterator.remove(), it will be O(n) to shift all the following elements

LinkedList:

  • O(n) get()
  • O(1) add()
  • if you insert or delete an element in the middle using ListIterator.add() or Iterator.remove(), it will be O(1)

Create request with POST, which response codes 200 or 201 and content

The idea is that the response body gives you a page that links you to the thing:

201 Created

The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location field is received, by the effective request URI.

This means that you would include a Location in the response header that gives the URL of where you can find the newly created thing:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597

Response body

They then go on to mention what you should include in the response body:

The 201 response payload typically describes and links to the resource(s) created.

For the human using the browser, you give them something they can look at, and click, to get to their newly created resource:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: text/html

Your answer has been saved! 
Click <A href="/a/36373586/12597">here</A> to view it.

If the page will only be used by a robot, the it makes sense to have the response be computer readable:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/xml

<createdResources>
   <questionID>1860645</questionID>
   <answerID>36373586</answerID>
   <primary>/a/36373586/12597</primary>
   <additional>
      <resource>http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586</resource>
      <resource>http://stackoverflow.com/a/1962757/12597</resource>
   </additional>
</createdResource>

Or, if you prefer:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/json

{ 
   "questionID": 1860645, 
   "answerID": 36373586,
   "primary": "/a/36373586/12597",
   "additional": [
      "http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586",
      "http://stackoverflow.com/a/36373586/12597"
   ]
}

The response is entirely up to you; it's arbitrarily what you'd like.

Cache friendly

Finally there's the optimization that I can pre-cache the created resource (because I already have the content; I just uploaded it). The server can return a date or ETag which I can store with the content I just uploaded:

See Section 7.2 for a discussion of the meaning and purpose of validator header fields, such as ETag and Last-Modified, in a 201 response.

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/23704283/12597
Content-Type: text/html
ETag: JF2CA53BOMQGU5LTOQQGC3RAMV4GC3LQNRSS4
Last-Modified: Sat, 02 Apr 2016 12:22:39 GMT 

Your answer has been saved! 
Click <A href="/a/36373586/12597">here</A> to view it.

And ETag s are purely arbitrary values. Having them be different when a resource changes (and caches need to be updated) is all that matters. The ETag is usually a hash (e.g. SHA2). But it can be a database rowversion, or an incrementing revision number. Anything that will change when the thing changes.

Should Jquery code go in header or footer?

Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.

preg_match(); - Unknown modifier '+'

Try this code:

preg_match('/[a-zA-Z]+<\/a>.$/', $lastgame, $match);
print_r($match);

Using / as a delimiter means you also need to escape it here, like so: <\/a>.

UPDATE

preg_match('/<a.*<a.*>(.*)</', $lastgame, $match);
echo'['.$match[1].']';

Might not be the best way...

"Field has incomplete type" error

The problem is that your ui property uses a forward declaration of class Ui::MainWindowClass, hence the "incomplete type" error.

Including the header file in which this class is declared will fix the problem.

EDIT

Based on your comment, the following code:

namespace Ui
{
    class MainWindowClass;
}

does NOT declare a class. It's a forward declaration, meaning that the class will exist at some point, at link time.
Basically, it just tells the compiler that the type will exist, and that it shouldn't warn about it.

But the class has to be defined somewhere.

Note this can only work if you have a pointer to such a type.
You can't have a statically allocated instance of an incomplete type.

So either you actually want an incomplete type, and then you should declare your ui member as a pointer:

namespace Ui
{
    // Forward declaration - Class will have to exist at link time
    class MainWindowClass;
}

class MainWindow : public QMainWindow
{
    private:

        // Member needs to be a pointer, as it's an incomplete type
        Ui::MainWindowClass * ui;
};

Or you want a statically allocated instance of Ui::MainWindowClass, and then it needs to be declared. You can do it in another header file (usually, there's one header file per class).
But simply changing the code to:

namespace Ui
{
    // Real class declaration - May/Should be in a specific header file
    class MainWindowClass
    {};
}


class MainWindow : public QMainWindow
{
    private:

        // Member can be statically allocated, as the type is complete
        Ui::MainWindowClass ui;
};

will also work.

Note the difference between the two declarations. First uses a forward declaration, while the second one actually declares the class (here with no properties nor methods).

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

OnCreate:

//Add comment fragment
            container = FindViewById<FrameLayout>(Resource.Id.frmAttachPicture);
            mPictureFragment = new fmtAttachPicture();

            var trans = SupportFragmentManager.BeginTransaction();
            trans.Add(container.Id, mPictureFragment, "fmtPicture");
            trans.Show(mPictureFragment); trans.Commit();

This is how I hide the fragment in click event 1

//Close fragment
    var trans = SupportFragmentManager.BeginTransaction();
    trans.Hide(mPictureFragment);
    trans.AddToBackStack(null);
    trans.Commit();

Then Shows it back int event 2

var trans = SupportFragmentManager.BeginTransaction();
            trans.Show(mPictureFragment); trans.Commit();

Cordova app not displaying correctly on iPhone X (Simulator)

Just a note that the constant keyword use for safe-area margins has been updated to env for 11.2 beta+

https://webkit.org/blog/7929/designing-websites-for-iphone-x/

Angular2 - Radio Button Binding

Note - radio button binding is now a supported feature in RC4 onwards - see this answer

Radio button example using custom RadioControlValueAccessor similar to CheckboxControlValueAccessor (Updated with Angular 2 rc-1)

App.ts

import {Component} from "@angular/core";
import {FORM_DIRECTIVES} from "@angular/common";
import {RadioControlValueAccessor} from "./radio_value_accessor";
import {bootstrap} from '@angular/platform-browser-dynamic';

@Component({
    selector: "my-app",
    templateUrl: "template.html",
    directives: [FORM_DIRECTIVES, RadioControlValueAccessor]
})
export class App {

    model;

    constructor() {
        this.model = {
            sex: "female"
        };
    }
}

template.html

<div>
    <form action="">
        <input type="radio" [(ngModel)]="model.sex"  name="sex" value="male">Male<br>
        <input type="radio" [(ngModel)]="model.sex"  name="sex" value="female">Female
    </form>

    <input type="button" value="select male" (click)="model.sex='male'">
    <input type="button" value="select female" (click)="model.sex='female'">
    <div>Selected Radio: {{model.sex}}</div>
</div>

radio_value_accessor.ts

import {Directive, Renderer, ElementRef, forwardRef} from '@angular/core';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from '@angular/common';

export const RADIO_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => RadioControlValueAccessor),
    multi: true
};

@Directive({
   selector:
       'input[type=radio][ngControl],input[type=radio][ngFormControl],input[type=radio][ngModel]',
   host: {'(change)': 'onChange($event.target.value)', '(blur)': 'onTouched()'},
   bindings: [RADIO_VALUE_ACCESSOR]
})
export class RadioControlValueAccessor implements ControlValueAccessor {
   onChange = (_) => {};
   onTouched = () => {};

   constructor(private _renderer: Renderer, private _elementRef: ElementRef) {}

   writeValue(value: any): void {
       this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', value == this._elementRef.nativeElement.value);
   }
   registerOnChange(fn: (_: any) => {}): void { this.onChange = fn; }
   registerOnTouched(fn: () => {}): void { this.onTouched = fn; }
}

Source : https://github.com/angular2-school/angular2-radio-button

Plunker live demo : http://plnkr.co/edit/aggee6An1iHfwsqGoE3q?p=preview

Converting A String To Hexadecimal In Java

byte[] bytes = string.getBytes(CHARSET); // you didn't say what charset you wanted
BigInteger bigInt = new BigInteger(bytes);
String hexString = bigInt.toString(16); // 16 is the radix

You could return hexString at this point, with the caveat that leading null-chars will be stripped, and the result will have an odd length if the first byte is less than 16. If you need to handle those cases, you can add some extra code to pad with 0s:

StringBuilder sb = new StringBuilder();
while ((sb.length() + hexString.length()) < (2 * bytes.length)) {
  sb.append("0");
}
sb.append(hexString);
return sb.toString();

How to check if image exists with given url?

From here:

// when the DOM is ready
$(function () {
  var img = new Image();
  // wrap our new image in jQuery, then:
  $(img)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default    
      $(this).hide();
      // with the holding div #loader, apply:
      $('#loader')
        // remove the loading class (so no background spinner), 
        .removeClass('loading')
        // then insert our image
        .append(this);
      // fade our image in to create a nice effect
      $(this).fadeIn();
    })
    // if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded
    })
    // *finally*, set the src attribute of the new image to our image
    .attr('src', 'images/headshot.jpg');
});

Postgres: check if array field contains value?

This worked for me

let exampleArray = [1, 2, 3, 4, 5];
let exampleToString = exampleArray.toString(); //convert to toString
let query = `Select * from table_name where column_name in (${exampleToString})`; //Execute the query to get response

I have got the same problem, then after an hour of effort I got to know that the array should not be directly accessed in the query. So I then found that the data should be sent in the paranthesis it self, then again I have converted that array to string using toString method in js. So I have worked by executing the above query and got my expected result

Try catch statements in C

This is another way to do error handling in C which is more performant than using setjmp/longjmp. Unfortunately, it will not work with MSVC but if using only GCC/Clang is an option, then you might consider it. Specifically, it uses the "label as value" extension, which allows you to take the address of a label, store it in a value and and jump to it unconditionally. I'll present it using an example:

GameEngine *CreateGameEngine(GameEngineParams const *params)
{
    /* Declare an error handler variable. This will hold the address
       to jump to if an error occurs to cleanup pending resources.
       Initialize it to the err label which simply returns an
       error value (NULL in this example). The && operator resolves to
       the address of the label err */
    void *eh = &&err;

    /* Try the allocation */
    GameEngine *engine = malloc(sizeof *engine);
    if (!engine)
        goto *eh; /* this is essentially your "throw" */

    /* Now make sure that if we throw from this point on, the memory
       gets deallocated. As a convention you could name the label "undo_"
       followed by the operation to rollback. */
    eh = &&undo_malloc;

    /* Now carry on with the initialization. */
    engine->window = OpenWindow(...);
    if (!engine->window)
        goto *eh;   /* The neat trick about using approach is that you don't
                       need to remember what "undo" label to go to in code.
                       Simply go to *eh. */

    eh = &&undo_window_open;

    /* etc */

    /* Everything went well, just return the device. */
    return device;

    /* After the return, insert your cleanup code in reverse order. */
undo_window_open: CloseWindow(engine->window);
undo_malloc: free(engine);
err: return NULL;
}

If you so wish, you could refactor common code in defines, effectively implementing your own error-handling system.

/* Put at the beginning of a function that may fail. */
#define declthrows void *_eh = &&err

/* Cleans up resources and returns error result. */
#define throw goto *_eh

/* Sets a new undo checkpoint. */
#define undo(label) _eh = &&undo_##label

/* Throws if [condition] evaluates to false. */
#define check(condition) if (!(condition)) throw

/* Throws if [condition] evaluates to false. Then sets a new undo checkpoint. */
#define checkpoint(label, condition) { check(condition); undo(label); }

Then the example becomes

GameEngine *CreateGameEngine(GameEngineParams const *params)
{
    declthrows;

    /* Try the allocation */
    GameEngine *engine = malloc(sizeof *engine);
    checkpoint(malloc, engine);

    /* Now carry on with the initialization. */
    engine->window = OpenWindow(...);
    checkpoint(window_open, engine->window);

    /* etc */

    /* Everything went well, just return the device. */
    return device;

    /* After the return, insert your cleanup code in reverse order. */
undo_window_open: CloseWindow(engine->window);
undo_malloc: free(engine);
err: return NULL;
}

Loop through JSON in EJS

in my case, datas is an objects of Array for more information please Click Here

<% for(let [index,data] of datas.entries() || []){  %>
 Index : <%=index%>
 Data : <%=data%>
<%} %>

what's data-reactid attribute in html?

That's the HTML data attribute. See this for more detail: http://html5doctor.com/html5-custom-data-attributes/

Basically it's just a container of your custom data while still making the HTML valid. It's data- plus some unique identifier.

Pythonic way to combine FOR loop and IF statement

The following is a simplification/one liner from the accepted answer:

a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]

for x in (x for x in xyz if x not in a):
    print(x)

12
242

Notice that the generator was kept inline. This was tested on python2.7 and python3.6 (notice the parens in the print ;) )

Unable to Connect to GitHub.com For Cloning

You can make git replace the protocol for you

git config --global url."https://".insteadOf git://

See more at SO Bower install using only https?

How to use multiple conditions (With AND) in IIF expressions in ssrs

You don't need an IIF() at all here. The comparisons return true or false anyway.

Also, since this row visibility is on a group row, make sure you use the same aggregate function on the fields as you use in the fields in the row. So if your group row shows sums, then you'd put this in the Hidden property.

=Sum(Fields!OpeningStock.Value) = 0 And
Sum(Fields!GrossDispatched.Value) = 0 And 
Sum(Fields!TransferOutToMW.Value) = 0 And
Sum(Fields!TransferOutToDW.Value) = 0 And
Sum(Fields!TransferOutToOW.Value) = 0 And
Sum(Fields!NetDispatched.Value) = 0 And
Sum(Fields!QtySold.Value) = 0 And
Sum(Fields!StockAdjustment.Value) = 0 And
Sum(Fields!ClosingStock.Value) = 0

But with the above version, if one record has value 1 and one has value -1 and all others are zero then sum is also zero and the row could be hidden. If that's not what you want you could write a more complex expression:

=Sum(
    IIF(
        Fields!OpeningStock.Value=0 AND
        Fields!GrossDispatched.Value=0 AND
        Fields!TransferOutToMW.Value=0 AND
        Fields!TransferOutToDW.Value=0 AND 
        Fields!TransferOutToOW.Value=0 AND
        Fields!NetDispatched.Value=0 AND
        Fields!QtySold.Value=0 AND
        Fields!StockAdjustment.Value=0 AND
        Fields!ClosingStock.Value=0,
        0,
        1
    )
) = 0

This is essentially a fancy way of counting the number of rows in which any field is not zero. If every field is zero for every row in the group then the expression returns true and the row is hidden.

C#: Limit the length of a string?

Use Remove()...

string foo = "1234567890";
int trimLength = 5;

if (foo.Length > trimLength) foo = foo.Remove(trimLength);

// foo is now "12345"

How do I put my website's logo to be the icon image in browser tabs?

It is called 'favicon' and you need to add below code to the header section of your website.

Simply add this to the <head> section.

<link rel="icon" href="/your_path_to_image/favicon.jpg">

Determine on iPhone if user has enabled push notifications

Full easy copy and paste code built from @ZacBowling's solution (https://stackoverflow.com/a/1535427/2298002)

this will also bring the user to your app settings and allow them to enable immediately

I also added in a solution for checking if location services is enabled (and brings to settings as well)

// check if notification service is enabled
+ (void)checkNotificationServicesEnabled
{
    if (![[UIApplication sharedApplication] isRegisteredForRemoteNotifications])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Notification Services Disabled!"
                                                            message:@"Yo don't mess around bro! Enabling your Notifications allows you to receive important updates"
                                                           delegate:self
                                                  cancelButtonTitle:@"Cancel"
                                                  otherButtonTitles:@"Settings", nil];

        alertView.tag = 300;

        [alertView show];

        return;
    }
}

// check if location service is enabled (ref: https://stackoverflow.com/a/35982887/2298002)
+ (void)checkLocationServicesEnabled
{
    //Checking authorization status
    if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
    {

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled!"
                                                            message:@"You need to enable your GPS location right now!!"
                                                           delegate:self
                                                  cancelButtonTitle:@"Cancel"
                                                  otherButtonTitles:@"Settings", nil];

        //TODO if user has not given permission to device
        if (![CLLocationManager locationServicesEnabled])
        {
            alertView.tag = 100;
        }
        //TODO if user has not given permission to particular app
        else
        {
            alertView.tag = 200;
        }

        [alertView show];

        return;
    }
}

// handle bringing user to settings for each
+ (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if(buttonIndex == 0)// Cancel button pressed
    {
        //TODO for cancel
    }
    else if(buttonIndex == 1)// Settings button pressed.
    {
        if (alertView.tag == 100)
        {
            //This will open ios devices location settings
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];
        }
        else if (alertView.tag == 200)
        {
            //This will open particular app location settings
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
        else if (alertView.tag == 300)
        {
            //This will open particular app location settings
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
    }
}

GLHF!

Using Page_Load and Page_PreRender in ASP.Net

It depends on your requirements.

Page Load : Perform actions common to all requests, such as setting up a database query. At this point, server controls in the tree are created and initialized, the state is restored, and form controls reflect client-side data. See Handling Inherited Events.

Prerender :Perform any updates before the output is rendered. Any changes made to the state of the control in the prerender phase can be saved, while changes made in the rendering phase are lost. See Handling Inherited Events.

Reference: Control Execution Lifecycle MSDN

Try to read about

ASP.NET Page Life Cycle Overview ASP.NET

Control Execution Lifecycle

Regards

bodyParser is deprecated express 4

app.use(bodyParser.urlencoded({extended: true}));

I have the same problem but this work for me. You can try this extended part.

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Use the Bootstrap Customizer to generate a version of Bootstrap that has a taller navbar. The value you want to change is @navbar-height in the Navbar section.

Inspect your current implementation to see how tall your navbar is with the 50px brand image, and use that calculated height in the Customizer.

Weird PHP error: 'Can't use function return value in write context'

The problem is in the () you have to go []

if (isset($_POST('sms_code') == TRUE)

by

if (isset($_POST['sms_code'] == TRUE)

Python/Django: log to console under runserver, log to file under Apache

Text printed to stderr will show up in httpd's error log when running under mod_wsgi. You can either use print directly, or use logging instead.

print >>sys.stderr, 'Goodbye, cruel world!'

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

How to use JavaScript source maps (.map files)?

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

Same for CSS files. Once you take a SASS or LESS file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.

So, to answer you questions in order:

  • What is it for? To de-reference uglified code
  • How can a developer use it? You use it for debugging a production app. In development mode you can use the full version of Angular. In production, you would use the minified version.
  • Should I care about creating a js.map file? If you care about being able to debug production code easier, then yes, you should do it.
  • How does it get created? It is created at build time. There are build tools that can build your .map file for you as it does other files. https://github.com/gruntjs/grunt-contrib-uglify/issues/71

I hope this makes sense.

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

How do I parse command line arguments in Java?

Check these out:

Or roll your own:


For instance, this is how you use commons-cli to parse 2 string arguments:

import org.apache.commons.cli.*;

public class Main {


    public static void main(String[] args) throws Exception {

        Options options = new Options();

        Option input = new Option("i", "input", true, "input file path");
        input.setRequired(true);
        options.addOption(input);

        Option output = new Option("o", "output", true, "output file");
        output.setRequired(true);
        options.addOption(output);

        CommandLineParser parser = new DefaultParser();
        HelpFormatter formatter = new HelpFormatter();
        CommandLine cmd;

        try {
            cmd = parser.parse(options, args);
        } catch (ParseException e) {
            System.out.println(e.getMessage());
            formatter.printHelp("utility-name", options);

            System.exit(1);
        }

        String inputFilePath = cmd.getOptionValue("input");
        String outputFilePath = cmd.getOptionValue("output");

        System.out.println(inputFilePath);
        System.out.println(outputFilePath);

    }

}

usage from command line:

$> java -jar target/my-utility.jar -i asd                                                                                       
Missing required option: o

usage: utility-name
 -i,--input <arg>    input file path
 -o,--output <arg>   output file

TypeError: 'NoneType' object has no attribute '__getitem__'

The function move.CompleteMove(events) that you use within your class probably doesn't contain a return statement. So nothing is returned to self.values (==> None). Use return in move.CompleteMove(events) to return whatever you want to store in self.values and it should work. Hope this helps.

How many bits is a "word"?

I'm not familiar with either of these books, but the second is closer to current reality. The first may be discussing a specific processor.

Processors have been made with quite a variety of word sizes, not always a multiple of 8.

The 8086 and 8087 processors used 16 bit words, and it's likely this is the machine the first author was writing about.

More recent processors commonly use 32 or 64 bit words.

In the 50's and 60's there were machines with words sizes that seem quite strange to us now, such as 4, 9 and 36. Since about the 70's word size has commonly been a power of 2 and a multiple of 8.

Run MySQLDump without Locking Tables

This is ages too late, but good for anyone that is searching the topic. If you're not innoDB, and you're not worried about locking while you dump simply use the option:

--lock-tables=false

How do you get the current text contents of a QComboBox?

Getting the Text of ComboBox when the item is changed

     self.ui.comboBox.activated.connect(self.pass_Net_Adap)

  def pass_Net_Adap(self):
      print str(self.ui.comboBox.currentText())

How can I get the error message for the mail() function?

Try this. If I got any error on any file then I got error mail on my email id. Create two files index.php and checkErrorEmail.php and uploaded them to your server. Then load index.php with your browser.

Index.php

<?php
    include('checkErrorEmail.php');
    include('dereporting.php');
    $temp;
    echo 'hi '.$temp;
?>

checkErrorEmail.php

<?php
  // Destinations
  define("ADMIN_EMAIL", "[email protected]");
  //define("LOG_FILE", "/my/home/errors.log");

  // Destination types
  define("DEST_EMAIL", "1");
  //define("DEST_LOGFILE", "3");

  /* Examples */

  // Send an e-mail to the administrator
  //error_log("Fix me!", DEST_EMAIL, ADMIN_EMAIL);

  // Write the error to our log file
  //error_log("Error", DEST_LOGFILE, LOG_FILE);

  /**
    * my_error_handler($errno, $errstr, $errfile, $errline)
    *
    * Author(s): thanosb, ddonahue
    * Date: May 11, 2008
    * 
    * custom error handler
    *
    * Parameters:
    *  $errno:   Error level
    *  $errstr:  Error message
    *  $errfile: File in which the error was raised
    *  $errline: Line at which the error occurred
    */

  function my_error_handler($errno, $errstr, $errfile, $errline)
  {  
  echo "<br><br><br><br>errno ".$errno.",<br>errstr ".$errstr.",<br>errfile ".$errfile.",<br>errline ".$errline;
      if($errno)
      {
              error_log("Error: $errstr \n error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);
      }
    /*switch ($errno) {
      case E_USER_ERROR:
        // Send an e-mail to the administrator
        error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);

        // Write the error to our log file
        //error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_LOGFILE, LOG_FILE);
        break;

      case E_USER_WARNING:
        // Write the error to our log file
        //error_log("Warning: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
        break;

      case E_USER_NOTICE:
        // Write the error to our log file
       // error_log("Notice: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
        break;

      default:
        // Write the error to our log file
        //error_log("Unknown error [#$errno]: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
        break;
    }*/

    // Don't execute PHP's internal error handler
    return TRUE;
  }


  // Use set_error_handler() to tell PHP to use our method
  $old_error_handler = set_error_handler("my_error_handler");


?>

What is a practical use for a closure in JavaScript?

I like Mozilla's function factory example.

function makeAdder(x) {

    return function(y) {
        return x + y;
    };
}

var addFive = makeAdder(5);

console.assert(addFive(2) === 7);
console.assert(addFive(-5) === 0);

How can I use JQuery to post JSON data?

I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data

$.fn.postJSON = function(url, data) {
    return $.ajax({
            type: 'POST',
            url: url,
            data: data,
            dataType: 'json'
        });

How to change the default charset of a MySQL table?

You can change the default with an alter table set default charset but that won't change the charset of the existing columns. To change that you need to use a alter table modify column.

Changing the charset of a column only means that it will be able to store a wider range of characters. Your application talks to the db using the mysql client so you may need to change the client encoding as well.

Git merge develop into feature branch outputs "Already up-to-date" while it's not

You should first pull the changes from the develop branch and only then merge them to your branch:

git checkout develop 
git pull 
git checkout branch-x
git rebase develop

Or, when on branch-x:

git fetch && git rebase origin/develop

I have an alias that saves me a lot of time. Add to your ~/.gitconfig:

[alias]
    fr = "!f() { git fetch && git rebase origin/"$1"; }; f"

Now, all that you have to do is:

git fr develop

What’s the difference between Response.Write() andResponse.Output.Write()?

Here Response.Write():to display only string and you can not display any other data type values like int,date,etc.Conversion(from one data type to another) is not allowed. whereas Response .Output .Write(): you can display any type of data like int, date ,string etc.,by giving index values.

Here is example:

protected void Button1_Click(object sender, EventArgs e)
    {
       Response.Write ("hi good morning!"+"is it right?");//only strings are allowed        
       Response.Write("Scott is {0} at {1:d}", "cool", DateTime.Now);//this will give error(conversion is not allowed)
       Response.Output.Write("\nhi goood morning!");//works fine
       Response.Output.Write("Jai is {0} on {1:d}", "cool", DateTime.Now);//here the current date will be converted into string and displayed
    }

Call a React component method from outside

method 1 using ChildRef:

public childRef: any = React.createRef<Hello>();

public onButtonClick= () => {
    console.log(this.childRef.current); // this will have your child reference
}

<Hello ref = { this.childRef }/>
<button onclick="onButtonClick()">Click me!</button>

Method 2: using window register

public onButtonClick= () => {
    console.log(window.yourRef); // this will have your child reference
}

<Hello ref = { (ref) => {window.yourRef = ref} }/>`
<button onclick="onButtonClick()">Click me!</button>

How to copy and paste code without rich text formatting?

I have Far.exe as the first item in the start menu.

Richtext in the clipboard ->

ctrl-escape,arrdown,enter,shift-f4,$,enter
shift-insert,ctrl-insert,alt-backspace,
f10,enter

-> plaintext in the clipboard

Pros: no mouse, just blind typing, ends exactly where i was before

Cons: ANSI encoding - international symbols are lost

Luckily, I do not have to do that too often :)

Android Get Application's 'Home' Data Directory

Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:

ContextWrapper.getFilesDir()

Found here.

Linking static libraries to other static libraries

If you are using Visual Studio then yes, you can do this.

The library builder tool that comes with Visual Studio allows you to join libraries together on the command line. I don't know of any way to do this in the visual editor though.

lib.exe /OUT:compositelib.lib  lib1.lib lib2.lib

How to get response status code from jQuery.ajax?

You can check your respone content, just console.log it and you will see whitch property have a status code. If you do not understand jsons, please refer to the video: https://www.youtube.com/watch?v=Bv_5Zv5c-Ts

It explains very basic knowledge that let you feel more comfortable with javascript.

You can do it with shorter version of ajax request, please see code above:

$.get("example.url.com", function(data) {
                console.log(data);
            }).done(function() {
               // TO DO ON DONE
            }).fail(function(data, textStatus, xhr) {
                 //This shows status code eg. 403
                 console.log("error", data.status);
                 //This shows status message eg. Forbidden
                 console.log("STATUS: "+xhr);
            }).always(function() {
                 //TO-DO after fail/done request.
                 console.log("ended");
            });

Example console output:

error 403 
STATUS: Forbidden 
ended

Change background color of iframe issue

Put the Iframe between aside tags

<aside style="background-color:#FFF"> your IFRAME </aside>

Chart.js canvas resize

In IOS and Android the browser hides the toolbar when you are scrolling, thereby changing the size of the window which inturn lead chartjs to resize the graph. The solution is to maintain the aspect ratio.

var options = { 
    responsive: true,
    maintainAspectRatio: true
}

This should solve your problem.

intellij idea - Error: java: invalid source release 1.9

I've just had a similar issue. The project had opened using Java 9 but even after all the modules and project were set back to 1.8, I was still getting the error.

I needed to force Gradle to refresh the project and then everything ran as expected.

Int to Char in C#

(char)myint;

for example:

Console.WriteLine("(char)122 is {0}", (char)122);

yields:

(char)122 is z

How to change button color with tkinter

Another way to change color of a button if you want to do multiple operations along with color change. Using the Tk().after method and binding a change method allows you to change color and do other operations.

Label.destroy is another example of the after method.

    def export_win():
        //Some Operation
        orig_color = export_finding_graph.cget("background")
        export_finding_graph.configure(background = "green")

        tt = "Exported"
        label = Label(tab1_closed_observations, text=tt, font=("Helvetica", 12))
        label.grid(row=0,column=0,padx=10,pady=5,columnspan=3)

        def change(orig_color):
            export_finding_graph.configure(background = orig_color)

        tab1_closed_observations.after(1000, lambda: change(orig_color))
        tab1_closed_observations.after(500, label.destroy)


    export_finding_graph = Button(tab1_closed_observations, text='Export', command=export_win)
    export_finding_graph.grid(row=6,column=4,padx=70,pady=20,sticky='we',columnspan=3)

You can also revert to the original color.

how to detect search engine bots with php?

I use the following code which seems to be working fine:

function _bot_detected() {

  return (
    isset($_SERVER['HTTP_USER_AGENT'])
    && preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT'])
  );
}

update 16-06-2017 https://support.google.com/webmasters/answer/1061943?hl=en

added mediapartners

convert nan value to zero

You can use lambda function, an example for 1D array:

import numpy as np
a = [np.nan, 2, 3]
map(lambda v:0 if np.isnan(v) == True else v, a)

This will give you the result:

[0, 2, 3]

No internet on Android emulator - why and how to fix?

If you are using eclipse try:

Window > Preferences > Android > Launch

Default emulator options: -dns-server 8.8.8.8,8.8.4.4

What is the role of the package-lock.json?

It's an very important improvement for npm: guarantee exact same version of every package.

How to make sure your project built with same packages in different environments in a different time? Let's say, you may use ^1.2.3 in your package.json, or some of your dependencies are using that way, but how can u ensure each time npm install will pick up same version in your dev machine and in the build server? package-lock.json will ensure that.

npm install will re-generate the lock file, when on build server or deployment server, do npm ci (which will read from the lock file, and install the whole package tree)

Setting up Eclipse with JRE Path

Add the following to the eclipse.ini :

-vm


Java_Home_Variable\bin\javaw.exe

In my Case its

-vm

H:\usr\java\jdk1.6.0_16\bin\javaw.exe

Excel VBA date formats

To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.

Sub test_date_or_String()
 Set c = ActiveCell
 c.NumberFormat = "@"
 c.Value = CDate("03/04/2014")
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
 c.NumberFormat = "m/d/yyyy"
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
 c.Value = CDate("03/04/2014")
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date    
End Sub

How to insert an item at the beginning of an array in PHP?

Insert an item in the beginning of an associative array with string/custom key

<?php

$array = ['keyOne'=>'valueOne', 'keyTwo'=>'valueTwo'];

$array = array_reverse($array);

$array['newKey'] = 'newValue';

$array = array_reverse($array);

RESULT

[
  'newKey' => 'newValue',
  'keyOne' => 'valueOne',
  'keyTwo' => 'valueTwo'
]

How to echo out table rows from the db (php)

All of the snippets on this page can be dramatically reduced in size.

The mysqli result set object can be immediately fed to a foreach() (because it is "iterable") which eliminates the need to maked iterated _fetch() calls.

Imploding each row will allow your code to correctly print all columnar data in the result set without modifying the code.

$sql = "SELECT * FROM MY_TABLE";
echo '<table>';
    foreach (mysqli_query($conn, $sql) as $row) {
        echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
    }
echo '</table>';

If you want to encode html entities, you can map each row:

implode('</td><td>' . array_map('htmlspecialchars', $row))

If you don't want to use implode, you can simply access all row data using associative array syntax. ($row['id'])

What does `return` keyword mean inside `forEach` function?

The return exits the current function, but the iterations keeps on, so you get the "next" item that skips the if and alerts the 4...

If you need to stop the looping, you should just use a plain for loop like so:

$('button').click(function () {
   var arr = [1, 2, 3, 4, 5];
   for(var i = 0; i < arr.length; i++) {
     var n = arr[i]; 
     if (n == 3) {
         break;
      }
      alert(n);
   })
})

You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp

What is the difference between match_parent and fill_parent?

Functionally no difference, Google just changed the name from fill_parent to match_parent, from API level 8 (Android 2.2). FILL_PARENT is still available for compatibility reason.

LayoutParams.FILL_PARENT and LayoutParams.MATCH_PARENT both have value -1. Not sure what tempted google to change from Fill Parent to Match Parent :)

Since most of the phones are >= Android 2.2 .. you should use Match Parent for future compatibility... not sure when they will discontinue the older Fill Parent constant!

How do you create nested dict in Python?

It is important to remember when using defaultdict and similar nested dict modules such as nested_dict, that looking up a nonexistent key may inadvertently create a new key entry in the dict and cause a lot of havoc.

Here is a Python3 example with nested_dict module:

import nested_dict as nd
nest = nd.nested_dict()
nest['outer1']['inner1'] = 'v11'
nest['outer1']['inner2'] = 'v12'
print('original nested dict: \n', nest)
try:
    nest['outer1']['wrong_key1']
except KeyError as e:
    print('exception missing key', e)
print('nested dict after lookup with missing key.  no exception raised:\n', nest)

# Instead, convert back to normal dict...
nest_d = nest.to_dict(nest)
try:
    print('converted to normal dict. Trying to lookup Wrong_key2')
    nest_d['outer1']['wrong_key2']
except KeyError as e:
    print('exception missing key', e)
else:
    print(' no exception raised:\n')

# ...or use dict.keys to check if key in nested dict
print('checking with dict.keys')
print(list(nest['outer1'].keys()))
if 'wrong_key3' in list(nest.keys()):

    print('found wrong_key3')
else:
    print(' did not find wrong_key3')

Output is:

original nested dict:   {"outer1": {"inner2": "v12", "inner1": "v11"}}

nested dict after lookup with missing key.  no exception raised:  
{"outer1": {"wrong_key1": {}, "inner2": "v12", "inner1": "v11"}} 

converted to normal dict. 
Trying to lookup Wrong_key2 

exception missing key 'wrong_key2' 

checking with dict.keys 

['wrong_key1', 'inner2', 'inner1']  
did not find wrong_key3

Where to find free public Web Services?

https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.

Writing Python lists to columns in csv

If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:

import pandas as pd

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

df.to_csv('file.csv', index=False)

print(df)

   Col0  Col1  Col2
0     1     4     7
1     2     5     8
2     3     6     9

What are WSDL, SOAP and REST?

Every time someone mentions SOAP/WSDL, I think of objects and classes defined in xml...

"You use SOAP just the same way that you would any PHP class. However, in this case the class does not exist in the local applications file system, but at a remote site accessed over http." ... "If we think of using a SOAP service as just another PHP class then the WSDL document is a list of all the available class methods and properties. "

http://www.doublehops.com/2009/07/07/quick-tutorial-on-getting-started-with-soap-in-php/comment-page-1/

..and whenever someone talks about REST I think of HTTP's commands (request methods) like POST, GET and DELETE

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

I had this in a new project on Windows. npm install had created a node_modules folder for me, but it had somehow created the folder without giving me full control over it. I gave myself full control over node_modules and node_modules\.staging and it worked after that.

How to change port number in vue-cli project

Best way is to update the serve script command in your package.json file. Just append --port 3000 like so:

"scripts": {
  "serve": "vue-cli-service serve --port 3000",
  "build": "vue-cli-service build",
  "inspect": "vue-cli-service inspect",
  "lint": "vue-cli-service lint"
},

How to use ArrayAdapter<myClass>

I think this is the best approach. Using generic ArrayAdapter class and extends your own Object adapter is as simple as follows:

public abstract class GenericArrayAdapter<T> extends ArrayAdapter<T> {

  // Vars
  private LayoutInflater mInflater;

  public GenericArrayAdapter(Context context, ArrayList<T> objects) {
    super(context, 0, objects);
    init(context);
  }

  // Headers
  public abstract void drawText(TextView textView, T object);

  private void init(Context context) {
    this.mInflater = LayoutInflater.from(context);
  }

  @Override public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder vh;
    if (convertView == null) {
      convertView = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
      vh = new ViewHolder(convertView);
      convertView.setTag(vh);
    } else {
      vh = (ViewHolder) convertView.getTag();
    }

    drawText(vh.textView, getItem(position));

    return convertView;
  }

  static class ViewHolder {

    TextView textView;

    private ViewHolder(View rootView) {
      textView = (TextView) rootView.findViewById(android.R.id.text1);
    }
  }
}

and here your adapter (example):

public class SizeArrayAdapter extends GenericArrayAdapter<Size> {

  public SizeArrayAdapter(Context context, ArrayList<Size> objects) {
    super(context, objects);
  }

  @Override public void drawText(TextView textView, Size object) {
    textView.setText(object.getName());
  }

}

and finally, how to initialize it:

ArrayList<Size> sizes = getArguments().getParcelableArrayList(Constants.ARG_PRODUCT_SIZES);
SizeArrayAdapter sizeArrayAdapter = new SizeArrayAdapter(getActivity(), sizes);
listView.setAdapter(sizeArrayAdapter);

I've created a Gist with TextView layout gravity customizable ArrayAdapter:

https://gist.github.com/m3n0R/8822803

Newline in string attribute

I realize this is on older question but just wanted to add that

Environment.NewLine

also works if doing this through code.

Pointer arithmetic for void pointer in C

Pointer arithmetic is not allowed on void* pointers.

How to check type of files without extensions in python?

In the case of images, you can use the imghdr module.

>>> import imghdr
>>> imghdr.what('8e5d7e9d873e2a9db0e31f9dfc11cf47')  # You can pass a file name or a file object as first param. See doc for optional 2nd param.
'png'

Python 2 imghdr doc
Python 3 imghdr doc

css ellipsis on second line

Late Reply but a html line-break works as well, so you can do a html + css only solution. So it's bad practice to usually use the br element, but if you break your comment with br the text-overflow ellipsis will start on the next line of the html text.

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

How to remove the first and the last character of a string

use .replace(/.*\/(\S+)\//img,"$1")

"/installers/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services

"/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services

How to merge two json string in Python?

As of Python 3.5, you can merge two dicts with:

merged = {**dictA, **dictB}

(https://www.python.org/dev/peps/pep-0448/)

So:

jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)

etc.

How to make git mark a deleted and a new file as a file move?

For me it worked to stash save all the changes before the commit and pop them out again. This made git re-analyze the added / deleted files and it correctly marked them as moved.

Regex for numbers only

Use the beginning and end anchors.

Regex regex = new Regex(@"^\d$");

Use "^\d+$" if you need to match more than one digit.


Note that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ??????????. Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9.


If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.

How to plot a subset of a data frame in R?

with(dfr[dfr$var3 < 155,], plot(var1, var2)) should do the trick.

Edit regarding multiple conditions:

with(dfr[(dfr$var3 < 155) & (dfr$var4 > 27),], plot(var1, var2))

java.lang.UnsupportedClassVersionError

This was a fresh linux Mint xfce machine

I have been battling this for a about a week. I'm trying to learn Java on Netbeans IDE and so naturally I get the combo file straight from Oracle. Which is a package of the JDK and the Netbeans IDE together in a tar file located here.

located http://www.oracle.com/technetwork/java/javase/downloads/index.html file name JDK 8u25 with NetBeans 8.0.1

after installing them (or so I thought) I would make/compile a simple program like "hello world" and that would spit out a jar file that you would be able to run in a terminal. Keep in mind that the program ran in the Netbeans IDE.

I would end up with this error: java.lang.UnsupportedClassVersionError:

Even though I ran the file from oracle website I still had the old version of the Java runtime which was not compatible to run my jar file which was compiled with the new java runtime.

After messing with stuff that was mostly over my head from setting Paths to editing .bashrc with no remedy.

I came across a solution that was easy enough for even me. I have come across something that auto installs java and configures it on your system and it works with the latest 1.8.*

One of the steps is adding a PPA wasn't sure about this at first but seems ok as it has worked for me


sudo add-apt-repository ppa:webupd8team/java

sudo apt-get update

sudo apt-get install oracle-java8-installer


domenic@domenic-AO532h ~ $ java -version java version "1.8.0_25" Java(TM) SE Runtime Environment (build 1.8.0_25-b17) Java HotSpot(TM) Server VM (build 25.25-b02, mixed mode)

I think it also configures the browser java as well.

I hope this helps others.

Set field value with reflection

The method below sets a field on your object even if the field is in a superclass

/**
 * Sets a field value on a given object
 *
 * @param targetObject the object to set the field value on
 * @param fieldName    exact name of the field
 * @param fieldValue   value to set on the field
 * @return true if the value was successfully set, false otherwise
 */
public static boolean setField(Object targetObject, String fieldName, Object fieldValue) {
    Field field;
    try {
        field = targetObject.getClass().getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        field = null;
    }
    Class superClass = targetObject.getClass().getSuperclass();
    while (field == null && superClass != null) {
        try {
            field = superClass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            superClass = superClass.getSuperclass();
        }
    }
    if (field == null) {
        return false;
    }
    field.setAccessible(true);
    try {
        field.set(targetObject, fieldValue);
        return true;
    } catch (IllegalAccessException e) {
        return false;
    }
}

Mailto: Body formatting

Forget it; this might work with Outlook or maybe even GMail but you won't be able to get this working properly supporting most other E-mail clients out there (and there's a shitton of 'em).

You're better of using a simple PHP script (check out PHPMailer) or use a hosted solution (Google "email form hosted", "free email form hosting" or something similar)

By the way, you are looking for the term "Percent-encoding" (also called url-encoding and Javascript uses encodeUri/encodeUriComponent (make sure you understand the differences!)). You will need to encode a whole lot more than just newlines.

How do I remove diacritics (accents) from a string in .NET?

Imports System.Text
Imports System.Globalization

 Public Function DECODE(ByVal x As String) As String
        Dim sb As New StringBuilder
        For Each c As Char In x.Normalize(NormalizationForm.FormD).Where(Function(a) CharUnicodeInfo.GetUnicodeCategory(a) <> UnicodeCategory.NonSpacingMark)  
            sb.Append(c)
        Next
        Return sb.ToString()
    End Function

How can I use goto in Javascript?

There is a way this can be done, but it needs to be planned carefully. Take for example the following QBASIC program:

1 A = 1; B = 10;
10 print "A = ",A;
20 IF (A < B) THEN A = A + 1; GOTO 10
30 PRINT "That's the end."

Then create your JavaScript to initialize all variables first, followed by making an initial function call to start the ball rolling (we execute this initial function call at the end), and set up functions for every set of lines that you know will be executed in the one unit.

Follow this with the initial function call...

var a, b;
function fa(){
    a = 1;
    b = 10;
    fb();
}
function fb(){
    document.write("a = "+ a + "<br>");
    fc();
}
function fc(){
    if(a<b){
        a++;
        fb();
        return;
    }
    else
    {
    document.write("That's the end.<br>");
    }
}
fa();

The result in this instance is:

a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
a = 7
a = 8
a = 9
a = 10
That's the end.

Matplotlib-Animation "No MovieWriters Available"

I'm running Ubuntu 20 and I had a similar problem

Installed ffmpeg

pip install ffmpeg

then

sudo apt install ffmpeg

Multiple INSERT statements vs. single INSERT with multiple VALUES

The issue probably has to do with the time it takes to compile the query.

If you want to speed up the inserts, what you really need to do is wrap them in a transaction:

BEGIN TRAN;
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('6f3f7257-a3d8-4a78-b2e1-c9b767cfe1c1', 'First 0', 'Last 0', 0);
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('32023304-2e55-4768-8e52-1ba589b82c8b', 'First 1', 'Last 1', 1);
...
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('f34d95a7-90b1-4558-be10-6ceacd53e4c4', 'First 999', 'Last 999', 999);
COMMIT TRAN;

From C#, you might also consider using a table valued parameter. Issuing multiple commands in a single batch, by separating them with semicolons, is another approach that will also help.

Python Selenium Chrome Webdriver

You need to specify the path where your chromedriver is located.

  1. Download chromedriver for your desired platform from here.

  2. Place chromedriver on your system path, or where your code is.

  3. If not using a system path, link your chromedriver.exe (For non-Windows users, it's just called chromedriver):

    browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
    

    (Set executable_path to the location where your chromedriver is located.)

    If you've placed chromedriver on your System Path, you can shortcut by just doing the following:

    browser = webdriver.Chrome()

  4. If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:

    chmod +x chromedriver

  5. That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium

Are (non-void) self-closing tags valid in HTML5?

I would be very careful with self closing tags as this example demonstrates:

var a = '<span/><span/>';
var d = document.createElement('div');
d.innerHTML = a
console.log(d.innerHTML) // "<span><span></span></span>"

My gut feeling would have been <span></span><span></span> instead

How do you change Background for a Button MouseOver in WPF?

This worked well for me.

Button Style

<Style x:Key="TransparentStyle" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border>
                    <Border.Style>
                        <Style TargetType="{x:Type Border}">
                            <Style.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Background" Value="DarkGoldenrod"/>
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Border.Style>
                    <Grid Background="Transparent">
                        <ContentPresenter></ContentPresenter>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Button

<Button Style="{StaticResource TransparentStyle}" VerticalAlignment="Top" HorizontalAlignment="Right" Width="25" Height="25"
        Command="{Binding CloseWindow}">
    <Button.Content >
        <Grid Margin="0 0 0 0">
            <Path Data="M0,7 L10,17 M0,17 L10,7" Stroke="Blue" StrokeThickness="2" HorizontalAlignment="Center" Stretch="None" />
        </Grid>
    </Button.Content>
</Button>

Notes

  • The button displays a little blue cross, much like the one used to close a window.
  • By setting the background of the grid to "Transparent", it adds a hittest, which means that if the mouse is anywhere over the button, then it will work. Omit this tag, and the button will only light up if the mouse is over one of the vector lines in the icon (this is not very usable).

What's the difference between .bashrc, .bash_profile, and .environment?

The main difference with shell config files is that some are only read by "login" shells (eg. when you login from another host, or login at the text console of a local unix machine). these are the ones called, say, .login or .profile or .zlogin (depending on which shell you're using).

Then you have config files that are read by "interactive" shells (as in, ones connected to a terminal (or pseudo-terminal in the case of, say, a terminal emulator running under a windowing system). these are the ones with names like .bashrc, .tcshrc, .zshrc, etc.

bash complicates this in that .bashrc is only read by a shell that's both interactive and non-login, so you'll find most people end up telling their .bash_profile to also read .bashrc with something like

[[ -r ~/.bashrc ]] && . ~/.bashrc

Other shells behave differently - eg with zsh, .zshrc is always read for an interactive shell, whether it's a login one or not.

The manual page for bash explains the circumstances under which each file is read. Yes, behaviour is generally consistent between machines.

.profile is simply the login script filename originally used by /bin/sh. bash, being generally backwards-compatible with /bin/sh, will read .profile if one exists.

Filter LogCat to get only the messages from My Application in Android?

This has been working for me in git bash:

$ pid=$(adb shell ps | grep <package name> | cut -c11-15) ; adb logcat | grep $pid

Android saving file to external storage

Click Here for full description and source code

public void saveImage(Context mContext, Bitmap bitmapImage) {

  File sampleDir = new File(Environment.getExternalStorageDirectory() + "/" + "ApplicationName");

  TextView tvImageLocation = (TextView) findViewById(R.id.tvImageLocation);
  tvImageLocation.setText("Image Store At : " + sampleDir);

  if (!sampleDir.exists()) {
      createpathForImage(mContext, bitmapImage, sampleDir);
  } else {
      createpathForImage(mContext, bitmapImage, sampleDir);
  }
}

How to convert a PIL Image into a numpy array?

If your image is stored in a Blob format (i.e. in a database) you can use the same technique explained by Billal Begueradj to convert your image from Blobs to a byte array.

In my case, I needed my images where stored in a blob column in a db table:

def select_all_X_values(conn):
    cur = conn.cursor()
    cur.execute("SELECT ImageData from PiecesTable")    
    rows = cur.fetchall()    
    return rows

I then created a helper function to change my dataset into np.array:

X_dataset = select_all_X_values(conn)
imagesList = convertToByteIO(np.array(X_dataset))

def convertToByteIO(imagesArray):
    """
    # Converts an array of images into an array of Bytes
    """
    imagesList = []

    for i in range(len(imagesArray)):  
        img = Image.open(BytesIO(imagesArray[i])).convert("RGB")
        imagesList.insert(i, np.array(img))

    return imagesList

After this, I was able to use the byteArrays in my Neural Network.

plt.imshow(imagesList[0])

How to prepare a Unity project for git?

On the Unity Editor open your project and:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository (only if Unity ver < 4.5)
  2. Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save Scene and Project from File menu.
  5. Quit Unity and then you can delete the Library and Temp directory in the project directory. You can delete everything but keep the Assets and ProjectSettings directory.

If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:

cd to/your/unity/project/folder

git init

git add *

git commit -m "First commit"

git remote add origin [email protected]:username/project.git

git push -u origin master

You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).

Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.

And here's my own .gitignore recipe for my Unity projects:

# =============== #
# Unity generated #
# =============== #
Temp/
Obj/
UnityGenerated/
Library/
Assets/AssetStoreTools*

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db

Java generics - ArrayList initialization

Think of the ? as to mean "unknown". Thus, "ArrayList<? extends Object>" is to say "an unknown type that (or as long as it)extends Object". Therefore, needful to say, arrayList.add(3) would be putting something you know, into an unknown. I.e 'Forgetting'.

How to input a regex in string.replace?

str.replace() does fixed replacements. Use re.sub() instead.

How to convert CLOB to VARCHAR2 inside oracle pl/sql

Converting VARCHAR2 to CLOB

In PL/SQL a CLOB can be converted to a VARCHAR2 with a simple assignment, SUBSTR, and other methods. A simple assignment will only work if the CLOB is less then or equal to the size of the VARCHAR2. The limit is 32767 in PL/SQL and 4000 in SQL (although 12c allows 32767 in SQL).

For example, this code converts a small CLOB through a simple assignment and then coverts the beginning of a larger CLOB.

declare
    v_small_clob clob := lpad('0', 1000, '0');
    v_large_clob clob := lpad('0', 32767, '0') || lpad('0', 32767, '0');
    v_varchar2   varchar2(32767);
begin
    v_varchar2 := v_small_clob;
    v_varchar2 := substr(v_large_clob, 1, 32767);
end;

LONG?

The above code does not convert the value to a LONG. It merely looks that way because of limitations with PL/SQL debuggers and strings over 999 characters long.

For example, in PL/SQL Developer, open a Test window and add and debug the above code. Right-click on v_varchar2 and select "Add variable to Watches". Step through the code and the value will be set to "(Long Value)". There is a ... next to the text but it does not display the contents. PLSQL Developer Long Value

C#?

I suspect the real problem here is with C# but I don't know how enough about C# to debug the problem.

Excel VBA Password via Hex Editor

I have your answer, as I just had the same problem today:

Someone made a working vba code that changes the vba protection password to "macro", for all excel files, including .xlsm (2007+ versions). You can see how it works by browsing his code.

This is the guy's blog: http://lbeliarl.blogspot.com/2014/03/excel-removing-password-from-vba.html Here's the file that does the work: https://docs.google.com/file/d/0B6sFi5sSqEKbLUIwUTVhY3lWZE0/edit

Pasted from a previous post from his blog:

For Excel 2007/2010 (.xlsm) files do following steps:

  1. Create a new .xlsm file.
  2. In the VBA part, set a simple password (for instance 'macro').
  3. Save the file and exit.
  4. Change file extention to '.zip', open it by any archiver program.
  5. Find the file: 'vbaProject.bin' (in 'xl' folder).
  6. Extract it from archive.
  7. Open the file you just extracted with a hex editor.
  8. Find and copy the value from parameter DPB (value in quotation mark), example: DPB="282A84CBA1CBA1345FCCB154E20721DE77F7D2378D0EAC90427A22021A46E9CE6F17188A". (This value generated for 'macro' password. You can use this DPB value to skip steps 1-8)

  9. Do steps 4-7 for file with unknown password (file you want to unlock).

  10. Change DBP value in this file on value that you have copied in step 8.

    If copied value is shorter than in encrypted file you should populate missing characters with 0 (zero). If value is longer - that is not a problem (paste it as is).

  11. Save the 'vbaProject.bin' file and exit from hex editor.

  12. Replace existing 'vbaProject.bin' file with modified one.
  13. Change extention from '.zip' back to '.xlsm'
  14. Now, open the excel file you need to see the VBA code in. The password for the VBA code will simply be macro (as in the example I'm showing here).

Enabling/installing GD extension? --without-gd

if you are on a Debian based server (such as Ubuntu) you can run the following command:

apt-get install php-gd

Then once it is complete run:

/etc/init.d/apache2 restart

This will restart your server and enable GD in PHP.

If you are on another type of system you will need to use something else (like yum install) or compile directly into PHP.

Why does git perform fast-forward merges by default?

Let me expand a bit on a VonC's very comprehensive answer:


First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.

Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".


Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.

HTH

Add 10 seconds to a Date

Try this way.

Date.prototype.addSeconds = function(seconds) {
  var copiedDate = new Date(this.getTime());
  return new Date(copiedDate.getTime() + seconds * 1000);
}

Just call and assign new Date().addSeconds(10)

Inserting a string into a list without getting split into characters

I suggest to add the '+' operator as follows:

list = list + ['foo']

Hope it helps!

How Does Modulus Divison Work

Modulus division is pretty simple. It uses the remainder instead of the quotient.

    1.0833... <-- Quotient
   __
12|13
   12
    1 <-- Remainder
    1.00 <-- Remainder can be used to find decimal values
     .96
     .040
     .036
     .0040 <-- remainder of 4 starts repeating here, so the quotient is 1.083333...

13/12 = 1R1, ergo 13%12 = 1.


It helps to think of modulus as a "cycle".

In other words, for the expression n % 12, the result will always be < 12.

That means the sequence for the set 0..100 for n % 12 is:

{0,1,2,3,4,5,6,7,8,9,10,11,0,1,2,3,4,5,6,7,8,9,10,11,0,[...],4}

In that light, the modulus, as well as its uses, becomes much clearer.

in a "using" block is a SqlConnection closed on return or exception?

Dispose simply gets called when you leave the scope of using. The intention of "using" is to give developers a guaranteed way to make sure that resources get disposed.

From MSDN:

A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.

How to parse a text file with C#

One way that I've found really useful in situations like this is to go old-school and use the Jet OLEDB provider, together with a schema.ini file to read large tab-delimited files in using ADO.Net. Obviously, this method is really only useful if you know the format of the file to be imported.

public void ImportCsvFile(string filename)
{
    FileInfo file = new FileInfo(filename);

    using (OleDbConnection con = 
            new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
            file.DirectoryName + "\";
            Extended Properties='text;HDR=Yes;FMT=TabDelimited';"))
    {
        using (OleDbCommand cmd = new OleDbCommand(string.Format
                                  ("SELECT * FROM [{0}]", file.Name), con))
        {
            con.Open();

            // Using a DataReader to process the data
            using (OleDbDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    // Process the current reader entry...
                }
            }

            // Using a DataTable to process the data
            using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
            {
                DataTable tbl = new DataTable("MyTable");
                adp.Fill(tbl);

                foreach (DataRow row in tbl.Rows)
                {
                    // Process the current row...
                }
            }
        }
    }
} 

Once you have the data in a nice format like a datatable, filtering out the data you need becomes pretty trivial.

Variable length (Dynamic) Arrays in Java

I answered this question and no you do not need an arraylist or any other thing this was an assignment and I completed it so yes arrays can increase in size. Here is the link How to use Java Dynamic Array and here is the link for my question which i answered Java Dynamic arrays

Refer to a cell in another worksheet by referencing the current worksheet's name?

Here is how I made monthly page in similar manner as Fernando:

  1. I wrote manually on each page number of the month and named that place as ThisMonth. Note that you can do this only before you make copies of the sheet. After copying Excel doesn't allow you to use same name, but with sheet copy it does it still. This solution works also without naming.
  2. I added number of weeks in the month to location C12. Naming is fine also.
  3. I made five weeks on every page and on fifth week I made function

      =IF(C12=5,DATE(YEAR(B48),MONTH(B48),DAY(B48)+7),"")
    

    that empties fifth week if this month has only four weeks. C12 holds the number of weeks.

  4. ...
  5. I created annual Excel, so I had 12 sheets in it: one for each month. In this example name of the sheet is "Month". Note that this solutions works also with the ODS file standard except you need to change all spaces as "_" characters.
  6. I renamed first "Month" sheet as "Month (1)" so it follows the same naming principle. You could also name it as "Month1" if you wish, but "January" would require a bit more work.
  7. Insert following function on the first day field starting sheet #2:

     =INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!B15"))+INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!C12"))*7
    

    So in another word, if you fill four or five weeks on the previous sheet, this calculates date correctly and continues from correct date.

Convert string to a variable name

assign is good, but I have not found a function for referring back to the variable you've created in an automated script. (as.name seems to work the opposite way). More experienced coders will doubtless have a better solution, but this solution works and is slightly humorous perhaps, in that it gets R to write code for itself to execute.

Say I have just assigned value 5 to x (var.name <- "x"; assign(var.name, 5)) and I want to change the value to 6. If I am writing a script and don't know in advance what the variable name (var.name) will be (which seems to be the point of the assign function), I can't simply put x <- 6 because var.name might have been "y". So I do:

var.name <- "x"
#some other code...
assign(var.name, 5)
#some more code...

#write a script file (1 line in this case) that works with whatever variable name
write(paste0(var.name, " <- 6"), "tmp.R")
#source that script file
source("tmp.R")
#remove the script file for tidiness
file.remove("tmp.R")

x will be changed to 6, and if the variable name was anything other than "x", that variable will similarly have been changed to 6.

Left Join without duplicate rows from left table

You can do this using generic SQL with group by:

SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
     tbl_Media M
     ON M.Content_Id = C.Content_Id 
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;

Or with a correlated subquery:

SELECT C.Content_ID, C.Contt_Title,
       (SELECT M.Media_Id
        FROM tbl_Media M
        WHERE M.Content_Id = C.Content_Id
        ORDER BY M.MEDIA_ID DESC
        LIMIT 1
       ) as Media_Id
FROM tbl_Contents C 
ORDER BY C.Content_DatePublished ASC;

Of course, the syntax for limit 1 varies between databases. Could be top. Or rownum = 1. Or fetch first 1 rows. Or something like that.

How to convert IPython notebooks to PDF and HTML?

Only this answer would be useful to you if you have math, scientific formulae in your document. Even if you don't have them it works fine.

GUI way

  • open the jupyter notebook open the jupyter notebook

  • Go to Files > Download as > HTML or PDF via LaTeX Go to Files > Download as > HTML or PDF via LaTeX

  • Then check your Downloads folder for the file. PS: If LaTeX had any errors while compiling the PDF, it will fail. If this happens, download the HTML file and then use Web page to PDF tool or any other similar service to convert the HTML to PDF.

Command-Line way

  • Open the terminal
  • Navigate to the folder containing the jupyter notebook
  • type "jupyter nbconvert --to pdf your_jupyter_notebook.ipynb "

PS: If it fails, try Yogesh's answer.

Execute action when back bar button of UINavigationController is pressed

    override public func viewDidLoad() {
         super.viewDidLoad()
         self.navigationController?.navigationBar.topItem?.title = GlobalVariables.selectedMainIconName
         let image = UIImage(named: "back-btn")

         image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(Current[enter image description here][1]ViewController.back) )
    }

    func back() {
      self.navigationController?.popToViewController( self.navigationController!.viewControllers[ self.navigationController!.viewControllers.count - 2 ], animated: true)
    }

Fatal error: Call to undefined function mysql_connect()

Use. <?php $con = mysqli_connect('localhost', 'username', 'password', 'database'); ?>

In PHP 7. You probably have PHP 7 in XAMPP. You now have two option: MySQLi and PDO.

Android WSDL/SOAP service client

Android doesn't come with SOAP library. However, you can download 3rd party library here:
https://github.com/simpligility/ksoap2-android

If you need help using it, you might find this thread helpful:
How to call a .NET Webservice from Android using KSOAP2?

Setting up maven dependency for SQL Server

Be careful with the answers above. sqljdbc4.jar is not distributed with under a public license which is why it is difficult to include it in a jar for runtime and distribution. See my answer below for more details and a much better solution. Your life will become much easier as mine did once I found this answer.

https://stackoverflow.com/a/30111956/3368958

How to resolve the error on 'react-native start'

On windows 10 i highly recommend to install Linux Bash Shell.

Here is a nice guide to set it up: https://www.howtogeek.com/249966/how-to-install-and-use-the-linux-bash-shell-on-windows-10/

just follow the steps, choose your linux distribution and avoid as much possible to work with node on cmd since obvious instability.

Take in consideration Microsoft strongly warns against adding or modifying Linux files with Windows software, as described here: howtogeek.com/261383/how-to-access-your-ubuntu-bash-files-in-windows-and-your-windows-system-drive-in-bash/

Hope it helps!

Error ITMS-90717: "Invalid App Store Icon"

If you don't have a mac, on windows you can open Paint and save as PNG with correct dimensions 1024x1024

Check if checkbox is NOT checked on click - jQuery

Check out some of the answers to this question - I think it might apply to yours:

how to run click function after default behaviour of a element

I think you're running into an inconsistency in the browser implementation of the onclick function. Some choose to toggle the checkbox before the event is fired and some after.

Properties private set;

This is one possible solution although not very clean:

  1. Make the property you need to expose to BAL & DAL internal
  2. Mark BAL.dll & DAL.dll Internal Visible in assemblyinfo.cs

public class Person
{
    public Person(int id)
    {
         this.Id=id;
    }

    public string Name { get;  set; }
    public int Id { get; internal set; }
    public int Age { get; set; }
}

AssemblyInfo.cs for Entities.dll

[assembly: InternalsVisibleTo("DAL"), InternalsVisibleTo("BAL")]

That way all your internals will be visible to DAL & BAL. This may not be desirable but I'm just suggesting one possible solution.

This project references NuGet package(s) that are missing on this computer

For me it worked as I just copied a .nuget folder from a working solution to the existing one, and referenced it's content!

In AVD emulator how to see sdcard folder? and Install apk to AVD?

I have used the following procedure.

Android Studio 3.4.1

View>Tool Windows>Device File Explorer

enter image description here

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

Just in case anyone will search for it - I used it on several sites, always the customization and RD possibilities were a perfect fit for what I needed. Simple and it is free to use:

Clickable CSS Maps

One note for more scripts on a site: I had some annoying problems with getting to work a map (that worked as a graphic menu) in Drupal 7. There where many other script used, and after handling them, I got stuck with the map - it still didn't work, although the jquery.cssmap.js, CSS (both local) and the script in the where in the right place. Firebug showed me an error and I suddenly eureka - a simple oversight, I left the script code as it was in the example and there was a conflict. Just change the front function "$" to "jQuery" (or other handler) and it works perfect. :]

Here's what I ment (of course you can put it before instead of the ):

_x000D_
_x000D_
<script type="text/javascript">_x000D_
      jQuery(function($){_x000D_
        $('#map-country').cssMap({'size' : 810});_x000D_
       });_x000D_
    </script>
_x000D_
_x000D_
_x000D_

PostgreSQL 'NOT IN' and subquery

You could also use a LEFT JOIN and IS NULL condition:

SELECT 
  mac, 
  creation_date 
FROM 
  logs
    LEFT JOIN consols ON logs.mac = consols.mac
WHERE 
  logs_type_id=11
AND
  consols.mac IS NULL;

An index on the "mac" columns might improve performance.

How to select a value in dropdown javascript?

The simplest possible solution if you know the value

document.querySelector('option[value=" + value +"]').selected = true

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Make sure the user you are using to access your database has the privileges to do so.
GRANT ALL PRIVILEGES ON * . * TO 'user'@'localhost';
Where the first star can be replaced by database name, second star specifies table. Make sure to flush privileges after.

Authentication plugin 'caching_sha2_password' is not supported

I was facing the same error for 2 days, then finally I found a solution. I checked for all the installed connectors using pip list and uninstalled all the connectors. In my case they were:

  1. mysql-connector
  2. mysql-connector-python
  3. mysql-connector-python-rf

Uninstalled them using pip uninstall mysql-connector and finally downloaded and installed the mysql-connector-python from MySQL official website and it works well.

How to check whether mod_rewrite is enable on server?

  1. To check if mod_rewrite module is enabled, create a new php file in your root folder of your WAMP server. Enter the following

    phpinfo();

  2. Access your created file from your browser.

  3. CtrlF to open a search. Search for 'mod_rewrite'. If it is enabled you see it as 'Loaded Modules'

  4. If not, open httpd.conf (Apache Config file) and look for the following line.

    #LoadModule rewrite_module modules/mod_rewrite.so

  5. Remove the pound ('#') sign at the start and save the this file.

  6. Restart your apache server.

  7. Access the same php file in your browser.

  8. Search for 'mod_rewrite' again. You should be able to find it now.

break statement in "if else" - java

The "break" command does not work within an "if" statement.

If you remove the "break" command from your code and then test the code, you should find that the code works exactly the same without a "break" command as with one.

"Break" is designed for use inside loops (for, while, do-while, enhanced for and switch).

How should I escape commas and speech marks in CSV files so they work in Excel?

Below are the rules if you believe it's random. A utility function can be created on the basis of these rules.

  1. If the value contains a comma, newline or double quote, then the String value should be returned enclosed in double quotes.

  2. Any double quote characters in the value should be escaped with another double quote.

  3. If the value does not contain a comma, newline or double quote, then the String value should be returned unchanged.

Multi-threading in VBA

As you probably learned VBA does not natively support multithreading but. There are 3 methods to achieve multithreading:

  1. COM/dlls - e.g. C# and the Parallel class to run in separate threads
  2. Using VBscript worker threads - run your VBA code in separate VBscript threads
  3. Using VBA worker threads executed e.g. via VBscript - copy the Excel workbook and run your macro in parallel.

I compared all thread approaches here: http://analystcave.com/excel-multithreading-vba-vs-vbscript-vs-c-net/

Considering approach #3 I also made a VBA Multithreading Tool that allows you to easily add multithreading to VBA: http://analystcave.com/excel-vba-multithreading-tool/

See the examples below:

Multithreading a For Loop

Sub RunForVBA(workbookName As String, seqFrom As Long, seqTo As Long)
    For i = seqFrom To seqTo
        x = seqFrom / seqTo
    Next i
End Sub

Sub RunForVBAMultiThread()
    Dim parallelClass As Parallel 

    Set parallelClass = New Parallel 

    parallelClass.SetThreads 4 

    Call parallelClass.ParallelFor("RunForVBA", 1, 1000) 
End Sub

Run an Excel macro asynchronously

Sub RunAsyncVBA(workbookName As String, seqFrom As Long, seqTo As Long)
    For i = seqFrom To seqTo
        x = seqFrom / seqTo
    Next i
End Sub

Sub RunForVBAAndWait()
    Dim parallelClass As Parallel

    Set parallelClass  = New Parallel

    Call parallelClass.ParallelAsyncInvoke("RunAsyncVBA", ActiveWorkbook.Name, 1, 1000) 
    'Do other operations here
    '....

    parallelClass.AsyncThreadJoin 
End Sub

Password encryption/decryption code in .NET

You can use the managed .Net cryptography library, then save the encrypted string into the database. When you want to verify the password you can compare the stored database string with the hashed value of the user input. See here for more info about SHA512Managed

using System.Security.Cryptography;

    public static string EncryptSHA512Managed(string password)
    {
        UnicodeEncoding uEncode = new UnicodeEncoding();
        byte[] bytPassword = uEncode.GetBytes(password);
        SHA512Managed sha = new SHA512Managed();
        byte[] hash = sha.ComputeHash(bytPassword);
        return Convert.ToBase64String(hash);
    }

Using context in a fragment

Use fragments from Support Library -

android.support.v4.app.Fragment

and then override

void onAttach (Context context) {
  this.context = context;
}

This way you can be sure that context will always be a non-null value.

Combine several images horizontally with Python

If all image’s heights are same,

imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
  np.concatenate(
    [np.array(Image.open(x)) for x in imgs],
    axis=1
  )
)

maybe you can resize images before the concatenation like this,

imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
  np.concatenate(
    [np.array(Image.open(x).resize((640,480)) for x in imgs],
    axis=1
  )
)

What is the difference between document.location.href and document.location?

document.location is deprecated in favor of window.location, which can be accessed by just location, since it's a global object.

The location object has multiple properties and methods. If you try to use it as a string then it acts like location.href.

MySql sum elements of a column

select
  sum(a) as atotal,
  sum(b) as btotal,
  sum(c) as ctotal
from
  yourtable t
where
  t.id in (1, 2, 3)

Calculate difference between 2 date / times in Oracle SQL

Here's another option:

with tbl_demo AS
    (SELECT TO_DATE('11/26/2013 13:18:50', 'MM/DD/YYYY HH24:MI:SS') dt1
   , TO_DATE('11/28/2013 21:59:12', 'MM/DD/YYYY HH24:MI:SS') dt2 
     FROM dual)
SELECT dt1
     , dt2
     , round(dt2 - dt1,2) diff_days
     , round(dt2 - dt1,2)*24 diff_hrs
     , numtodsinterval((dt2 - dt1),'day') diff_dd_hh_mm_ss
  from tbl_demo;

When should I use Memcache instead of Memcached?

Memcached is a newer API, it also provides memcached as a session provider which could be great if you have a farm of server.

After the version is still really low 0.2 but I have used both and I didn't encounter major problem, so I would go to memcached since it's new.

fastest way to export blobs from table into individual files

For me what worked by combining all the posts I have read is:

1.Enable OLE automation - if not enabled

sp_configure 'show advanced options', 1;  
GO  
RECONFIGURE;  
GO  
sp_configure 'Ole Automation Procedures', 1;  
GO  
RECONFIGURE;  
GO

2.Create a folder where the generated files will be stored:

C:\GREGTESTING

3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
enter image description here

CREATE TABLE [dbo].[Document](
    [Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [Extension] [varchar](50) NULL,
    [FileName] [varchar](200) NULL,
    [Doc_Content] [varbinary](max) NULL   
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
    SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)

Important note!

Don't forget to add in Doc_Content column the varbinary of file you want to generate!

4.Run the below script

DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max) 
, @fPath varchar(max)  
, @folderPath  varchar(max)

--Get Data into temp Table variable so that we can iterate over it 
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num]  varchar(100) , [FileName]  varchar(100), [Doc_Content] varBinary(max) )



INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM  [dbo].[Document]



SELECT @i = COUNT(1) FROM @Doctable   

WHILE @i >= 1   

BEGIN    

SELECT 
    @data = [Doc_Content],
    @fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
    @folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;  
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+  @fPath   

--Reset the variables for next use
SELECT @data = NULL  
, @init = NULL
, @fPath = NULL  
, @folderPath = NULL
SET @i -= 1
END   

5.The results is shown below: enter image description here

Updating .class file in jar

Jar is an archive, you can replace a file in it by yourself in your favourite file manager (Total Commander for example).

SignalR Console app example

To build on @dyslexicanaboko's answer for dotnet core, here is a client console application:

Create a helper class:

using System;
using Microsoft.AspNetCore.SignalR.Client;

namespace com.stackoverflow.SignalRClientConsoleApp
{
    public class SignalRConnection
    {
        public async void Start()
        {
            var url = "http://signalr-server-url/hubname";

            var connection = new HubConnectionBuilder()
                .WithUrl(url)
                .WithAutomaticReconnect()
                .Build();

            // receive a message from the hub
            connection.On<string, string>("ReceiveMessage", (user, message) => OnReceiveMessage(user, message));

            var t = connection.StartAsync();

            t.Wait();

            // send a message to the hub
            await connection.InvokeAsync("SendMessage", "ConsoleApp", "Message from the console app");
        }

        private void OnReceiveMessage(string user, string message)
        {
            Console.WriteLine($"{user}: {message}");
        }

    }
}

Then implement in your console app's entry point:

using System;

namespace com.stackoverflow.SignalRClientConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var signalRConnection = new SignalRConnection();
            signalRConnection.Start();

            Console.Read();
        }
    }
}

How to format number of decimal places in wpf using style/template?

You should use the StringFormat on the Binding. You can use either standard string formats, or custom string formats:

<TextBox Text="{Binding Value, StringFormat=N2}" />
<TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" />

Note that the StringFormat only works when the target property is of type string. If you are trying to set something like a Content property (typeof(object)), you will need to use a custom StringFormatConverter (like here), and pass your format string as the ConverterParameter.

Edit for updated question

So, if your ViewModel defines the precision, I'd recommend doing this as a MultiBinding, and creating your own IMultiValueConverter. This is pretty annoying in practice, to go from a simple binding to one that needs to be expanded out to a MultiBinding, but if the precision isn't known at compile time, this is pretty much all you can do. Your IMultiValueConverter would need to take the value, and the precision, and output the formatted string. You'd be able to do this using String.Format.

However, for things like a ContentControl, you can much more easily do this with a Style:

<Style TargetType="{x:Type ContentControl}">
    <Setter Property="ContentStringFormat" 
            Value="{Binding Resolution, StringFormat=N{0}}" />
</Style>

Any control that exposes a ContentStringFormat can be used like this. Unfortunately, TextBox doesn't have anything like that.

What are OLTP and OLAP. What is the difference between them?

OLTP: It stands for OnLine Transaction Processing and is used for managing current day to day data information.
OLAP: It stands for OnLine Analytical Processing and is used to maintain the past history of data and mainly used for data analysis, it can also be referred to as warehouse.

Java 8 Lambda filter by Lists

Look this:

List<Client> result = clients
    .stream()
    .filter(c -> 
        (users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
        .collect(Collectors.toList());

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

git: How to diff changed files versus previous versions after a pull?

If you do a straight git pull then you will either be 'fast-forwarded' or merge an unknown number of commits from the remote repository. This happens as one action though, so the last commit that you were at immediately before the pull will be the last entry in the reflog and can be accessed as HEAD@{1}. This means that you can do:

git diff HEAD@{1}

However, I would strongly recommend that if this is something you find yourself doing a lot then you should consider just doing a git fetch and examining the fetched branch before manually merging or rebasing onto it. E.g. if you're on master and were going to pull in origin/master:

git fetch

git log HEAD..origin/master

 # looks good, lets merge

git merge origin/master

How to know when a web page was last updated?

In general, there is no way to know when something on another site has been changed. If the site offers an RSS feed, you should try that. If the site does not offer an RSS feed (or if the RSS feed doesn't include the information you're looking for), then you have to scrape and compare.

Why is Tkinter Entry's get function returning nothing?

you need to put a textvariable in it, so you can use set() and get() method :

var=StringVar()
x= Entry (root,textvariable=var)

Declare and initialize a Dictionary in Typescript

Edit: This has since been fixed in the latest TS versions. Quoting @Simon_Weaver's comment on the OP's post:

Note: this has since been fixed (not sure which exact TS version). I get these errors in VS, as you would expect: Index signatures are incompatible. Type '{ firstName: string; }' is not assignable to type 'IPerson'. Property 'lastName' is missing in type '{ firstName: string; }'.


Apparently this doesn't work when passing the initial data at declaration. I guess this is a bug in TypeScript, so you should raise one at the project site.

You can make use of the typed dictionary by splitting your example up in declaration and initialization, like:

var persons: { [id: string] : IPerson; } = {};
persons["p1"] = { firstName: "F1", lastName: "L1" };
persons["p2"] = { firstName: "F2" }; // will result in an error

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

I had a similar experience with Chai-Webdriver for Selenium. I added await to the assertion and it fixed the issue:

Example using Cucumberjs:

Then(/I see heading with the text of Tasks/, async function() {
    await chai.expect('h1').dom.to.contain.text('Tasks');
});

Create session factory in Hibernate 4

Try this!

package your.package;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil
{
    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    static
    {
        try
        {
//          Configuration configuration = new Configuration();
            Configuration configuration = new Configuration().configure();

            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
        catch (HibernateException he)
        {
            System.err.println("Error creating Session: " + he);
            throw new ExceptionInInitializerError(he);
        }
    }

    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    } 
}