Programs & Examples On #Imageview

Android widget that displays an arbitrary image or drawable, such as an icon.

Changing ImageView source

You're supposed to use setImageResource instead of setBackgroundResource.

set height of imageview as matchparent programmatically

imageView.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;

How to set tint for an image view programmatically in android?

Adding to ADev's answer (which in my opinion is the most correct), since the widespread adoption of Kotlin, and its useful extension functions:

fun ImageView.setTint(context: Context, @ColorRes colorId: Int) {
    val color = ContextCompat.getColor(context, colorId)
    val colorStateList = ColorStateList.valueOf(color)
    ImageViewCompat.setImageTintList(this, colorStateList)
}

I think this is a function which could be useful to have in any Android project!

How can I get zoom functionality for images?

This is a very late addition to this thread but I've been working on an image view that supports zoom and pan and has a couple of features I haven't found elsewhere. This started out as a way of displaying very large images without causing OutOfMemoryErrors, by subsampling the image when zoomed out and loading higher resolution tiles when zoomed in. It now supports use in a ViewPager, rotation manually or using EXIF information (90° stops), override of selected touch events using OnClickListener or your own GestureDetector or OnTouchListener, subclassing to add overlays, pan while zooming, and fling momentum.

It's not intended as a general use replacement for ImageView so doesn't extend it, and doesn't support display of images from resources, only assets and external files. It requires SDK 10.

Source is on GitHub, and there's a sample that illustrates use in a ViewPager.

https://github.com/davemorrissey/subsampling-scale-image-view

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

You can just basically revert your code using some other built in methods.

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

How to load an ImageView by URL in Android?

From Android developer:

// show The Image in a ImageView
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
            .execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");

public void onClick(View v) {
    startActivity(new Intent(this, IndexActivity.class));
    finish();

}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}

Make sure you have the following permissions set in your AndroidManifest.xml to access the internet.

<uses-permission android:name="android.permission.INTERNET" />

Android: how to convert whole ImageView to Bitmap?

This is a working code

imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache());

ImageView in circular through xml

I have a simple solution. Create a new Image asset by right clicking your package name and selecting New->Image asset. Enter name (any name) and path (location of image in your system). Then click Next and Finish. If you enter name of image as 'img', a round image with the name 'img_round' is created automatically in mipmap folder.

Then, do this :

<ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@mipmap/img_round"/>

Your preview may still show a rectangular image. But if you run the app on your device, it will be round.

Scale Image to fill ImageView width and keep aspect ratio

To create an image with width equals screen width, and height proportionally set according to aspect ratio, do the following.

Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                        // creating the image that maintain aspect ratio with width of image is set to screenwidth.
                        int width = imageView.getMeasuredWidth();
                        int diw = resource.getWidth();
                        if (diw > 0) {
                            int height = 0;
                            height = width * resource.getHeight() / diw;
                            resource = Bitmap.createScaledBitmap(resource, width, height, false);
                        }
                                              imageView.setImageBitmap(resource);
                    }
                });

Hope this helps.

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

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

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

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

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

Quick answer:

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="center"
        android:src="@drawable/yourImage"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Android fade in and fade out with ImageView

you can do it by two simple point and change in your code

1.In your xml in anim folder of your project, Set the fade in and fade out duration time not equal

2.In you java class before the start of fade out animation, set second imageView visibility Gone then after fade out animation started set second imageView visibility which you want to fade in visible

fadeout.xml

<alpha
    android:duration="4000"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="0.0" />

fadein.xml

<alpha
    android:duration="6000"
    android:fromAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="1.0" />

In you java class

Animation animFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
    ImageView iv = (ImageView) findViewById(R.id.imageView1);
    ImageView iv2 = (ImageView) findViewById(R.id.imageView2);
    iv.setVisibility(View.VISIBLE);
    iv2.setVisibility(View.GONE);
    animFadeOut.reset();
    iv.clearAnimation();
    iv.startAnimation(animFadeOut);

    Animation animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
    iv2.setVisibility(View.VISIBLE);
    animFadeIn.reset();
    iv2.clearAnimation();
    iv2.startAnimation(animFadeIn);

Custom ImageView with drop shadow

I manage to apply gradient border using this code..

public static Bitmap drawShadow(Bitmap bitmap, int leftRightThk, int bottomThk, int padTop) {
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int newW = w - (leftRightThk * 2);
    int newH = h - (bottomThk + padTop);

    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    Bitmap bmp = Bitmap.createBitmap(w, h, conf);
    Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas c = new Canvas(bmp);

    // Left
    int leftMargin = (leftRightThk + 7)/2;
    Shader lshader = new LinearGradient(0, 0, leftMargin, 0, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP);
    paint.setShader(lshader);
    c.drawRect(0, padTop, leftMargin, newH, paint); 

    // Right
    Shader rshader = new LinearGradient(w - leftMargin, 0, w, 0, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
    paint.setShader(rshader);
    c.drawRect(newW, padTop, w, newH, paint);

    // Bottom
    Shader bshader = new LinearGradient(0, newH, 0, bitmap.getHeight(), Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
    paint.setShader(bshader);
    c.drawRect(leftMargin -3, newH, newW + leftMargin + 3, bitmap.getHeight(), paint);
    c.drawBitmap(sbmp, leftRightThk, 0, null);

    return bmp;
}

hope this helps !

Adding text to ImageView in Android

With a FrameLayout you can place a text on top of an image view, the frame layout holding both an imageView and a textView.

If that's not enough and you want something more fancy like 'drawing' text, you need to draw text on a canvas - a sample is here: How to draw RTL text (Arabic) onto a Bitmap and have it ordered properly?

How to make an ImageView with rounded corners?

If you don't want to border affects the image, use this class. Unfortunately, I didn't find any approach to draw a transparent area on the canvas came to onDraw(). So, here is created a new bitmap and it's drawn on a real canvas.

The view is useful if you want to make a disappearing border. If you set borderWidth to 0, the border will disappear and the image remains with rounder corners exactly like the border was. I.e. it looks like the border is drawn exactly by the image edges.

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView


class RoundedImageViewWithBorder @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0) : AppCompatImageView(context, attrs, defStyleAttr) {

    var borderColor: Int = 0
        set(value) {
            invalidate()
            field = value
        }
    var borderWidth: Int = 0
        set(value) {
            invalidate()
            field = value
        }
    var cornerRadius: Float = 0f
        set(value) {
            invalidate()
            field = value
        }

    private var bitmapForDraw: Bitmap? = null
    private var canvasForDraw: Canvas? = null
    private val transparentPaint = Paint().apply {
        isAntiAlias = true
        color = Color.TRANSPARENT
        style = Paint.Style.STROKE
        xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
    }

    private val borderPaint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.STROKE
    }

    private val transparentAreaRect = RectF()
    private val borderRect = RectF()

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundedImageViewWithBorder)

        try {
            borderWidth = typedArray.getDimensionPixelSize(R.styleable.RoundedImageViewWithBorder_border_width, 0)
            borderColor = typedArray.getColor(R.styleable.RoundedImageViewWithBorder_border_color, 0)
            cornerRadius = typedArray.getDimensionPixelSize(R.styleable.RoundedImageViewWithBorder_corner_radius, 0).toFloat()

        } finally {
            typedArray.recycle()
        }
    }

    @SuppressLint("CanvasSize", "DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        if (canvas.height <=0 || canvas.width <=0) {
            return
        }

        if (canvasForDraw?.height != canvas.height || canvasForDraw?.width != canvas.width) {
            val newBitmap = Bitmap.createBitmap(canvas.width, canvas.height, Bitmap.Config.ARGB_8888)
            bitmapForDraw = newBitmap
            canvasForDraw = Canvas(newBitmap)
        }
        
        bitmapForDraw?.eraseColor(Color.TRANSPARENT)

        // Draw existing content
        super.onDraw(canvasForDraw)

        if (borderWidth > 0) {
            canvasForDraw?.let { drawWithBorder(it) }
        } else {
            canvasForDraw?.let { drawWithoutBorder(it) }
        }

        // Draw everything on real canvas
        bitmapForDraw?.let { canvas.drawBitmap(it, 0f, 0f, null) }
    }

    private fun drawWithBorder(canvas: Canvas) {
        // Draw transparent area
        transparentPaint.strokeWidth = borderWidth.toFloat() * 4
        transparentAreaRect.apply {
            left = -borderWidth.toFloat() * 1.5f
            top = -borderWidth.toFloat() * 1.5f
            right = canvas.width.toFloat() + borderWidth.toFloat() * 1.5f
            bottom = canvas.height.toFloat() + borderWidth.toFloat() * 1.5f
        }
        canvasForDraw?.drawRoundRect(transparentAreaRect, borderWidth.toFloat() * 2 + cornerRadius, borderWidth.toFloat() * 2 + cornerRadius, transparentPaint)

        // Draw border
        borderPaint.color = borderColor
        borderPaint.strokeWidth = borderWidth.toFloat()
        borderRect.apply {
            left = borderWidth.toFloat() / 2
            top = borderWidth.toFloat() / 2
            right = canvas.width.toFloat() - borderWidth.toFloat() / 2
            bottom = canvas.height.toFloat() - borderWidth.toFloat() / 2
        }
        canvas.drawRoundRect(borderRect, cornerRadius - borderWidth.toFloat() / 2, cornerRadius - borderWidth.toFloat() / 2, borderPaint)
    }

    private fun drawWithoutBorder(canvas: Canvas) {
        // Draw transparent area
        transparentPaint.strokeWidth = cornerRadius * 4
        transparentAreaRect.apply {
            left = -cornerRadius * 2
            top = -cornerRadius * 2
            right = canvas.width.toFloat() + cornerRadius * 2
            bottom = canvas.height.toFloat() + cornerRadius * 2
        }
        canvasForDraw?.drawRoundRect(transparentAreaRect, cornerRadius * 3, cornerRadius * 3, transparentPaint)
    }

}

In values:

<declare-styleable name="RoundedImageViewWithBorder">
    <attr name="corner_radius" format="dimension|string" />
    <attr name="border_width" format="dimension|reference" />
    <attr name="border_color" format="color|reference" />
</declare-styleable>

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

How do you setLayoutParams() for an ImageView?

You need to set the LayoutParams of the ViewGroup the ImageView is sitting in. For example if your ImageView is inside a LinearLayout, then you create a

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

This is because it's the parent of the View that needs to know what size to allocate to the View.

How can I give an imageview click effect like a button on Android?

Here is my code. The idea is that ImageView gets color filter when user touches it, and color filter is removed when user stops touching it.

Martin Booka Weser, András, Ah Lam, altosh, solution doesn't work when ImageView has also onClickEvent. worawee.s and kcoppock (with ImageButton) solution requires background, which has no sense when ImageView is not transparent.

This one is extension of AZ_ idea about color filter.

class PressedEffectStateListDrawable extends StateListDrawable {

    private int selectionColor;

    public PressedEffectStateListDrawable(Drawable drawable, int selectionColor) {
        super();
        this.selectionColor = selectionColor;
        addState(new int[] { android.R.attr.state_pressed }, drawable);
        addState(new int[] {}, drawable);
    }

    @Override
    protected boolean onStateChange(int[] states) {
        boolean isStatePressedInArray = false;
        for (int state : states) {
            if (state == android.R.attr.state_pressed) {
                isStatePressedInArray = true;
            }
        }
        if (isStatePressedInArray) {
            super.setColorFilter(selectionColor, PorterDuff.Mode.MULTIPLY);
        } else {
            super.clearColorFilter();
        }
        return super.onStateChange(states);
    }

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

usage:

Drawable drawable = new FastBitmapDrawable(bm);
imageView.setImageDrawable(new PressedEffectStateListDrawable(drawable, 0xFF33b5e5));

how to set image from url for imageView

if you are making a RecyclerView and using an adapter, what worked for me was:

@Override
public void onBindViewHolder(ADAPTERVIEWHOLDER holder, int position) {
    MODEL model = LIST.get(position);
    holder.TEXTVIEW.setText(service.getTitle());
    holder.TEXTVIEW.setText(service.getDesc());

    Context context = holder.IMAGEVIEW.getContext();
    Picasso.with(context).load(model.getImage()).into(holder.IMAGEVIEW);
}

Adding gif image in an ImageView in android

Use Webview to load gif like as

webView = (WebView) findViewById(R.id.webView);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/1.gif");

Border for an Image view in Android?

Create Border

Create an xml file (e.g. "frame_image_view.xml") with the following content in your drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="@dimen/borderThickness"
        android:color="@color/borderColor" />
    <padding
        android:bottom="@dimen/borderThickness"
        android:left="@dimen/borderThickness"
        android:right="@dimen/borderThickness"
        android:top="@dimen/borderThickness" />
    <corners android:radius="1dp" /> <!-- remove line to get sharp corners -->
</shape>

Replace @dimen/borderThickness and @color/borderColor with whatever you want or add corresponding dimen / color.

Add the Drawable as background to your ImageView:

<ImageView
        android:id="@+id/my_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/frame_image_view"
        android:cropToPadding="true"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter" />

You have to use android:cropToPadding="true", otherwise the defined padding has no effect. Alternatively use android:padding="@dimen/borderThickness" in your ImageView to achieve the same. If the border frames the parent instead of your ImageView, try to use android:adjustViewBounds="true".

Change Color of Border

The easiest way to change your border color in code is using the tintBackgound attribute.

ImageView img = findViewById(R.id.my_image_view);
img.setBackgroundTintList(ColorStateList.valueOf(Color.RED); // changes border color to red

or

ImageView img = findViewById(R.id.my_image_view);
img.setBackgroundTintList(getColorStateList(R.color.newColor));

Don't forget to define your newColor.

How to set margin of ImageView using code, not xml

All the above examples will actually REPLACE any params already present for the View, which may not be desired. The below code will just extend the existing params, without replacing them:

ImageView myImage = (ImageView) findViewById(R.id.image_view);
MarginLayoutParams marginParams = (MarginLayoutParams) image.getLayoutParams();
marginParams.setMargins(left, top, right, bottom);

How to show image using ImageView in Android

In res folder select the XML file in which you want to view your images,

<ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:src="@drawable/imagep1" />

Android set bitmap to Imageview

this code works with me

 ImageView carView = (ImageView) v.findViewById(R.id.car_icon);

                            byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
                            InputStream input=new ByteArrayInputStream(decodedString);
                            Bitmap ext_pic = BitmapFactory.decodeStream(input);
                            carView.setImageBitmap(ext_pic);

Android: resizing imageview in XML

for example:

<ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="42dp"  
  android:maxHeight="42dp"  
  android:scaleType="fitCenter"  
  android:layout_marginLeft="3dp"  
  android:src="@drawable/icon"  
  /> 

Add property android:scaleType="fitCenter" and android:adjustViewBounds="true".

android - save image into gallery

I've tried a lot of things to let this work on Marshmallow and Lollipop. Finally i ended up moving the saved picture to the DCIM folder (new Google Photo app scan images only if they are inside this folder apparently)

public static File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
         .format(System.currentTimeInMillis());
    File storageDir = new File(Environment
         .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/");
    if (!storageDir.exists())
        storageDir.mkdirs();
    File image = File.createTempFile(
            timeStamp,                   /* prefix */
            ".jpeg",                     /* suffix */
            storageDir                   /* directory */
    );
    return image;
}

And then the standard code for scanning files which you can find in the Google Developers site too.

public static void addPicToGallery(Context context, String photoPath) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(photoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    context.sendBroadcast(mediaScanIntent);
}

Please remember that this folder could not be present in every device in the world and that starting from Marshmallow (API 23), you need to request the permission to WRITE_EXTERNAL_STORAGE to the user.

How can I show an image using the ImageView component in javafx and fxml?

Please find below example to load image using JavaFX.

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.image.Image;
    import javafx.scene.image.ImageView;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;

    public class LoadImage extends Application {

    public static void main(String[] args) {
    Application.launch(args);
    }
    @Override
    public void start(Stage primaryStage) {
    primaryStage.setTitle("Load Image");

    StackPane sp = new StackPane();
    Image img = new Image("javafx.jpg");
    ImageView imgView = new ImageView(img);
    sp.getChildren().add(imgView);

    //Adding HBox to the scene
    Scene scene = new Scene(sp);
    primaryStage.setScene(scene);
    primaryStage.show();
    }

  }

Create one source folder with name Image in your project and add your image to that folder otherwise you can directly load image from external URL like following.

Image img = new Image("http://mikecann.co.uk/wp-content/uploads/2009/12/javafx_logo_color_1.jpg");

How to set image in imageview in android?

1> You can add image from layout itself:

<ImageView
                android:id="@+id/iv_your_image"
                android:layout_width="wrap_content"
                android:layout_height="25dp"
                android:background="@mipmap/your_image"
                android:padding="2dp" />

OR

2> Programmatically in java class:

ImageView ivYouImage= (ImageView)findViewById(R.id.iv_your_image);
        ivYouImage.setImageResource(R.mipmap.ic_changeImage);

OR for fragments:

View rowView= inflater.inflate(R.layout.your_layout, null, true);

ImageView ivYouImage= (ImageView) rowView.findViewById(R.id.iv_your_image);
        ivYouImage.setImageResource(R.mipmap.ic_changeImage);

Change Image of ImageView programmatically in Android

That happens because you're setting the src of the ImageView instead of the background.

Use this instead:

qImageView.setBackgroundResource(R.drawable.thumbs_down);

Here's a thread that talks about the differences between the two methods.

android: stretch image in imageview to fit screen

use this:

ImageView.setAdjustViewBounds(true);

Android ImageView setImageResource in code

This is how to set an image into ImageView using the setImageResource() method:

ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);

How to show imageView full screen on imageView click?

Yes I got the trick.

public void onClick(View v) {

            if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ){
                imgDisplay.setSystemUiVisibility( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION );

            }
            else if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB )
                imgDisplay.setSystemUiVisibility( View.STATUS_BAR_HIDDEN );
            else{}

    }

