Programs & Examples On #Jsr196

JSR 196: Java Authentication Service Provider Interface for Containers

Restricting input to textbox: allowing only numbers and decimal point

I chose to tackle this on the oninput event in order to handle the issue for keyboard pasting, mouse pasting and key strokes. Pass true or false to indicate decimal or integer validation.

It's basically three steps in three one liners. If you don't want to truncate the decimals comment the third step. Adjustments for rounding can be made in the third step as well.

// Example Decimal usage;
// <input type="text"  oninput="ValidateNumber(this, true);" />
// Example Integer usage:
// <input type="text"  oninput="ValidateNumber(this, false);" />
function ValidateNumber(elm, isDecimal) {
    try {

        // For integers, replace everything except for numbers with blanks.
        if (!isDecimal) 
            elm.value = elm.value.replace(/[^0-9]/g, ''); 
        else {
            // 1. For decimals, replace everything except for numbers and periods with blanks.
            // 2. Then we'll remove all leading ocurrences (duplicate) periods
            // 3. Then we'll chop off anything after two decimal places.

            // 1. replace everything except for numbers and periods with blanks.
            elm.value = elm.value.replace(/[^0-9.]/g, '');

            //2. remove all leading ocurrences (duplicate) periods
            elm.value = elm.value.replace(/\.(?=.*\.)/g, '');

            // 3. chop off anything after two decimal places.
            // In comparison to lengh, our index is behind one count, then we add two for our decimal places.
            var decimalIndex = elm.value.indexOf('.');
            if (decimalIndex != -1) { elm.value = elm.value.substr(0, decimalIndex + 3); }
        }
    }
    catch (err) {
        alert("ValidateNumber " + err);
    }
}

Why does the 260 character path length limit exist in Windows?

As to how to cope with the path size limitation on Windows - using 7zip to pack (and unpack) your path-length sensitive files seems like a viable workaround. I've used it to transport several IDE installations (those Eclipse plugin paths, yikes!) and piles of autogenerated documentation and haven't had a single problem so far.

Not really sure how it evades the 260 char limit set by Windows (from a technical PoV), but hey, it works!

More details on their SourceForge page here:

"NTFS can actually support pathnames up to 32,000 characters in length."

7-zip also support such long names.

But it's disabled in SFX code. Some users don't like long paths, since they don't understand how to work with them. That is why I have disabled it in SFX code.

and release notes:

9.32 alpha 2013-12-01

  • Improved support for file pathnames longer than 260 characters.

4.44 beta 2007-01-20

  • 7-Zip now supports file pathnames longer than 260 characters.

IMPORTANT NOTE: For this to work properly, you'll need to specify the destination path in the 7zip "Extract" dialog directly, rather than dragging & dropping the files into the intended folder. Otherwise the "Temp" folder will be used as an interim cache and you'll bounce into the same 260 char limitation once Windows Explorer starts moving the files to their "final resting place". See the replies to this question for more information.

How do I install Python packages in Google's Colab?

Joining the party late, but just as a complement, I ran into some problems with Seaborn not so long ago, because CoLab installed a version with !pip that wasn't updated. In my specific case, I couldn't use Scatterplot, for example. The answer to this is below:

To install the module, all you need is:

!pip install seaborn

To upgrade it to the most updated version:

!pip install --upgrade seaborn

If you want to install a specific version

!pip install seaborn==0.9.0

I believe all the rules common to pip apply normally, so that pretty much should work.

Regular expression search replace in Sublime Text 2

Important: Use the ( ) parentheses in your search string

While the previous answer is correct there is an important thing to emphasize! All the matched segments in your search string that you want to use in your replacement string must be enclosed by ( ) parentheses, otherwise these matched segments won't be accessible to defined variables such as $1, $2 or \1, \2 etc.

For example we want to replace 'em' with 'px' but preserve the digit values:

    margin: 10em;  /* Expected: margin: 10px */
    margin: 2em;   /* Expected: margin: 2px */
  • Replacement string: margin: $1px or margin: \1px
  • Search string (CORRECT): margin: ([0-9]*)em // with parentheses
  • Search string (INCORRECT): margin: [0-9]*em

CORRECT CASE EXAMPLE: Using margin: ([0-9]*)em search string (with parentheses). Enclose the desired matched segment (e.g. $1 or \1) by ( ) parentheses as following:

  • Find: margin: ([0-9]*)em (with parentheses)
  • Replace to: margin: $1px or margin: \1px
  • Result:
    margin: 10px;
    margin: 2px;

INCORRECT CASE EXAMPLE: Using margin: [0-9]*em search string (without parentheses). The following regex pattern will match the desired lines but matched segments will not be available in replaced string as variables such as $1 or \1:

  • Find: margin: [0-9]*em (without parentheses)
  • Replace to: margin: $1px or margin: \1px
  • Result:
    margin: px; /* `$1` is undefined */
    margin: px; /* `$1` is undefined */

How to set breakpoints in inline Javascript in Google Chrome?

I know the Q is not about Firefox but I did not want to add a copy of this question to just answer it myself.

For Firefox you need to add debugger; to be able to do what @matt-ball suggested for the script tag.

So on your code, you add debugger above the line you want to debug and then you can add breakpoints. If you just set the breakpoints on the browser it won't stop.

If this is not the place to add a Firefox answer given that the question is about Chrome. Don't :( minus the answer just let me know where I should post it and I'll happily move the post. :)

How to convert all tables from MyISAM into InnoDB?

It hasn't been mentioned yet, so I'll write it for posterity:

If you're migrating between DB servers (or have another reason you'd dump and reload your dta), you can just modify the output from mysqldump:

mysqldump --no-data DBNAME | sed 's/ENGINE=MyISAM/ENGINE=InnoDB/' > my_schema.sql;
mysqldump --no-create-info DBNAME > my_data.sql;

Then load it again:

mysql DBNAME < my_schema.sql && mysql DBNAME < my_data.sql

(Also, in my limited experience, this can be a much faster process than altering the tables ‘live’. It probably depends on the type of data and indexes.)

Two decimal places using printf( )

What you want is %.2f, not 2%f.

Also, you might want to replace your %d with a %f ;)

#include <cstdio>
int main()
{
printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456);
return 0;
}

This will output:

When this number: 94.945600 is assigned to 2 dp, it will be: 94.95

See here for a full description of the printf formatting options: printf

How to check what version of jQuery is loaded?

I have found this to be the shortest and simplest way to check if jQuery is loaded:

if (window.jQuery) {
    // jQuery is available.

    // Print the jQuery version, e.g. "1.0.0":
    console.log(window.jQuery.fn.jquery);
}

This method is used by http://html5boilerplate.com and others.

How To Make Circle Custom Progress Bar in Android

I did a simple class which u can use to make custom ProgressBar dialog. Actually it has 2 default layouts: - First dialog with no panel with progress bar and animated text centered over it - Second normal dialog with panel, progress bar, title and msg

It is just a class, so not a customizable library which u can import in your project, so you need to copy it and change it how you want. It is a DialogFragment class, but you can use it inside an activity as a normal fragment just like you do with classic fragment by using FragmentManager.

Code of the dialog class:

public class ProgressBarDialog extends DialogFragment {

private static final String TAG = ProgressBarDialog.class.getSimpleName();
private static final String KEY = TAG.concat(".key");
// Argument Keys
private static final String KEY_DIALOG_TYPE = KEY.concat(".dialogType");
private static final String KEY_TITLE = KEY.concat(".title");
private static final String KEY_PROGRESS_TEXT = KEY.concat(".progressText");
private static final String KEY_CUSTOM_LAYOUT_BUILDER = KEY.concat(".customLayoutBuilder");
// Class Names
private static final String CLASS_GRADIENT_STATE = "GradientState";
// Field Names
private static final String FIELD_THICKNESS = "mThickness";
private static final String FIELD_INNER_RADIUS = "mInnerRadius";

/** Dialog Types **/
private static final int TYPE_PROGRESS_BAR_ONLY_NO_ANIM = 0x0;
private static final int TYPE_PROGRESS_BAR_ONLY_ROTATE_ANIM = 0x1;
private static final int TYPE_PROGRESS_BAR_ONLY_FADE_ANIM = 0x2;
private static final int TYPE_PROGRESS_BAR_AND_MSG = 0xF;

/** Animations Values **/
private static final long CENTER_TEXT_VIEWS_ANIMATION_DURATION = 250L;
private static final long CENTER_TEXT_VIEWS_START_OFFSET_MULTIPLIER = 250L;

private MaterialProgressBar mProgressBar;
private LinearLayout mllTextContainer;
private TextView mtvTitle;
private TextView mtvProgressText;

private List<TextView> mCenterTextViews;
private int mDialogType;
private String mTitle;
private String mProgressText;
private CustomLayoutBuilder mCustomLayoutBuilder;

/** Public Static Factory Methods **/
public static ProgressBarDialog initLayoutProgressBarOnlyNoAnim(String text, CustomLayoutBuilder builder){
    return initLayoutProgressBarOnly(TYPE_PROGRESS_BAR_ONLY_NO_ANIM, text, builder);
}

public static ProgressBarDialog initLayoutProgressBarOnlyRotateAnim(String text, CustomLayoutBuilder builder){
    return initLayoutProgressBarOnly(TYPE_PROGRESS_BAR_ONLY_ROTATE_ANIM, text, builder);
}

public static ProgressBarDialog initLayoutProgressBarOnlyFadeAnim(String text, CustomLayoutBuilder builder){
    return initLayoutProgressBarOnly(TYPE_PROGRESS_BAR_ONLY_FADE_ANIM, text, builder);
}

public static ProgressBarDialog initLayoutProgressBarAndMsg(String title, String text, CustomLayoutBuilder builder){
    ProgressBarDialog mInstance = new ProgressBarDialog();
    Bundle args = new Bundle();
    args.putInt(KEY_DIALOG_TYPE, TYPE_PROGRESS_BAR_AND_MSG);
    args.putString(KEY_TITLE, title);
    args.putString(KEY_PROGRESS_TEXT, text);
    args.putParcelable(KEY_CUSTOM_LAYOUT_BUILDER, builder);
    mInstance.setArguments(args);
    return mInstance;
}

/** Private Static Factory Methods **/
private static ProgressBarDialog initLayoutProgressBarOnly(int animation, String text, CustomLayoutBuilder builder){
    ProgressBarDialog mInstance = new ProgressBarDialog();
    Bundle args = new Bundle();
    args.putInt(KEY_DIALOG_TYPE, animation);
    args.putString(KEY_PROGRESS_TEXT, text);
    args.putParcelable(KEY_CUSTOM_LAYOUT_BUILDER, builder);
    mInstance.setArguments(args);
    return mInstance;
}

/** Override Lifecycle Methods **/
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initData();
}

@Override @Nullable
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.dialog_progress_bar, container, false);
    initViews(view);
    if(getContext() != null && mCustomLayoutBuilder != null) {
        mProgressBar.setIndeterminateDrawable(getResources().getDrawable(mCustomLayoutBuilder.getLayoutResID()));
        initShapes();
    }
    return view;
}

private void initShapes(){
    if(mProgressBar.getIndeterminateDrawable() instanceof LayerDrawable) {
        LayerDrawable layerDrawable = (LayerDrawable) mProgressBar.getIndeterminateDrawable();
        for (int i = 0; i < layerDrawable.getNumberOfLayers(); i++) {
            if(layerDrawable.getDrawable(i) instanceof RotateDrawable) {
                RotateDrawable rotateDrawable = (RotateDrawable) layerDrawable.getDrawable(i);
                int[] fromToDeg = mCustomLayoutBuilder.getDegreesMatrixRow(i);
                if(fromToDeg.length > 0){
                    rotateDrawable.setFromDegrees(fromToDeg[CustomLayoutBuilder.INDEX_FROM_DEGREES]);
                    rotateDrawable.setToDegrees(fromToDeg[CustomLayoutBuilder.INDEX_TO_DEGREES]);
                }
                if(rotateDrawable.getDrawable() instanceof GradientDrawable){
                    GradientDrawable gradientDrawable = (GradientDrawable) rotateDrawable.getDrawable();
                    int innerRadius = getResources().getDimensionPixelSize(mCustomLayoutBuilder.getInnerRadius(i));
                    if(mDialogType == TYPE_PROGRESS_BAR_AND_MSG){
                        innerRadius /= 3;
                    }
                    int thickness = getResources().getDimensionPixelSize(mCustomLayoutBuilder.getThickness(i));
                    int[] colors = mCustomLayoutBuilder.getColorsMatrixRow(i);
                    if(colors.length > 0x0){
                        gradientDrawable.setColors(DataUtils.resourcesIDsToColors(this.getContext(), colors));
                    }
                    if(innerRadius != -0x1){
                        DataUtils.setSubClassFieldIntValue(gradientDrawable.getConstantState(), gradientDrawable.getClass(), CLASS_GRADIENT_STATE, FIELD_INNER_RADIUS, innerRadius);
                    }
                    if(thickness != -0x1){
                        DataUtils.setSubClassFieldIntValue(gradientDrawable.getConstantState(), gradientDrawable.getClass(), CLASS_GRADIENT_STATE, FIELD_THICKNESS, thickness);
                    }
                }
            }
        }
    }
}

@Override
public void onStart() {
    super.onStart();
    setWindowSize();
    startAnimation();
}

/** Public Methods **/
public void changeTextViews(String progressText){
    mProgressText = progressText;
    initTextViews();
    startAnimation();
}

public String getProgressText(){
    return mProgressText;
}

/** Private Methods **//** Init Methods **/
private void initData(){
    if(getArguments() != null) {
        if (getArguments().containsKey(KEY_DIALOG_TYPE)) {
            mDialogType = getArguments().getInt(KEY_DIALOG_TYPE);
        }
        if(getArguments().containsKey(KEY_TITLE)){
            mTitle = getArguments().getString(KEY_TITLE);
        }
        if (getArguments().containsKey(KEY_PROGRESS_TEXT)) {
            mProgressText = getArguments().getString(KEY_PROGRESS_TEXT);
        }
        if (getArguments().containsKey(KEY_CUSTOM_LAYOUT_BUILDER)){
            mCustomLayoutBuilder = getArguments().getParcelable(KEY_CUSTOM_LAYOUT_BUILDER);
        }
    }
    mCenterTextViews = new ArrayList<>();
}

private void initViews(View layout){
    if(layout != null){
        switch(mDialogType){
            case TYPE_PROGRESS_BAR_ONLY_NO_ANIM:
            case TYPE_PROGRESS_BAR_ONLY_ROTATE_ANIM:
            case TYPE_PROGRESS_BAR_ONLY_FADE_ANIM:
                if(getDialog() != null && getDialog().getWindow() != null) {
                    getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                }
                LinearLayout mLayoutProgressBarOnly = layout.findViewById(R.id.layout_progress_bar_only);
                mLayoutProgressBarOnly.setVisibility(LinearLayout.VISIBLE);
                mProgressBar = layout.findViewById(R.id.dpb_progress_bar);
                if(mCustomLayoutBuilder.getProgressBarWidthDimen() != -0x1){
                    ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) mProgressBar.getLayoutParams();
                    lp.width = getResources().getDimensionPixelSize(mCustomLayoutBuilder.getProgressBarWidthDimen());
                    lp.height = getResources().getDimensionPixelSize(mCustomLayoutBuilder.getProgressBarHeightDimen());
                    mProgressBar.setLayoutParams(lp);
                }
                mllTextContainer = layout.findViewById(R.id.dpb_text_container);
                initTextViews();
                break;
            case TYPE_PROGRESS_BAR_AND_MSG:
                LinearLayout mLayoutProgressBarAndMsg = layout.findViewById(R.id.layout_progress_bar_and_msg);
                mLayoutProgressBarAndMsg.setVisibility(LinearLayout.VISIBLE);
                mProgressBar = layout.findViewById(R.id.dpb_progress_bar_and_msg);
                mtvTitle = layout.findViewById(R.id.pbd_title);
                mtvProgressText = layout.findViewById(R.id.dpb_progress_msg);
                initProgressMsg();
                break;
        }
    }
}