But it didn't solve my problem completely. I want to hide the horizontal scrollview too, which is in front of the imageView (below), which can't be hidden in this.

Full screen background image in an activity

The easiest way:

Step 1: Open AndroidManifest.xml file

You can see the file here!

Step 2: Locate android:theme="@style/AppTheme" >

Step 3: Change to android:theme="@style/Theme.AppCompat.NoActionBar" >

Step 4: Then Add ImageView & Image

Step 4: That's it!

Android ImageView Fixing Image Size

You can also try this, suppose if you want to make a back image button and you have "500x500 png" and want it to fit in small button size.

Use dp to fix ImageView's size.

add this line of code to your Imageview.

android:scaleType="fitXY"

EXAMPLE:

<ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/imageView2"
        android:src="@drawable/Backicon"
        android:scaleType="fitXY"
        />

Android: Rotate image in imageview by an angle

just write this in your onactivityResult

            Bitmap yourSelectedImage= BitmapFactory.decodeFile(filePath);
            Matrix mat = new Matrix();
            mat.postRotate((270)); //degree how much you rotate i rotate 270
            Bitmap bMapRotate=Bitmap.createBitmap(yourSelectedImage, 0,0,yourSelectedImage.getWidth(),yourSelectedImage.getHeight(), mat, true);
            image.setImageBitmap(bMapRotate);
            Drawable d=new BitmapDrawable(yourSelectedImage);
            image.setBackground(d); 

Get Bitmap attached to ImageView

Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();

Android get image from gallery into ImageView

The original answer is that your path has to join prefix like Uri.parse("file://" + file.getPath);

Show Image View from file path?

How To Show Images From Folder path in Android

Very First: Make Sure You Have Add Permissions into Mainfest file:

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

:Make a Class MyGallery

public class MyGallery extends Activity {


    private GridView gridView;
    private String _location;

    private String newFolder = "/IslamicGif/";
    private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    private AdView mAdView;
    private ArrayList<Bitmap> photo = new ArrayList<Bitmap>();
    public static String[] imageFileList;
    TextView gallerytxt;

    public static ImageAdapter imageAdapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.mygallery);
        /*if (MenuClass.mInterstitialAd.isLoaded()) {
            MenuClass.mInterstitialAd.show();
        }*/

        gallerytxt = (TextView) findViewById(R.id.gallerytxt);
        /*gallerytxt.setTextSize(20);
        int[] color = {Color.YELLOW,Color.WHITE};
        float[] position = {0, 1};
        Shader.TileMode tile_mode0= Shader.TileMode.REPEAT; // or TileMode.REPEAT;
        LinearGradient lin_grad0 = new LinearGradient(0, 0, 0, 200,color,position, tile_mode0);
        Shader shader_gradient0 = lin_grad0;
        gallerytxt.getPaint().setShader(shader_gradient0);*/
        ImageButton btn_back = (ImageButton) findViewById(R.id.btn_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyGallery.this.finish();
            }
        });


        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);
        gridView = (GridView) findViewById(R.id.gridView);

        new MyGalleryAsy().execute();

        gridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(MyGallery.this, ImageDetail.class);
                intent.putExtra("ImgUrl", imageFileList[pos]);

                //Toast.makeText(MyGallery.this,"image detail"+pos,Toast.LENGTH_LONG).show();
                startActivity(intent);
            }
        });


    }

    protected void onStart() {
        super.onStart();
        if (ImageDetail.deleted) {
            photo = new ArrayList<Bitmap>();
            new MyGalleryAsy().execute();
            ImageDetail.deleted = false;
        }

    }

    public class MyGalleryAsy extends AsyncTask<Void, Void, Void> {
        private ProgressDialog dialog;
        Bitmap mBitmap;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(MyGallery.this, "", "Loading ...", true);
            dialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            readImage();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            dialog.dismiss();
            DisplayMetrics displayMatrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMatrics);
            int screenWidth = displayMatrics.widthPixels / 3;

            if (photo.size() > 0) {
                imageAdapter = new ImageAdapter(MyGallery.this, screenWidth);
                gridView.setAdapter(imageAdapter);
            }

        }

    }


    private void readImage() {
        // TODO Auto-generated method stub


        try {
            if (isSdPresent()) {
                _location = extStorageDirectory + newFolder;
            } else
                _location = getFilesDir() + newFolder;
            File file1 = new File(_location);

            if (file1.isDirectory()) { // sdCard == true
                imageFileList = file1.list();
                if (imageFileList != null) {
                    for (int i = 0; i < imageFileList.length; i++) {
                        try {
                            photo.add(BitmapFactory.decodeFile(_location + imageFileList[i].trim()));
                        } catch (Exception e) {
                            // TODO: handle exception
                            //Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
                        }
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public static boolean isSdPresent() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public class ImageAdapter extends BaseAdapter {

        private Context context;
        private LayoutInflater layoutInflater;
        private int width;
        private int mGalleryItemBackground;

        public ImageAdapter(Context c) {
            context = c;

        }

        public ImageAdapter(Context c, int width) {
            context = c;
            this.width = width;
        }

        public int getCount() {
            return photo.size();
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = layoutInflater.inflate(R.layout.galleryadapter, null);

            RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.galleryLayout);

            ImageView imageView = new ImageView(context);
            layout.addView(imageView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            layout.setLayoutParams(new GridView.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
            imageView.setImageBitmap(photo.get(position));

            return v;

        }

        public void updateItemList(ArrayList<Bitmap> newItemList) {
            photo = newItemList;
            notifyDataSetChanged();
        }
    }


}

Now create its Xml Class

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:orientation="vertical">

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/colorPrimary"
    android:minHeight="?attr/actionBarSize">

    <TextView
        android:id="@+id/gallerytxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:fontFamily="@string/font_fontFamily_medium"
        android:text="My Gallery"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/black"
        android:textStyle="bold" />

    <ImageButton
        android:id="@+id/btn_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="12dp"
        android:background="@drawable/ic_arrow_back_black_24dp" />
</RelativeLayout>


<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_gravity="center|bottom"
    android:visibility="gone"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_id" />

<GridView
    android:id="@+id/gridView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/adView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/relativeLayout"
    android:horizontalSpacing="5dp"
    android:numColumns="2"
    android:smoothScrollbar="true"
    android:verticalSpacing="5dp"></GridView>
## Also Make Adapter galleryadapter.xml ##
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="@+id/galleryLayout"
android:padding="2dp">
[![enter image description here][1]][1]

To see the Image in Detail create a new Class ImageDetail:##

 public class ImageDetail extends Activity implements OnClickListener {
    public static InterstitialAd mInterstitialAd;
    private ImageView mainImageView;
    private LinearLayout menuTop;
    private TableLayout menuBottom;
    private Boolean onOff = true;
    private ImageView delButton, mailButton, shareButton;

    private String imgUrl = null;
    private AdView mAdView;
    TextView titletxt;
    private String newFolder = "/IslamicGif/";
    private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    public static boolean deleted = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.image_detail);

        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);
        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                mAdView.setVisibility(View.VISIBLE);
            }
        });
        mainImageView = (ImageView) findViewById(R.id.mainImageView);
        menuTop = (LinearLayout) findViewById(R.id.menuTop);
        menuBottom = (TableLayout) findViewById(R.id.menuBottom);
        titletxt = (TextView) findViewById(R.id.titletxt);
        titletxt.setTextSize(22);
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId(getString(R.string.interstial_id));

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                requestNewInterstitial();

            }
        });
        requestNewInterstitial();
        delButton = (ImageView) findViewById(R.id.delButton);
        mailButton = (ImageView) findViewById(R.id.mailButton);
        shareButton = (ImageView) findViewById(R.id.shareButton);

        Bundle exBundle = getIntent().getExtras();
        if (exBundle != null) {
            imgUrl = exBundle.getString("ImgUrl");
        }
        if (isSdPresent()) {
            imgUrl = extStorageDirectory + newFolder + imgUrl;
        } else
            imgUrl = getFilesDir() + newFolder + imgUrl;

        if (imgUrl != null) {
            GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(mainImageView);
            Glide.with(this).load(imgUrl).into(imageViewTarget);

        }


        delButton.setOnClickListener(this);
        mailButton.setOnClickListener(this);
        shareButton.setOnClickListener(this);


    }

    public static boolean isSdPresent() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }


    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.shareButton:
                Image_Link();
                break;
            case R.id.delButton:
                deleted();
                break;
            case R.id.mailButton:
                sendemail();
                break;
            default:
                break;
        }
    }

    private void sendemail() {

        try {

            File photo = new File(imgUrl);
            Uri imageuri = Uri.fromFile(photo);


            String url = Constant.AppUrl;

            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append("Face Placer App Available here..Play Link");
            int start = builder.length();
            builder.append(url);
            int end = builder.length();

            builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
            String[] recipients2 = new String[]{"[email protected]", "",};
            emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
            emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
            emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
            emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
            emailIntent2.setType("text/html");
            emailIntent2.setType("image/JPEG");
            startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));

        } catch (Exception e) {
            // TODO: handle exception

            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
        }
    }


    private void Image_Link() {

        try {

            File photo = new File(imgUrl);
            Uri imageuri = Uri.fromFile(photo);


            String url = Constant.AppUrl;

            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append("Face Placer App Available here..Play Link");
            int start = builder.length();
            builder.append(url);
            int end = builder.length();

            builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
            String[] recipients2 = new String[]{"[email protected]", "",};
            emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
            emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
            emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
            emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
            emailIntent2.setType("text/html");
            emailIntent2.putExtra(Intent.EXTRA_TEXT, "Face Placer App Available here..Play Link " + url);
            emailIntent2.setType("image/JPEG");
            startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));

        } catch (Exception e) {
            // TODO: handle exception

            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
        }
    }


    private void deleted() {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(ImageDetail.this);
        builder.setTitle(getString(R.string.removeoption));
        builder.setMessage(getString(R.string.deleteimage));
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                dialog.cancel();
                File fileDel = new File(imgUrl);
                boolean isCheck1 = fileDel.delete();

                if (isCheck1) {
                    deleted = true;
                    finish();
                    MyGallery.imageAdapter.notifyDataSetChanged();

                } else {
                    Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
                }
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                dialog.cancel();

            }
        });
        Dialog dialog = builder.create();
        dialog.show();


    }


    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            return false;
        } else
            return true;
    }

    private void requestNewInterstitial() {
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
                .build();

        mInterstitialAd.loadAd(adRequest);
    }

}

Create its xml image_detail.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bg"
android:orientation="vertical">

<ImageView
    android:id="@+id/mainImageView"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentBottom="true"
    android:contentDescription="@string/app_name"
    android:focusable="true"
    android:focusableInTouchMode="true" />

<LinearLayout
    android:id="@+id/adlayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:orientation="horizontal"
    android:visibility="gone"></LinearLayout>

<LinearLayout
    android:id="@+id/menuTop"
    android:layout_width="fill_parent"
    android:layout_height="56dp"
    android:layout_alignWithParentIfMissing="true"
    android:layout_below="@+id/adlayout"
    android:background="@color/colorPrimary"
    android:orientation="vertical"
    android:padding="10.0dip"
    android:visibility="visible">

    <TextView
        android:id="@+id/titletxt"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Islamic Gifs"
        android:textColor="#000000"
        android:textSize="22sp"
        android:textStyle="bold" />
</LinearLayout>

<TableLayout
    android:id="@+id/menuBottom"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="@color/colorPrimary"
    android:padding="10.0dip"
    android:stretchColumns="*"
    android:visibility="visible">

    <TableRow>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/mailButton"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:background="@drawable/selector_shareimage"
                android:contentDescription="@string/app_name" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/shareButton"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:background="@drawable/selector_shareimage_small"
                android:contentDescription="@string/app_name" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/delButton"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:background="@drawable/selector_delete"
                android:contentDescription="@string/app_name" />
        </LinearLayout>
    </TableRow>
</TableLayout>

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/menuTop"
    android:layout_centerHorizontal="true"
    android:visibility="gone"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_id"></com.google.android.gms.ads.AdView>

Add your own Drawable to Selector class,and create it res>drawable>selector_shareimage.xml

<?xml version="1.0" encoding="utf-8"?>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_selected="true"/>
<item android:drawable="@drawable/result_bt_mail_s"/>

enter image description here

Dont forget to add in application tag for sdk version 29 and 30 legacy to add this line

android:requestLegacyExternalStorage="true"

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:requestLegacyExternalStorage="true"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

ImageView rounded corners

Based on Nihal's answer ( https://stackoverflow.com/a/42234152/2832027 ), here is a pure XML version that gives a rectangle with rounded corners on API 24 and above. On below API 24, it will show no rounded corners.

Usage:

<ImageView
    android:id="@+id/thumbnail"
    android:layout_width="150dp"
    android:layout_height="200dp"
    android:foreground="@drawable/rounded_corner_mask"/>

rounded_corner_mask.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:gravity="bottom|right">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M0,10 A10,10 0 0,0 10,0 L10,10 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

    <item
        android:gravity="bottom|left">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M0,0 A10,10 0 0,0 10,10 L0,10 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

    <item
        android:gravity="top|left">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M10,0 A10,10 0 0,0 0,10 L0,0 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

    <item
        android:gravity="top|right">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M10,10 A10,10 0 0,0 0,0 L10,0 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

</layer-list>

What's the best three-way merge tool?

vimdiff. It's great. All you need is a window three feet wide.

enter image description here

In Go's http package, how do I get the query string on a POST request?

Below is an example:

value := r.FormValue("field")

for more info. about http package, you could visit its documentation here. FormValue basically returns POST or PUT values, or GET values, in that order, the first one that it finds.

How do I import an existing Java keystore (.jks) file into a Java installation?

You can bulk import all aliases from one keystore to another:

keytool -importkeystore -srckeystore source.jks -destkeystore dest.jks

Updating Anaconda fails: Environment Not Writable Error

I was also suffered by same problem. I resolved the problem by reinstalling anaconda(While installation at this time I selected "just for me" as user) and my problem was solved.Try the same

How to print a two dimensional array?

Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.

public void printGrid(int[][] in){  
    for(int i = 0; i < 20; i++){  
        for(int j = 0; j < 20; j++){  
            if(in[i][j] == 1)  
                System.out.print('X' + "\t");
            else
                System.out.print(in[i][j] + "\t");
        }
        System.out.print("\n");
    }
}

What's the difference between passing by reference vs. passing by value?

If you don't want to change the value of the original variable after passing it into a function, the function should be constructed with a "pass by value" parameter.

Then the function will have ONLY the value but not the address of the passed in variable. Without the variable's address, the code inside the function cannot change the variable value as seen from the outside of the function.

But if you want to give the function the ability to change the value of the variable as seen from the outside, you need to use pass by reference. As both the value and the address (reference) are passed in and available inside the function.

scp (secure copy) to ec2 instance without password

My hadoopec2cluster.pem file was the only one in the directory on my local mac, couldn't scp it to aws using scp -i hadoopec2cluster.pem hadoopec2cluster.pem ubuntu@serverip:~.

Copied hadoopec2cluster.pem to hadoopec2cluster_2.pem and then scp -i hadoopec2cluster.pem hadoopec2cluster_2.pem ubuntu@serverip:~. Voila!

Sending mail attachment using Java

Using Spring Framework , you can add many attachments :

package com.mkyong.common;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class MailMail
{
    private JavaMailSender mailSender;
    private SimpleMailMessage simpleMailMessage;

    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
        this.simpleMailMessage = simpleMailMessage;
    }

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendMail(String dear, String content) {

       MimeMessage message = mailSender.createMimeMessage();

       try{
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(simpleMailMessage.getFrom());
        helper.setTo(simpleMailMessage.getTo());
        helper.setSubject(simpleMailMessage.getSubject());
        helper.setText(String.format(
            simpleMailMessage.getText(), dear, content));

        FileSystemResource file = new FileSystemResource("/home/abdennour/Documents/cv.pdf");
        helper.addAttachment(file.getFilename(), file);

         }catch (MessagingException e) {
        throw new MailParseException(e);
         }
         mailSender.send(message);
         }
}

To know how to configure your project to deal with this code , complete reading this tutorial .

Remove Safari/Chrome textinput/textarea glow

This effect can occur on non-input elements, too. I've found the following works as a more general solution

:focus {
  outline-color: transparent;
  outline-style: none;
}

Update: You may not have to use the :focus selector. If you have an element, say <div id="mydiv">stuff</div>, and you were getting the outer glow on this div element, just apply like normal:

#mydiv {
  outline-color: transparent;
  outline-style: none;
}

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

Convert a tensor to numpy array in Tensorflow?

You need to:

  1. encode the image tensor in some format (jpeg, png) to binary tensor
  2. evaluate (run) the binary tensor in a session
  3. turn the binary to stream
  4. feed to PIL image
  5. (optional) displaythe image with matplotlib

Code:

import tensorflow as tf
import matplotlib.pyplot as plt
import PIL

...

image_tensor = <your decoded image tensor>
jpeg_bin_tensor = tf.image.encode_jpeg(image_tensor)

with tf.Session() as sess:
    # display encoded back to image data
    jpeg_bin = sess.run(jpeg_bin_tensor)
    jpeg_str = StringIO.StringIO(jpeg_bin)
    jpeg_image = PIL.Image.open(jpeg_str)
    plt.imshow(jpeg_image)

This worked for me. You can try it in a ipython notebook. Just don't forget to add the following line:

%matplotlib inline

What is a "callback" in C and how are they implemented?