private void initTextViews(){
    if(!TextUtils.isEmpty(mProgressText)){
        clearTextContainer();
        for(char digit : mProgressText.toCharArray()){
            TextView tv = new TextView(getContext(), null, 0x0, R.style.PBDCenterTextStyleWhite);
            if(mCustomLayoutBuilder.getProgressMsgColor() != CustomLayoutBuilder.DEFAULT_COLOR && getContext() != null){
                tv.setTextColor(ActivityCompat.getColor(getContext(), mCustomLayoutBuilder.getProgressMsgColor()));
            }
            if(mCustomLayoutBuilder.getProgressMsgDimen() != CustomLayoutBuilder.DEFAULT_DIMEN){
                tv.setTextSize(getResources().getDimension(mCustomLayoutBuilder.getProgressMsgDimen()));
            }
            tv.setText(String.valueOf(digit));
            mCenterTextViews.add(tv);
            mllTextContainer.addView(tv);
        }
    }
}

private void initProgressMsg(){
    mtvTitle.setText(mTitle);
    mtvProgressText.setText(mProgressText);
    if(mCustomLayoutBuilder.getProgressMsgColor() != CustomLayoutBuilder.DEFAULT_COLOR){
        mtvProgressText.setTextColor(mCustomLayoutBuilder.getProgressMsgColor());
    }
    if(mCustomLayoutBuilder.getProgressMsgDimen() != CustomLayoutBuilder.DEFAULT_DIMEN){
        mtvProgressText.setTextSize(getResources().getDimension(mCustomLayoutBuilder.getProgressMsgDimen()));
    }
}

private void clearTextContainer(){
    if(mllTextContainer.getChildCount() >= 0x0){
        for(int i=0; i < mllTextContainer.getChildCount(); i++){
            View v = mllTextContainer.getChildAt(i);
            if(v instanceof TextView){
                TextView tv = (TextView) v;
                if(tv.getAnimation() != null){
                    tv.clearAnimation();
                }
            }
        }
    }
    mllTextContainer.removeAllViews();
}

private void setWindowSize(){
    Dialog dialog = getDialog();
    if(dialog != null && dialog.getWindow() != null){
        int width = 0x0, height = 0x0;
        switch(mDialogType){
            case TYPE_PROGRESS_BAR_ONLY_NO_ANIM:
            case TYPE_PROGRESS_BAR_ONLY_ROTATE_ANIM:
            case TYPE_PROGRESS_BAR_ONLY_FADE_ANIM:
                width = ViewGroup.LayoutParams.WRAP_CONTENT;        //getResources().getDimensionPixelSize(R.dimen.pbd_window_width);
                height = ViewGroup.LayoutParams.WRAP_CONTENT;       //getResources().getDimensionPixelSize(R.dimen.pbd_window_height);
                break;
            case TYPE_PROGRESS_BAR_AND_MSG:
                width = ViewGroup.LayoutParams.MATCH_PARENT;
                height = ViewGroup.LayoutParams.WRAP_CONTENT;       //getResources().getDimensionPixelSize(R.dimen.pbd_textual_window_height);
                break;
        }
        dialog.getWindow().setLayout(width, height);
    }
}

/** Animation Methods **/
private void startAnimation(){
    switch(mDialogType){
        case TYPE_PROGRESS_BAR_ONLY_ROTATE_ANIM:
        startRotateAnimations();
        break;
        case TYPE_PROGRESS_BAR_ONLY_FADE_ANIM:
        startFadeInAnimations();
        break;
    }
}

private void startRotateAnimations(){
    for(TextView tv : mCenterTextViews){
        if(tv != null && tv.getText() != null && !TextUtils.isEmpty(tv.getText().toString().trim())) {
            int i = mCenterTextViews.indexOf(tv);
            RotateAnimation anim = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            anim.setDuration(CENTER_TEXT_VIEWS_ANIMATION_DURATION);
            anim.setFillAfter(true);
            anim.setStartOffset(CENTER_TEXT_VIEWS_START_OFFSET_MULTIPLIER * i);
            if (i == (mCenterTextViews.size() - 0x1)) {
                anim.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        startRotateAnimations();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }
            tv.startAnimation(anim);
        }
    }
}

private void startFadeInAnimations(){
    for(TextView tv : mCenterTextViews){
        if(tv != null && tv.getText() != null && !TextUtils.isEmpty(tv.getText().toString().trim())) {
            int i = mCenterTextViews.indexOf(tv);
            AlphaAnimation anim = new AlphaAnimation(0x1, 0x0);
            anim.setDuration(CENTER_TEXT_VIEWS_ANIMATION_DURATION);
            anim.setFillAfter(true);
            anim.setStartOffset(CENTER_TEXT_VIEWS_START_OFFSET_MULTIPLIER * i);
            if (i == (mCenterTextViews.size() - 0x1)) {
                anim.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        startFadeOutAnimations();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }
            tv.startAnimation(anim);
        }
    }
}

private void startFadeOutAnimations(){
    for(TextView tv : mCenterTextViews){
        int i = mCenterTextViews.indexOf(tv);
        AlphaAnimation anim = new AlphaAnimation(0x0, 0x1);
        anim.setDuration(CENTER_TEXT_VIEWS_ANIMATION_DURATION);
        anim.setFillAfter(true);
        anim.setStartOffset(CENTER_TEXT_VIEWS_START_OFFSET_MULTIPLIER * i);
        if(i == (mCenterTextViews.size() - 0x1)){
            anim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    startFadeInAnimations();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        tv.startAnimation(anim);
    }
}

/** Progress Bar Custom Layout Builder Class **/
public static class CustomLayoutBuilder implements Parcelable {

    /** Shapes **/
    private static final int RING = GradientDrawable.RING;

    /** Colors **/
    private static final int[][] COLORS_MATRIX_RYGB = new int[][]{
        new int[]{ R.color.transparent, R.color.transparent, R.color.material_red_A700 },
        new int[]{ R.color.transparent, R.color.transparent, R.color.material_amber_A700 },
        new int[]{ R.color.transparent, R.color.transparent, R.color.material_light_green_A700 },
        new int[]{ R.color.transparent, R.color.transparent, R.color.material_blue_A700 }
    };
    private static final int DEFAULT_COLOR = -0x1;

    /** Dimens **/
    private static final int DEFAULT_DIMEN = -0x1;
    private static final int[] DEFAULT_PROGRESS_BAR_DIMEN = new int[]{};

    /** Indexes **/
    private static final int INDEX_PROGRESS_BAR_WIDTH = 0x0;
    private static final int INDEX_PROGRESS_BAR_HEIGHT = 0x1;
    private static final int INDEX_FROM_DEGREES = 0x0;
    private static final int INDEX_TO_DEGREES = 0x1;

    /** Arrays Sizes **/
    private static final int SIZE_PROGRESS_BAR_DIMENS_ARRAY = 0x2;

    /** Matrix Columns Number **/
    private static final int NUM_COLUMNS_DEGREES_MATRIX = 0x2;      /* Degrees Matrix Index                     ->  degrees[3]  =   { fromDegrees, toDegrees } */
    private static final int NUM_COLUMNS_COLORS_MATRIX = 0x3;       /* GradientDrawable Colors Matrix Index     ->  colors[3]   =   { startColor, centerColor, endColor } */

    /** Drawables Layout Resource IDs **/
    private static final int LAYOUT_RES_PROGRESS_BAR_RINGS = R.drawable.progress_bar_rings;

    /** Layout Data: Four Rings Overlaid **/
    private static final int RINGS_OVERLAID_LAYERS = 0x4;
    private static final int[][] RINGS_OVERLAID_DEGREES = new int[][]{ new int[]{ 300, 660 }, new int[]{ 210, 570 }, new int[]{ 120, 480 }, new int[]{ 30, 390 } };
    private static final int[] RINGS_OVERLAID_SHAPES = new int[]{ RING, RING, RING, RING };
    private static final int[] RINGS_OVERLAID_INNER_RADIUS = new int[]{ R.dimen.pbd_inner_radius_60dp, R.dimen.pbd_inner_radius_60dp, R.dimen.pbd_inner_radius_60dp, R.dimen.pbd_inner_radius_60dp};
    private static final int[] RINGS_OVERLAID_THICKNESS = new int[]{ R.dimen.pbd_thickness_40dp, R.dimen.pbd_thickness_30dp, R.dimen.pbd_thickness_20dp, R.dimen.pbd_thickness_10dp };

    /** Layout Data: Four Rings Spaced **/
    private static final int RINGS_SPACED_LAYERS = 0x4;
    private static final int[][] RINGS_SPACED_DEGREES = new int[][]{ new int[]{ 180, 540 }, new int[]{ 0, 360 }, new int[]{ 90, 450 }, new int[]{ 270, 630 } };
    private static final int[] RINGS_SPACED_SHAPES = new int[]{ RING, RING, RING, RING };
    private static final int[] RINGS_SPACED_INNER_RADIUS = new int[]{ R.dimen.pbd_inner_radius_30dp, R.dimen.pbd_inner_radius_60dp, R.dimen.pbd_inner_radius_90dp, R.dimen.pbd_inner_radius_120dp };
    private static final int[] RINGS_SPACED_THICKNESS = new int[]{ R.dimen.pbd_thickness_10dp, R.dimen.pbd_thickness_15dp, R.dimen.pbd_thickness_20dp, R.dimen.pbd_thickness_25dp };

    private int mLayoutResID;
    private int[] mProgressBarDimens;
    private int mNumLayers;
    private int[][] mRotateDegrees;
    private int[] mShapes;
    private int[] mInnerRadius;
    private int[] mThickness;
    private int[][] mColors;
    private int mProgressMsgColor;
    private int mProgressMsgDimen;

    public static Parcelable.Creator CREATOR = new CreatorCustomLayoutBuilder();

    /** Constructors **/
    private CustomLayoutBuilder(int layoutResID, int[] progressBarDimens, int numLayers, int[][] degreesMatrix, int[] shapes, int[] innerRadius, int[] thickness,
                                int[][] colorsMatrix, int msgColor, int progressMsgDimen){
        mLayoutResID = layoutResID;
        mProgressBarDimens = progressBarDimens;
        mNumLayers = numLayers;
        mRotateDegrees = degreesMatrix;
        mShapes = shapes;
        mInnerRadius = innerRadius;
        mThickness = thickness;
        mColors = colorsMatrix;
        mProgressMsgColor = msgColor;
        mProgressMsgDimen = progressMsgDimen;
    }

    private CustomLayoutBuilder(Parcel in){
        mLayoutResID = in.readInt();
        mProgressBarDimens = new int[SIZE_PROGRESS_BAR_DIMENS_ARRAY];
        in.readIntArray(mProgressBarDimens);
        mNumLayers = in.readInt();
        int[] tempArray = new int[NUM_COLUMNS_DEGREES_MATRIX * mNumLayers];
        in.readIntArray(tempArray);
        mRotateDegrees = DataUtils.arrayToMatrix(tempArray, NUM_COLUMNS_DEGREES_MATRIX);
        mShapes = new int[mNumLayers];
        in.readIntArray(mShapes);
        mInnerRadius = new int[mNumLayers];
        in.readIntArray(mInnerRadius);
        mThickness = new int[mNumLayers];
        in.readIntArray(mThickness);
        tempArray = new int[NUM_COLUMNS_COLORS_MATRIX * mNumLayers];
        in.readIntArray(tempArray);
        mColors = DataUtils.arrayToMatrix(tempArray, NUM_COLUMNS_COLORS_MATRIX);
        mProgressMsgColor = in.readInt();
        mProgressMsgDimen = in.readInt();
    }

    /** Public Static Factory Methods **/
    public static CustomLayoutBuilder initLayoutRingsOverlaid(){
        return new CustomLayoutBuilder(LAYOUT_RES_PROGRESS_BAR_RINGS, DEFAULT_PROGRESS_BAR_DIMEN, RINGS_OVERLAID_LAYERS, RINGS_OVERLAID_DEGREES, RINGS_OVERLAID_SHAPES,
                RINGS_OVERLAID_INNER_RADIUS, RINGS_OVERLAID_THICKNESS, COLORS_MATRIX_RYGB, R.color.material_white, DEFAULT_DIMEN);
    }

    public static CustomLayoutBuilder initLayoutRingsOverlaid(int[] resProgBarDimens, int resProgMsgColor, int resProgMsgDimen){
        return new CustomLayoutBuilder(LAYOUT_RES_PROGRESS_BAR_RINGS, resProgBarDimens, RINGS_OVERLAID_LAYERS, RINGS_OVERLAID_DEGREES, RINGS_OVERLAID_SHAPES,
                RINGS_OVERLAID_INNER_RADIUS, RINGS_OVERLAID_THICKNESS, COLORS_MATRIX_RYGB, resProgMsgColor, resProgMsgDimen);
    }

    public static CustomLayoutBuilder initLayoutRingsSpaced(){
        return new CustomLayoutBuilder(LAYOUT_RES_PROGRESS_BAR_RINGS, DEFAULT_PROGRESS_BAR_DIMEN, RINGS_SPACED_LAYERS, RINGS_SPACED_DEGREES, RINGS_SPACED_SHAPES,
                RINGS_SPACED_INNER_RADIUS, RINGS_SPACED_THICKNESS, COLORS_MATRIX_RYGB, DEFAULT_COLOR, DEFAULT_DIMEN);
    }

    /** Override Parcelable Methods **/
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mLayoutResID);
        out.writeIntArray(mProgressBarDimens);
        out.writeInt(mNumLayers);
        out.writeIntArray(DataUtils.matrixToArray(mRotateDegrees));
        out.writeIntArray(mShapes);
        out.writeIntArray(mInnerRadius);
        out.writeIntArray(mThickness);
        out.writeIntArray(DataUtils.matrixToArray(mColors));
        out.writeInt(mProgressMsgColor);
        out.writeInt(mProgressMsgDimen);
    }

    /** Getter & Setter Methods **/
    private int getLayoutResID() {
        return mLayoutResID;
    }

    private void setLayoutResID(int layoutResID) {
        this.mLayoutResID = layoutResID;
    }

    private int[] getProgressBarDimens() {
        return mProgressBarDimens;
    }

    private void setProgressBarDimens(int[] progressBarDimens) {
        this.mProgressBarDimens = progressBarDimens;
    }

    private int getProgressBarWidthDimen(){         // Used to check if 'mProgressBarDimens' array is set.
        if(mProgressBarDimens != null && mProgressBarDimens.length == SIZE_PROGRESS_BAR_DIMENS_ARRAY){
            return mProgressBarDimens[INDEX_PROGRESS_BAR_WIDTH];
        } else {
            return -0x1;
        }
    }

    private int getProgressBarHeightDimen(){
        return mProgressBarDimens[INDEX_PROGRESS_BAR_HEIGHT];
    }

    private int getNumLayers() {
        return mNumLayers;
    }

    private void setNumLayers(int numLayers) {
        this.mNumLayers = numLayers;
    }

    private int[][] getRotateDegrees() {
        return mRotateDegrees;
    }

    private void setRotateDegrees(int[][] rotateDegrees) {
        this.mRotateDegrees = rotateDegrees;
    }

    private int[] getShapes() {
        return mShapes;
    }

    private void setShapes(int[] shapes) {
        this.mShapes = shapes;
    }

    private int[] getInnerRadius() {
        return mInnerRadius;
    }

    private void setInnerRadius(int[] innerRadius) {
        this.mInnerRadius = innerRadius;
    }

    private int[] getThickness() {
        return mThickness;
    }

    private void setThickness(int[] thickness) {
        this.mThickness = thickness;
    }

    private int[][] getColorsMatrix() {
        return mColors;
    }

    private void setColorsMatrix(int[][] colorsMatrix) {
        this.mColors = colorsMatrix;
    }

    private int getProgressMsgColor() {
        return mProgressMsgColor;
    }

    private void setProgressMsgColor(int progressMsgColor) {
        this.mProgressMsgColor = progressMsgColor;
    }

    private int getProgressMsgDimen() {
        return mProgressMsgDimen;
    }

    private void setProgressMsgDimen(int progressMsgDimen) {
        this.mProgressMsgDimen = progressMsgDimen;
    }

    /** Public Methods **/
    private int[] getDegreesMatrixRow(int numRow){
        if(mRotateDegrees != null && mRotateDegrees.length > numRow) {
            return mRotateDegrees[numRow];
        } else {
            return new int[]{};
        }
    }

    private int getShape(int position){
        if(mShapes != null && mShapes.length > position){
            return mShapes[position];
        } else {
            return -0x1;
        }
    }

    private int getInnerRadius(int position){
        if(mInnerRadius != null && mInnerRadius.length > position){
            return mInnerRadius[position];
        } else {
            return -0x1;
        }
    }

    private int getThickness(int position){
        if(mThickness != null && mThickness.length > position){
            return mThickness[position];
        } else {
            return -0x1;
        }
    }

    private int[] getColorsMatrixRow(int numRow) {
        if(mColors != null && mColors.length > numRow){
            return mColors[numRow];
        } else {
            return new int[]{};
        }
    }

    /** Private Static Class Parcelable Creator **/
    private static class CreatorCustomLayoutBuilder implements Parcelable.Creator<CustomLayoutBuilder> {

        @Override
        public CustomLayoutBuilder createFromParcel(Parcel in) {
            return new CustomLayoutBuilder(in);
        }

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

    }

}
}
  • The class has a progress bar with no dialog and custom text over it. The text can have 2 animations:

  • Fade In -> Fade Out animation: digits will fade out like a sequentially from left to right. At end of text will restart from left.

  • Rotate Animation: same sequential behavior but the digits rotate on themself one by one instead of fading out.

  • Other way is a Progress Bar with a dialog (Title + Message)