A callback in C is a function that is provided to another function to "call back to" at some point when the other function is doing its task.

There are two ways that a callback is used: synchronous callback and asynchronous callback. A synchronous callback is provided to another function which is going to do some task and then return to the caller with the task completed. An asynchronous callback is provided to another function which is going to start a task and then return to the caller with the task possibly not completed.

A synchronous callback is typically used to provide a delegate to another function to which the other function delegates some step of the task. Classic examples of this delegation are the functions bsearch() and qsort() from the C Standard Library. Both of these functions take a callback which is used during the task the function is providing so that the type of the data being searched, in the case of bsearch(), or sorted, in the case of qsort(), does not need to be known by the function being used.

For instance here is a small sample program with bsearch() using different comparison functions, synchronous callbacks. By allowing us to delegate the data comparison to a callback function, the bsearch() function allows us to decide at run time what kind of comparison we want to use. This is synchronous because when the bsearch() function returns the task is complete.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int iValue;
    int kValue;
    char label[6];
} MyData;

int cmpMyData_iValue (MyData *item1, MyData *item2)
{
    if (item1->iValue < item2->iValue) return -1;
    if (item1->iValue > item2->iValue) return 1;
    return 0;
}

int cmpMyData_kValue (MyData *item1, MyData *item2)
{
    if (item1->kValue < item2->kValue) return -1;
    if (item1->kValue > item2->kValue) return 1;
    return 0;
}

int cmpMyData_label (MyData *item1, MyData *item2)
{
    return strcmp (item1->label, item2->label);
}

void bsearch_results (MyData *srch, MyData *found)
{
        if (found) {
            printf ("found - iValue = %d, kValue = %d, label = %s\n", found->iValue, found->kValue, found->label);
        } else {
            printf ("item not found, iValue = %d, kValue = %d, label = %s\n", srch->iValue, srch->kValue, srch->label);
        }
}

int main ()
{
    MyData dataList[256] = {0};

    {
        int i;
        for (i = 0; i < 20; i++) {
            dataList[i].iValue = i + 100;
            dataList[i].kValue = i + 1000;
            sprintf (dataList[i].label, "%2.2d", i + 10);
        }
    }

//  ... some code then we do a search
    {
        MyData srchItem = { 105, 1018, "13"};
        MyData *foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_iValue );

        bsearch_results (&srchItem, foundItem);

        foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_kValue );
        bsearch_results (&srchItem, foundItem);

        foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_label );
        bsearch_results (&srchItem, foundItem);
    }
}

An asynchronous callback is different in that when the called function to which we provide a callback returns, the task may not be completed. This type of callback is often used with asynchronous I/O in which an I/O operation is started and then when it is completed, the callback is invoked.

In the following program we create a socket to listen for TCP connection requests and when a request is received, the function doing the listening then invokes the callback function provided. This simple application can be exercised by running it in one window while using the telnet utility or a web browser to attempt to connect in another window.

I lifted most of the WinSock code from the example Microsoft provides with the accept() function at https://msdn.microsoft.com/en-us/library/windows/desktop/ms737526(v=vs.85).aspx

This application starts a listen() on the local host, 127.0.0.1, using port 8282 so you could use either telnet 127.0.0.1 8282 or http://127.0.0.1:8282/.

This sample application was created as a console application with Visual Studio 2017 Community Edition and it is using the Microsoft WinSock version of sockets. For a Linux application the WinSock functions would need to be replaced with the Linux alternatives and the Windows threads library would use pthreads instead.

#include <stdio.h>
#include <winsock2.h>
#include <stdlib.h>
#include <string.h>

#include <Windows.h>

// Need to link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

// function for the thread we are going to start up with _beginthreadex().
// this function/thread will create a listen server waiting for a TCP
// connection request to come into the designated port.
// _stdcall modifier required by _beginthreadex().
int _stdcall ioThread(void (*pOutput)())
{
    //----------------------
    // Initialize Winsock.
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != NO_ERROR) {
        printf("WSAStartup failed with error: %ld\n", iResult);
        return 1;
    }
    //----------------------
    // Create a SOCKET for listening for
    // incoming connection requests.
    SOCKET ListenSocket;
    ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ListenSocket == INVALID_SOCKET) {
        wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }
    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port for the socket that is being bound.
    struct sockaddr_in service;
    service.sin_family = AF_INET;
    service.sin_addr.s_addr = inet_addr("127.0.0.1");
    service.sin_port = htons(8282);

    if (bind(ListenSocket, (SOCKADDR *)& service, sizeof(service)) == SOCKET_ERROR) {
        printf("bind failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    //----------------------
    // Listen for incoming connection requests.
    // on the created socket
    if (listen(ListenSocket, 1) == SOCKET_ERROR) {
        printf("listen failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    //----------------------
    // Create a SOCKET for accepting incoming requests.
    SOCKET AcceptSocket;
    printf("Waiting for client to connect...\n");

    //----------------------
    // Accept the connection.
    AcceptSocket = accept(ListenSocket, NULL, NULL);
    if (AcceptSocket == INVALID_SOCKET) {
        printf("accept failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    else
        pOutput ();   // we have a connection request so do the callback

    // No longer need server socket
    closesocket(ListenSocket);

    WSACleanup();
    return 0;
}

// our callback which is invoked whenever a connection is made.
void printOut(void)
{
    printf("connection received.\n");
}

#include <process.h>

int main()
{
     // start up our listen server and provide a callback
    _beginthreadex(NULL, 0, ioThread, printOut, 0, NULL);
    // do other things while waiting for a connection. In this case
    // just sleep for a while.
    Sleep(30000);
}

How remove border around image in css?

<img id="instapic01" class="samples" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"/>

Python division

I'm somewhat surprised that no one has mentioned that the original poster might have liked rational numbers to result. Should you be interested in this, the Python-based program Sage has your back. (Currently still based on Python 2.x, though 3.x is under way.)

sage: (20-10) / (100-10)
1/9

This isn't a solution for everyone, because it does do some preparsing so these numbers aren't ints, but Sage Integer class elements. Still, worth mentioning as a part of the Python ecosystem.

How to read XML response from a URL in java?

I found that the above answer caused me an exception when I tried to instantiate the parser. I found the following code that resolved this at http://docstore.mik.ua/orelly/xml/sax2/ch03_02.htm.

import org.xml.sax.*;
import javax.xml.parsers.*;

XMLReader        parser;

try {
    SAXParserFactory factory;

    factory = SAXParserFactory.newInstance ();
    factory.setNamespaceAware (true);
    parser = factory.newSAXParser ().getXMLReader ();
    // success!

} catch (FactoryConfigurationError err) {
    System.err.println ("can't create JAXP SAXParserFactory, "
    + err.getMessage ());
} catch (ParserConfigurationException err) {
    System.err.println ("can't create XMLReader with namespaces, "
    + err.getMessage ());
} catch (SAXException err) {
    System.err.println ("Hmm, SAXException, " + err.getMessage ());
}

Search All Fields In All Tables For A Specific Value (Oracle)

Borrowing, slightly enhancing and simplifying from this Blog post the following simple SQL statement seems to do the job quite well:

SELECT DISTINCT (:val) "Search Value", TABLE_NAME "Table", COLUMN_NAME "Column"
FROM cols,
     TABLE (XMLSEQUENCE (DBMS_XMLGEN.GETXMLTYPE(
       'SELECT "' || COLUMN_NAME || '" FROM "' || TABLE_NAME || '" WHERE UPPER("'
       || COLUMN_NAME || '") LIKE UPPER(''%' || :val || '%'')' ).EXTRACT ('ROWSET/ROW/*')))
ORDER BY "Table";

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

While using mysql version 8.0 + , use the following syntax to update root password after starting mysql daemon with --skip-grant-tables option

UPDATE user SET PASSWORD FOR 'root'@'localhost' = PASSWORD('your_new_password')

How to get source code of a Windows executable?

You can't get the C++ source from an exe, and you can only get some version of the C# source via reflection.

What is the difference between printf() and puts() in C?

int puts(const char *s);

puts() writes the string s and a trailing newline to stdout.

int printf(const char *format, ...);

The function printf() writes output to stdout, under the control of a format string that specifies how subsequent arguments are converted for output.

I'll use this opportunity to ask you to read the documentation.

Excel to CSV with UTF8 encoding

Using Notepad++

This will fix the corrupted CSV file saved by Excel and re-save it in the proper encoding.

  • Export CSV from Excel
  • Load into Notepad++
  • Fix encoding
  • Save

Excel saves in CP-1252 / Windows-1252. Open the CSV file in Notepad++. Select

Encoding > Character Sets > Western European > Windows-1252

Then

Encoding > Convert to UTF-8
File > Save

First tell Notepad++ the encoding, then convert. Some of these other answers are converting without setting the proper encoding first, mangling the file even more. They would turn what should be into ?. If your character does not fit into CP-1252 then it was already lost when it was saved as CSV. Use another answer for that.

How to generate range of numbers from 0 to n in ES2015 only?

For numbers 0 to 5

[...Array(5).keys()];
=> [0, 1, 2, 3, 4]

creating charts with angularjs

The ZingChart library has an AngularJS directive that was built in-house. Features include:

  • Full access to the entire ZingChart library (all charts, maps, and features)
  • Takes advantage of Angular's 2-way data binding, making data and chart elements easy to update
  • Support from the development team

    ...
    $scope.myJson = {
    type : 'line',
       series : [
          { values : [54,23,34,23,43] },{ values : [10,15,16,20,40] }
       ]
    };
    ...
    
    <zingchart id="myChart" zc-json="myJson" zc-height=500 zc-width=600></zingchart>
    

There is a full demo with code examples available.

Find JavaScript function definition in Chrome

You can print the function by evaluating the name of it in the console, like so

> unknownFunc
function unknownFunc(unknown) {
    alert('unknown seems to be ' + unknown);
}

this won't work for built-in functions, they will only display [native code] instead of the source code.

EDIT: this implies that the function has been defined within the current scope.

Python - How to convert JSON File to Dataframe

Creating dataframe from dictionary object.

import pandas as pd
data = [{'name': 'vikash', 'age': 27}, {'name': 'Satyam', 'age': 14}]
df = pd.DataFrame.from_dict(data, orient='columns')

df
Out[4]:
   age  name
0   27  vikash
1   14  Satyam

If you have nested columns then you first need to normalize the data:

data = [
  {
    'name': {
      'first': 'vikash',
      'last': 'singh'
    },
    'age': 27
  },
  {
    'name': {
      'first': 'satyam',
      'last': 'singh'
    },
    'age': 14
  }
]

df = pd.DataFrame.from_dict(pd.json_normalize(data), orient='columns')

df    
Out[8]:
age name.first  name.last
0   27  vikash  singh
1   14  satyam  singh

Source:

Best Practice to Use HttpClient in Multithreaded Environment

I think you will want to use ThreadSafeClientConnManager.

You can see how it works here: http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html

Or in the AndroidHttpClient which uses it internally.

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

So, rather return the whole object first, just wrap it to json_encode and then return it. This will return a proper and valid object.

public function id($id){
    $promotion = Promotion::find($id);
    return json_encode($promotion);
}

Or, For DB this will be just like,

public function id($id){
    $promotion = DB::table('promotions')->first();
    return json_encode($promotion);
}

I think it may help someone else.

Google Maps API Multiple Markers with Infowindows

function setMarkers(map,locations){

for (var i = 0; i < locations.length; i++)
 {  

 var loan = locations[i][0];
 var lat = locations[i][1];
 var long = locations[i][2];
 var add =  locations[i][3];

 latlngset = new google.maps.LatLng(lat, long);

 var marker = new google.maps.Marker({  
          map: map, title: loan , position: latlngset  
 });
 map.setCenter(marker.getPosition());


 marker.content = "<h3>Loan Number: " + loan +  '</h3>' + "Address: " + add;


 google.maps.events.addListener(marker,'click', function(map,marker){
          map.infowindow.setContent(marker.content);
          map.infowindow.open(map,marker);

 });

 }
}

Then move var infowindow = new google.maps.InfoWindow() to the initialize() function:

function initialize() {

    var myOptions = {
      center: new google.maps.LatLng(33.890542, 151.274856),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP

    };
    var map = new google.maps.Map(document.getElementById("default"),
        myOptions);
    map.infowindow = new google.maps.InfoWindow();

    setMarkers(map,locations)

  }

jQuery AJAX Character Encoding

I have tried to read a local json/text file using $.ajax and the encoding didn't work at first.. I got it working by saving the json file as UTF-8 encoding. This can be done simply by windows notepad.. use "save as", and then below the file name you can set the encoding to UTF-8.

good luck!

Checking for Undefined In React

I was face same problem ..... And I got solution by using typeof()

if (typeof(value) !== 'undefined' && value != null) {
         console.log('Not Undefined and Not Null')
  } else {
         console.log('Undefined or Null')
}

You must have to use typeof() to identified undefined

How to center a window on the screen in Tkinter?

CENTERING THE WINDOW IN PYTHON Tkinter This is the most easiest thing in tkinter because all we must know is the dimension of the window as well as the dimensions of the computer screen. I come up with the following code which can help someone somehow and i did add some comments so that they can follow up.

code

    #  create a window first
    root = Tk()
    # define window dimensions width and height
    window_width = 800
    window_height = 500
    # get the screen size of your computer [width and height using the root object as foolows]
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    # Get the window position from the top dynamically as well as position from left or right as follows
    position_top = int(screen_height/2 -window_height/2)
    position_right = int(screen_width / 2 - window_width/2)
    # this is the line that will center your window
    root.geometry(f'{window_width}x{window_height}+{position_right}+{position_top}')
    # initialise the window
    root.mainloop(0)

How can I combine hashes in Perl?

Quick Answer (TL;DR)


    %hash1 = (%hash1, %hash2)

    ## or else ...

    @hash1{keys %hash2} = values %hash2;

    ## or with references ...

    $hash_ref1 = { %$hash_ref1, %$hash_ref2 };

Overview

  • Context: Perl 5.x
  • Problem: The user wishes to merge two hashes1 into a single variable

Solution

  • use the syntax above for simple variables
  • use Hash::Merge for complex nested variables

Pitfalls

See also


Footnotes

1 * (aka associative-array, aka dictionary)

How to change progress bar's progress color in Android

One more little thing, the theme solution does work if you inherit a base theme, so for app compact your theme should be:

<style name="AppTheme.Custom" parent="@style/Theme.AppCompat">
    <item name="colorAccent">@color/custom</item>
</style>

And then set this in the progress bar theme

<ProgressBar
    android:id="@+id/progressCircle_progressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:theme="@style/AppTheme.Custom"
    android:indeterminate="true"/>

run program in Python shell

From the same folder, you can do:

import test

How to sleep for five seconds in a batch file/cmd

One hack is to (mis)use the ping command:

ping 127.0.0.1 -n 6 > nul

Explanation:

  • ping is a system utility that sends ping requests. ping is available on all versions of Windows.
  • 127.0.0.1 is the IP address of localhost. This IP address is guaranteed to always resolve, be reachable, and immediately respond to pings.
  • -n 6 specifies that there are to be 6 pings. There is a 1s delay between each ping, so for a 5s delay you need to send 6 pings.
  • > nul suppress the output of ping, by redirecting it to nul.

Remove rows with all or some NAs (missing values) in data.frame

If you want control over how many NAs are valid for each row, try this function. For many survey data sets, too many blank question responses can ruin the results. So they are deleted after a certain threshold. This function will allow you to choose how many NAs the row can have before it's deleted:

delete.na <- function(DF, n=0) {
  DF[rowSums(is.na(DF)) <= n,]
}

By default, it will eliminate all NAs:

delete.na(final)
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
6 ENSG00000221312    0    1    2    3    2

Or specify the maximum number of NAs allowed:

delete.na(final, 2)
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
4 ENSG00000207604    0   NA   NA    1    2
6 ENSG00000221312    0    1    2    3    2

How to destroy Fragment?

If you don't remove manually these fragments, they are still attached to the activity. Your activity is not destroyed so these fragments are too. To remove (so destroy) these fragments, you can call:

fragmentTransaction.remove(yourfragment).commit()

Hope it helps to you

css label width not taking effect

give the style

display:inline-block;

hope this will help'

how to display data values on Chart.js

Following this good answer, I'd use these options for a bar chart:

var chartOptions = {
    animation: false,
    responsive : true,
    tooltipTemplate: "<%= value %>",
    tooltipFillColor: "rgba(0,0,0,0)",
    tooltipFontColor: "#444",
    tooltipEvents: [],
    tooltipCaretSize: 0,
    onAnimationComplete: function()
    {
        this.showTooltip(this.datasets[0].bars, true);
    }
};

window.myBar = new Chart(ctx1).Bar(chartData, chartOptions);

Bar Chart

This still uses the tooltip system and his advantages (automatic positionning, templating, ...) but hiding the decorations (background color, caret, ...)

How do I concatenate two strings in Java?

This should work

public class StackOverflowTest
{  
    public static void main(String args[])
    {
        int theNumber = 42;
        System.out.println("Your number is " + theNumber + "!");
    }
}

Interview Question: Merge two sorted singly linked lists without creating new nodes

Simple code in javascript to merge two linked list inplace.

function mergeLists(l1, l2) {
    let head = new ListNode(0); //dummy
    let curr = head;
    while(l1 && l2) {
        if(l2.val >= l1.val) {
            curr.next = l1;
            l1 = l1.next;
        } else {
            curr.next = l2;
            l2=l2.next
        }
        curr = curr.next;
    }
    if(!l1){
        curr.next=l2;
    }
    if(!l2){
        curr.next=l1;
    } 
    return head.next;
}

How can I listen for a click-and-hold in jQuery?

Try this:

var thumbnailHold;

    $(".image_thumb").mousedown(function() {
        thumbnailHold = setTimeout(function(){
             checkboxOn(); // Your action Here

         } , 1000);
     return false;
});

$(".image_thumb").mouseup(function() {
    clearTimeout(thumbnailHold);
});

How to convert JSON data into a Python object

If you are using python 3.6+, you can use marshmallow-dataclass. Contrarily to all the solutions listed above, it is both simple, and type safe:

from marshmallow_dataclass import dataclass

@dataclass
class User:
    name: str

user = User.Schema().load({"name": "Ramirez"})

Is there a jQuery unfocus method?

This works for me:

// Document click blurer
$(document).on('mousedown', '*:not(input,textarea)', function() {
    try {
        var $a = $(document.activeElement).prop("disabled", true);
        setTimeout(function() {
            $a.prop("disabled", false);
        });
    } catch (ex) {}
});

jQuery show for 5 seconds then hide

You can use .delay() before an animation, like this:

$("#myElem").show().delay(5000).fadeOut();

If it's not an animation, use setTimeout() directly, like this:

$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);

You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.

Or, another option is to use .delay() and .queue() yourself, like this:

$("#myElem").show().delay(5000).queue(function(n) {
  $(this).hide(); n();
});

How can I pass POST parameters in a URL?

Parameters in the URL are GET parameters, a request body, if present, is POST data. So your basic premise is by definition not achievable.

You should choose whether to use POST or GET based on the action. Any destructive action, i.e. something that permanently changes the state of the server (deleting, adding, editing) should always be invoked by POST requests. Any pure "information retrieval" should be accessible via an unchanging URL (i.e. GET requests).

To make a POST request, you need to create a <form>. You could use Javascript to create a POST request instead, but I wouldn't recommend using Javascript for something so basic. If you want your submit button to look like a link, I'd suggest you create a normal form with a normal submit button, then use CSS to restyle the button and/or use Javascript to replace the button with a link that submits the form using Javascript (depending on what reproduces the desired behavior better). That'd be a good example of progressive enhancement.

How to fix a collation conflict in a SQL Server query?

if the database is maintained by you then simply create a new database and import the data from the old one. the collation problem is solved!!!!!

How to edit an Android app?

You would need to decompile the apk as Davis suggested, can use tools such as apkTool , then if you need to change the source code you would need other tools to do that.

You would then need to put the apk back together and sign it, if you don't have the original key used to sign the apk this means the new apk will have a different signature.

If the developer employed any obfuscation or other techniques to protect the app then it gets more complicated.

In short its a pretty complex and technical procedure, so if the developer is really just out of reach, its better to wait until he is in reach. And ask for the source code next time.

C++ Pass A String

The obvious way would be to call the function like this

print(string("Yo!"));

jQuery UI themes and HTML tables

Why noy just use the theme styles in the table? i.e.

<table>
  <thead class="ui-widget-header">
    <tr>
      <th>Id</th>
      <th>Description</th>
    </td>
  </thead>
  <tbody class="ui-widget-content">
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
      .
      .
      .
  </tbody>
</table>

And you don't need to use any code...

SQL: how to use UNION and order by a specific select?

@Adrien's answer is not working. It gives an ORA-01791.

The correct answer (for the question that is asked) should be:

select id
from 
 (SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
  UNION ALL
  SELECT id, 1 as ordered FROM b -- returns 2,1
  )
group by id
order by min(ordered)

Explanation:

  1. The "UNION ALL" is combining the 2 sets. A "UNION" is wastefull because the 2 sets could not be the same, because the ordered field is different.
  2. The "group by" is then eliminating duplicates
  3. The "order by min (ordered)" is assuring the elements of table b are first

This solves all the cases, even when table b has more or different elements then table a

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Along with the embed, I also had to install the Google Cast extension in my browser.

<iframe width="1280" height="720" src="https://www.youtube.com/embed/4u856utdR94" frameborder="0" allowfullscreen></iframe>

How to allow Cross domain request in apache2

In httpd.conf

  1. Make sure these are loaded:
LoadModule headers_module modules/mod_headers.so

LoadModule rewrite_module modules/mod_rewrite.so
  1. In the target directory:
<Directory "**/usr/local/PATH**">
    AllowOverride None
    Require all granted

    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
    Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
    Header always set Access-Control-Expose-Headers "Content-Security-Policy, Location"
    Header always set Access-Control-Max-Age "600"

    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [R=200,L]

</Directory>

If running outside container, you may need to restart apache service.

SaveFileDialog setting default path and file type?

The SaveFileDialog control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.

  1. Set the property InitialDirectory to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.

  2. That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).

Just as a quick example (there are alternative ways to do it). savefile is a control of type SaveFileDialog

SaveFileDialog savefile = new SaveFileDialog(); 
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

if (savefile.ShowDialog() == DialogResult.OK)
{
    using (StreamWriter sw = new StreamWriter(savefile.FileName))
        sw.WriteLine ("Hello World!");
}

Transactions in .net

There are 2 main kinds of transactions; connection transactions and ambient transactions. A connection transaction (such as SqlTransaction) is tied directly to the db connection (such as SqlConnection), which means that you have to keep passing the connection around - OK in some cases, but doesn't allow "create/use/release" usage, and doesn't allow cross-db work. An example (formatted for space):

using (IDbTransaction tran = conn.BeginTransaction()) {
    try {
        // your code
        tran.Commit();
    }  catch {
        tran.Rollback();
        throw;
    }
}

Not too messy, but limited to our connection "conn". If we want to call out to different methods, we now need to pass "conn" around.

The alternative is an ambient transaction; new in .NET 2.0, the TransactionScope object (System.Transactions.dll) allows use over a range of operations (suitable providers will automatically enlist in the ambient transaction). This makes it easy to retro-fit into existing (non-transactional) code, and to talk to multiple providers (although DTC will get involved if you talk to more than one).

For example:

using(TransactionScope tran = new TransactionScope()) {
    CallAMethodThatDoesSomeWork();
    CallAMethodThatDoesSomeMoreWork();
    tran.Complete();
}

Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.

If your code errors, Dispose() will be called without Complete(), so it will be rolled back. The expected nesting etc is supported, although you can't roll-back an inner transaction yet complete the outer transaction: if anybody is unhappy, the transaction is aborted.

The other advantage of TransactionScope is that it isn't tied just to databases; any transaction-aware provider can use it. WCF, for example. Or there are even some TransactionScope-compatible object models around (i.e. .NET classes with rollback capability - perhaps easier than a memento, although I've never used this approach myself).

All in all, a very, very useful object.

Some caveats:

  • On SQL Server 2000, a TransactionScope will go to DTC immediately; this is fixed in SQL Server 2005 and above, it can use the LTM (much less overhead) until you talk to 2 sources etc, when it is elevated to DTC.
  • There is a glitch that means you might need to tweak your connection string

Maven: Non-resolvable parent POM

I had the issue that two reactor build pom.xml files had the same artefactId.

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

The first backslash in your string is being interpreted as a special character, in fact because it's followed by a "U" it's being interpreted as the start of a unicode code point.

To fix this you need to escape the backslashes in the string. I don't know Python specifically but I'd guess you do it by doubling the backslashes:

data = open("C:\\Users\\miche\\Documents\\school\\jaar2\\MIK\\2.6\\vektis_agb_zorgverlener")

How can I print each command before executing?

The easiest way to do this is to let bash do it:

set -x

Or run it explicitly as bash -x myscript.

C++ wait for user input

You can try

#include <iostream>
#include <conio.h>

int main() {

    //some codes

    getch();
    return 0;
}

What is the difference between max-device-width and max-width for mobile web?

max-width is the width of the target display area, e.g. the browser; max-device-width is the width of the device's entire rendering area, i.e. the actual device screen.

• If you are using the max-device-width, when you change the size of the browser window on your desktop, the CSS style won't change to different media query setting;

• If you are using the max-width, when you change the size of the browser on your desktop, the CSS will change to different media query setting and you might be shown with the styling for mobiles, such as touch-friendly menus.

Convert javascript array to string

jQuery.each is just looping over the array, it doesn't do anything with the return value?. You are looking for jQuery.map (I also think that get() is unnecessary as you are not dealing with jQuery objects):

var blkstr = $.map(value, function(val,index) {                    
     var str = index + ":" + val;
     return str;
}).join(", ");  

DEMO


But why use jQuery at all in this case? map only introduces an unnecessary function call per element.

var values = [];

for(var i = 0, l = value.length; i < l; i++) {
    values.push(i + ':' + value[i]);
}

// or if you actually have an object:

for(var id in value) {
    if(value.hasOwnProperty(id)) {
        values.push(id + ':' + value[id]);
    }
}

var blkstr = values.join(', ');

?: It only uses the return value whether it should continue to loop over the elements or not. Returning a "falsy" value will stop the loop.

element not interactable exception in selenium web automation

If it's working in the debug, then wait must be the proper solution.
I will suggest to use the explicit wait, as given below:

WebDriverWait wait = new WebDriverWait(new ChromeDriver(), 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#Passwd")));

How to put php inside JavaScript?

you need quotes around the string in javascript

var htmlString="<?php echo $htmlString; ?>";

Convert char to int in C#

Has anyone considered using int.Parse() and int.TryParse() like this

int bar = int.Parse(foo.ToString());

Even better like this

int bar;
if (!int.TryParse(foo.ToString(), out bar))
{
    //Do something to correct the problem
}

It's a lot safer and less error prone

Full path from file input using jQuery

Well, getting full path is not possible but we can have a temporary path.

Try This:

It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-

JSFIDDLE

Here is the code :-

HTML:-

<input type="file" id="i_file" value=""> 
<input type="button" id="i_submit" value="Submit">
    <br>
<img src="" width="200" style="display:none;" />
        <br>
<div id="disp_tmp_path"></div>

JS:-

$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
    $("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));

    $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});

Its not exactly what you were looking for, but may be it can help you somewhere.

How can I list ALL grants a user received?

The most comprehensive and reliable method I know is still by using DBMS_METADATA:

select dbms_metadata.get_granted_ddl( 'SYSTEM_GRANT', :username ) from dual;
select dbms_metadata.get_granted_ddl( 'OBJECT_GRANT', :username ) from dual;
select dbms_metadata.get_granted_ddl( 'ROLE_GRANT', :username ) from dual;

(username must be written all uppercase)

Interesting answers though.

How to parse a CSV file in Bash?

We can parse csv files with quoted strings and delimited by say | with following code

while read -r line
do
    field1=$(echo "$line" | awk -F'|' '{printf "%s", $1}' | tr -d '"')
    field2=$(echo "$line" | awk -F'|' '{printf "%s", $2}' | tr -d '"')

    echo "$field1 $field2"
done < "$csvFile"

awk parses the string fields to variables and tr removes the quote.

Slightly slower as awk is executed for each field.

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

For visual studio 2019 
change the code in aspx.cs page

    <%@ Register Assembly="CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"
        Namespace="CrystalDecisions.Web" TagPrefix="CR" %>

in web config:

    <configSections>
        <sectionGroup name="businessObjects">
          <sectionGroup name="crystalReports">
            <section name="rptBuildProvider" type="CrystalDecisions.Shared.RptBuildProviderHandler, CrystalDecisions.Shared, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304, Custom=null"/>
          </sectionGroup>
        </sectionGroup>
      </configSections>


 <assemblies>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="CrystalDecisions.CrystalReports.Engine, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
        <add assembly="CrystalDecisions.ReportSource, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
        <add assembly="CrystalDecisions.Shared, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
        <add assembly="CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
        <add assembly="CrystalDecisions.ReportAppServer.ClientDoc, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
        <add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
        <add assembly="Microsoft.ReportViewer.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
        <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="CrystalDecisions.CrystalReports.Engine, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
        <add assembly="CrystalDecisions.ReportSource, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
        <add assembly="CrystalDecisions.Shared, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
        <add assembly="CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
        <add assembly="CrystalDecisions.ReportAppServer.ClientDoc, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
      </assemblies>

 <buildProviders>
        <add extension=".rpt" type="CrystalDecisions.Web.Compilation.RptBuildProvider, CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
        <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
      </buildProviders>

SQL Inner join 2 tables with multiple column conditions and update

You should join T1 and T2 tables using sql joins in order to analyze from two tables. Link for learn joins : https://www.w3schools.com/sql/sql_join.asp

Simple argparse example wanted: 1 argument, 3 results

Here's the way I do it with argparse (with multiple args):

parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())

args will be a dictionary containing the arguments:

if args['foo'] == 'Hello':
    # code here

if args['bar'] == 'World':
    # code here

In your case simply add only one argument.

php hide ALL errors

To hide errors only from users but displaying logs errors in apache log

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

1 - Displaying error only in log
2 - hide from users

Saving and loading objects and using pickle

As for your second problem:

 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "C:\Python31\lib\pickle.py", line
 1365, in load encoding=encoding,
 errors=errors).load() EOFError