Rotation Animation

Dialog Progress Bar

Converting a PDF to PNG

You can use ImageMagick without separating the first page of the PDF with other tools. Just do

convert -density 288 cover.pdf[0] -resize 25% cover.png


Here I increase the nominal density by 400% (72*4=288) and then resize by 1/4 (25%). This gives a much better quality for the resulting png.

However, if the PDF is CMYK, PNG does not support that. It would need to be converted to sRGB, especially if it has transparency, since Ghostscript cannot handle CMYK with alpha.

convert -density 288 -colorspace sRGB -resize 25% cover.pdf[0] cover.png

Zsh: Conda/Pip installs command not found

Simply copy your Anaconda bin directory and paste it at the bottom of ~/.zshrc.

For me the path is /home/theorangeguy/miniconda3/bin, so I ran:

echo ". /home/theorangeguy/miniconda3/bin" >> ~/.zshrc

This edited the ~/.zshrc. Now do:

source ~/.zshrc

It worked like a charm.

How can I make XSLT work in chrome?

Well it does not work if the XML file (starting by the standard PI:

<?xml-stylesheet type="text/xsl" href="..."?>

for referencing the XSL stylesheet) is served as "application/xml". In that case, Chrome will still download the referenced XSL stylesheet, but nothing will be rendered, as it will silently change the document types from "application/xml" into "Document" (!??) and "text/xsl" into "Stylesheet" (!??), and then will attempt to render the XML document as if it was an HTML(5) document, without running first its XSLT processor. And Nothing at all will be displayed in the screen (whose content will continue to show the previous page from which the XML page was referenced, and will continue spinning the icon, as if the document was never completely loaded.

You can perfectly use the Chrome console, that shows that all resources are loaded, but they are incorrectly interpreted.

So yes, Chrome currently only render XML files (with its optional leading XSL stylesheet declaration), only if it is served as "text/xml", but not as "application/xml" as it should for client-side rendered XML with an XSL declaration.

For XML files served as "text/xml" or "application/xml" and that do not contain an XSL stylesheet declaration, Chrome should still use a default stylesheet to render it as a DOM tree, or at least as its text source. But it does not, and here again it attempts to render it as if it was HTML, and bugs immediately on many scripts (including a default internal one) that attempt to access to "document.body" for handling onLoad events and inject some javascript handler in it.

An example of site that does not work as expected (the Common Lisp documentation) in Chrome, but works in IE which supports client-side XSLT:

http://common-lisp.net/project/bknr/static/lmman/toc.html

This index page above is displayed correctly, but all links will drive to XML documents with a basic XSL declaration to an existing XSL stylesheet document, and you can wait indefinitely, thinking that the chapters have problems to be downloaded. All you can do to read the docuemntation is to open the console and read the source code in the Resources tab.

How do you make an element "flash" in jQuery

just give elem.fadeOut(10).fadeIn(10);

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

My problem solved with these :

1- Add this to your head :

<base href="/" />

2- Use this in app.config

$locationProvider.html5Mode(true);

Split text file into smaller multiple text file using command line

My requirement was a bit different. I often work with Comma Delimited and Tab Delimited ASCII files where a single line is a single record of data. And they're really big, so I need to split them into manageable parts (whilst preserving the header row).

So, I reverted back to my classic VBScript method and bashed together a small .vbs script that can be run on any Windows computer (it gets automatically executed by the WScript.exe script host engine on Window).

The benefit of this method is that it uses Text Streams, so the underlying data isn't loaded into memory (or, at least, not all at once). The result is that it's exceptionally fast and it doesn't really need much memory to run. The test file I just split using this script on my i7 was about 1 GB in file size, had about 12 million lines of test and made 25 part files (each with about 500k lines each) – the processing took about 2 minutes and it didn’t go over 3 MB memory used at any point.

The caveat here is that it relies on the text file having "lines" (meaning each record is delimited with a CRLF) as the Text Stream object uses the "ReadLine" function to process a single line at a time. But hey, if you're working with TSV or CSV files, it's perfect.

Option Explicit

Private Const INPUT_TEXT_FILE = "c:\bigtextfile.txt"  'The full path to the big file
Private Const REPEAT_HEADER_ROW = True                'Set to True to duplicate the header row in each part file
Private Const LINES_PER_PART = 500000                 'The number of lines per part file

Dim oFileSystem, oInputFile, oOutputFile, iOutputFile, iLineCounter, sHeaderLine, sLine, sFileExt, sStart

sStart = Now()

sFileExt = Right(INPUT_TEXT_FILE,Len(INPUT_TEXT_FILE)-InstrRev(INPUT_TEXT_FILE,".")+1)
iLineCounter = 0
iOutputFile = 1

Set oFileSystem = CreateObject("Scripting.FileSystemObject")
Set oInputFile = oFileSystem.OpenTextFile(INPUT_TEXT_FILE, 1, False)
Set oOutputFile = oFileSystem.OpenTextFile(Replace(INPUT_TEXT_FILE, sFileExt, "_" & iOutputFile & sFileExt), 2, True)

If REPEAT_HEADER_ROW Then
    iLineCounter = 1
    sHeaderLine = oInputFile.ReadLine()
    Call oOutputFile.WriteLine(sHeaderLine)
End If

Do While Not oInputFile.AtEndOfStream
    sLine = oInputFile.ReadLine()
    Call oOutputFile.WriteLine(sLine)
    iLineCounter = iLineCounter + 1
    If iLineCounter Mod LINES_PER_PART = 0 Then
        iOutputFile = iOutputFile + 1
        Call oOutputFile.Close()
        Set oOutputFile = oFileSystem.OpenTextFile(Replace(INPUT_TEXT_FILE, sFileExt, "_" & iOutputFile & sFileExt), 2, True)
        If REPEAT_HEADER_ROW Then
            Call oOutputFile.WriteLine(sHeaderLine)
        End If
    End If
Loop

Call oInputFile.Close()
Call oOutputFile.Close()
Set oFileSystem = Nothing

Call MsgBox("Done" & vbCrLf & "Lines Processed:" & iLineCounter & vbCrLf & "Part Files: " & iOutputFile & vbCrLf & "Start Time: " & sStart & vbCrLf & "Finish Time: " & Now())

How to apply two CSS classes to a single element

1) Use multiple classes inside the class attribute, separated by whitespace (ref):

<a class="c1 c2">aa</a>

2) To target elements that contain all of the specified classes, use this CSS selector (no space) (ref):

.c1.c2 {
}

Writing sqlplus output to a file

Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt). You can check where you are spooling by issuing spool command.

Compiling and Running Java Code in Sublime Text 2

Make sure u install JDK/JRE first.

If you are mac user than follow this steps:

open terminal go to your root dictionary by typing

cd ..

repeatedly. use

ls

to see if u have reach the root

you will see Library folder Now follow this path Library/Java/JVM/bin Once you get into bin you can see JavaC file

Now u need to get the path of this folder for that just write this command

pwd

Copy paste it to your sublime JavaC file and build java code in sublime by cmd+b.

jquery: get elements by class name and add css to each of them

What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.

There is also a shorter form for $(document).ready(function(){...}) in $(function(){...}).

So, this is all you need:

$(function(){
  $('div.easy_editor').css('border','9px solid red');
});

If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:

$(function(){
  $('.easy_editor').css('border','9px solid red');
});

Stylesheet not loaded because of MIME-type

I had this error for a Bootstrap template.

<link href="starter-template.css" rel="stylesheet">

Then I removed the rel="stylesheet" from the link, i.e.:

<link href="starter-template.css">

And everything works fine. Try this if you are using Bootstrap templates.

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

How to get source code of a Windows executable?

I would (and have) used IDA Pro to decompile executables. It creates semi-complete code, you can decompile to assembly or C.

If you have a copy of the debug symbols around, load those into IDA before decompiling and it will be able to name many of the functions, parameters, etc.

Deleting queues in RabbitMQ

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
               'localhost'))
channel = connection.channel()

channel.queue_delete(queue='queue-name')

connection.close()

Install pika package as follows

$ sudo pip install pika==0.9.8

The installation depends on pip and git-core packages, you may need to install them first.

On Ubuntu:

$ sudo apt-get install python-pip git-core

On Debian:

$ sudo apt-get install python-setuptools git-core
$ sudo easy_install pip

On Windows: To install easy_install, run the MS Windows Installer for setuptools

> easy_install pip
> pip install pika==0.9.8

Unknown URL content://downloads/my_downloads

For those who are getting Error Unknown URI: content://downloads/public_downloads. I managed to solve this by getting a hint given by @Commonsware in this answer. I found out the class FileUtils on GitHub. Here InputStream methods are used to fetch file from Download directory.

 // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);

                if (id != null && id.startsWith("raw:")) {
                    return id.substring(4);
                }

                String[] contentUriPrefixesToTry = new String[]{
                        "content://downloads/public_downloads",
                        "content://downloads/my_downloads",
                        "content://downloads/all_downloads"
                };

                for (String contentUriPrefix : contentUriPrefixesToTry) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
                    try {
                        String path = getDataColumn(context, contentUri, null, null);
                        if (path != null) {
                            return path;
                        }
                    } catch (Exception e) {}
                }

                // path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
                String fileName = getFileName(context, uri);
                File cacheDir = getDocumentCacheDir(context);
                File file = generateFileName(fileName, cacheDir);
                String destinationPath = null;
                if (file != null) {
                    destinationPath = file.getAbsolutePath();
                    saveFileFromUri(context, uri, destinationPath);
                }

                return destinationPath;
            }

Batch files: List all files in a directory with relative paths

This answer will not work correctly with root paths containing equal signs (=). (Thanks @dbenham for pointing that out.)


EDITED: Fixed the issue with paths containing !, again spotted by @dbenham (thanks!).

Alternatively to calculating the length and extracting substrings you could use a different approach:

  • store the root path;

  • clear the root path from the file paths.

Here's my attempt (which worked for me):

@ECHO OFF
SETLOCAL DisableDelayedExpansion
SET "r=%__CD__%"
FOR /R . %%F IN (*) DO (
  SET "p=%%F"
  SETLOCAL EnableDelayedExpansion
  ECHO(!p:%r%=!
  ENDLOCAL
)

The r variable is assigned with the current directory. Unless the current directory is the root directory of a disk drive, it will not end with \, which we amend by appending the character. (No longer the case, as the script now reads the __CD__ variable, whose value always ends with \ (thanks @jeb!), instead of CD.)

In the loop, we store the current file path into a variable. Then we output the variable, stripping the root path along the way.

Infinite Recursion with Jackson JSON and Hibernate JPA issue

In my case it was enough to change relation from:

@OneToMany(mappedBy = "county")
private List<Town> towns;

to:

@OneToMany
private List<Town> towns;

another relation stayed as it was:

@ManyToOne
@JoinColumn(name = "county_id")
private County county;

How can I store HashMap<String, ArrayList<String>> inside a list?

First, let me fix a little bit your declaration:

List<Map<String, List<String>>> listOfMapOfList = 
    new HashList<Map<String, List<String>>>();

Please pay attention that I used concrete class (HashMap) only once. It is important to use interface where you can to be able to change the implementation later.

Now you want to add element to the list, don't you? But the element is a map, so you have to create it:

Map<String, List<String>> mapOfList = new HashMap<String, List<String>>();

Now you want to populate the map. Fortunately you can use utility that creates lists for you, otherwise you have to create list separately:

mapOfList.put("mykey", Arrays.asList("one", "two", "three"));

OK, now we are ready to add the map into the list:

listOfMapOfList.add(mapOfList);

BUT:

Stop creating complicated collections right now! Think about the future: you will probably have to change the internal map to something else or list to set etc. This will probably cause you to re-write significant parts of your code. Instead define class that contains you data and then add it to one-dimentional collection:

Let's call your class Student (just as example):

public Student {
    private String firstName;
    private String lastName;
    private int studentId;

    private Colectiuon<String> courseworks = Collections.emtpyList();

    //constructors, getters, setters etc
}

Now you can define simple collection:

Collection<Student> students = new ArrayList<Student>();

If in future you want to put your students into map where key is the studentId, do it:

Map<Integer, Student> students = new HashMap<Integer, Student>();

Binary Data in JSON String. Something better than Base64

Just to add the resource and complexity standpoint to the discussion. Since doing PUT/POST and PATCH for storing new resources and altering them, one should remember that the content transfer is an exact representation of the content that is stored and that is received by issuing a GET operation.

A multi-part message is often used as a savior but for simplicity reason and for more complex tasks, I prefer the idea of giving the content as a whole. It is self-explaining and it is simple.

And yes JSON is something crippling but in the end JSON itself is verbose. And the overhead of mapping to BASE64 is a way to small.

Using Multi-Part messages correctly one has to either dismantle the object to send, use a property path as the parameter name for automatic combination or will need to create another protocol/format to just express the payload.

Also liking the BSON approach, this is not that widely and easily supported as one would like it to be.

Basically, we just miss something here but embedding binary data as base64 is well established and way to go unless you really have identified the need to do the real binary transfer (which is hardly often the case).

How to do join on multiple criteria, returning all combinations of both criteria

It sounds like you want to list all the metrics?

SELECT Criteria1, Criteria2, Metric1 As Metric
FROM Table1
UNION ALL
SELECT Criteria1, Criteria2, Metric2 As Metric
FROM Table2
ORDER BY 1, 2

If you only want one Criteria1+Criteria2 combination, group them:

SELECT Criteria1, Criteia2, SUM(Metric) AS Metric
FROM (
    SELECT Criteria1, Criteria2, Metric1 As Metric
    FROM Table1
    UNION ALL
    SELECT Criteria1, Criteria2, Metric2 As Metric
    FROM Table2
)
ORDER BY Criteria1, Criteria2

Jenkins not executing jobs (pending - waiting for next executor)

  • go to Jenkins -> Manage Jenkins -> Manage Nodes
  • examine the "master" node.(Click on configure icon)

In my case No of executors was set to 0. Increased it and issue got fixed.

Why is Spring's ApplicationContext.getBean considered bad?

One of the coolest benefits of using something like Spring is that you don't have to wire your objects together. Zeus's head splits open and your classes appear, fully formed with all of their dependencies created and wired-in, as needed. It's magical and fantastic.

The more you say ClassINeed classINeed = (ClassINeed)ApplicationContext.getBean("classINeed");, the less magic you're getting. Less code is almost always better. If your class really needed a ClassINeed bean, why didn't you just wire it in?

That said, something obviously needs to create the first object. There's nothing wrong with your main method acquiring a bean or two via getBean(), but you should avoid it because whenever you're using it, you're not really using all of the magic of Spring.

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

I'm currently working on such a statement and figured out another fact to notice: INSERT OR REPLACE will replace any values not supplied in the statement. For instance if your table contains a column "lastname" which you didn't supply a value for, INSERT OR REPLACE will nullify the "lastname" if possible (constraints allow it) or fail.

Show Hide div if, if statement is true

You can use css or js for hiding a div. In else statement you can write it as:

else{
?>
<style type="text/css">#divId{
display:none;
}</style>
<?php
}