After you have read the contents of the file, the file pointer will be at the end of the file - there will be no further data to read. You have to rewind the file so that it will be read from the beginning again:

file.seek(0)

What you usually want to do though, is to use a context manager to open the file and read data from it. This way, the file will be automatically closed after the block finishes executing, which will also help you organize your file operations into meaningful chunks.

Finally, cPickle is a faster implementation of the pickle module in C. So:

In [1]: import _pickle as cPickle

In [2]: d = {"a": 1, "b": 2}

In [4]: with open(r"someobject.pickle", "wb") as output_file:
   ...:     cPickle.dump(d, output_file)
   ...:

# pickle_file will be closed at this point, preventing your from accessing it any further

In [5]: with open(r"someobject.pickle", "rb") as input_file:
   ...:     e = cPickle.load(input_file)
   ...:

In [7]: print e
------> print(e)
{'a': 1, 'b': 2}

Mergesort with Python

def merge(l1, l2, out=[]):
    if l1==[]: return out+l2
    if l2==[]: return out+l1
    if l1[0]<l2[0]: return merge(l1[1:], l2, out+l1[0:1])
    return merge(l1, l2[1:], out+l2[0:1])
def merge_sort(l): return (lambda h: l if h<1 else merge(merge_sort(l[:h]), merge_sort(l[h:])))(len(l)/2)
print(merge_sort([1,4,6,3,2,5,78,4,2,1,4,6,8]))

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

I believe there is a maximum number of concurrent http requests that browsers will make to the same domain, which is in the order of 4-8 requests depending on the user's settings and browser.

You could set up your requests to go to different domains, which may or may not be feasible. The Yahoo guys did a lot of research in this area, which you can read about (here). Remember that every new domain you add also requires a DNS lookup. The YSlow guys recommend between 2 and 4 domains to achieve a good compromise between parallel requests and DNS lookups, although this is focusing on the page's loading time, not subsequent AJAX requests.

Can I ask why you want to make so many requests? There is good reasons for the browsers limiting the number of requests to the same domain. You will be better off bundling requests if possible.

T-SQL - function with default parameters

One way around this problem is to use stored procedures with an output parameter.

exec sp_mysprocname @returnvalue output, @firstparam = 1, @secondparam=2

values you do not pass in default to the defaults set in the stored procedure itself. And you can get the results from your output variable.

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

Dim NuevoLibro As Workbook
Dim NombreLibro As String
    NombreLibro = "LibroPrueba"
'---Creamos nuevo libro y lo guardamos
    Set NuevoLibro = Workbooks.Add
        With NuevoLibro
            .SaveAs Filename:=NuevaRuta & NombreLibro, FileFormat:=52
        End With
                                                    '*****************************
                                                        'valores para FileFormat
                                                        '.xlsx = 51 '(52 for Mac)
                                                        '.xlsm = 52 '(53 for Mac)
                                                        '.xlsb = 50 '(51 for Mac)
                                                        '.xls = 56 '(57 for Mac)
                                                    '*****************************

Using Python's os.path, how do I go up one directory?

To get the folder of a file just use:

os.path.dirname(path) 

To get a folder up just use os.path.dirname again

os.path.dirname(os.path.dirname(path))

You might want to check if __file__ is a symlink:

if os.path.islink(__file__): path = os.readlink (__file__)

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

Check for the name of the file, i.e pom.xml file is spelled correctly with proper file extension .xml.

Example for this error are

pom.ml pm.xl

Configure Log4Net in web application

I also had the similar issue. Logs were not creating.

Please check logger attribute name should match with your LogManager.GetLogger("name")

<logger name="Mylog">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>



private static readonly ILog Log = LogManager.GetLogger("Mylog");

Draw a line in a div

Answered this just to emphasize @rblarsen comment on question :

You don't need the style tags in the CSS-file

If you remove the style tag from your css file it will work.

How can I configure Logback to log different levels for a logger to different destinations?

I use logback.groovy to configure my logback but you can do it with xml config as well:

import static ch.qos.logback.classic.Level.*
import static ch.qos.logback.core.spi.FilterReply.DENY
import static ch.qos.logback.core.spi.FilterReply.NEUTRAL
import ch.qos.logback.classic.boolex.GEventEvaluator
import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.core.filter.EvaluatorFilter

def patternExpression = "%date{ISO8601} [%5level] %msg%n"

appender("STDERR", ConsoleAppender) {
    filter(EvaluatorFilter) {
      evaluator(GEventEvaluator) {
        expression = 'e.level.toInt() >= WARN.toInt()'
      }
      onMatch = NEUTRAL
      onMismatch = DENY
    }
    encoder(PatternLayoutEncoder) {
      pattern = patternExpression
    }
    target = "System.err"
  }