Or in jQuery

else{
?>
<script type="text/javascript">$('#divId').hide()</script>
<?php
}

Or in javascript

else{
?>
<script type="text/javascript">document.getElementById('divId').style.display = 'none';</script>
<?php
}

Finish all activities at a time

@Override
    public void onBackPressed(){
        MaterialAlertDialogBuilder alert = new MaterialAlertDialogBuilder(BorrowForm.this, MyTheme);
        alert.setTitle("Confirmation");
        alert.setCancelable(false);
        alert.setMessage("App will exit. Data will not be saved. Continue?");
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast toast = Toast.makeText(BorrowForm.this, "App terminated.", Toast.LENGTH_SHORT);
                toast.getView().setBackgroundColor(Color.parseColor("#273036"));
                toast.setGravity(Gravity.CENTER_HORIZONTAL,0,0);
                TextView toastMessage=(TextView) toast.getView().findViewById(android.R.id.message);
                toastMessage.setTextColor(Color.WHITE);
                toast.show();
                finishAffinity();
            }
        });
        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        alert.setCancelable(false);
        alert.show();
    }

Maven2: Missing artifact but jars are in place

i download the missing jar and placed in the .m2 repository fixed the problem =]

get the selected index value of <select> tag in php

$gender = $_POST['gender'];
echo $gender;  

it will echoes the selected value.

How to read a file without newlines?

You can read the whole file and split lines using str.splitlines:

temp = file.read().splitlines()

Or you can strip the newline by hand:

temp = [line[:-1] for line in file]

Note: this last solution only works if the file ends with a newline, otherwise the last line will lose a character.

This assumption is true in most cases (especially for files created by text editors, which often do add an ending newline anyway).

If you want to avoid this you can add a newline at the end of file:

with open(the_file, 'r+') as f:
    f.seek(-1, 2)  # go at the end of the file
    if f.read(1) != '\n':
        # add missing newline if not already present
        f.write('\n')
        f.flush()
        f.seek(0)
    lines = [line[:-1] for line in f]

Or a simpler alternative is to strip the newline instead:

[line.rstrip('\n') for line in file]

Or even, although pretty unreadable:

[line[:-(line[-1] == '\n') or len(line)+1] for line in file]

Which exploits the fact that the return value of or isn't a boolean, but the object that was evaluated true or false.


The readlines method is actually equivalent to:

def readlines(self):
    lines = []
    for line in iter(self.readline, ''):
        lines.append(line)
    return lines

# or equivalently

def readlines(self):
    lines = []
    while True:
        line = self.readline()
        if not line:
            break
        lines.append(line)
    return lines

Since readline() keeps the newline also readlines() keeps it.

Note: for symmetry to readlines() the writelines() method does not add ending newlines, so f2.writelines(f.readlines()) produces an exact copy of f in f2.

How to convert a const char * to std::string

std::string str(c_str, strnlen(c_str, max_length));

At Christian Rau's request:

strnlen is specified in POSIX.1-2008 and available in GNU's glibc and the Microsoft run-time library. It is not yet found in some other systems; you may fall back to Gnulib's substitute.

JavaScript Regular Expression Email Validation

Email validation is easy to get wrong. I would therefore recommend that you use Verimail.js.

Why?

  • Syntax validation (according to RFC 822).
  • IANA TLD validation
  • Spelling suggestion for the most common TLDs and email domains
  • Deny temporary email account domains such as mailinator.com
  • jQuery plugin support

Another great thing with Verimail.js is that it has spelling suggestion for the most common email domains and registered TLDs. This can lower your bounce rate drastically for users that misspell common domain names such as gmail.com, hotmail.com, aol.com, aso..

Example:

How to use it?

The easiest way is to download and include verimail.jquery.js on your page. After that, hookup Verimail by running the following function on the input-box that needs the validation:

$("input#email-address").verimail({
    messageElement: "p#status-message"
});

The message element is an optional element that displays a message such as "Invalid email.." or "Did you mean [email protected]?". If you have a form and only want to proceed if the email is verified, you can use the function getVerimailStatus as shown below:

if($("input#email-address").getVerimailStatus() < 0){
    // Invalid email
}else{
    // Valid email
}

The getVerimailStatus-function returns an integer code according to the object Comfirm.AlphaMail.Verimail.Status. As shown above, if the status is a negative integer value, then the validation should be treated as a failure. But if the value is greater or equal to 0, then the validation should be treated as a success.

Regex: match everything but specific pattern

Regex: match everything but:

Demo note: the newline \n is used inside negated character classes in demos to avoid match overflow to the neighboring line(s). They are not necessary when testing individual strings.

Anchor note: In many languages, use \A to define the unambiguous start of string, and \z (in Python, it is \Z, in JavaScript, $ is OK) to define the very end of the string.

Dot note: In many flavors (but not POSIX, TRE, TCL), . matches any char but a newline char. Make sure you use a corresponding DOTALL modifier (/s in PCRE/Boost/.NET/Python/Java and /m in Ruby) for the . to match any char including a newline.

Backslash note: In languages where you have to declare patterns with C strings allowing escape sequences (like \n for a newline), you need to double the backslashes escaping special characters so that the engine could treat them as literal characters (e.g. in Java, world\. will be declared as "world\\.", or use a character class: "world[.]"). Use raw string literals (Python r'\bworld\b'), C# verbatim string literals @"world\.", or slashy strings/regex literal notations like /world\./.

Proper indentation for Python multiline strings

You can use this function trim_indent.

import re


def trim_indent(s: str):
    s = re.sub(r'^\n+', '', s)
    s = re.sub(r'\n+$', '', s)
    spaces = re.findall(r'^ +', s, flags=re.MULTILINE)
    if len(spaces) > 0 and len(re.findall(r'^[^\s]', s, flags=re.MULTILINE)) == 0:
        s = re.sub(r'^%s' % (min(spaces)), '', s, flags=re.MULTILINE)
    return s


print(trim_indent("""


        line one
            line two
                line three
            line two
        line one


"""))

Result:

"""
line one
    line two
        line three
    line two
line one
"""

MS Access VBA: Sending an email through Outlook

Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.

Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")

Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing


End Sub

Git says remote ref does not exist when I delete remote branch

The command git branch -a shows remote branches that exist in your local repository. This may sound a bit confusing but to understand it, you have to understand that there is a difference between a remote branch, and a branch that exists in a remote repository. Remote branches are local branches that map to branches of the remote repository. So the set of remote branches represent the state of the remote repository.

The usual way to update the list of remote branches is to use git fetch. This automatically gets an updated list of branches from the remote and sets up remote branches in the local repository, also fetching any commit objects you may be missing.

However, by default, git fetch does not remove remote branches that no longer have a counterpart branch on the remote. In order to do that, you explicitly need to prune the list of remote branches:

git fetch --prune

This will automatically get rid of remote branches that no longer exist on the remote. Afterwards, git branch -r will show you an updated list of branches that really exist on the remote: And those you can delete using git push.

That being said, in order to use git push --delete, you need to specify the name of the branch on the remote repository; not the name of your remote branch. So to delete the branch test (represented by your remote branch origin/test), you would use git push origin --delete test.

Where can I find Android source code online?

This eclipse plugin allows for inline source viewing and even stepping inside the Android source code:

http://code.google.com/p/adt-addons/

(edit: specifically the "Android Sources" plugin: http://adt-addons.googlecode.com/svn/trunk/source/com.android.ide.eclipse.source.update/)

How to import an excel file in to a MySQL database

There's a simple online tool that can do this called sqlizer.io.

Screenshot from sqlizer.com

You upload an XLSX file to it, enter a sheet name and cell range, and it will generate a CREATE TABLE statement and a bunch of INSERT statements to import all your data into a MySQL database.

(Disclaimer: I help run SQLizer)

How to change line-ending settings

For a repository setting solution, that can be redistributed to all developers, check out the text attribute in the .gitattributes file. This way, developers dont have to manually set their own line endings on the repository, and because different repositories can have different line ending styles, global core.autocrlf is not the best, at least in my opinion.

For example unsetting this attribute on a given path [. - text] will force git not to touch line endings when checking in and checking out. In my opinion, this is the best behavior, as most modern text editors can handle both type of line endings. Also, if you as a developer still want to do line ending conversion when checking in, you can still set the path to match certain files or set the eol attribute (in .gitattributes) on your repository.

Also check out this related post, which describes .gitattributes file and text attribute in more detail: What's the best CRLF (carriage return, line feed) handling strategy with Git?

div inside php echo

Try this,

<?php  if ( ($cart->count_product) > 0) { ?>
         <div class="my_class"><?php print $cart->count_product; ?></div>
<?php } else { 
          print ''; 
}  ?>

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');
});

RegEx for valid international mobile phone number

Even if you write a regular expression that matches exactly the subset "valid phone numbers" out of strings, there is no way to guarantee (by way of a regular expression) that they are valid mobile phone numbers. In several countries, mobile phone numbers are indistinguishable from landline phone numbers without at least a number plan lookup, and in some cases, even that won't help. For example, in Sweden, lots of people have "ported" their regular, landline-like phone number to their mobile phone. It's still the same number as they had before, but now it goes to a mobile phone instead of a landline.

Since valid phone numbers consist only of digits, I doubt that rolling your own would risk missing some obscure case of phone number at least. If you want to have better certainty, write a generator that takes a list of all valid country codes, and requires one of them at the beginning of the phone number to be matched by the generated regular expression.

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

Don't use invalidations. They cannot be reverted and you will be charged. They only way it works for me is reducing the TTL and wait.

Regards

Escape a string for a sed replace pattern

The only three literal characters which are treated specially in the replace clause are / (to close the clause), \ (to escape characters, backreference, &c.), and & (to include the match in the replacement). Therefore, all you need to do is escape those three characters:

sed "s/KEYWORD/$(echo $REPLACE | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')/g"

Example:

$ export REPLACE="'\"|\\/><&!"
$ echo fooKEYWORDbar | sed "s/KEYWORD/$(echo $REPLACE | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')/g"
foo'"|\/><&!bar

How to show live preview in a small popup of linked page on mouse over on link?

You can use an iframe to display a preview of the page on mouseover:

_x000D_
_x000D_
.box{_x000D_
    display: none;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
a:hover + .box,.box:hover{_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    z-index: 100;_x000D_
}
_x000D_
This live preview for <a href="https://en.wikipedia.org/">Wikipedia</a>_x000D_
  <div class="box">_x000D_
    <iframe src="https://en.wikipedia.org/" width = "500px" height = "500px">_x000D_
    </iframe>_x000D_
  </div> _x000D_
remains open on mouseover.
_x000D_
_x000D_
_x000D_

Here's an example with multiple live previews:

_x000D_
_x000D_
.box{_x000D_
    display: none;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
a:hover + .box,.box:hover{_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    z-index: 100;_x000D_
}
_x000D_
Live previews for <a href="https://en.wikipedia.org/">Wikipedia</a>_x000D_
  <div class="box">_x000D_
     <iframe src="https://en.wikipedia.org/" width = "500px" height = "500px">_x000D_
     </iframe>_x000D_
  </div> _x000D_
and <a href="https://www.jquery.com/">JQuery</a>_x000D_
  <div class="box">_x000D_
     <iframe src="https://www.jquery.com/" width = "500px" height = "500px">_x000D_
     </iframe>_x000D_
  </div> _x000D_
will appear when these links are moused over.
_x000D_
_x000D_
_x000D_

What version of Python is on my Mac?

Use the which command. It will show you the path

which python

In which conda environment is Jupyter executing?

to show which conda env a notebook is using just type in a cell:

!conda info

if you have grep, a more direct way:

!conda info | grep 'active env'

Set background colour of cell to RGB value of data in cell

Sub AddColor()
    For Each cell In Selection
        R = Round(cell.Value)
        G = Round(cell.Offset(0, 1).Value)
        B = Round(cell.Offset(0, 2).Value)
        Cells(cell.Row, 1).Resize(1, 4).Interior.Color = RGB(R, G, B)
    Next cell
End Sub

Assuming that there are 3 columns R, G and B (in this order). Select first column ie R. press alt+F11 and run the above code. We have to select the first column (containing R or red values) and run the code every time we change the values to reflect the changes.

I hope this simpler code helps !

How to set up java logging using a properties file? (java.util.logging)

Okay, first intuition is here:

handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler
.level = ALL

The Java prop file parser isn't all that smart, I'm not sure it'll handle this. But I'll go look at the docs again....

In the mean time, try:

handlers = java.util.logging.FileHandler
java.util.logging.ConsoleHandler.level = ALL

Update

No, duh, needed more coffee. Nevermind.

While I think more, note that you can use the methods in Properties to load and print a prop-file: it might be worth writing a minimal program to see what java thinks it reads in that file.


Another update

This line:

    FileInputStream configFile = new FileInputStream("/path/to/app.properties"));

has an extra end-paren. It won't compile. Make sure you're working with the class file you think you are.

Easiest way to detect Internet connection on iOS?

Checking the Internet connection availability in (iOS) Xcode 8.2 , Swift 3.0

This is simple method for checking the network availability. I managed to translate it to Swift 2.0 and here the final code. The existing Apple Reachability class and other third party libraries seemed to be too complicated to translate to Swift.

This works for both 3G and WiFi connections.

Don’t forget to add “SystemConfiguration.framework” to your project builder.

//Create new swift class file Reachability in your project.

import SystemConfiguration

public class Reachability {
class func isConnectedToNetwork() -> Bool {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)
    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }
    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability! , &flags) {
        return false
    }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
   }
}

// Check network connectivity from anywhere in project by using this code.

if Reachability.isConnectedToNetwork() == true {
     print("Internet connection OK")
} else {
 print("Internet connection FAILED")
}

CSS Display an Image Resized and Cropped

Live Example: https://jsfiddle.net/de4Lt57z/

HTML:

<div class="crop">
  <img src="example.jpg" alt="..." />
</div>

CSS:

    .crop img{
      width:400px;
      height:300px;
      position: absolute;
      clip: rect(0px,200px, 150px, 0px);
      }

Explanation: Here image is resized by width and height value of the image. And crop is done by clip property.

For details about clip property follow: http://tympanus.net/codrops/2013/01/16/understanding-the-css-clip-property/

What is the list of supported languages/locales on Android?

Just FYI, if you are unable to set any locale, the problem might be below attribute in your app level gradle file:

resConfigs "en", "hi" //to specify allowed locales for your app

So, if you want to support any locale other than English and Hindi, specify your locale here or just remove above line. By default your app will support all the locales.

Thanks :)

How to quickly check if folder is empty (.NET)?

If you don't mind leaving pure C# and going for WinApi calls, then you might want to consider the PathIsDirectoryEmpty() function. According to the MSDN, the function:

Returns TRUE if pszPath is an empty directory. Returns FALSE if pszPath is not a directory, or if it contains at least one file other than "." or "..".