appender("STDOUT", ConsoleAppender) {
    filter(EvaluatorFilter) {
      evaluator(GEventEvaluator) {
        expression = 'e.level.toInt() < WARN.toInt()'
      }
      onMismatch = DENY
      onMatch = NEUTRAL
    }
    encoder(PatternLayoutEncoder) {
      pattern = patternExpression
    }
    target = "System.out"
}

logger("org.hibernate.type", WARN)
logger("org.hibernate", WARN)
logger("org.springframework", WARN)

root(INFO,["STDERR","STDOUT"])

I think to use GEventEvaluator is simplier because there is no need to create filter classes.
I apologize for my English!

Check if value exists in enum in TypeScript

For anyone who comes here looking to validate if a string is one of the values of an enum and type convert it, I wrote this function that returns the proper type and returns undefined if the string is not in the enum.

function keepIfInEnum<T>(
  value: string,
  enumObject: { [key: string]: T }
) {
  if (Object.values(enumObject).includes((value as unknown) as T)) {
    return (value as unknown) as T;
  } else {
    return undefined;
  }
}

As an example:

enum StringEnum {
  value1 = 'FirstValue',
  value2 = 'SecondValue',
}
keepIfInEnum<StringEnum>('FirstValue', StringEnum)  // 'FirstValue'
keepIfInEnum<StringEnum>('OtherValue', StringEnum)  // undefined

Git: How to pull a single file from a server repository in Git?

This can be the solution:

git fetch

git checkout origin/master -- FolderPathName/fileName

Thanks.

How do I import/include MATLAB functions?

You should be able to put them in your ~/matlab on unix.

I'm not sure which directory matlab looks in for windows, but you should be able to figure it out by executing userpath from the matlab command line.

Increasing (or decreasing) the memory available to R processes

From:

http://gking.harvard.edu/zelig/docs/How_do_I2.html (mirror)

Windows users may get the error that R has run out of memory.

If you have R already installed and subsequently install more RAM, you may have to reinstall R in order to take advantage of the additional capacity.

You may also set the amount of available memory manually. Close R, then right-click on your R program icon (the icon on your desktop or in your programs directory). Select ``Properties'', and then select the ``Shortcut'' tab. Look for the ``Target'' field and after the closing quotes around the location of the R executible, add

--max-mem-size=500M

as shown in the figure below. You may increase this value up to 2GB or the maximum amount of physical RAM you have installed.

If you get the error that R cannot allocate a vector of length x, close out of R and add the following line to the ``Target'' field:

--max-vsize=500M

or as appropriate. You can always check to see how much memory R has available by typing at the R prompt

memory.limit()

which gives you the amount of available memory in MB. In previous versions of R you needed to use: round(memory.limit()/2^20, 2).

How do I mock an autowired @Value field in Spring with Mockito?

Also note that I have no explicit "setter" methods (e.g. setDefaultUrl) in my class and I don't want to create any just for the purposes of testing.

One way to resolve this is change your class to use Constructor Injection, that is used for testing and Spring injection. No more reflection :)

So, you can pass any String using the constructor:

class MySpringClass {

    private final String defaultUrl;
    private final String defaultrPassword;

    public MySpringClass (
         @Value("#{myProps['default.url']}") String defaultUrl, 
         @Value("#{myProps['default.password']}") String defaultrPassword) {
        this.defaultUrl = defaultUrl;
        this.defaultrPassword= defaultrPassword;
    }

}

And in your test, just use it:

MySpringClass MySpringClass  = new MySpringClass("anyUrl", "anyPassword");

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

Creating a comma separated list from IList<string> or IEnumerable<string>

FYI, the .NET 4.0 version of string.Join() has some extra overloads, that work with IEnumerable instead of just arrays, including one that can deal with any type T:

public static string Join(string separator, IEnumerable<string> values)
public static string Join<T>(string separator, IEnumerable<T> values)

nginx: [emerg] "server" directive is not allowed here

Example valid nginx.conf for reverse proxy; In case someone is stuck like me. where 10.x.x.x is the server where you are running the nginx proxy server and to which you are connecting to with the browser, and 10.y.y.y is where your real web server is running

events {
  worker_connections  4096;  ## Default: 1024
}
http {
 server {
   listen 80;
   listen [::]:80;

   server_name 10.x.x.x;
 
   location / {
       proxy_pass http://10.y.y.y:80/;
       proxy_set_header Host $host;
   }
 }
}

Here is the snippet if you want to do SSL pass through. That is if 10.y.y.y is running a HTTPS webserver. Here 10.x.x.x, or where the nignx runs is listening to port 443, and all traffic to 443 is directed to your target web server

events {
  worker_connections  4096;  ## Default: 1024
}

stream {
  server {
    listen     443;
    proxy_pass 10.y.y.y:443;
  }
}

and you can serve it up in docker too

 docker run --name nginx-container --rm --net=host   -v /home/core/nginx/nginx.conf:/etc/nginx/nginx.conf nginx

Bootstrap 4 img-circle class not working

Now the class is this

_x000D_
_x000D_
 <img src="img/img5.jpg" width="200px" class="rounded-circle float-right">
_x000D_
_x000D_
_x000D_

AngularJS - convert dates in controller

item.date = $filter('date')(item.date, "dd/MM/yyyy"); // for conversion to string

http://docs.angularjs.org/api/ng.filter:date

But if you are using HTML5 type="date" then the ISO format yyyy-MM-dd MUST be used.

item.dateAsString = $filter('date')(item.date, "yyyy-MM-dd");  // for type="date" binding


<input type="date" ng-model="item.dateAsString" value="{{ item.dateAsString }}" pattern="dd/MM/YYYY"/>

http://www.w3.org/TR/html-markup/input.date.html

NOTE: use of pattern="" with type="date" looks non-standard, but it appears to work in the expected way in Chrome 31.

How to show Snackbar when Activity starts?

I have had trouble myself displaying Snackbar until now. Here is the simplest way to display a Snackbar. To display it as your Main Activity Starts, just put these two lines inside your OnCreate()

    Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Welcome To Main Activity", Snackbar.LENGTH_LONG);
    snackbar.show();

P.S. Just make sure you have imported the Android Design Support.(As mentioned in the question).

For Kotlin,

Snackbar.make(findViewById(android.R.id.content), message, Snackbar.LENGTH_SHORT).show()

Why would I use dirname(__FILE__) in an include or include_once statement?

Let's say I have a (fake) directory structure like:

.../root/
        /app
            bootstrap.php
        /scripts
            something/
                somescript.php
        /public
            index.php

Now assume that bootstrap.php has some code included for setting up database connections or some other kind of boostrapping stuff.

Assume you want to include a file in boostrap.php's folder called init.php. Now, to avoid scanning the entire include path with include 'init.php', you could use include './init.php'.

There's a problem though. That ./ will be relative to the script that included bootstrap.php, not bootstrap.php. (Technically speaking, it will be relative to the working directory.)

dirname(__FILE__) allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap.php resides.

(Note: since PHP 5.3, you can use __DIR__ in place of dirname(__FILE__).)

Now, why not just use include 'init.php';?

As odd as it is at first though, . is not guaranteed to be in the include path. Sometimes to avoid useless stat()'s people remove it from the include path when they are rarely include files in the same directory (why search the current directory when you know includes are never going to be there?).

Note: About half of this answer is address in a rather old post: What's better of require(dirname(__FILE__).'/'.'myParent.php') than just require('myParent.php')?

Streaming via RTSP or RTP in HTML5

With VLC i'm able to transcode a live RTSP stream (mpeg4) to an HTTP stream in a OGG format (Vorbis/Theora). The quality is poor but the video work in Chrome 9. I have also tested with a trancoding in WEBM (VP8) but it's don't seem to work (VLC have the option but i don't know if it's really implemented for now..)

The first to have a doc on this should notify us ;)

Get exit code for command in bash/ksh

There are several things wrong with your script.

Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don't capture 'ERROR_CODE' so that is always zero (undefined).

It's good practice to surround your variable references with curly braces, too. Your code might look like:

#!/bin/sh
command="/bin/date -u"          #...Example Only

safeRunCommand() {
   cmnd="$@"                    #...insure whitespace passed and preserved
   $cmnd
   ERROR_CODE=$?                #...so we have it for the command we want
   if [ ${ERROR_CODE} != 0 ]; then
      printf "Error when executing command: '${command}'\n"
      exit ${ERROR_CODE}        #...consider 'return()' here
   fi
}

safeRunCommand $command
command="cp"
safeRunCommand $command

Reorder HTML table rows using drag-and-drop

Building upon the fiddle from @tim, this version tightens the scope and formatting, and converts bind() -> on(). It's designed to bind on a dedicated td as the handle instead of the entire row. In my use case, I have input fields so the "drag anywhere on the row" approach felt confusing.

Tested working on desktop. Only partial success with mobile touch. Can't get it to run correctly on SO's runnable snippet for some reason...

_x000D_
_x000D_
let ns = {
  drag: (e) => {
    let el = $(e.target),
      d = $('body'),
      tr = el.closest('tr'),
      sy = e.pageY,
      drag = false,
      index = tr.index();

    tr.addClass('grabbed');

    function move(e) {
      if (!drag && Math.abs(e.pageY - sy) < 10)
        return;
      drag = true;
      tr.siblings().each(function() {
        let s = $(this),
          i = s.index(),
          y = s.offset().top;
        if (e.pageY >= y && e.pageY < y + s.outerHeight()) {
          i < tr.index() ? s.insertAfter(tr) : s.insertBefore(tr);
          return false;
        }
      });
    }

    function up(e) {
      if (drag && index !== tr.index())
        drag = false;

      d.off('mousemove', move).off('mouseup', up);
      //d.off('touchmove', move).off('touchend', up); //failed attempt at touch compatibility
      tr.removeClass('grabbed');
    }
    d.on('mousemove', move).on('mouseup', up);
    //d.on('touchmove', move).on('touchend', up);
  }
};

$(document).ready(() => {
  $('body').on('mousedown touchstart', '.drag', ns.drag);
});
_x000D_
.grab {
  cursor: grab;
  user-select: none
}

tr.grabbed {
  box-shadow: 4px 1px 5px 2px rgba(0, 0, 0, 0.5);
}

tr.grabbed:active {
  user-input: none;
}

tr.grabbed:active * {
  user-input: none;
  cursor: grabbing !important;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th></th>
      <th>Drag the rows below...</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class='grab'>&vellip;</td>
      <td><input type="text" value="Row 1" /></td>
    </tr>
    <tr>
      <td class='grab'>&vellip;</td>
      <td><input type="text" value="Row 2" /></td>
    </tr>
    <tr>
      <td class='grab'>&vellip;</td>
      <td><input type="text" value="Row 3" /></td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Express.js - app.listen vs server.listen

There is one more difference of using the app and listening to http server is when you want to setup for https server

To setup for https, you need the code below:

var https = require('https');
var server = https.createServer(app).listen(config.port, function() {
    console.log('Https App started');
});

The app from express will return http server only, you cannot set it in express, so you will need to use the https server command

var express = require('express');
var app = express();
app.listen(1234);

Test a weekly cron job

I normally test by running the job i created like this:

It is easier to use two terminals to do this.

run job:

#./jobname.sh

go to:

#/var/log and run 

run the following:

#tailf /var/log/cron

This allows me to see the cron logs update in real time. You can also review the log after you run it, I prefer watching in real time.

Here is an example of a simple cron job. Running a yum update...

#!/bin/bash
YUM=/usr/bin/yum
$YUM -y -R 120 -d 0 -e 0 update yum
$YUM -y -R 10 -e 0 -d 0 update

Here is the breakdown:

First command will update yum itself and next will apply system updates.

-R 120 : Sets the maximum amount of time yum will wait before performing a command

-e 0 : Sets the error level to 0 (range 0 - 10). 0 means print only critical errors about which you must be told.

-d 0 : Sets the debugging level to 0 - turns up or down the amount of things that are printed. (range: 0 - 10).

-y : Assume yes; assume that the answer to any question which would be asked is yes

After I built the cron job I ran the below command to make my job executable.

#chmod +x /etc/cron.daily/jobname.sh 

Hope this helps, Dorlack

Difference between "managed" and "unmanaged"

Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).

http://en.wikipedia.org/wiki/Managed_code

http://www.developer.com/net/cplus/article.php/2197621/Managed-Unmanaged-Native-What-Kind-of-Code-Is-This.htm

how to change any data type into a string in python

Be careful if you really want to "change" the data type. Like in other cases (e.g. changing the iterator in a for loop) this might bring up unexpected behaviour:

>> dct = {1:3, 2:1}
>> len(str(dct))
12
>> print(str(dct))
{1: 31, 2: 0}
>> l = ["all","colours"]
>> len(str(l))
18

Show pop-ups the most elegant way

Angular-ui comes with dialog directive.Use it and set templateurl to whatever page you want to include.That is the most elegant way and i have used it in my project as well. You can pass several other parameters for dialog as per need.

How do I convert a String object into a Hash object?

This short little snippet will do it, but I can't see it working with a nested hash. I think it's pretty cute though

STRING.gsub(/[{}:]/,'').split(', ').map{|h| h1,h2 = h.split('=>'); {h1 => h2}}.reduce(:merge)

Steps 1. I eliminate the '{','}' and the ':' 2. I split upon the string wherever it finds a ',' 3. I split each of the substrings that were created with the split, whenever it finds a '=>'. Then, I create a hash with the two sides of the hash I just split apart. 4. I am left with an array of hashes which I then merge together.

EXAMPLE INPUT: "{:user_id=>11, :blog_id=>2, :comment_id=>1}" RESULT OUTPUT: {"user_id"=>"11", "blog_id"=>"2", "comment_id"=>"1"}

SSRS expression to format two decimal places does not show zeros

Format(Fields!CUL1.Value, "0.00") would work better since @abe suggests they want to show 0.00 , and if the value was 0, "#0.##" would show "0".

Including a css file in a blade template?

include the css file into your blade template in laravel

  1. move css file into public->css folder in your laravel project.
  2. use <link rel="stylesheet" href="{{ asset('css/filename') }}">

so css is applied in a blade.php file.

Replacing last character in a String with java

i want to replace last ',' with space

if (fieldName.endsWith(",")) {
    fieldName = fieldName.substring(0, fieldName.length() - 1) + " ";
}

If you want to remove the trailing comma, simply get rid of the + " ".

How to do encryption using AES in Openssl

I am trying to write a sample program to do AES encryption using Openssl.

This answer is kind of popular, so I'm going to offer something more up-to-date since OpenSSL added some modes of operation that will probably help you.

First, don't use AES_encrypt and AES_decrypt. They are low level and harder to use. Additionally, it's a software-only routine, and it will never use hardware acceleration, like AES-NI. Finally, its subject to endianess issues on some obscure platforms.

Instead, use the EVP_* interfaces. The EVP_* functions use hardware acceleration, like AES-NI, if available. And it does not suffer endianess issues on obscure platforms.

Second, you can use a mode like CBC, but the ciphertext will lack integrity and authenticity assurances. So you usually want a mode like EAX, CCM, or GCM. (Or you manually have to apply a HMAC after the encryption under a separate key.)

Third, OpenSSL has a wiki page that will probably interest you: EVP Authenticated Encryption and Decryption. It uses GCM mode.

Finally, here's the program to encrypt using AES/GCM. The OpenSSL wiki example is based on it.

#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include <string.h>   

int main(int arc, char *argv[])
{
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();     

    /* Set up the key and iv. Do I need to say to not hard code these in a real application? :-) */

    /* A 256 bit key */
    static const unsigned char key[] = "01234567890123456789012345678901";

    /* A 128 bit IV */
    static const unsigned char iv[] = "0123456789012345";

    /* Message to be encrypted */
    unsigned char plaintext[] = "The quick brown fox jumps over the lazy dog";

    /* Some additional data to be authenticated */
    static const unsigned char aad[] = "Some AAD data";

    /* Buffer for ciphertext. Ensure the buffer is long enough for the
     * ciphertext which may be longer than the plaintext, dependant on the
     * algorithm and mode
     */
    unsigned char ciphertext[128];

    /* Buffer for the decrypted text */
    unsigned char decryptedtext[128];

    /* Buffer for the tag */
    unsigned char tag[16];

    int decryptedtext_len = 0, ciphertext_len = 0;

    /* Encrypt the plaintext */
    ciphertext_len = encrypt(plaintext, strlen(plaintext), aad, strlen(aad), key, iv, ciphertext, tag);

    /* Do something useful with the ciphertext here */
    printf("Ciphertext is:\n");
    BIO_dump_fp(stdout, ciphertext, ciphertext_len);
    printf("Tag is:\n");
    BIO_dump_fp(stdout, tag, 14);

    /* Mess with stuff */
    /* ciphertext[0] ^= 1; */
    /* tag[0] ^= 1; */

    /* Decrypt the ciphertext */
    decryptedtext_len = decrypt(ciphertext, ciphertext_len, aad, strlen(aad), tag, key, iv, decryptedtext);

    if(decryptedtext_len < 0)
    {
        /* Verify error */
        printf("Decrypted text failed to verify\n");
    }
    else
    {
        /* Add a NULL terminator. We are expecting printable text */
        decryptedtext[decryptedtext_len] = '\0';

        /* Show the decrypted text */
        printf("Decrypted text is:\n");
        printf("%s\n", decryptedtext);
    }

    /* Remove error strings */
    ERR_free_strings();

    return 0;
}

void handleErrors(void)
{
    unsigned long errCode;

    printf("An error occurred\n");
    while(errCode = ERR_get_error())
    {
        char *err = ERR_error_string(errCode, NULL);
        printf("%s\n", err);
    }
    abort();
}