That seems to be a function which does exactly what you want, so it is probably well optimised for that task (although I haven't tested that).

To call it from C#, the pinvoke.net site should help you. (Unfortunately, it doesn't describe this certain function yet, but you should be able to find some functions with similar arguments and return type there and use them as the basis for your call. If you look again into the MSDN, it says that the DLL to import from is shlwapi.dll)

powershell is missing the terminator: "

In my specific case of the same issue, it was caused by not having the Powershell script saved with an encoding of Windows-1252 or UFT-8 WITH BOM.

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

To fix this problem, you have to install OpenSSL development package, which is available in standard repositories of all modern Linux distributions.

To install OpenSSL development package on Debian, Ubuntu or their derivatives:

$ sudo apt-get install libssl-dev

To install OpenSSL development package on Fedora, CentOS or RHEL:

$ sudo yum install openssl-devel 

Edit : As @isapir has pointed out, for Fedora version>=22 use the DNF package manager :

dnf install openssl-devel

laravel 5.4 upload image

This code will store the image in database.

$('#image').change(function(){
        // FileReader function for read the file.
        let reader = new FileReader();
        var base64;
        reader.readAsDataURL(this.files[0]); 

        //Read File
        let filereader = new FileReader();
        var selectedFile = this.files[0];

        // Onload of file read the file content
        filereader.onload = function(fileLoadedEvent) {
            base64 = fileLoadedEvent.target.result;
            $("#pimage").val(JSON.stringify(base64));
        };

        filereader.readAsDataURL(selectedFile); 
 });

HTML content should be like this.

<div class="col-xs-12 col-sm-4 col-md-4 user_frm form-group">
        <input id="image" type="file" class="inputMaterial" name="image">        
        <input type="hidden" id="pimage" name="pimage" value="">
        <span class="bar"></span>
    </div>

Store image data in database like this:

//property_image longtext(database field type)

 $data= array(
      'property_image' => trim($request->get('pimage'),'"')
 );

Display image:

<img src="{{$result->property_image}}" >

How to convert .pem into .key?

CA's don't ask for your private keys! They only asks for CSR to issue a certificate for you.

If they have your private key, it's possible that your SSL certificate will be compromised and end up being revoked.

Your .key file is generated during CSR generation and, most probably, it's somewhere on your PC where you generated the CSR.

That's why private key is called "Private" - because nobody can have that file except you.

Twitter-Bootstrap-2 logo image on top of navbar

You should remove navbar-fixed-top class otherwise navbar stays fixed on top of page where you want logo.


If you want to place logo inside navbar:

Navbar height (set in @navbarHeight LESS variable) is 40px by default. Your logo has to fit inside or you have to make navbar higher first.

Then use brand class:

<div class="navbar navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container">
      <a href="/" class="brand"><img alt="" src="/logo.gif" /></a>
    </div>
  </div>
</div>

If your logo is higher than 20px, you have to fix stylesheets as well.

If you do that in LESS:

.navbar .brand {
  @elementHeight: 32px;
  padding: ((@navbarHeight - @elementHeight) / 2 - 2) 20px ((@navbarHeight - @elementHeight) / 2 + 2);
}

@elementHeight should be set to your image height.

Padding calculation is taken from Twitter Bootstrap LESS - https://github.com/twitter/bootstrap/blob/v2.0.4/less/navbar.less#L51-52

Alternatively you can calculate padding values yourself and use pure CSS.

This works for Twitter Bootstrap versions 2.0.x, should work in 2.1 as well, but padding calculation was changed a bit: https://github.com/twitter/bootstrap/blob/v2.1.0/less/navbar.less#L50

Convert all data frame character columns to factors

I noticed "[" indexing columns fails to create levels when iterating:

for ( a_feature in convert.to.factors) {
feature.df[a_feature] <- factor(feature.df[a_feature]) }

It creates, e.g. for the "Status" column:

Status : Factor w/ 1 level "c(\"Success\", \"Fail\")" : NA NA NA ...

Which is remedied by using "[[" indexing:

for ( a_feature in convert.to.factors) {
feature.df[[a_feature]] <- factor(feature.df[[a_feature]]) }

Giving instead, as desired:

. Status : Factor w/ 2 levels "Success", "Fail" : 1 1 2 1 ...

How can I specify the default JVM arguments for programs I run from eclipse?

Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:

-Xmx512m -ea -Djava.awt.headless=true

When to use margin vs padding in CSS

Margin is on the outside of block elements while padding is on the inside.

  • Use margin to separate the block from things outside it
  • Use padding to move the contents away from the edges of the block.

enter image description here

VB.NET - Remove a characters from a String

You can use the string.replace method

string.replace("character to be removed", "character to be replaced with")

Dim strName As String
strName.Replace("[", "")

How to plot ROC curve in Python

It is not at all clear what the problem is here, but if you have an array true_positive_rate and an array false_positive_rate, then plotting the ROC curve and getting the AUC is as simple as:

import matplotlib.pyplot as plt
import numpy as np

x = # false_positive_rate
y = # true_positive_rate 

# This is the ROC curve
plt.plot(x,y)
plt.show() 

# This is the AUC
auc = np.trapz(y,x)

Blue and Purple Default links, how to remove?

By default link color is blue and the visited color is purple. Also, the text-decoration is underlined and the color is blue. If you want to keep the same color for visited, hover and focus then follow below code-

For example color is: #000

a:visited, a:hover, a:focus {
    text-decoration: none;
    color: #000;
}

If you want to use a different color for hover, visited and focus. For example Hover color: red visited color: green and focus color: yellow then follow below code

   a:hover {
        color: red;
    }
    a:visited {
        color: green;
    }
    a:focus {
        color: yellow;
    }

NB: good practice is to use color code.

Is there a way to word-wrap long words in a div?

You can try specifying a width for the div, whether it be in pixels, percentages or ems, and at that point the div will remain that width and the text will wrap automatically then within the div.

How do I perform an insert and return inserted identity with Dapper?

The InvalidCastException you are getting is due to SCOPE_IDENTITY being a Decimal(38,0).

You can return it as an int by casting it as follows:

string sql = @"
INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
SELECT CAST(SCOPE_IDENTITY() AS INT)";

int id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();

Can iterators be reset in Python?

I see many answers suggesting itertools.tee, but that's ignoring one crucial warning in the docs for it:

This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().

Basically, tee is designed for those situation where two (or more) clones of one iterator, while "getting out of sync" with each other, don't do so by much -- rather, they say in the same "vicinity" (a few items behind or ahead of each other). Not suitable for the OP's problem of "redo from the start".

L = list(DictReader(...)) on the other hand is perfectly suitable, as long as the list of dicts can fit comfortably in memory. A new "iterator from the start" (very lightweight and low-overhead) can be made at any time with iter(L), and used in part or in whole without affecting new or existing ones; other access patterns are also easily available.

As several answers rightly remarked, in the specific case of csv you can also .seek(0) the underlying file object (a rather special case). I'm not sure that's documented and guaranteed, though it does currently work; it would probably be worth considering only for truly huge csv files, in which the list I recommmend as the general approach would have too large a memory footprint.

Javascript window.open pass values using POST

I used a variation of the above but instead of printing html I built a form and submitted it to the 3rd party url:

    var mapForm = document.createElement("form");
    mapForm.target = "Map";
    mapForm.method = "POST"; // or "post" if appropriate
    mapForm.action = "http://www.url.com/map.php";

    var mapInput = document.createElement("input");
    mapInput.type = "text";
    mapInput.name = "addrs";
    mapInput.value = data;
    mapForm.appendChild(mapInput);

    document.body.appendChild(mapForm);

    map = window.open("", "Map", "status=0,title=0,height=600,width=800,scrollbars=1");

if (map) {
    mapForm.submit();
} else {
    alert('You must allow popups for this map to work.');
}

How to use ng-repeat without an html element

As of AngularJS 1.2 there's a directive called ng-repeat-start that does exactly what you ask for. See my answer in this question for a description of how to use it.

Removing the password from a VBA project

I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.

This one does not use SendKeys.

Let me know if this helps! JFV

Printing the correct number of decimal points with cout

I had an issue for integers while wanting consistent formatting.

A rewrite for completeness:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    //    floating point formatting example
    cout << fixed << setprecision(2) << 122.345 << endl;
    //    Output:  122.34

    //    integer formatting example
    cout << fixed << setprecision(2) << double(122) << endl;
    //    Output:  122.00
}

jQuery toggle CSS?

You might want to use jQuery's .addClass and .removeClass commands, and create two different classes for the states. This, to me, would be the best practice way of doing it.

Removing all script tags from html with JS Regular Expression

Regexes are beatable, but if you have a string version of HTML that you don't want to inject into a DOM, they may be the best approach. You may want to put it in a loop to handle something like:

<scr<script>Ha!</script>ipt> alert(document.cookie);</script>

Here's what I did, using the jquery regex from above:

var SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
while (SCRIPT_REGEX.test(text)) {
    text = text.replace(SCRIPT_REGEX, "");
}

How to make space between LinearLayout children?

You can get the LayoutParams of parent LinearLayout and apply to the individual views this way:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(8,8,8,8);
  • Take care that setMargins() take pixels as int data type.So, convert to dp before adding values
  • Above code will set height and width to wrap_content. you can customise it.

Is Tomcat running?

I always do

tail -f logs/catalina.out

When I see there

INFO: Server startup in 77037 ms

then I know the server is up.

Query to get all rows from previous month

Here's another alternative. Assuming you have an indexed DATE or DATETIME type field, this should use the index as the formatted dates will be type converted before the index is used. You should then see a range query rather than an index query when viewed with EXPLAIN.

SELECT
    * 
FROM
    table