int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *aad,
            int aad_len, unsigned char *key, unsigned char *iv,
            unsigned char *ciphertext, unsigned char *tag)
{
    EVP_CIPHER_CTX *ctx = NULL;
    int len = 0, ciphertext_len = 0;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

    /* Initialise the encryption operation. */
    if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
        handleErrors();

    /* Set IV length if default 12 bytes (96 bits) is not appropriate */
    if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
        handleErrors();

    /* Initialise key and IV */
    if(1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();

    /* Provide any AAD data. This can be called zero or more times as
     * required
     */
    if(aad && aad_len > 0)
    {
        if(1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len))
            handleErrors();
    }

    /* Provide the message to be encrypted, and obtain the encrypted output.
     * EVP_EncryptUpdate can be called multiple times if necessary
     */
    if(plaintext)
    {
        if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
            handleErrors();

        ciphertext_len = len;
    }

    /* Finalise the encryption. Normally ciphertext bytes may be written at
     * this stage, but this does not occur in GCM mode
     */
    if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
    ciphertext_len += len;

    /* Get the tag */
    if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag))
        handleErrors();

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    return ciphertext_len;
}

int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad,
            int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv,
            unsigned char *plaintext)
{
    EVP_CIPHER_CTX *ctx = NULL;
    int len = 0, plaintext_len = 0, ret;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

    /* Initialise the decryption operation. */
    if(!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
        handleErrors();

    /* Set IV length. Not necessary if this is 12 bytes (96 bits) */
    if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
        handleErrors();

    /* Initialise key and IV */
    if(!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();

    /* Provide any AAD data. This can be called zero or more times as
     * required
     */
    if(aad && aad_len > 0)
    {
        if(!EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len))
            handleErrors();
    }

    /* Provide the message to be decrypted, and obtain the plaintext output.
     * EVP_DecryptUpdate can be called multiple times if necessary
     */
    if(ciphertext)
    {
        if(!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
            handleErrors();

        plaintext_len = len;
    }

    /* Set expected tag value. Works in OpenSSL 1.0.1d and later */
    if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, tag))
        handleErrors();

    /* Finalise the decryption. A positive return value indicates success,
     * anything else is a failure - the plaintext is not trustworthy.
     */
    ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    if(ret > 0)
    {
        /* Success */
        plaintext_len += len;
        return plaintext_len;
    }
    else
    {
        /* Verify failed */
        return -1;
    }
}

Print to the same line and not a new line?

As of end of 2020 and Python 3.8.5 on linux console for me only this works:

print('some string', end='\r')

Credit goes to: This post

How to use a dot "." to access members of dictionary?

I've always kept this around in a util file. You can use it as a mixin on your own classes too.

class dotdict(dict):
    """dot.notation access to dictionary attributes"""
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

mydict = {'val':'it works'}
nested_dict = {'val':'nested works too'}
mydict = dotdict(mydict)
mydict.val
# 'it works'

mydict.nested = dotdict(nested_dict)
mydict.nested.val
# 'nested works too'

Pycharm: run only part of my Python file

I found out an easier way.

  • go to File -> Settings -> Keymap
  • Search for Execute Selection in Console and reassign it to a new shortcut, like Crl + Enter.

This is the same shortcut to the same action in Spyder and R-Studio.

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

Ok, when you know for sure other applications that used the same process worked; on your new application make sure you have the data access reference and the three dll files...

I downloaded ODAC1120320Xcopy_32bit this from the Oracle site:

http://www.oracle.com/technetwork/database/windows/downloads/utilsoft-087491.html

Reference: Oracle.DataAccess.dll (ODAC1120320Xcopy_32bit\odp.net4\odp.net\bin\4\Oracle.DataAccess.dll)

Include these 3 files within your project:

  • oci.dll (ODAC1120320Xcopy_32bit\instantclient_11_2\oci.dll)
  • oraociei11.dll (ODAC1120320Xcopy_32bit\instantclient_11_2\oraociei11.dll)
  • OraOps11w.dll (ODAC1120320Xcopy_32bit\odp.net4\bin\OraOps11w.dll)

When I tried to create another application with the correct reference and files I would receive that error message.

The fix: Highlighted all three of the files and selected "Copy To Output" = Copy if newer. I did copy if newer since one of the dll's is above 100MB and any updates I do will not copy those files again.

I also ran into a registry error, this fixed it.

public void updateRegistryForOracleNLS()
{
    RegistryKey oracle = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\ORACLE");
    oracle.SetValue("NLS_LANG", "AMERICAN_AMERICA.WE8MSWIN1252");
}

For the Oracle nls_lang list, see this site: https://docs.oracle.com/html/B13804_02/gblsupp.htm

After that, everything worked smooth.

I hope it helps.

Using Cookie in Asp.Net Mvc 4

Try using Response.SetCookie(), because Response.Cookies.Add() can cause multiple cookies to be added, whereas SetCookie will update an existing cookie.

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

The first version is preferable:

  • It works for all kinds of keys, so you can, for example, say {1: 'one', 2: 'two'}. The second variant only works for (some) string keys. Using different kinds of syntax depending on the type of the keys would be an unnecessary inconsistency.
  • It is faster:

    $ python -m timeit "dict(a='value', another='value')"
    1000000 loops, best of 3: 0.79 usec per loop
    $ python -m timeit "{'a': 'value','another': 'value'}"
    1000000 loops, best of 3: 0.305 usec per loop
    
  • If the special syntax for dictionary literals wasn't intended to be used, it probably wouldn't exist.

Export and import table dump (.sql) using pgAdmin

  1. In pgAdmin, select the required target schema in object tree (databases->your_db_name->schemas->your_target_schema)
  2. Click on Plugins/PSQL Console (in top-bar)
  3. Write \i /path/to/yourfile.sql
  4. Press enter

Sticky Header after scrolling down

Here's a start. Basically, we copy the header on load, and then check (using .scrollTop() or window.scrollY) to see when the user scrolls beyond a point (e.g. 200pixels). Then we simply toggle a class (in this case .down) which moves the original into view.

Lastly all we need to do is apply a transition: top 0.2s ease-in to our clone, so that when it's in the .down state it slides into view. Dunked does it better, but with a little playing around it's easy to configure

CSS

header {
  position: relative;
  width: 100%;
  height: 60px;
}

header.clone {
  position: fixed;
  top: -65px;
  left: 0;
  right: 0;
  z-index: 999;
  transition: 0.2s top cubic-bezier(.3,.73,.3,.74);
}

body.down header.clone {
  top: 0;
}

either Vanilla JS (polyfill as required)

var sticky = {
  sticky_after: 200,
  init: function() {
    this.header = document.getElementsByTagName("header")[0];
    this.clone = this.header.cloneNode(true);
    this.clone.classList.add("clone");
    this.header.insertBefore(this.clone);
    this.scroll();
    this.events();
  },

  scroll: function() {
    if(window.scrollY > this.sticky_after) {
      document.body.classList.add("down");
    }
    else {
      document.body.classList.remove("down");
    }
  },

  events: function() {
    window.addEventListener("scroll", this.scroll.bind(this));
  }
};

document.addEventListener("DOMContentLoaded", sticky.init.bind(sticky));

or jQuery

$(document).ready(function() {
  var $header = $("header"),
      $clone = $header.before($header.clone().addClass("clone"));

  $(window).on("scroll", function() {
    var fromTop = $("body").scrollTop();
    $('body').toggleClass("down", (fromTop > 200));
  });
});

Newer Reflections

Whilst the above answers the OP's original question of "How does Dunked achieve this effect?", I wouldn't recommend this approach. For starters, copying the entire top navigation could be pretty costly, and there's no real reason why we can't use the original (with a little bit of work).

Furthermore, Paul Irish and others, have written about how animating with translate() is better than animating with top. Not only is it more performant, but it also means that you don't need to know the exact height of your element. The above solution would be modified with the following (See JSFiddle):

header.clone {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  transform: translateY(-100%);
  transition: 0.2s transform cubic-bezier(.3,.73,.3,.74);
}

body.down header.clone {
  transform: translateY(0);
}

The only drawback with using transforms is, that whilst browser support is pretty good, you'll probably want to add vendor prefixed versions to maximize compatibility.

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Big O, how do you calculate/approximate it?

What often gets overlooked is the expected behavior of your algorithms. It doesn't change the Big-O of your algorithm, but it does relate to the statement "premature optimization. . .."

Expected behavior of your algorithm is -- very dumbed down -- how fast you can expect your algorithm to work on data you're most likely to see.

For instance, if you're searching for a value in a list, it's O(n), but if you know that most lists you see have your value up front, typical behavior of your algorithm is faster.

To really nail it down, you need to be able to describe the probability distribution of your "input space" (if you need to sort a list, how often is that list already going to be sorted? how often is it totally reversed? how often is it mostly sorted?) It's not always feasible that you know that, but sometimes you do.

Fatal error: Class 'ZipArchive' not found in

On Amazon ec2 with Ubuntu + nginx + php7, I had the same issues, solved it using:

sudo apt-get install php7.0-zip

What does mscorlib stand for?

It stands for

Microsoft's Common Object Runtime Library

and it is the primary assembly for the Framework Common Library.

It contains the following namespaces:

 System
 System.Collections
 System.Configuration.Assemblies
 System.Diagnostics
 System.Diagnostics.SymbolStore
 System.Globalization
 System.IO
 System.IO.IsolatedStorage
 System.Reflection
 System.Reflection.Emit
 System.Resources
 System.Runtime.CompilerServices
 System.Runtime.InteropServices
 System.Runtime.InteropServices.Expando
 System.Runtime.Remoting
 System.Runtime.Remoting.Activation
 System.Runtime.Remoting.Channels
 System.Runtime.Remoting.Contexts
 System.Runtime.Remoting.Lifetime
 System.Runtime.Remoting.Messaging
 System.Runtime.Remoting.Metadata
 System.Runtime.Remoting.Metadata.W3cXsd2001
 System.Runtime.Remoting.Proxies
 System.Runtime.Remoting.Services
 System.Runtime.Serialization
 System.Runtime.Serialization.Formatters
 System.Runtime.Serialization.Formatters.Binary
 System.Security
 System.Security.Cryptography
 System.Security.Cryptography.X509Certificates
 System.Security.Permissions
 System.Security.Policy
 System.Security.Principal
 System.Text
 System.Threading
 Microsoft.Win32 

Interesting info about MSCorlib:

  • The .NET 2.0 assembly will reference and use the 2.0 mscorlib.The .NET 1.1 assembly will reference the 1.1 mscorlib but will use the 2.0 mscorlib at runtime (due to hard-coded version redirects in theruntime itself)
  • In GAC there is only one version of mscorlib, you dont find 1.1 version on GAC even if you have 1.1 framework installed on your machine. It would be good if somebody can explain why MSCorlib 2.0 alone is in GAC whereas 1.x version live inside framework folder
  • Is it possible to force a different runtime to be loaded by the application by making a config setting in your app / web.config? you won’t be able to choose the CLR version by settings in the ConfigurationFile – at that point, a CLR will already be running, and there can only be one per process. Immediately after the CLR is chosen the MSCorlib appropriate for that CLR is loaded.

Android center view in FrameLayout doesn't work

Set 'center_horizontal' and 'center_vertical' or just 'center' of the layout_gravity attribute of the widget

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MovieActivity"
    android:id="@+id/mainContainerMovie"
    >


    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#3a3f51b5"
       />

    <ProgressBar
        android:id="@+id/movieprogressbar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal" />
</FrameLayout>

How can I check if a file exists in Perl?

if (-e $base_path)
{ 
 # code
}

-e is the 'existence' operator in Perl.

You can check permissions and other attributes using the code on this page.

How do I dynamically change the content in an iframe using jquery?

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
      $(document).ready(function(){
        var locations = ["http://webPage1.com", "http://webPage2.com"];
        var len = locations.length;
        var iframe = $('#frame');
        var i = 0;
        setInterval(function () {
            iframe.attr('src', locations[++i % len]);
        }, 30000);
      });
    </script>
  </head>
  <body>
    <iframe id="frame"></iframe>
  </body>
</html>

java.lang.NoClassDefFoundError in junit

I was following this video: https://www.youtube.com/watch?v=WHPPQGOyy_Y but failed to run the test. After that, I deleted all the downloaded files and add the Junit using the step in the picture.

enter image description here

Xamarin.Forms ListView: Set the highlight color of a tapped item

The easiest way to accomplish this on android is by adding the following code to your custom style :

@android:color/transparent

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

Enhanced @Artefacto 's solution - corrected typos and simplified code, working for both - empty && non-empty directories .

  function recursive_rmdir($dir) { 
    if( is_dir($dir) ) { 
      $objects = array_diff( scandir($dir), array('..', '.') );
      foreach ($objects as $object) { 
        $objectPath = $dir."/".$object;
        if( is_dir($objectPath) )
          recursive_rmdir($objectPath);
        else
          unlink($objectPath); 
      } 
      rmdir($dir); 
    } 
  }

What is the best way to create and populate a numbers table?

Some of the suggested methods are basing on system objects (for example on the 'sys.objects'). They are assuming these system objects contain enough records to generate our numbers.

I would not base on anything which does not belong to my application and over which I do not have full control. For example: the content of these sys tables may change, the tables may not be valid anymore in new version of SQL etc.

As a solution, we can create our own table with records. We then use that one instead these system related objects (table with all numbers should be fine if we know the range in advance otherwise we could go for the one to do the cross join on).

The CTE based solution is working fine but it has limits related to the nested loops.

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

Simple WPF RadioButton Binding?

I know it's way way overdue, but I have an alternative solution, which is lighter and simpler. Derive a class from System.Windows.Controls.RadioButton and declare two dependency properties RadioValue and RadioBinding. Then in the class code, override OnChecked and set the RadioBinding property value to that of the RadioValue property value. In the other direction, trap changes to the RadioBinding property using a callback, and if the new value is equal to the value of the RadioValue property, set its IsChecked property to true.

Here's the code:

public class MyRadioButton : RadioButton
{
    public object RadioValue
    {
        get { return (object)GetValue(RadioValueProperty); }
        set { SetValue(RadioValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for RadioValue.
       This enables animation, styling, binding, etc...
    public static readonly DependencyProperty RadioValueProperty =
        DependencyProperty.Register(
            "RadioValue", 
            typeof(object), 
            typeof(MyRadioButton), 
            new UIPropertyMetadata(null));

    public object RadioBinding
    {
        get { return (object)GetValue(RadioBindingProperty); }
        set { SetValue(RadioBindingProperty, value); }
    }

    // Using a DependencyProperty as the backing store for RadioBinding.
       This enables animation, styling, binding, etc...
    public static readonly DependencyProperty RadioBindingProperty =
        DependencyProperty.Register(
            "RadioBinding", 
            typeof(object), 
            typeof(MyRadioButton), 
            new FrameworkPropertyMetadata(
                null, 
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 
                OnRadioBindingChanged));

    private static void OnRadioBindingChanged(
        DependencyObject d,
        DependencyPropertyChangedEventArgs e)
    {
        MyRadioButton rb = (MyRadioButton)d;
        if (rb.RadioValue.Equals(e.NewValue))
            rb.SetCurrentValue(RadioButton.IsCheckedProperty, true);
    }

    protected override void OnChecked(RoutedEventArgs e)
    {
        base.OnChecked(e);
        SetCurrentValue(RadioBindingProperty, RadioValue);
    }
}

XAML usage:

<my:MyRadioButton GroupName="grp1" Content="Value 1"
    RadioValue="val1" RadioBinding="{Binding SelectedValue}"/>
<my:MyRadioButton GroupName="grp1" Content="Value 2"
    RadioValue="val2" RadioBinding="{Binding SelectedValue}"/>
<my:MyRadioButton GroupName="grp1" Content="Value 3"
    RadioValue="val3" RadioBinding="{Binding SelectedValue}"/>
<my:MyRadioButton GroupName="grp1" Content="Value 4"
    RadioValue="val4" RadioBinding="{Binding SelectedValue}"/>

Hope someone finds this useful after all this time :)

How to apply CSS page-break to print a table with lots of rows?

I have looked around for a fix for this. I have a jquery mobile site that has a final print page and it combines dozens of pages. I tried all the fixes above but the only thing I could get to work is this:

<div style="clear:both!important;"/></div>
<div style="page-break-after:always"></div> 
<div style="clear:both!important;"/> </div>

Logging framework incompatibility

Just to help those in a similar situation to myself...

This can be caused when a dependent library has accidentally bundled an old version of slf4j. In my case, it was tika-0.8. See https://issues.apache.org/jira/browse/TIKA-556

The workaround is exclude the component and then manually depends on the correct, or patched version.

EG.

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>0.8</version>
    <exclusions>
        <exclusion>
            <!-- NOTE: Version 4.2 has bundled slf4j -->
            <groupId>edu.ucar</groupId>
            <artifactId>netcdf</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <!-- Patched version 4.2-min does not bundle slf4j -->
    <groupId>edu.ucar</groupId>
    <artifactId>netcdf</artifactId>
    <version>4.2-min</version>
</dependency>

Is it possible to create a File object from InputStream

Since Java 7, you can do it in one line even without using any external libraries:

Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);

See the API docs.

How can I build a recursive function in python?

I'm wondering whether you meant "recursive". Here is a simple example of a recursive function to compute the factorial function:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

The two key elements of a recursive algorithm are:

  • The termination condition: n == 0
  • The reduction step where the function calls itself with a smaller number each time: factorial(n - 1)

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

Output ("echo") a variable to a text file

Your sample code seems to be OK. Thus, the root problem needs to be dug up somehow. Let's eliminate chance for typos in the script. First off, make sure you put Set-Strictmode -Version 2.0 in the beginning of your script. This will help you to catch misspelled variable names. Like so,

# Test.ps1
set-strictmode -version 2.0 # Comment this line and no error will be reported.
$foo = "bar"
set-content -path ./test.txt -value $fo # Error! Should be "$foo"

PS C:\temp> .\test.ps1
The variable '$fo' cannot be retrieved because it has not been set.
At C:\temp\test.ps1:3 char:40
+ set-content -path ./test.txt -value $fo <<<<
    + CategoryInfo          : InvalidOperation: (fo:Token) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

The next part about question marks sounds like you have a problem with Unicode. What's the output when you type the file with Powershell like so,

$file = "\\server\share\file.txt"
cat $file

How to implement Rate It feature in Android App

As you see from the other post you have linked, there isn't a way for the app to know if the user has left a review or not. And for good reason.

Think about it, if an app could tell if the user has left a review or not, the developer could restrict certain features that would only be unlocked if the user leaves a 5/5 rating. This would lead the other users of Google Play to not trust the reviews and would undermine the rating system.

The alternative solutions I have seen is that the app reminds the user to submit a rating whenever the app is opened a specific number of times, or a set interval. For example, on every 10th time the app is opened, ask the user to leave a rating and provide a "already done" and "remind me later" button. Keep showing this message if the user has chosen to remind him/her later. Some other apps developers show this message with an increasing interval (like, 5, 10, 15nth time the app is opened), because if a user hasn't left a review on the, for example, 100th time the app was opened, it's probably likely s/he won't be leaving one.

This solution isn't perfect, but I think it's the best you have for now. It does lead you to trust the user, but realize that the alternative would mean a potentially worse experience for everyone in the app market.

Login to remote site with PHP cURL

View the source of the login page. Look for the form HTML tag. Within that tag is something that will look like action= Use that value as $url, not the URL of the form itself.

Also, while you are there, verify the input boxes are named what you have them listed as.

For example, a basic login form will look similar to:

<form method='post' action='postlogin.php'>
    Email Address: <input type='text' name='email'>
    Password: <input type='password' name='password'>
</form>

Using the above form as an example, change your value of $url to:

$url="http://www.myremotesite.com/postlogin.php";

Verify the values you have listed in $postdata:

$postdata = "email=".$username."&password=".$password;

and it should work just fine.

JetBrains / IntelliJ keyboard shortcut to collapse all methods

You Can Go To setting > editor > general > code folding and check "show code folding outline" .

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Therefore:

for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

Invalid column name sql error

first create database name "School" than create table "students" with following columns 1. id 2. name 3. address

now open visual studio and create connection:

namespace school
{
    public partial class Form1 : Form
    {
        SqlConnection scon;


        public Form1()
        {

            InitializeComponent();

            scon = new SqlConnection("Data Source = ABC-PC; trusted_connection = yes; Database = school; connection timeout = 30");
        }

//create command

SqlCommand scom = new SqlCommand("insert into students (id,name,address) values(@id,@name,@address)", scon);

//pass parameters

scom.Parameters.Add("id", SqlDbType.Int);
scom.Parameters["id"].Value = textBox1.Text;

           scom.Parameters.Add("name", SqlDbType.VarChar);
            scom.Parameters["name"].Value = this.textBox2.Text;

            scom.Parameters.Add("address", SqlDbType.VarChar);
            scom.Parameters["address"].Value = this.textBox6.Text;


            scon.Open();
            scom.ExecuteNonQuery();
            scon.Close();
            reset();

        }

also check solution here: http://solutions.musanitech.com/?p=6

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

I was able to solve the problem in my react native project by simply adding

configurations {
        all*.exclude group: 'com.android.support', module: 'support-compat'
        all*.exclude group: 'com.android.support', module: 'support-core-ui'
    }

at the end of my android\app\build.gradle file

Generate random numbers following a normal distribution in C/C++

Take a look at what I found.

This library uses the Ziggurat algorithm.

Vertical (rotated) text in HTML table

-moz-transform: rotate(7.5deg);  /* FF3.5+ */
-o-transform: rotate(7.5deg);  /* Opera 10.5 */
-webkit-transform: rotate(7.5deg);  /* Saf3.1+, Chrome */
filter:  progid:DXImageTransform.Microsoft.BasicImage(rotation=1);  /* IE6,IE7 allows only 1, 2, 3 */
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)"; /* IE8 allows only 1 2 or 3*/

MySQL Workbench - Connect to a Localhost

Sounds like you only installed the MySQL Client Tools (MySQL Workbench). You have to install the MySQL Database server, configure and start it.

http://dev.mysql.com/downloads/

You probably want the MySQL Community Server download.

TypeError: $(...).modal is not a function with bootstrap Modal

Other answers din't work for me in my react.js application, so I have used plain JavaScript for this.

Below solution worked:

  1. Give an id for close part of the modal/dialog ("myModalClose" in below example)
<span>
   className="close cursor-pointer"
   data-dismiss="modal"
   aria-label="Close"
                     id="myModalClose"
>
...
  1. Generate a click event to the above close button, using that id:
   document.getElementById("myModalClose").click();

Possibly you could generate same click on close button, using jQuery too.

Hope that helps.

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

Installing pip packages to $HOME folder

While you can use a virtualenv, you don't need to. The trick is passing the PEP370 --user argument to the setup.py script. With the latest version of pip, one way to do it is:

pip install --user mercurial

This should result in the hg script being installed in $HOME/.local/bin/hg and the rest of the hg package in $HOME/.local/lib/pythonx.y/site-packages/.

Note, that the above is true for Python 2.6. There has been a bit of controversy among the Python core developers about what is the appropriate directory location on Mac OS X for PEP370-style user installations. In Python 2.7 and 3.2, the location on Mac OS X was changed from $HOME/.local to $HOME/Library/Python. This might change in a future release. But, for now, on 2.7 (and 3.2, if hg were supported on Python 3), the above locations will be $HOME/Library/Python/x.y/bin/hg and $HOME/Library/Python/x.y/lib/python/site-packages.

Can PHP cURL retrieve response headers AND body in a single request?

Return response headers with a reference parameter:

<?php
$data=array('device_token'=>'5641c5b10751c49c07ceb4',
            'content'=>'????test'
           );
$rtn=curl_to_host('POST', 'http://test.com/send_by_device_token', array(), $data, $resp_headers);
echo $rtn;
var_export($resp_headers);

function curl_to_host($method, $url, $headers, $data, &$resp_headers)
         {$ch=curl_init($url);
          curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $GLOBALS['POST_TO_HOST.LINE_TIMEOUT']?$GLOBALS['POST_TO_HOST.LINE_TIMEOUT']:5);
          curl_setopt($ch, CURLOPT_TIMEOUT, $GLOBALS['POST_TO_HOST.TOTAL_TIMEOUT']?$GLOBALS['POST_TO_HOST.TOTAL_TIMEOUT']:20);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
          curl_setopt($ch, CURLOPT_HEADER, 1);

          if ($method=='POST')
             {curl_setopt($ch, CURLOPT_POST, true);
              curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
             }
          foreach ($headers as $k=>$v)
                  {$headers[$k]=str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $k)))).': '.$v;
                  }
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          $rtn=curl_exec($ch);
          curl_close($ch);

          $rtn=explode("\r\n\r\nHTTP/", $rtn, 2);    //to deal with "HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK...\r\n\r\n..." header
          $rtn=(count($rtn)>1 ? 'HTTP/' : '').array_pop($rtn);
          list($str_resp_headers, $rtn)=explode("\r\n\r\n", $rtn, 2);

          $str_resp_headers=explode("\r\n", $str_resp_headers);
          array_shift($str_resp_headers);    //get rid of "HTTP/1.1 200 OK"
          $resp_headers=array();
          foreach ($str_resp_headers as $k=>$v)
                  {$v=explode(': ', $v, 2);
                   $resp_headers[$v[0]]=$v[1];
                  }

          return $rtn;
         }
?>

Get all child views inside LinearLayout at once

Get all views from any type of layout

public List<View> getAllViews(ViewGroup layout){
        List<View> views = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            views.add(layout.getChildAt(i));
        }
        return views;
}

Get all TextView from any type of layout

public List<TextView> getAllTextViews(ViewGroup layout){
        List<TextView> views = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            View v =layout.getChildAt(i);
            if(v instanceof TextView){
                views.add((TextView)v);
            }
        }
        return views;
}

Calling variable defined inside one function from another function

def oneFunction(lists):
    category=random.choice(list(lists.keys()))
    word=random.choice(lists[category])
    return word

def anotherFunction():
    for letter in word:             
        print("_",end=" ")

Convert .pem to .crt and .key

Converting Using OpenSSL

These commands allow you to convert certificates and keys to different formats to make them compatible with specific types of servers or software.

  • Convert a DER file (.crt .cer .der) to PEM

    openssl x509 -inform der -in certificate.cer -out certificate.pem
    
  • Convert a PEM file to DER

    openssl x509 -outform der -in certificate.pem -out certificate.der
    
  • Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM

    openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes
    
    You can add -nocerts to only output the private key or add -nokeys to only output the certificates.
    
  • Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12)

    openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
    
  • Convert PEM to CRT (.CRT file)

    openssl x509 -outform der -in certificate.pem -out certificate.crt
    

OpenSSL Convert PEM

  • Convert PEM to DER

    openssl x509 -outform der -in certificate.pem -out certificate.der
    
  • Convert PEM to P7B

    openssl crl2pkcs7 -nocrl -certfile certificate.cer -out certificate.p7b -certfile CACert.cer
    
  • Convert PEM to PFX

    openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
    

OpenSSL Convert DER

  • Convert DER to PEM

    openssl x509 -inform der -in certificate.cer -out certificate.pem
    

OpenSSL Convert P7B

  • Convert P7B to PEM

    openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
    
  • Convert P7B to PFX

    openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
    
    openssl pkcs12 -export -in certificate.cer -inkey privateKey.key -out certificate.pfx -certfile CACert.cer
    

OpenSSL Convert PFX

  • Convert PFX to PEM

    openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes
    

Generate rsa keys by OpenSSL

  • Using OpenSSL on the command line you’d first need to generate a public and private key, you should password protect this file using the -passout argument, there are many different forms that this argument can take so consult the OpenSSL documentation about that.

    openssl genrsa -out private.pem 1024
    
  • This creates a key file called private.pem that uses 1024 bits. This file actually have both the private and public keys, so you should extract the public one from this file:

    openssl rsa -in private.pem -out public.pem -outform PEM -pubout
    
    or
    
    openssl rsa -in private.pem -pubout > public.pem
    
    or
    
    openssl rsa -in private.pem -pubout -out public.pem
    

    You’ll now have public.pem containing just your public key, you can freely share this with 3rd parties. You can test it all by just encrypting something yourself using your public key and then decrypting using your private key, first we need a bit of data to encrypt:

  • Example file :

    echo 'too many secrets' > file.txt
    
  • You now have some data in file.txt, lets encrypt it using OpenSSL and the public key:

    openssl rsautl -encrypt -inkey public.pem -pubin -in file.txt -out file.ssl
    
  • This creates an encrypted version of file.txt calling it file.ssl, if you look at this file it’s just binary junk, nothing very useful to anyone. Now you can unencrypt it using the private key:

    openssl rsautl -decrypt -inkey private.pem -in file.ssl -out decrypted.txt
    
  • You will now have an unencrypted file in decrypted.txt:

    cat decrypted.txt
    |output -> too many secrets
    

RSA TOOLS Options in OpenSSL

  • NAME

    rsa - RSA key processing tool

  • SYNOPSIS

    openssl rsa [-help] [-inform PEM|NET|DER] [-outform PEM|NET|DER] [-in filename] [-passin arg] [-out filename] [-passout arg] [-aes128] [-aes192] [-aes256] [-camellia128] [-camellia192] [-camellia256] [-des] [-des3] [-idea] [-text] [-noout] [-modulus] [-check] [-pubin] [-pubout] [-RSAPublicKey_in] [-RSAPublicKey_out] [-engine id]

  • DESCRIPTION

    The rsa command processes RSA keys. They can be converted between various forms and their components printed out. Note this command uses the traditional SSLeay compatible format for private key encryption: newer applications should use the more secure PKCS#8 format using the pkcs8 utility.

  • COMMAND OPTIONS

    -help
    

    Print out a usage message.

    -inform DER|NET|PEM
    

    This specifies the input format. The DER option uses an ASN1 DER encoded form compatible with the PKCS#1 RSAPrivateKey or SubjectPublicKeyInfo format. The PEM form is the default format: it consists of the DER format base64 encoded with additional header and footer lines. On input PKCS#8 format private keys are also accepted. The NET form is a format is described in the NOTES section.

    -outform DER|NET|PEM
    

    This specifies the output format, the options have the same meaning as the -inform option.

    -in filename
    

    This specifies the input filename to read a key from or standard input if this option is not specified. If the key is encrypted a pass phrase will be prompted for.

    -passin arg
    

    the input file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.

    -out filename
    

    This specifies the output filename to write a key to or standard output if this option is not specified. If any encryption options are set then a pass phrase will be prompted for. The output filename should not be the same as the input filename.

    -passout password
    

    the output file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.

    -aes128|-aes192|-aes256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea
    

    These options encrypt the private key with the specified cipher before outputting it. A pass phrase is prompted for. If none of these options is specified the key is written in plain text. This means that using the rsa utility to read in an encrypted key with no encryption option can be used to remove the pass phrase from a key, or by setting the encryption options it can be use to add or change the pass phrase. These options can only be used with PEM format output files.

    -text
    

    prints out the various public or private key components in plain text in addition to the encoded version.

    -noout
    

    this option prevents output of the encoded version of the key.

    -modulus
    

    this option prints out the value of the modulus of the key.

    -check
    

    this option checks the consistency of an RSA private key.

    -pubin
    

    by default a private key is read from the input file: with this option a public key is read instead.

    -pubout
    

    by default a private key is output: with this option a public key will be output instead. This option is automatically set if the input is a public key.

    -RSAPublicKey_in, -RSAPublicKey_out
    

    like -pubin and -pubout except RSAPublicKey format is used instead.

    -engine id
    

    specifying an engine (by its unique id string) will cause rsa to attempt to obtain a functional reference to the specified engine, thus initialising it if needed. The engine will then be set as the default for all available algorithms.

  • NOTES

    The PEM private key format uses the header and footer lines:

    -----BEGIN RSA PRIVATE KEY-----
    
    -----END RSA PRIVATE KEY-----
    

    The PEM public key format uses the header and footer lines:

    -----BEGIN PUBLIC KEY-----
    
    -----END PUBLIC KEY-----
    

    The PEM RSAPublicKey format uses the header and footer lines:

    -----BEGIN RSA PUBLIC KEY-----
    
    -----END RSA PUBLIC KEY-----
    

    The NET form is a format compatible with older Netscape servers and Microsoft IIS .key files, this uses unsalted RC4 for its encryption. It is not very secure and so should only be used when necessary.

    Some newer version of IIS have additional data in the exported .key files. To use these with the utility, view the file with a binary editor and look for the string "private-key", then trace back to the byte sequence 0x30, 0x82 (this is an ASN1 SEQUENCE). Copy all the data from this point onwards to another file and use that as the input to the rsa utility with the -inform NET option.

    EXAMPLES

    To remove the pass phrase on an RSA private key:

     openssl rsa -in key.pem -out keyout.pem
    

    To encrypt a private key using triple DES:

     openssl rsa -in key.pem -des3 -out keyout.pem
    

    To convert a private key from PEM to DER format:

      openssl rsa -in key.pem -outform DER -out keyout.der
    

    To print out the components of a private key to standard output:

      openssl rsa -in key.pem -text -noout
    

    To just output the public part of a private key:

      openssl rsa -in key.pem -pubout -out pubkey.pem
    

    Output the public part of a private key in RSAPublicKey format:

      openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem
    

Sort & uniq in Linux shell

sort -u will be slightly faster, because it does not need to pipe the output between two commands

also see my question on the topic: calling uniq and sort in different orders in shell

Getting cursor position in Python

I found a way to do it that doesn't depend on non-standard libraries!

Found this in Tkinter

self.winfo_pointerxy()

How to have a a razor action link open in a new tab?

You are setting it't type as submit. That means that browser should post your <form> data to the server.

In fact a tag has no type attribute according to w3schools.

So remote type attribute and it should work for you.

Maven compile with multiple src directories

This worked for me

<build>
    <sourceDirectory>.</sourceDirectory>
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
        <includes>
            <include>src/main/java/**/*.java</include>
            <include>src/main2/java/**/*.java</include>
        </includes>
        </configuration>
        </plugin>
    </plugins>
</build>

Convert seconds to hh:mm:ss in Python

If you use divmod, you are immune to different flavors of integer division:

# show time strings for 3800 seconds

# easy way to get mm:ss
print "%02d:%02d" % divmod(3800, 60)

# easy way to get hh:mm:ss
print "%02d:%02d:%02d" % \
    reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
        [(3800,),60,60])


# function to convert floating point number of seconds to
# hh:mm:ss.sss
def secondsToStr(t):
    return "%02d:%02d:%02d.%03d" % \
        reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
            [(round(t*1000),),1000,60,60])

print secondsToStr(3800.123)

Prints:

63:20
01:03:20
01:03:20.123

Django - iterate number in for loop of a template

[Django HTML template doesn't support index as of now], but you can achieve the goal:

If you use Dictionary inside Dictionary in views.py then iteration is possible using key as index. example:

{% for key, value in DictionartResult.items %} <!-- dictionartResult is a dictionary having key value pair-->
<tr align="center">
    <td  bgcolor="Blue"><a href={{value.ProjectName}}><b>{{value.ProjectName}}</b></a></td>
    <td> {{ value.atIndex0 }} </td>         <!-- atIndex0 is a key which will have its value , you can treat this key as index to resolve-->
    <td> {{ value.atIndex4 }} </td>
    <td> {{ value.atIndex2 }} </td>
</tr>
{% endfor %}

Elseif you use List inside dictionary then not only first and last iteration can be controlled, but all index can be controlled. example:

{% for key, value in DictionaryResult.items %}
    <tr align="center">
    {% for project_data in value %}
        {% if  forloop.counter <= 13 %}  <!-- Here you can control the iteration-->
            {% if forloop.first %}
                <td bgcolor="Blue"><a href={{project_data}}><b> {{ project_data }} </b></a></td> <!-- it will always refer to project_data[0]-->
            {% else %}
                <td> {{ project_data }} </td> <!-- it will refer to all items in project_data[] except at index [0]-->
            {% endif %}
            {% endif %}
    {% endfor %}
    </tr>
{% endfor %}

End If ;)

// Hope have covered the solution with Dictionary, List, HTML template, For Loop, Inner loop, If Else. Django HTML Documentaion for more methods: https://docs.djangoproject.com/en/2.2/ref/templates/builtins/

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

Access Session attribute on jstl

You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

Use the JSTL.

Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

public SomeType getQuestionPaperID() {
    //...
}

method in your bean.

Once you have that, you can display the value of this property using this code :

<c:out value="${Questions.questionPaperID}" />

or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

<c:out value="${sessionScope.Questions.questionPaperID}" />

Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

Is it possible to create static classes in PHP (like in C#)?

You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct() you'll get an error).

Therefore you'd have to create an initialize() function and call it in each method:

<?php

class Hello
{
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$greeting .= ' There!';
        self::$initialized = true;
    }

    public static function greet()
    {
        self::initialize();
        echo self::$greeting;
    }
}

Hello::greet(); // Hello There!


?>

ASP.NET Core Identity - get current user

Assuming your code is inside an MVC controller:

public class MyController : Microsoft.AspNetCore.Mvc.Controller

From the Controller base class, you can get the IClaimsPrincipal from the User property

System.Security.Claims.ClaimsPrincipal currentUser = this.User;

You can check the claims directly (without a round trip to the database):

bool IsAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); // Get user id:

Other fields can be fetched from the database's User entity:

  1. Get the user manager using dependency injection

    private UserManager<ApplicationUser> _userManager;
    
    //class constructor
    public MyController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }
    
  2. And use it:

    var user = await _userManager.GetUserAsync(User);
    var email = user.Email;
    

How do I fix a NoSuchMethodError?

I ran into similar issue.

Caused by: java.lang.NoSuchMethodError: com.abc.Employee.getEmpId()I

Finally I identified the root cause was changing the data type of variable.

  1. Employee.java --> Contains the variable (EmpId) whose Data Type has been changed from int to String.
  2. ReportGeneration.java --> Retrieves the value using the getter, getEmpId().

We are supposed to rebundle the jar by including only the modified classes. As there was no change in ReportGeneration.java I was only including the Employee.class in Jar file. I had to include the ReportGeneration.class file in the jar to solve the issue.

adding classpath in linux

Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH% is used to represent value of existing path variable in Windows while ${PATH} is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:

export CLASSPATH=${CLASSPATH}:/new/path

but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:

  1. -cp options overrides CLASSPATH environment variable.
  2. Classpath defined in Manifest file overrides both -cp and CLASSPATH envorinment variable.

Reference: How Classpath works in Java.

Creating a dynamic choice field

There's built-in solution for your problem: ModelChoiceField.

Generally, it's always worth trying to use ModelForm when you need to create/change database objects. Works in 95% of the cases and it's much cleaner than creating your own implementation.

Add to Array jQuery

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.

Random date in C#

Useful extension based of @Jeremy Thompson's solution

public static class RandomExtensions
{
    public static DateTime Next(this Random random, DateTime start, DateTime? end = null)
    {
        end ??= new DateTime();
        int range = (end.Value - start).Days;
        return start.AddDays(random.Next(range));
    }
}

When does socket.recv(recv_size) return?

I think you conclusions are correct but not accurate.

As the docs indicates, socket.recv is majorly focused on the network buffers.

When socket is blocking, socket.recv will return as long as the network buffers have bytes. If bytes in the network buffers are more than socket.recv can handle, it will return the maximum number of bytes it can handle. If bytes in the network buffers are less than socket.recv can handle, it will return all the bytes in the network buffers.

Center a popup window on screen?

This would work out based on your screen size

<html>
<body>
<button onclick="openfunc()">Click here to open window at center</button>
<script>
function openfunc() {
windowWidth = 800;
windowHeight = 720;
 var left = (screen.width - windowWidth) / 2;
            var top = (screen.height - windowHeight) / 4;
            var myWindow = window.open("https://www.google.com",'_blank','width=' + windowWidth + ', height=' + windowHeight + ', top=' + top + ', left=' + left);
}
</script>
</body>
</html>

Log4Net configuring log level

Use threshold.

For example:

   <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <threshold value="WARN"/>
        <param name="File" value="File.log" />
        <param name="AppendToFile" value="true" />
        <param name="RollingStyle" value="Size" />
        <param name="MaxSizeRollBackups" value="10" />
        <param name="MaximumFileSize" value="1024KB" />
        <param name="StaticLogFileName" value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <param name="Header" value="[Server startup]&#13;&#10;" />
            <param name="Footer" value="[Server shutdown]&#13;&#10;" />
            <param name="ConversionPattern" value="%d %m%n" />
        </layout>
    </appender>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
        <threshold value="ERROR"/>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread]- %message%newline" />
        </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <threshold value="INFO"/>
        <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%thread] %m%n" />
        </layout>
    </appender>

In this example all INFO and above are sent to Console, all WARN are sent to file and ERRORs are sent to the Event-Log.

Common elements in two lists

You can use set intersection operations with your ArrayList objects.

Something like this:

List<Integer> l1 = new ArrayList<Integer>();

l1.add(1);
l1.add(2);
l1.add(3);

List<Integer> l2= new ArrayList<Integer>();
l2.add(4);
l2.add(2);
l2.add(3);

System.out.println("l1 == "+l1);
System.out.println("l2 == "+l2);

List<Integer> l3 = new ArrayList<Integer>(l2);
l3.retainAll(l1);

    System.out.println("l3 == "+l3);

Now, l3 should have only common elements between l1 and l2.

CONSOLE OUTPUT
l1 == [1, 2, 3]
l2 == [4, 2, 3]
l3 == [2, 3]

Exposing a port on a live Docker container

Based on Robm's answer I have created a Docker image and a Bash script called portcat.

Using portcat, you can easily map multiple ports to an existing Docker container. An example using the (optional) Bash script:

curl -sL https://raw.githubusercontent.com/archan937/portcat/master/script/install | sudo bash
portcat my-awesome-container 3456 4444:8080

And there you go! Portcat is mapping:

  • port 3456 to my-awesome-container:3456
  • port 4444 to my-awesome-container:8080

Please note that the Bash script is optional, the following commands:

ipAddress=$(docker inspect my-awesome-container | grep IPAddress | grep -o '[0-9]\{1,3\}\(\.[0-9]\{1,3\}\)\{3\}' | head -n 1)
docker run -p 3456:3456 -p 4444:4444 --name=alpine-portcat -it pmelegend/portcat:latest $ipAddress 3456 4444:8080

I hope portcat will come in handy for you guys. Cheers!

Appropriate datatype for holding percent values?

Assuming two decimal places on your percentages, the data type you use depends on how you plan to store your percentages. If you are going to store their fractional equivalent (e.g. 100.00% stored as 1.0000), I would store the data in a decimal(5,4) data type with a CHECK constraint that ensures that the values never exceed 1.0000 (assuming that is the cap) and never go below 0 (assuming that is the floor). If you are going to store their face value (e.g. 100.00% is stored as 100.00), then you should use decimal(5,2) with an appropriate CHECK constraint. Combined with a good column name, it makes it clear to other developers what the data is and how the data is stored in the column.

How do I express "if value is not empty" in the VBA language?

Why not just use the built-in Format() function?

Dim vTest As Variant
vTest = Empty ' or vTest = null or vTest = ""

If Format(vTest) = vbNullString Then
    doSomethingWhenEmpty() 
Else
   doSomethingElse() 
End If

Format() will catch empty variants as well as null ones and transforms them in strings. I use it for things like null/empty validations and to check if an item has been selected in a combobox.

Excel VBA, How to select rows based on data in a column?

Yes using Option Explicit is a good habit. Using .Select however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the Activesheet which might not be what you actually wanted.

Is this what you are trying?

Option Explicit

Sub Sample()
    Dim lastRow As Long, i As Long
    Dim CopyRange As Range

    '~~> Change Sheet1 to relevant sheet name
    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then
                If CopyRange Is Nothing Then
                    Set CopyRange = .Rows(i)
                Else
                    Set CopyRange = Union(CopyRange, .Rows(i))
                End If
            Else
                Exit For
            End If
        Next

        If Not CopyRange Is Nothing Then
            '~~> Change Sheet2 to relevant sheet name
            CopyRange.Copy Sheets("Sheet2").Rows(1)
        End If
    End With
End Sub

NOTE

If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10

If you want to copy all rows which have data then use this code.

Option Explicit

Sub Sample()
    Dim lastRow As Long, i As Long
    Dim CopyRange As Range

    '~~> Change Sheet1 to relevant sheet name
    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then
                If CopyRange Is Nothing Then
                    Set CopyRange = .Rows(i)
                Else
                    Set CopyRange = Union(CopyRange, .Rows(i))
                End If
            End If
        Next

        If Not CopyRange Is Nothing Then
            '~~> Change Sheet2 to relevant sheet name
            CopyRange.Copy Sheets("Sheet2").Rows(1)
        End If
    End With
End Sub

Hope this is what you wanted?

Sid

The project description file (.project) for my project is missing

If you move the files for whatever reason manually, then Elipse lost the reference and output a missing project file error, but the reason is thaty you move manually the files and Eclipse lost the reference

Iterating Over Dictionary Key Values Corresponding to List in Python

Dictionaries have a built in function called iterkeys().

Try:

for team in league.iterkeys():
    runs_scored = float(league[team][0])
    runs_allowed = float(league[team][1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print win_percentage

this in equals method

this is the current Object instance. Whenever you have a non-static method, it can only be called on an instance of your object.

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
{
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;


    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    {
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),
            typeof(SetPropertyAction));


        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
        {
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }
        }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),
            typeof(SetPropertyAction));


        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
        {
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }
        }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),
            typeof(SetPropertyAction));


        // Private Implementation.

        protected override void Invoke(object parameter)
        {
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(
                PropertyName,
                BindingFlags.Instance|BindingFlags.Public
                |BindingFlags.NonPublic|BindingFlags.InvokeMethod);

            propertyInfo.SetValue(target, PropertyValue);
        }
    }
}

In this case I'm binding to a property called DialogResult on my viewmodel.

<Grid>

    <Button>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        Cancel
    </Button>

</Grid>

How to create two columns on a web page?

I found a real cool Grid which I also use for columns. Check it out Simple Grid. Wich this CSS you can simply use:

<div class="grid">
    <div class="col-1-2">
       <div class="content">
           <p>...insert content left side...</p>
       </div>
    </div>
    <div class="col-1-2">
       <div class="content">
           <p>...insert content right side...</p>
       </div>
    </div>
</div>

I use it for all my projects.

Setting selected values for ng-options bound select elements

Using ng-selected for selected value. I Have successfully implemented code in AngularJS v1.3.2

_x000D_
_x000D_
<select ng-model="objBillingAddress.StateId"  >_x000D_
   <option data-ng-repeat="c in States" value="{{c.StateId}}" ng-selected="objBillingAddress.BillingStateId==c.StateId">{{c.StateName}}</option>_x000D_
                                                </select>
_x000D_
_x000D_
_x000D_

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

Abort Ajax requests using jQuery

It's an asynchronous request, meaning once it's sent it's out there.

In case your server is starting a very expensive operation due to the AJAX request, the best you can do is open your server to listen for cancel requests, and send a separate AJAX request notifying the server to stop whatever it's doing.

Otherwise, simply ignore the AJAX response.

How to change color of the back arrow in the new material theme?

Here's how I did it in Material Components:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="drawerArrowStyle">@style/AppTheme.DrawerArrowToggle</item>
</style>

<style name="AppTheme.DrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/white</item>
</style>

Broken references in Virtualenvs

I had a similar issue and i solved it by just rebuilding the virtual environment with virtualenv .

Calling a particular PHP function on form submit

Write this code

<?php
    if(isset($_POST['submit'])){
        echo 'Hello World';
    } 
?>

<html>
     <body>
         <form method="post">
             <input type="text" name="studentname">
             <input type="submit" name="submit" value="click">
         </form>
     </body>
</html>

How to use XPath preceding-sibling correctly

You don't need to go level up and use .. since all buttons are on the same level:

//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']

Upgrade version of Pandas

Add your C:\WinPython-64bit-3.4.4.1\python_***\Scripts folder to your system PATH variable by doing the following:

  1. Select Start, select Control Panel. double click System, and select the Advanced tab.
  2. Click Environment Variables. ...

  3. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. ...

  4. Reopen Command prompt window

Bind failed: Address already in use

It also happens when you have not give enough permissions(read and write) to your sock file!

Just add expected permission to your sock contained folder and your sock file:

 chmod ug+rw /path/to/your/
 chmod ug+rw /path/to/your/file.sock

Then have fun!

Replace single quotes in SQL Server

You could use char(39)

insert into my_table values('hi, my name'+char(39)+'s tim.')

Or in this case:

Replace(@strip,char(39),'')

How can I loop through all rows of a table? (MySQL)

You should really use a set based solution involving two queries (basic insert):

INSERT INTO TableB (Id2Column, Column33, Column44)
SELECT id, column1, column2 FROM TableA

UPDATE TableA SET column1 = column2 * column3

And for your transform:

INSERT INTO TableB (Id2Column, Column33, Column44)
SELECT 
    id, 
    column1 * column4 * 100, 
    (column2 / column12) 
FROM TableA

UPDATE TableA SET column1 = column2 * column3

Now if your transform is more complicated than that and involved multiple tables, post another question with the details.

Python Regex - How to Get Positions and Values of Matches

note that the span & group are indexed for multi capture groups in a regex

regex_with_3_groups=r"([a-z])([0-9]+)([A-Z])"
for match in re.finditer(regex_with_3_groups, string):
    for idx in range(0, 4):
        print(match.span(idx), match.group(idx))

how to calculate binary search complexity

For Binary Search, T(N) = T(N/2) + O(1) // the recurrence relation

Apply Masters Theorem for computing Run time complexity of recurrence relations : T(N) = aT(N/b) + f(N)

Here, a = 1, b = 2 => log (a base b) = 1

also, here f(N) = n^c log^k(n) //k = 0 & c = log (a base b)

So, T(N) = O(N^c log^(k+1)N) = O(log(N))

Source : http://en.wikipedia.org/wiki/Master_theorem

Is there a function to split a string in PL/SQL?

I like the look of that apex utility. However its also good to know about the standard oracle functions you can use for this: subStr and inStr http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions001.htm

How to enable CORS in AngularJs

This answer outlines two ways to workaround APIs that don't support CORS:

  • Use a CORS Proxy
  • Use JSONP if the API Supports it

One workaround is to use a CORS PROXY:

_x000D_
_x000D_
angular.module("app",[])
.run(function($rootScope,$http) { 
     var proxy = "//cors-anywhere.herokuapp.com";
     var url = "http://api.ipify.org/?format=json";
     $http.get(proxy +'/'+ url)
       .then(function(response) {
         $rootScope.response = response.data;
     }).catch(function(response) {
         $rootScope.response = 'ERROR: ' + response.status;
     })     
})
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
   Response = {{response}}
</body>
_x000D_
_x000D_
_x000D_

For more information, see


Use JSONP if the API supports it:

 var url = "//api.ipify.org/";
 var trust = $sce.trustAsResourceUrl(url);
 $http.jsonp(trust,{params: {format:'jsonp'}})
   .then(function(response) {
     console.log(response);
     $scope.response = response.data;
 }).catch(function(response) {
     console.log(response);
     $scope.response = 'ERROR: ' + response.status;
 }) 

The DEMO on PLNKR

For more information, see

how to check if object already exists in a list

Another point to mention is that you should ensure that your equality function is as you expect. You should override the equals method to set up what properties of your object have to match for two instances to be considered equal.

Then you can just do mylist.contains(item)

In SQL Server, what does "SET ANSI_NULLS ON" mean?

SET ANSI_NULLS ON

IT Returns all values including null values in the table

SET ANSI_NULLS off

it Ends when columns contains null values

What does it mean to inflate a view from an xml file?

I think here "inflating a view" means fetching the layout.xml file drawing a view specified in that xml file and POPULATING ( = inflating ) the parent viewGroup with the created View.

Easy way to turn JavaScript array into comma-separated list?

Simple Array

_x000D_
_x000D_
let simpleArray = [1,2,3,4]
let commaSeperated = simpleArray.join(",");
console.log(commaSeperated);
_x000D_
_x000D_
_x000D_

Array of Objects with a particular attributes as comma separated.

_x000D_
_x000D_
let arrayOfObjects = [
{
id : 1,
name : "Name 1",
address : "Address 1"
},
{
id : 2,
name : "Name 2",
address : "Address 2"
},
{
id : 3,
name : "Name 3",
address : "Address 3"
}]
let names = arrayOfObjects.map(x => x.name).join(", ");
console.log(names);
_x000D_
_x000D_
_x000D_

MySQL & Java - Get id of the last inserted value (JDBC)

Alternatively you can do:

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getString(1);
}

But use Sean Bright's answer instead for your scenario.