WHERE 
    date_created >= DATE_FORMAT( CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01' ) 
AND
    date_created < DATE_FORMAT( CURRENT_DATE, '%Y/%m/01' )

How do I get the computer name in .NET

You can have access of the machine name using Environment.MachineName.

React - Display loading screen while DOM is rendering?

If anyone looking for a drop-in, zero-config and zero-dependencies library for the above use-case, try pace.js (http://github.hubspot.com/pace/docs/welcome/).

It automatically hooks to events (ajax, readyState, history pushstate, js event loop etc) and show a customizable loader.

Worked well with our react/relay projects (handles navigation changes using react-router, relay requests) (Not affliated; had used pace.js for our projects and it worked great)

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

for reading the entire line you can use nextLine()

Flutter command not found

First, download the Flutter here: https://flutter.dev/docs/get-started/install/macos

When you created the folder with Flutter SDK, open it in Terminal using the following command:

cd ~/development

If there is no development folder run this command first:

mkdir /development

After that, you need to run the unzip command. Make sure you specify the correct path to the downloaded Flutter archive file. Run the command below:

unzip ~/Downloads/flutter_macos_1.17.1-stable.zip

Setting the Flutter tool path

In order to set up the Flutter tool path you should run this command:

export PATH="$PATH:`pwd`/flutter/bin"

Next, you need to know which shell you are using. For this run this command:

echo $SHELL

Depending on the shell run the following command: [Note, the command you will be using depends on the shell you have.]

sudo nano ~/.zshrc

or

sudo nano /.bashrc 

After that in the new window, you need to add a path to the flutter tool.

Use the following command:

export PATH=$PATH:~/development/flutter/bin

The next thing you need to do is to check the Flutter dependencies.

For this, run the command:

flutter doctor

This operation will help you to identify if there are any dependencies you need to install. After the results will be prepared click Agree and wait for the installation of the needed dependencies to complete the setup. enter image description here

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

Check if a folder exist in a directory and create them using C#

using System.IO;
...

Directory.CreateDirectory(@"C:\MP_Upload");

Directory.CreateDirectory does exactly what you want: It creates the directory if it does not exist yet. There's no need to do an explicit check first.

Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing.

(This also means that all directories along the path are created if needed: CreateDirectory(@"C:\a\b\c\d") suffices, even if C:\a does not exist yet.)


Let me add a word of caution about your choice of directory, though: Creating a folder directly below the system partition root C:\ is frowned upon. Consider letting the user choose a folder or creating a folder in %APPDATA% or %LOCALAPPDATA% instead (use Environment.GetFolderPath for that). The MSDN page of the Environment.SpecialFolder enumeration contains a list of special operating system folders and their purposes.

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

just add

$autoload['helper'] = array('url');

in autoload.php in your config file

How to get the number of days of difference between two dates on mysql?

Get days between Current date to destination Date

 SELECT DATEDIFF('2019-04-12', CURDATE()) AS days;

output

days

 335

How to run TypeScript files from command line?

Write yourself a simple bash wrapper may helps.

#!/bin/bash
npx tsc $1 && node ${1%%.ts}

"Please try running this command again as Root/Administrator" error when trying to install LESS

This is what I had to do to get started with a Less compiler to avoid issues as mentionned in the OP:

  1. Install node.js
  2. Install NPM with Terminal: sudo npm install npm -g
  3. Install a Less compiler with Terminal: sudo npm install -g less (the sudo makes all the difference)
  4. If you're using PHPstorm: Go to "Preferences… > Plugins" and install NodeJS-plugin (might need to "browse repositories" to find it) and restart PHPstorm (as prompted)
  5. After that go to Plugins once again: Install Less compiler (might need to "browse repositories" to find it) and restart PHPstorm (as prompted)
  6. Once you have a project set up, go to "Settings > Tools > Filewatchers" and add "Less". The path (of the "Program") should read something like this: /usr/local/bin/lessc
  7. Make sure Track only root files is checked in the settings of 6.

m2e error in MavenArchiver.getManifest()

I also faced the similar issues, changing the version from 2.0.0.RELEASE to 1.5.10.RELEASE worked for me, please try it before downgrading the maven version

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<dependencies>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
 </dependency>  
</dependencies>

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

How to pass a form input value into a JavaScript function

More stable approach:

<form onsubmit="foo($("#formValueId").val());return false;">
<input type="text" id="formValueId"/>
<input type="submit" value="Text on the button"/>
</form>

The return false; is to prevent actual form submit (assuming you want that).

How to delete all files and folders in a folder by cmd call

try this, this will search all MyFolder under root dir and delete all folders named MyFolder

for /d /r "C:\Users\test" %%a in (MyFolder\) do if exist "%%a" rmdir /s /q "%%a"

How to apply !important using .css()?

May be it look's like this:

Cache

var node = $('.selector')[0];
OR
var node = document.querySelector('.selector');

Set CSS

node.style.setProperty('width', '100px', 'important');

Remove CSS

node.style.removeProperty('width');
OR
node.style.width = '';

Reading CSV file and storing values into an array

LINQ way:

var lines = File.ReadAllLines("test.txt").Select(a => a.Split(';'));
var csv = from line in lines
          select (from piece in line
                  select piece);

^^Wrong - Edit by Nick

It appears the original answerer was attempting to populate csv with a 2 dimensional array - an array containing arrays. Each item in the first array contains an array representing that line number with each item in the nested array containing the data for that specific column.

var csv = from line in lines
          select (line.Split(',')).ToArray();

Nginx -- static file serving confusion with root & alias

In your case, you can use root directive, because $uri part of the location directive is the same with last root directive part.

Nginx documentation advices it as well:
When location matches the last part of the directive’s value:

location /images/ {
    alias /data/w3/images/;
}

it is better to use the root directive instead:

location /images/ {
    root /data/w3;
}

and root directive will append $uri to the path.

Finding out current index in EACH loop (Ruby)

x.each_with_index { |v, i| puts "current index...#{i}" }

Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"

You can also do this

public class Example extends Activity {
    final Context context = this;
    final Dialog dialog = new Dialog(context);
}

This worked for me !!

How to check whether an object has certain method/property?

You could write something like that :

public static bool HasMethod(this object objectToCheck, string methodName)
{
    var type = objectToCheck.GetType();
    return type.GetMethod(methodName) != null;
} 

Edit : you can even do an extension method and use it like this

myObject.HasMethod("SomeMethod");

jQuery to remove an option from drop down list, given option's text/value

$('#id option').remove();

This will clear the Drop Down list. if you want to clear to select value then $("#id option:selected").remove();

How to show one layout on top of the other programmatically in my case?

Use a FrameLayout with two children. The two children will be overlapped. This is recommended in one of the tutorials from Android actually, it's not a hack...

Here is an example where a TextView is displayed on top of an ImageView:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <ImageView  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 

    android:scaleType="center"
    android:src="@drawable/golden_gate" />

  <TextView
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginBottom="20dip"
    android:layout_gravity="center_horizontal|bottom"

    android:padding="12dip"

    android:background="#AA000000"
    android:textColor="#ffffffff"

    android:text="Golden Gate" />

</FrameLayout>

Here is the result

How to check if file already exists in the folder

Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"

Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.

If System.IO.File.Exists(SavePath) Then
   'The file exists
Else
    'the file doesn't exist
End If

Installing pip packages to $HOME folder

I would use virtualenv at your HOME directory.

$ sudo easy_install -U virtualenv
$ cd ~
$ virtualenv .
$ bin/pip ...

You could then also alter ~/.(login|profile|bash_profile), whichever is right for your shell to add ~/bin to your PATH and then that pip|python|easy_install would be the one used by default.

Jenkins fails when running "service start jenkins"

I had below error:

Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.

Solution was to revert the NAME to jenkins in the below file (Earlier I have changed it to 'NAME=ubuntu'):

sudo vi /etc/default/jenkins
    NAME=jenkins

Now restart passed:

sudo service jenkins restart
sudo systemctl restart jenkins.service

Hope that helps.

What's the PowerShell syntax for multiple values in a switch statement?

The switch doesn't appear to be case sensitive in PowerShell 5.1. All four of the $someString examples below work.

$someString = "YES"
$someString = "yes"
$someString = "yEs"
$someString = "y"

switch ($someString) {
   {"y","yes"} { "You entered Yes." }
   Default { "You didn't enter Yes."}
}

Here is my $PSVersionTable data.

Name                           Value
----                           -----
PSVersion                      5.1.17763.771
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17763.771
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

How to run a stored procedure in oracle sql developer?

Try to execute the procedure like this,

var c refcursor;
execute pkg_name.get_user('14232', '15', 'TDWL', 'SA', 1, :c);
print c;

Mail multipart/alternative vs multipart/mixed

Use multipart/mixed with the first part as multipart/alternative and subsequent parts for the attachments. In turn, use text/plain and text/html parts within the multipart/alternative part.

A capable email client should then recognise the multipart/alternative part and display the text part or html part as necessary. It should also show all of the subsequent parts as attachment parts.

The important thing to note here is that, in multipart MIME messages, it is perfectly valid to have parts within parts. In theory, that nesting can extend to any depth. Any reasonably capable email client should then be able to recursively process all of the message parts.

What is an Intent in Android?

what is Intent ?

It is a kind of message or information that is passed to the components. It is used to launch an activity, display a web page, send sms, send email etc.

There are two types of intents in android:

Implicit Intent
Explicit Intent

Implicit intent is used to invoke the system components

Example

Intent i = newIntent(android.content.Intent.ACTION_VIEW,Uri.parse(“http://www.amazon.com”));

startActivity(i);

Explicit intent is used to invoke the activity class.

Example

Intent intent = newIntent (this, SecondActivity.class);

startActivity(intent);

you can read more

http://www.vogella.com/tutorials/AndroidIntent/article.html#intents_overview http://developer.android.com/reference/android/content/Intent.html

How to change screen resolution of Raspberry Pi

TV Sony Bravia KLV-32T550A Below mention config works greatly You should add the following into the /boot/config.txt to force the output to HDMI and set the

resolution 82   1920x1080   60Hz    1080p

hdmi_ignore_edid=0xa5000080
hdmi_force_hotplug=1
hdmi_boost=7
hdmi_group=2
hdmi_mode=82
hdmi_drive=1

What is an efficient way to implement a singleton pattern in Java?

Sometimes a simple "static Foo foo = new Foo();" is not enough. Just think of some basic data insertion you want to do.

On the other hand you would have to synchronize any method that instantiates the singleton variable as such. Synchronisation is not bad as such, but it can lead to performance issues or locking (in very very rare situations using this example. The solution is

public class Singleton {

    private static Singleton instance = null;

    static {
          instance = new Singleton();
          // do some of your instantiation stuff here
    }

    private Singleton() {
          if(instance!=null) {
                  throw new ErrorYouWant("Singleton double-instantiation, should never happen!");
          }
    }

    public static getSingleton() {
          return instance;
    }

}

Now what happens? The class is loaded via the class loader. Directly after the class was interpreted from a byte Array, the VM executes the static { } - block. that's the whole secret: The static-block is only called once, the time the given class (name) of the given package is loaded by this one class loader.

Using BeautifulSoup to extract text without tags

I think you could solve this with .strip() in gazpacho:

Input:

html = """\
<p>
  <strong class="offender">YOB:</strong> 1987<br />
  <strong class="offender">RACE:</strong> WHITE<br />
  <strong class="offender">GENDER:</strong> FEMALE<br />
  <strong class="offender">HEIGHT:</strong> 5'05''<br />
  <strong class="offender">WEIGHT:</strong> 118<br />
  <strong class="offender">EYE COLOR:</strong> GREEN<br />
  <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""

Code:

soup = Soup(html)
text = soup.find("p").strip(whitespace=False) # to keep \n characters intact
lines = [
    line.strip()
    for line in text.split("\n")
    if line != ""
]
data = dict([line.split(": ") for line in lines])

Output:

print(data)
# {'YOB': '1987',
#  'RACE': 'WHITE',
#  'GENDER': 'FEMALE',
#  'HEIGHT': "5'05''",
#  'WEIGHT': '118',
#  'EYE COLOR': 'GREEN',
#  'HAIR COLOR': 'BROWN'}

Set order of columns in pandas dataframe

You can also use OrderedDict:

In [183]: from collections import OrderedDict

In [184]: data = OrderedDict()

In [185]: data['one thing'] = [1,2,3,4]

In [186]: data['second thing'] = [0.1,0.2,1,2]

In [187]: data['other thing'] = ['a','e','i','o']

In [188]: frame = pd.DataFrame(data)

In [189]: frame
Out[189]:
   one thing  second thing other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           2.0           o

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

To anyone who is still interested in this question: If: 1-decodeByteArray returns null 2-Base64.decode throws bad-base64 Exception

Here is the solution: -You should consider the value sent to you from API is Base64 Encoded and should be decoded first in order to cast it to a Bitmap object! -Take a look at your Base64 encoded String, If it starts with

data:image/jpg;base64

The Base64.decode won't be able to decode it, So it has to be removed from your encoded String:

final String encodedString = "data:image/jpg;base64, ....";                        
final String pureBase64Encoded = encodedString.substring(encodedString.indexOf(",")  + 1);

Now the pureBase64Encoded object is ready to be decoded:

final byte[] decodedBytes = Base64.decode(pureBase64Encoded, Base64.DEFAULT);

Now just simply use the line below to turn this into a Bitmap Object! :

Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);

Or if you're using the great library Glide:

Glide.with(CaptchaFragment.this).load(decodedBytes).crossFade().fitCenter().into(mCatpchaImageView);

This should do the job! It wasted one day on this and came up to this solution!

Note: If you are still getting bad-base64 error consider other Base64.decode flags like Base64.URL_SAFE and so on

How to call a method in MainActivity from another class?

I would suggest, one should not make object of an Activity type class.

MainActivity mActivity = new MainActivity();  // BIG NO TO THIS.

All Activities in Android must go through the Activity lifecycle so that they have a valid context attached to them.

By treating an Activity as a normal Java class, you end up with a null context. As most methods in an Activity are called on its Context, you will get a null pointer exception, which is why your app crashes.

Instead, move all such methods which need to be called from other classes into a Utility class which accepts a valid context in its constructor, and then use that context in the methods to do the work.

How to add an image to the emulator gallery in android studio?

After trying to add an image via the Device Monitor or via drop, I could find it when exploring, but it was still not shown in the Gallery.

For me, it helped to eject the (virtual) sdcard from Settings > Storage & USB and reinserting it.

How can I get Android Wifi Scan Results into a list?

Try this code

public class WiFiDemo extends Activity implements OnClickListener
 {      
    WifiManager wifi;       
    ListView lv;
    TextView textStatus;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
    SimpleAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        textStatus = (TextView) findViewById(R.id.textStatus);
        buttonScan = (Button) findViewById(R.id.buttonScan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.list);

        wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }   
        this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
        lv.setAdapter(this.adapter);

        registerReceiver(new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context c, Intent intent) 
            {
               results = wifi.getScanResults();
               size = results.size();
            }
        }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));                    
    }

    public void onClick(View view) 
    {
        arraylist.clear();          
        wifi.startScan();

        Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
        try 
        {
            size = size - 1;
            while (size >= 0) 
            {   
                HashMap<String, String> item = new HashMap<String, String>();                       
                item.put(ITEM_KEY, results.get(size).SSID + "  " + results.get(size).capabilities);

                arraylist.add(item);
                size--;
                adapter.notifyDataSetChanged();                 
            } 
        }
        catch (Exception e)
        { }         
    }    
}

WiFiDemo.xml :

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textStatus"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Status" />

        <Button
            android:id="@+id/buttonScan"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:text="Scan" />
    </LinearLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="20dp"></ListView>
</LinearLayout>

For ListView- row.xml

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

    <TextView
        android:id="@+id/list_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14dp" />
</LinearLayout>

Add these permission in AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Convert List to Pandas Dataframe Column

For Converting a List into Pandas Core Data Frame, we need to use DataFrame Method from pandas Package.

There are Different Ways to Perform the Above Operation.

import pandas as pd

  1. pd.DataFrame({'Column_Name':Column_Data})
  • Column_Name : String
  • Column_Data : List Form
  1. Data = pd.DataFrame(Column_Data)

    Data.columns = ['Column_Name']

So, for the above mentioned issue, the code snippet is

import pandas as pd

Content = ['Thanks You',
           'Its fine no problem',
           'Are you sure']

Data = pd.DataFrame({'Text': Content})

Repeat rows of a data.frame

There is a lovely vectorized solution that repeats only certain rows n-times each, possible for example by adding an ntimes column to your data frame:

  A B   C ntimes
1 j i 100      2
2 K P 101      4
3 Z Z 102      1

Method:

df <- data.frame(A=c("j","K","Z"), B=c("i","P","Z"), C=c(100,101,102), ntimes=c(2,4,1))
df <- as.data.frame(lapply(df, rep, df$ntimes))

Result:

  A B   C ntimes
1 Z Z 102      1
2 j i 100      2
3 j i 100      2
4 K P 101      4
5 K P 101      4
6 K P 101      4
7 K P 101      4

This is very similar to Josh O'Brien and Mark Miller's method:

df[rep(seq_len(nrow(df)), df$ntimes),]

However, that method appears quite a bit slower:

df <- data.frame(A=c("j","K","Z"), B=c("i","P","Z"), C=c(100,101,102), ntimes=c(2000,3000,4000))

microbenchmark::microbenchmark(
  df[rep(seq_len(nrow(df)), df$ntimes),],
  as.data.frame(lapply(df, rep, df$ntimes)),
  times = 10
)

Result:

Unit: microseconds
                                      expr      min       lq      mean   median       uq      max neval
   df[rep(seq_len(nrow(df)), df$ntimes), ] 3563.113 3586.873 3683.7790 3613.702 3657.063 4326.757    10
 as.data.frame(lapply(df, rep, df$ntimes))  625.552  654.638  676.4067  668.094  681.929  799.893    10

Bootstrap : TypeError: $(...).modal is not a function

If you are using any layout page then, move script sections from bottom to head section in layout page. bcz, javascript files should be loaded first. This worked for me

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

I can see great answers, so there's no need to repeat here, so I'd like to offer some advice:

I would recommend using a Unix Timestamp integer instead of a human-readable date format to handle time internally, then use PHP's date() function to convert the timestamp value into a human-readable date format for user display. Here's a crude example of how it should be done:

// Get unix timestamp in seconds
$current_time = date();

// Or if you need millisecond precision

// Get unix timestamp in milliseconds
$current_time = microtime(true);

Then use $current_time as needed in your app (store, add or subtract, etc), then when you need to display the date value it to your users, you can use date() to specify your desired date format:

// Display a human-readable date format
echo date('d-m-Y', $current_time);

This way you'll avoid much headache dealing with date formats, conversions and timezones, as your dates will be in a standardized format (Unix Timestamp) that is compact, timezone-independent (always in UTC) and widely supported in programming languages and databases.

What is offsetHeight, clientHeight, scrollHeight?

My descriptions for the three:

  • offsetHeight: How much of the parent's "relative positioning" space is taken up by the element. (ie. it ignores the element's position: absolute descendents)
  • clientHeight: Same as offset-height, except it excludes the element's own border, margin, and the height of its horizontal scroll-bar (if it has one).
  • scrollHeight: How much space is needed to see all of the element's content/descendents (including position: absolute ones) without scrolling.

Then there is also:

Check if a string within a list contains a specific string with Linq

LINQ Any() would do the job:

bool contains = myList.Any(s => s.Contains(pattern));

Any(), MSDN:

Determines whether any element of a sequence satisfies a condition

CSS : center form in page horizontally and vertically

you can use display:flex to do this : http://codepen.io/anon/pen/yCKuz

html,body {
  height:100%;
  width:100%;
  margin:0;
}
body {
  display:flex;
}
form {
  margin:auto;/* nice thing of auto margin if display:flex; it center both horizontal and vertical :) */
}

or display:table http://codepen.io/anon/pen/LACnF/

body, html {   
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    display:table;
}
body {
    display:table-cell;
    vertical-align:middle;
}
form {
    display:table;/* shrinks to fit content */
    margin:auto;
}

Text not wrapping inside a div element

you can add this line: word-break:break-all; to your CSS-code

facebook: permanent Page Access Token?

If you are requesting only page data, then you can use a page access token. You will only have to authorize the user once to get the user access token; extend it to two months validity then request the token for the page. This is all explained in Scenario 5. Note, that the acquired page access token is only valid for as long as the user access token is valid.

How to append rows to an R data frame

A more generic solution for might be the following.

    extendDf <- function (df, n) {
    withFactors <- sum(sapply (df, function(X) (is.factor(X)) )) > 0
    nr          <- nrow (df)
    colNames    <- names(df)
    for (c in 1:length(colNames)) {
        if (is.factor(df[,c])) {
            col         <- vector (mode='character', length = nr+n) 
            col[1:nr]   <- as.character(df[,c])
            col[(nr+1):(n+nr)]<- rep(col[1], n)  # to avoid extra levels
            col         <- as.factor(col)
        } else {
            col         <- vector (mode=mode(df[1,c]), length = nr+n)
            class(col)  <- class (df[1,c])
            col[1:nr]   <- df[,c] 
        }
        if (c==1) {
            newDf       <- data.frame (col ,stringsAsFactors=withFactors)
        } else {
            newDf[,c]   <- col 
        }
    }
    names(newDf) <- colNames
    newDf
}

The function extendDf() extends a data frame with n rows.

As an example:

aDf <- data.frame (l=TRUE, i=1L, n=1, c='a', t=Sys.time(), stringsAsFactors = TRUE)
extendDf (aDf, 2)
#      l i n c                   t
# 1  TRUE 1 1 a 2016-07-06 17:12:30
# 2 FALSE 0 0 a 1970-01-01 01:00:00
# 3 FALSE 0 0 a 1970-01-01 01:00:00

system.time (eDf <- extendDf (aDf, 100000))
#    user  system elapsed 
#   0.009   0.002   0.010
system.time (eDf <- extendDf (eDf, 100000))
#    user  system elapsed 
#   0.068   0.002   0.070

Swift Beta performance: sorting arrays

func partition(inout list : [Int], low: Int, high : Int) -> Int {
    let pivot = list[high]
    var j = low
    var i = j - 1
    while j < high {
        if list[j] <= pivot{
            i += 1
            (list[i], list[j]) = (list[j], list[i])
        }
        j += 1
    }
    (list[i+1], list[high]) = (list[high], list[i+1])
    return i+1
}

func quikcSort(inout list : [Int] , low : Int , high : Int) {

    if low < high {
        let pIndex = partition(&list, low: low, high: high)
        quikcSort(&list, low: low, high: pIndex-1)
        quikcSort(&list, low: pIndex + 1, high: high)
    }
}

var list = [7,3,15,10,0,8,2,4]
quikcSort(&list, low: 0, high: list.count-1)

var list2 = [ 10, 0, 3, 9, 2, 14, 26, 27, 1, 5, 8, -1, 8 ]
quikcSort(&list2, low: 0, high: list2.count-1)

var list3 = [1,3,9,8,2,7,5]
quikcSort(&list3, low: 0, high: list3.count-1) 

This is my Blog about Quick Sort- Github sample Quick-Sort

You can take a look at Lomuto's partitioning algorithm in Partitioning the list. Written in Swift.

How to make div follow scrolling smoothly with jQuery?

Since this question is getting a lot of views and the tutorial linked in the most voted answer appears to be offline, I took the time to clean up this script.

See it live here: JSFiddle

JavaScript:

(function($) {
    var element = $('.follow-scroll'),
        originalY = element.offset().top;

    // Space between element and top of screen (when scrolling)
    var topMargin = 20;

    // Should probably be set in CSS; but here just for emphasis
    element.css('position', 'relative');

    $(window).on('scroll', function(event) {
        var scrollTop = $(window).scrollTop();

        element.stop(false, false).animate({
            top: scrollTop < originalY
                    ? 0
                    : scrollTop - originalY + topMargin
        }, 300);
    });
})(jQuery);

Alert after page load

$(window).on('load', function () {
 alert('Alert after page load');
        }
    });

How can I use getSystemService in a non-activity class (LocationManager)?

I don't know if this will help, but I did this:

LocationManager locationManager  = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);

Spring Resttemplate exception handling

Here is my POST method with HTTPS which returns a response body for any type of bad responses.

public String postHTTPSRequest(String url,String requestJson)
{
    //SSL Context
    CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    //Initiate REST Template
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    //Send the Request and get the response.
    HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
    ResponseEntity<String> response;
    String stringResponse = "";
    try {
        response = restTemplate.postForEntity(url, entity, String.class);
        stringResponse = response.getBody();
    }
    catch (HttpClientErrorException e)
    {
        stringResponse = e.getResponseBodyAsString();
    }
    return stringResponse;
}

What is the $? (dollar question mark) variable in shell scripting?

It is well suited for debugging in case your script exit if set -e is used. For example, put echo $? after the command that cause it to exit and see the returned error value.

jQuery/JavaScript: accessing contents of an iframe

If the <iframe> is from the same domain, the elements are easily accessible as

$("#iFrame").contents().find("#someDiv").removeClass("hidden");

Reference

PDOException SQLSTATE[HY000] [2002] No such file or directory

I'm running on MAMP Pro and had this similar problem when trying to migrate (create db tables). Tried a few of these mentioned suggestions as well but didn't do it for me.

So, simply (after an hour googling), I added two things to the /config/database.php.

'port' => '1234',
'unix_socket' => '/path/to/my/socket/mysqld.sock'

Works fine now!

how to make password textbox value visible when hover an icon

I use this one line of code, it should do it:

<input type="password"
       onmousedown="this.type='text'"
       onmouseup="this.type='password'"
       onmousemove="this.type='password'">

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

I don't use Retrofit and for OkHttp here is the only solution for self-signed certificate that worked for me:

  1. Get a certificate from our site like in Gowtham's question and put it into res/raw dir of the project:

    echo -n | openssl s_client -connect elkews.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ./res/raw/elkews_cert.crt
    
  2. Use Paulo answer to set ssl factory (nowadays using OkHttpClient.Builder()) but without RestAdapter creation.

  3. Then add the following solution to fix: SSLPeerUnverifiedException: Hostname not verified

So the end of Paulo's code (after sslContext initialization) that is working for me looks like the following:

...
OkHttpClient.Builder builder = new OkHttpClient.Builder().sslSocketFactory(sslContext.getSocketFactory());
builder.hostnameVerifier(new HostnameVerifier() {
  @Override
  public boolean verify(String hostname, SSLSession session) {
    return "secure.elkews.com".equalsIgnoreCase(hostname);
});
OkHttpClient okHttpClient = builder.build();

Can't clone a github repo on Linux via HTTPS

I met the same problem, the error message and OS info are as follows

OS info:

CentOS release 6.5 (Final)

Linux 192-168-30-213 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

error info:

Initialized empty Git repository in /home/techops/pyenv/.git/ Password: error: while accessing https://[email protected]/pyenv/pyenv.git/info/refs

fatal: HTTP request failed

git & curl version info

git info :git version 1.7.1

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 Protocols: tftp ftp telnet dict ldap ldaps http file https ftps scp sftp Features: GSS-Negotiate IDN IPv6 Largefile NTLM SSL libz

debugging

$ curl --verbose https://github.com

  • About to connect() to github.com port 443 (#0)
  • Trying 13.229.188.59... connected
  • Connected to github.com (13.229.188.59) port 443 (#0)
  • Initializing NSS with certpath: sql:/etc/pki/nssdb
  • CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none
  • NSS error -12190
  • Error in TLS handshake, trying SSLv3... GET / HTTP/1.1 User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 Host: github.com Accept: /

  • Connection died, retrying a fresh connect

  • Closing connection #0
  • Issue another request to this URL: 'https://github.com'
  • About to connect() to github.com port 443 (#0)
  • Trying 13.229.188.59... connected
  • Connected to github.com (13.229.188.59) port 443 (#0)
  • TLS disabled due to previous handshake failure
  • CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none
  • NSS error -12286
  • Closing connection #0
  • SSL connect error curl: (35) SSL connect error

after upgrading curl , libcurl and nss , git clone works fine again, so here it is. the update command is as follows

sudo yum update -y nss curl libcurl

Is there a way to get version from package.json in nodejs code?

I found that the following code fragment worked best for me. Since it uses require to load the package.json, it works regardless the current working directory.

var pjson = require('./package.json');
console.log(pjson.version);

A warning, courtesy of @Pathogen:

Doing this with Browserify has security implications.
Be careful not to expose your package.json to the client, as it means that all your dependency version numbers, build and test commands and more are sent to the client.
If you're building server and client in the same project, you expose your server-side version numbers too. Such specific data can be used by an attacker to better fit the attack on your server.

Couldn't connect to server 127.0.0.1:27017

After removing mongod.lock which was inside the data directory in my windows OS,it was still showing the same error message. I had to run mongod with --dbpath to make the mongo command run without errors.

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

When you use prototype, the function will only be loaded only once into memory (independently on the amount of objects you create) and you can override the function whenever you want.

Make Bootstrap's Carousel both center AND responsive?

On Boostrap 4 simply add mx-auto to your carousel image class.

<div class="carousel-item">
  <img class="d-block mx-auto" src="http://placehold.it/600x400" />
</div> 

Combine with the samples from the bootstrap carousel documentation as desired.

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

If you use this, check man sudo too:

#!/bin/bash

sudo echo "Hi, I'm root"

sudo -u nobody echo "I'm nobody"

sudo -u 1000 touch /test_user

How do I ignore a directory with SVN?

"Thank-you" svn for such a hideous, bogus and difficult way to ignore files.

So I wrote a script svn-ignore-all:

#!/bin/sh

# svn-ignore-all

# usage: 
#   1. run svn status to see what is going on at each step 
#   2. add or commit all files that you DO want to have in svn
#   3. remove any random files that you don't want to svn:ignore
#   4. run this script to svn:ignore everything marked '?' in output of `svn status`

svn status |
grep '^?' |
sed 's/^? *//' |
while read f; do
    d=`dirname "$f"`
    b=`basename "$f"`
    ignore=`svn propget svn:ignore "$d"`
    if [ -n "$ignore" ]; then
        ignore="$ignore
"
    fi
    ignore="$ignore$b"
    svn propset svn:ignore "$ignore" "$d"
done

Also, to ignore specific list of files / pathnames, we can use this variant svn-ignore. I guess svn-ignore-all should really be like xargs svn-ignore.

#!/bin/sh

# svn-ignore

# usage:
#   svn-ignore file/to/ignore ...

for f; do
    d=`dirname "$f"`
    b=`basename "$f"`
    ignore=`svn propget svn:ignore "$d"`
    if [ -n "$ignore" ]; then
        ignore="$ignore
"
    fi
    ignore="$ignore$b"
    svn propset svn:ignore "$ignore" "$d"
done

One more thing: I tend to pollute my svn checkouts with many random files. When it's time to commit, I move those files into an 'old' subdirectory, and tell svn to ignore 'old'.

How to print full stack trace in exception?

1. Create Method: If you pass your exception to the following function, it will give you all methods and details which are reasons of the exception.

public string GetAllFootprints(Exception x)
{
        var st = new StackTrace(x, true);
        var frames = st.GetFrames();
        var traceString = new StringBuilder();

        foreach (var frame in frames)
        {
            if (frame.GetFileLineNumber() < 1)
                continue;

            traceString.Append("File: " + frame.GetFileName());
            traceString.Append(", Method:" + frame.GetMethod().Name);
            traceString.Append(", LineNumber: " + frame.GetFileLineNumber());
            traceString.Append("  -->  ");
        }

        return traceString.ToString();
}

2. Call Method: You can call the method like this.

try
{
    // code part which you want to catch exception on it
}
catch(Exception ex)
{
    Debug.Writeline(GetAllFootprints(ex));
}

3. Get the Result:

File: c:\MyProject\Program.cs, Method:MyFunction, LineNumber: 29  -->  
File: c:\MyProject\Program.cs, Method:Main, LineNumber: 16  --> 

AngularJS: Can't I set a variable value on ng-click?

If you are using latest versions of Angular (2/5/6) :

In your component.ts

//x.component.ts
prefs = false;

hidePrefs(){
   this.prefs = true;
}

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

When solving this issue for myself, I used this GitHub tutorial, which analysed the cause of this issue. If we read in between the lines, it says it needs system as well as python graph viz. In addition to conda install, we would need to run:

conda install -c conda-forge python-graphviz

Then restart the kernel; it works like a charm.

Sending private messages to user

This is pretty simple here is an example

Add your command code here like:

if (cmd === `!dm`) {
 let dUser =
  message.guild.member(message.mentions.users.first()) ||
  message.guild.members.get(args[0]);
 if (!dUser) return message.channel.send("Can't find user!");
 if (!message.member.hasPermission('ADMINISTRATOR'))
  return message.reply("You can't you that command!");
 let dMessage = args.join(' ').slice(22);
 if (dMessage.length < 1) return message.reply('You must supply a message!');

 dUser.send(`${dUser} A moderator from WP Coding Club sent you: ${dMessage}`);

 message.author.send(
  `${message.author} You have sent your message to ${dUser}`
 );
}

How to send an email using PHP?

For most projects, I use Swift mailer these days. It's a very flexible and elegant object-oriented approach to sending emails, created by the same people who gave us the popular Symfony framework and Twig template engine.


Basic usage :

require 'mail/swift_required.php';

$message = Swift_Message::newInstance()
    // The subject of your email
    ->setSubject('Jane Doe sends you a message')
    // The from address(es)
    ->setFrom(array('[email protected]' => 'Jane Doe'))
    // The to address(es)
    ->setTo(array('[email protected]' => 'Frank Stevens'))
    // Here, you put the content of your email
    ->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');

if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
    echo json_encode([
        "status" => "OK",
        "message" => 'Your message has been sent!'
    ], JSON_PRETTY_PRINT);
} else {
    echo json_encode([
        "status" => "error",
        "message" => 'Oops! Something went wrong!'
    ], JSON_PRETTY_PRINT);
}

See the official documentation for more info on how to use Swift mailer.

Get IPv4 addresses from Dns.GetHostEntry()

Have you looked at all the addresses in the return, discard the ones of family InterNetworkV6 and retain only the IPv4 ones?

Bash: Echoing a echo command with a variable in bash

You just need to use single quotes:

$ echo "$TEST"
test
$ echo '$TEST'
$TEST

Inside single quotes special characters are not special any more, they are just normal characters.

Converting Varchar Value to Integer/Decimal Value in SQL Server

You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:

If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.

Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.

Fastest way to remove first char in a String

You could profile it, if you really cared. Write a loop of many iterations and see what happens. Chances are, however, that this is not the bottleneck in your application, and TrimStart seems the most semantically correct. Strive to write code readably before optimizing.

How to know if other threads have finished?

Many things have been changed in last 6 years on multi-threading front.

Instead of using join() and lock API, you can use

1.ExecutorService invokeAll() API

Executes the given tasks, returning a list of Futures holding their status and results when all complete.

2.CountDownLatch

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

3.ForkJoinPool or newWorkStealingPool() in Executors is other way

4.Iterate through all Future tasks from submit on ExecutorService and check the status with blocking call get() on Future object

Have a look at related SE questions:

How to wait for a thread that spawns it's own thread?

Executors: How to synchronously wait until all tasks have finished if tasks are created recursively?

Python Linked List

class Node(object):
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next

    def setData(self, data):
        self.data = data
        return self.data

    def setNext(self, next):
        self.next = next

    def getNext(self):
        return self.next

    def hasNext(self):
        return self.next != None


class singleLinkList(object):

    def __init__(self):
        self.head = None

    def isEmpty(self):
        return self.head == None

    def insertAtBeginning(self, data):
        newNode = Node()
        newNode.setData(data)

        if self.listLength() == 0:
            self.head = newNode
        else:
            newNode.setNext(self.head)
            self.head = newNode

    def insertAtEnd(self, data):
        newNode = Node()
        newNode.setData(data)

        current = self.head

        while current.getNext() != None:
            current = current.getNext()

        current.setNext(newNode)

    def listLength(self):
        current = self.head
        count = 0

        while current != None:
            count += 1
            current = current.getNext()
        return count

    def print_llist(self):
        current = self.head
        print("List Start.")
        while current != None:
            print(current.getData())
            current = current.getNext()

        print("List End.")



if __name__ == '__main__':
    ll = singleLinkList()
    ll.insertAtBeginning(55)
    ll.insertAtEnd(56)
    ll.print_llist()
    print(ll.listLength())

Connect to sqlplus in a shell script and run SQL scripts

For example:

sqlplus -s admin/password << EOF
whenever sqlerror exit sql.sqlcode;
set echo off 
set heading off

@pl_script_1.sql
@pl_script_2.sql

exit;
EOF

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

Happened to me after renaming an uncommitted file in Android Studio.

Git seemed to have the old version in its repository, even if it didn´t exist anymore.

fetch, pull, checkout, add all and so on did not help in my case!

So I opened the Git GUI of TortoiseGit which showed me the exact file that caused trouble.

Afterwards I deleted the file from the repository with

git rm -r --cached /path/to/affected/file

and the problem was gone

Why not use tables for layout in HTML?

Here's a section of html from a recent project:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>{DYNAMIC(TITLE)}</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <link rel="stylesheet" type="text/css" href="./styles/base.css" />
</head>
<body>
    <div id="header">
        <h1><!-- Page title --></h1>
        <ol id="navigation">
            <!-- Navigation items -->
        </ol>
        <div class="clearfix"></div>
    </div>
    <div id="sidebar">
        <!-- Sidebar content -->
    </div>
    <!-- Page content -->
    <p id="footer"><!-- Footer content --></p>
</body>
</html>

And here's that same code as a table based layout.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>{DYNAMIC(TITLE)}</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <link rel="stylesheet" type="text/css" href="./styles/base.css" />
</head>
<body>
    <table cellspacing="0">
        <tr>
            <td><!-- Page Title --></td>
            <td>
                <table>
                    <tr>
                        <td>Navitem</td>
                        <td>Navitem</td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>

    <table>
        <tr>
            <td><!-- Page content --></td>
            <td><!-- Sidebar content --></td>
        </tr>
        <tr>
            <td colspan="2">Footer</td>
        </tr>
    </table>
</body>
</html>

The only cleanliness I see in that table based layout is the fact that I'm overzealous with my indentation. I'm sure that the content section would have a further two embedded tables.

Another thing to think about: filesizes. I've found that table-based layouts are twice the size of their CSS counterparts usually. On our hig-speed broadband that isn't a huge issue but it is on those with dial up modems.

Function pointer as a member of a C struct

The pointer str is never allocated. It should be malloc'd before use.

How to extract svg as file from web page

For me its very easy just install following tool in chrome server :

svg-grabber

Once you're on a web page, click the extension's icon next to the URL bar and a new tab will open showing you all the SVG files it found on the page. You can copy an SVG file to your clipboard, download only the few you need, or click the 'Download all SVGs' button to add them all to a zipped file and download them.

For detail check here

Hope it will helpful.

Could not find any resources appropriate for the specified culture or the neutral culture

In my case, the issue caused by the wrong order of class definitions. For example, I had added another class definition before my Form class:

namespace MyBuggyWorld
{
    public class BackendObject //This hack broke the VS 2017 winform designer and resources linker!
    {
        public TcpClient ActiveClient { get; set; }
        public BackgroundWorker ActiveWorker { get; set; }
    }

    public partial class FormMain : Form
    {
    }
}

After moving BackendObject to the end of the file (better yet would be to move it to a separate file), doing project clean + rebuild resolved the issue.

How do I install PyCrypto on Windows?

For VS2010:

SET VS90COMNTOOLS=%VS100COMNTOOLS%

For VS2012:

SET VS90COMNTOOLS=%VS110COMNTOOLS%

then Call:

pip install pyCrypto 

How do I create a Bash alias?

You can add an alias or a function in your startup script file. Usually this is .bashrc, .bash_login or .profile file in your home directory.

Since these files are hidden you will have to do an ls -a to list them. If you don't have one you can create one.


If I remember correctly, when I had bought my Mac, the .bash_login file wasn't there. I had to create it for myself so that I could put prompt info, alias, functions, etc. in it.

Here are the steps if you would like to create one:

  1. Start up Terminal
  2. Type cd ~/ to go to your home folder
  3. Type touch .bash_profile to create your new file.
  4. Edit .bash_profile with your favorite editor (or you can just type open -e .bash_profile to open it in TextEdit.
  5. Type . .bash_profile to reload .bash_profile and update any alias you add.

No Main class found in NetBeans

Press the hammer to the left of the green arrow (run), for the program to clean & build project. Press green arrow. Select Main Class.

Hope it works for u.

Getting full-size profile picture

As noted above, it appears that the cover photo of the profile album is a hi-res profile picture. I would check for the album type of "profile" rather than the name though, as the name may not be consistent across different languages, but the type should be.

To reduce the number of requests / parsing, you can use this fql: "select cover_object_id from album where type='profile' and owner = user_id"

And then you can construct the image url with: "https://graph.facebook.com/" + cover_object_id + "/picture&type=normal&access_token=" + access_token

Looks like there is no "large" type for this image, but the "normal" one is still quite large.

As noted above, this photo may be less accessible than the public profile picture. You need the user_photos or friend_photos permission to access it.

Select the top N values by group

Since dplyr 1.0.0, the slice_max()/slice_min() functions were implemented:

mtcars %>%
 group_by(cyl) %>%
 slice_max(mpg, n = 2, with_ties = FALSE)

    mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1  33.9     4  71.1    65  4.22  1.84  19.9     1     1     4     1
2  32.4     4  78.7    66  4.08  2.2   19.5     1     1     4     1
3  21.4     6 258     110  3.08  3.22  19.4     1     0     3     1
4  21       6 160     110  3.9   2.62  16.5     0     1     4     4
5  19.2     8 400     175  3.08  3.84  17.0     0     0     3     2
6  18.7     8 360     175  3.15  3.44  17.0     0     0     3     2

The documentation on with_ties parameter:

Should ties be kept together? The default, TRUE, may return more rows than you request. Use FALSE to ignore ties, and return the first n rows.

CSS hide scroll bar if not needed

You can use overflow:auto;

You can also control the x or y axis individually with the overflow-x and overflow-y properties.

Example:

.content {overflow:auto;}
.content {overflow-y:auto;}
.content {overflow-x:auto;}

How to pass arguments within docker-compose?

This feature was added in Compose 1.6.

Reference: https://docs.docker.com/compose/compose-file/#args

services:
  web:
    build:
      context: .
      args:
        FOO: foo

How to check the exit status using an if statement

Alternative to explicit if statement

Minimally:

test $? -eq 0 || echo "something bad happened"

Complete:

EXITCODE=$?
test $EXITCODE -eq 0 && echo "something good happened" || echo "something bad happened"; 
exit $EXITCODE

Sending JSON object to Web API

Change:

 data: JSON.stringify({ model: source })

To:

 data: {model: JSON.stringify(source)}

And in your controller you do this:

public void PartSourceAPI(string model)
{
       System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

   var result = js.Deserialize<PartSourceModel>(model);
}

If the url you use in jquery is /api/PartSourceAPI then the controller name must be api and the action(method) should be PartSourceAPI

Chart.js - Formatting Y axis

An undocumented feature of the ChartJS library is that if you pass in a function instead of a string, it will use your function to render the y-axis's scaleLabel.

So while, "<%= Number(value).toFixed(2).replace('.',',') + ' $' %>" works, you could also do:

scaleLabel: function (valuePayload) {
    return Number(valuePayload.value).toFixed(2).replace('.',',') + '$';
}

If you're doing anything remotely complicated, I'd recommend doing this instead.

How to generate XML file dynamically using PHP?

$query=mysql_query("select * from tablename")or die(mysql_error()); 
$xml="<libraray>\n\t\t";
while($data=mysql_fetch_array($query))
{

    $xml .="<mail_address>\n\t\t";
    $xml .= "<id>".$data['id']."</id>\n\t\t";
    $xml .= "<email>".$data['email_address']."</email>\n\t\t";
    $xml .= "<verify_code>".$data['verify']."</verify_code>\n\t\t";
    $xml .= "<status>".$data['status']."</status>\n\t\t";
    $xml.="</mail_address>\n\t";
}
$xml.="</libraray>\n\r";
$xmlobj=new SimpleXMLElement($xml);
$xmlobj->asXML("text.xml");

Its simple just connect with your database it will create test.xml file in your project folder

How to make a progress bar

I used this progress bar. For more information on this you can go through this link i.e customization, coding etc.

<script type="text/javascript">

var myProgressBar = null
var timerId = null

function loadProgressBar(){
myProgressBar = new ProgressBar("my_progress_bar_1",{
    borderRadius: 10,
    width: 300,
    height: 20,
    maxValue: 100,
    labelText: "Loaded in {value,0} %",
    orientation: ProgressBar.Orientation.Horizontal,
    direction: ProgressBar.Direction.LeftToRight,
    animationStyle: ProgressBar.AnimationStyle.LeftToRight1,
    animationSpeed: 1.5,
    imageUrl: 'images/v_fg12.png',
    backgroundUrl: 'images/h_bg2.png',
    markerUrl: 'images/marker2.png'
});

timerId = window.setInterval(function() {
    if (myProgressBar.value >= myProgressBar.maxValue)
        myProgressBar.setValue(0);
    else
        myProgressBar.setValue(myProgressBar.value+1);

},
100);
}

loadProgressBar();
</script>

Hope this may be helpful to somenone.

How to listen for changes to a MongoDB collection?

Many of these answers will only give you new records and not updates and/or are extremely ineffecient

The only reliable, performant way to do this is to create a tailable cursor on local db: oplog.rs collection to get ALL changes to MongoDB and do with it what you will. (MongoDB even does this internally more or less to support replication!)

Explanation of what the oplog contains: https://www.compose.com/articles/the-mongodb-oplog-and-node-js/

Example of a Node.js library that provides an API around what is available to be done with the oplog: https://github.com/cayasso/mongo-oplog

In Python how should I test if a variable is None, True or False

I believe that throwing an exception is a better idea for your situation. An alternative will be the simulation method to return a tuple. The first item will be the status and the second one the result:

result = simulate(open("myfile"))
if not result[0]:
  print "error parsing stream"
else:
  ret= result[1]

Access elements of parent window from iframe

Have the below js inside the iframe and use ajax to submit the form.

$(function(){

   $("form").submit(e){
        e.preventDefault();

       //Use ajax to submit the form
       $.ajax({
          url: this.action,
          data: $(this).serialize(),
          success: function(){
             window.parent.$("#target").load("urlOfThePageToLoad");
          });
       });

   });

});

JavaScript: SyntaxError: missing ) after argument list

You have an extra closing } in your function.

var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
    nav[i].addEventListener('click',function(){
            console.log('haha');
        }        // <== remove this brace
    }, false);
};

You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.

How to parse a JSON string to an array using Jackson

I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.

 Main Class:-

String jsonStr = "[{\r\n" + "       \"name\": \"John\",\r\n" + "        \"city\": \"Berlin\",\r\n"
                + "         \"cars\": [\r\n" + "            \"FIAT\",\r\n" + "          \"Toyata\"\r\n"
                + "     ],\r\n" + "     \"job\": \"Teacher\"\r\n" + "   },\r\n" + " {\r\n"
                + "     \"name\": \"Mark\",\r\n" + "        \"city\": \"Oslo\",\r\n" + "        \"cars\": [\r\n"
                + "         \"VW\",\r\n" + "            \"Toyata\"\r\n" + "     ],\r\n"
                + "     \"job\": \"Doctor\"\r\n" + "    }\r\n" + "]";

        ObjectMapper mapper = new ObjectMapper();

        MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);

        for (MyPojo itr : jsonObj) {

            System.out.println("Val of getName is: " + itr.getName());
            System.out.println("Val of getCity is: " + itr.getCity());
            System.out.println("Val of getJob is: " + itr.getJob());
            System.out.println("Val of getCars is: " + itr.getCars() + "\n");

        }

POJO:

public class MyPojo {

private List<String> cars = new ArrayList<String>();

private String name;

private String job;

private String city;

public List<String> getCars() {
    return cars;
}

public void setCars(List<String> cars) {
    this.cars = cars;
}

public String getName() {
    return name;
}

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

public String getJob() {
    return job;
}

public void setJob(String job) {
    this.job = job;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
} }

  RESULT:-
         Val of getName is: John
         Val of getCity is: Berlin
         Val of getJob is: Teacher
         Val of getCars is: [FIAT, Toyata]

          Val of getName is: Mark
          Val of getCity is: Oslo
          Val of getJob is: Doctor
          Val of getCars is: [VW, Toyata]

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

One more idea for anyone else getting this...

I had some gzipped svg, but it had a php error in the output, which caused this error message. (Because there was text in the middle of gzip binary.) Fixing the php error solved it.

Can I obtain method parameter name using Java reflection?

Yes.
Code must be compiled with Java 8 compliant compiler with option to store formal parameter names turned on (-parameters option).
Then this code snippet should work:

Class<String> clz = String.class;
for (Method m : clz.getDeclaredMethods()) {
   System.err.println(m.getName());
   for (Parameter p : m.getParameters()) {
    System.err.println("  " + p.getName());
   }
}

C++ String Declaring

In C++ you can declare a string like this:

#include <string>

using namespace std;

int main()
{
    string str1("argue2000"); //define a string and Initialize str1 with "argue2000"    
    string str2 = "argue2000"; // define a string and assign str2 with "argue2000"
    string str3;  //just declare a string, it has no value
    return 1;
}

calculating number of days between 2 columns of dates in data frame

You could find the difference between dates in columns in a data frame by using the function difftime as follows:

df$diff_in_days<- difftime(df$datevar1 ,df$datevar2 , units = c("days"))

c# razor url parameter from view

I've found the solution in this thread

@(ViewContext.RouteData.Values["parameterName"])

Copy a variable's value into another

For strings or input values you could simply use this:

var a = $('#some_hidden_var').val(),
b = a.substr(0);

How to turn off caching on Firefox?

If you're working with server side code you could generate a random number and append it to the end of the src in the following manner....

src="yourJavascriptFile.js?randomNumber=434534"

with the randomNumber being randomly generated each time.

How do I convert a String to an int in Java?

Integer.decode

You can also use public static Integer decode(String nm) throws NumberFormatException.

It also works for base 8 and 16:

// base 10
Integer.parseInt("12");     // 12 - int
Integer.valueOf("12");      // 12 - Integer
Integer.decode("12");       // 12 - Integer
// base 8
// 10 (0,1,...,7,10,11,12)
Integer.parseInt("12", 8);  // 10 - int
Integer.valueOf("12", 8);   // 10 - Integer
Integer.decode("012");      // 10 - Integer
// base 16
// 18 (0,1,...,F,10,11,12)
Integer.parseInt("12",16);  // 18 - int
Integer.valueOf("12",16);   // 18 - Integer
Integer.decode("#12");      // 18 - Integer
Integer.decode("0x12");     // 18 - Integer
Integer.decode("0X12");     // 18 - Integer
// base 2
Integer.parseInt("11",2);   // 3 - int
Integer.valueOf("11",2);    // 3 - Integer

If you want to get int instead of Integer you can use:

  1. Unboxing:

    int val = Integer.decode("12"); 
    
  2. intValue():

    Integer.decode("12").intValue();
    

Android Studio - How to Change Android SDK Path

in windows press ctrl+shift+alt+s which will open project properties where you can find first option named SDK Location click on it and there you can change SDK path, JDK path and NDK path also

py2exe - generate single executable file

You should create an installer, as mentioned before. Even though it is also possible to let py2exe bundle everything into a single executable, by setting bundle_files option to 1 and the zipfile keyword argument to None, I don't recommend this for PyGTK applications.

That's because of GTK+ tries to load its data files (locals, themes, etc.) from the directory it was loaded from. So you have to make sure that the directory of your executable contains also the libraries used by GTK+ and the directories lib, share and etc from your installation of GTK+. Otherwise you will get problems running your application on a machine where GTK+ is not installed system-wide.

For more details read my guide to py2exe for PyGTK applications. It also explains how to bundle everything, but GTK+.

How do I refresh a DIV content?

For div refreshing without creating div inside yours with same id, you should use this inside your function

$("#yourDiv").load(" #yourDiv > *");

CASE .. WHEN expression in Oracle SQL

You can rewrite it to use the ELSE condition of a CASE:

SELECT status,
       CASE status
         WHEN 'i' THEN 'Inactive'
         WHEN 't' THEN 'Terminated'
         ELSE 'Active'
       END AS StatusText
FROM   stage.tst 

missing private key in the distribution certificate on keychain

I got into this situation ("Missing private key.") after Xcode failed to create new distribution certificate - an unknown error occurred.

Then, I struggled to obtain the private key or to generate new certificate. From the certificate manager in Xcode I got strange errors like "The passphrase you entered is wrong". But it did not even ask me for any passphrase.

What helped me was:

  1. Revoke all not-working distribution certificates at developer.apple.com
  2. Restart my Mac

After that, Xcode was able to create new distribution certificate and no private key was missing.

Lesson learned: Restart your Mac as much as your Windows ;)

HTTP Content-Type Header and JSON

Content-Type: application/json is just the content header. The content header is just information about the type of returned data, ex::JSON,image(png,jpg,etc..),html.

Keep in mind, that JSON in JavaScript is an array or object. If you want to see all the data, use console.log instead of alert:

alert(response.text); // Will alert "[object Object]" string
console.log(response.text); // Will log all data objects

If you want to alert the original JSON content as a string, then add single quotation marks ('):

echo "'" . json_encode(array('text' => 'omrele')) . "'";
// alert(response.text) will alert {"text":"omrele"}

Do not use double quotes. It will confuse JavaScript, because JSON uses double quotes on each value and key:

echo '<script>var returndata=';
echo '"' . json_encode(array('text' => 'omrele')) . '"';
echo ';</script>';

// It will return the wrong JavaScript code:
<script>var returndata="{"text":"omrele"}";</script>

Reset textbox value in javascript

First, select the element. You can usually use the ID like this:

$("#searchField"); // select element by using "#someid"

Then, to set the value, use .val("something") as in:

$("#searchField").val("something"); // set the value

Note that you should only run this code when the element is available. The usual way to do this is:

$(document).ready(function() { // execute when everything is loaded
    $("#searchField").val("something"); // set the value
});