Programs & Examples On #Drawrect

Method in UIView/NSView class. Draws the receiver’s image within the passed-in rectangle.

Can I execute a function after setState is finished updating?

setState(updater[, callback]) is an async function:

https://facebook.github.io/react/docs/react-component.html#setstate

You can execute a function after setState is finishing using the second param callback like:

this.setState({
    someState: obj
}, () => {
    this.afterSetStateFinished();
});

The same can be done with hooks in React functional component:

https://github.com/the-road-to-learn-react/use-state-with-callback#usage

Look at useStateWithCallbackLazy:

import { useStateWithCallbackLazy } from 'use-state-with-callback';

const [count, setCount] = useStateWithCallbackLazy(0);

setCount(count + 1, () => {
   afterSetCountFinished();
});

Class is not abstract and does not override abstract method

If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

Triangle Draw Method

Use a line algorithm to connect point A with point C, and in an outer loop, let point A wander towards point B with the same line algorithm and with the wandering coordinates, repeat drawing that line. You can probably also include a z delta with which is also incremented iteratively. For the line algorithm, just calculate two or three slopes for the delta change of each coordinate and set one slope to 1 after changing the two others proportionally so they are below 1. This is very important for drawing closed geometrical areas between connected mesh particles. Take a look at the Qt Elastic Nodes example and now imagine drawing triangles between the nodes after stretching this over a skeleton. As long as it will remain online

Android Image View Pinch Zooming

I made my own custom imageview with pinch to zoom. There is no limits/borders on Chirag Ravals code, so user can drag the image off the screen. This will fix it.

Here is the CustomImageView class:

    public class CustomImageVIew extends ImageView implements OnTouchListener {


    private Matrix matrix = new Matrix();
    private Matrix savedMatrix = new Matrix();

    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;

    private int mode = NONE;

    private PointF mStartPoint = new PointF();
    private PointF mMiddlePoint = new PointF();
    private Point mBitmapMiddlePoint = new Point();

    private float oldDist = 1f;
    private float matrixValues[] = {0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f};
    private float scale;
    private float oldEventX = 0;
    private float oldEventY = 0;
    private float oldStartPointX = 0;
    private float oldStartPointY = 0;
    private int mViewWidth = -1;
    private int mViewHeight = -1;
    private int mBitmapWidth = -1;
    private int mBitmapHeight = -1;
    private boolean mDraggable = false;


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

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

    public CustomImageVIew(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.setOnTouchListener(this);
    }

    @Override
    public void onSizeChanged (int w, int h, int oldw, int oldh){
        super.onSizeChanged(w, h, oldw, oldh);
        mViewWidth = w;
        mViewHeight = h;
    }

    public void setBitmap(Bitmap bitmap){
        if(bitmap != null){
            setImageBitmap(bitmap);

            mBitmapWidth = bitmap.getWidth();
            mBitmapHeight = bitmap.getHeight();
            mBitmapMiddlePoint.x = (mViewWidth / 2) - (mBitmapWidth /  2);
            mBitmapMiddlePoint.y = (mViewHeight / 2) - (mBitmapHeight / 2);

            matrix.postTranslate(mBitmapMiddlePoint.x, mBitmapMiddlePoint.y);
            this.setImageMatrix(matrix);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event){
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            savedMatrix.set(matrix);
            mStartPoint.set(event.getX(), event.getY());
            mode = DRAG;
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            oldDist = spacing(event);
            if(oldDist > 10f){
                savedMatrix.set(matrix);
                midPoint(mMiddlePoint, event);
                mode = ZOOM;
            }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_POINTER_UP:
            mode = NONE;
            break;
        case MotionEvent.ACTION_MOVE:
            if(mode == DRAG){
                drag(event);
            } else if(mode == ZOOM){
                zoom(event);
            } 
            break;
        }

        return true;
    }



   public void drag(MotionEvent event){
       matrix.getValues(matrixValues);

       float left = matrixValues[2];
       float top = matrixValues[5];
       float bottom = (top + (matrixValues[0] * mBitmapHeight)) - mViewHeight;
       float right = (left + (matrixValues[0] * mBitmapWidth)) -mViewWidth;

       float eventX = event.getX();
       float eventY = event.getY();
       float spacingX = eventX - mStartPoint.x;
       float spacingY = eventY - mStartPoint.y;
       float newPositionLeft = (left  < 0 ? spacingX : spacingX * -1) + left;
       float newPositionRight = (spacingX) + right;
       float newPositionTop = (top  < 0 ? spacingY : spacingY * -1) + top;
       float newPositionBottom = (spacingY) + bottom;
       boolean x = true;
       boolean y = true;

       if(newPositionRight < 0.0f || newPositionLeft > 0.0f){
           if(newPositionRight < 0.0f && newPositionLeft > 0.0f){
               x = false;
           } else{
               eventX = oldEventX;
               mStartPoint.x = oldStartPointX;
           }
       }
       if(newPositionBottom < 0.0f || newPositionTop > 0.0f){
           if(newPositionBottom < 0.0f && newPositionTop > 0.0f){
               y = false;
           } else{
               eventY = oldEventY;
               mStartPoint.y = oldStartPointY;
           }
       }

       if(mDraggable){
           matrix.set(savedMatrix);
           matrix.postTranslate(x? eventX - mStartPoint.x : 0, y? eventY - mStartPoint.y : 0);
           this.setImageMatrix(matrix);
           if(x)oldEventX = eventX;
           if(y)oldEventY = eventY;
           if(x)oldStartPointX = mStartPoint.x;
           if(y)oldStartPointY = mStartPoint.y;
       }

   }

   public void zoom(MotionEvent event){
       matrix.getValues(matrixValues);

       float newDist = spacing(event);
       float bitmapWidth = matrixValues[0] * mBitmapWidth;
       float bimtapHeight = matrixValues[0] * mBitmapHeight;
       boolean in = newDist > oldDist;

       if(!in && matrixValues[0] < 1){
           return;
       }
       if(bitmapWidth > mViewWidth || bimtapHeight > mViewHeight){
           mDraggable = true;
       } else{
           mDraggable = false;
       }

       float midX = (mViewWidth / 2);
       float midY = (mViewHeight / 2);

       matrix.set(savedMatrix);
       scale = newDist / oldDist;
       matrix.postScale(scale, scale, bitmapWidth > mViewWidth ? mMiddlePoint.x : midX, bimtapHeight > mViewHeight ? mMiddlePoint.y : midY); 

       this.setImageMatrix(matrix);


   }





    /** Determine the space between the first two fingers */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);

        return (float)Math.sqrt(x * x + y * y);
    }

    /** Calculate the mid point of the first two fingers */
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }


}

This is how you can use it in your activity:

CustomImageVIew mImageView = (CustomImageVIew)findViewById(R.id.customImageVIew1);
mImage.setBitmap(your bitmap);

And layout:

<your.package.name.CustomImageVIew
        android:id="@+id/customImageVIew1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginBottom="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="15dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" 
        android:scaleType="matrix"/> // important

Can I draw rectangle in XML?

try this

                <TableRow
                    android:layout_width="match_parent"
                    android:layout_marginTop="5dp"
                    android:layout_height="wrap_content">

                    <View
                        android:layout_width="15dp"
                        android:layout_height="15dp"
                        android:background="#3fe1fa" />

                    <TextView
                        android:textSize="12dp"
                        android:paddingLeft="10dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        android:text="1700 Market Street"
                        android:id="@+id/textView8" />
                </TableRow>

output

enter image description here

Android canvas draw rectangle

paint.setStrokeWidth(3);

paint.setColor(BLACK);

and either one of your drawRect should work.

Linq Query Group By and Selecting First Items

var results = list.GroupBy(x => x.Category)
            .Select(g => g.OrderBy(x => x.SortByProp).FirstOrDefault());

For those wondering how to do this for groups that are not necessarily sorted correctly, here's an expansion of this answer that uses method syntax to customize the sort order of each group and hence get the desired record from each.

Note: If you're using LINQ-to-Entities you will get a runtime exception if you use First() instead of FirstOrDefault() here as the former can only be used as a final query operation.

How to draw a custom UIView that is just a circle - iPhone app

Swift 3 - custom class, easy to reuse. It uses backgroundColor set in UI builder

import UIKit

@IBDesignable
class CircleBackgroundView: UIView {

    override func layoutSubviews() {
        super.layoutSubviews()
        layer.cornerRadius = bounds.size.width / 2
        layer.masksToBounds = true
    }

}

How to draw in JPanel? (Swing/graphics Java)

Note the extra comments.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

class JavaPaintUI extends JFrame {

    private int tool = 1;
    int currentX, currentY, oldX, oldY;

    public JavaPaintUI() {
        initComponents();
    }

    private void initComponents() {
        // we want a custom Panel2, not a generic JPanel!
        jPanel2 = new Panel2();

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
        jPanel2.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent evt) {
                jPanel2MousePressed(evt);
            }
            public void mouseReleased(MouseEvent evt) {
                jPanel2MouseReleased(evt);
            }
        });
        jPanel2.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent evt) {
                jPanel2MouseDragged(evt);
            }
        });

        // add the component to the frame to see it!
        this.setContentPane(jPanel2);
        // be nice to testers..
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
    }// </editor-fold>

    private void jPanel2MouseDragged(MouseEvent evt) {
        if (tool == 1) {
            currentX = evt.getX();
            currentY = evt.getY();
            oldX = currentX;
            oldY = currentY;
            System.out.println(currentX + " " + currentY);
            System.out.println("PEN!!!!");
        }
    }

    private void jPanel2MousePressed(MouseEvent evt) {
        oldX = evt.getX();
        oldY = evt.getY();
        System.out.println(oldX + " " + oldY);
    }


    //mouse released//
    private void jPanel2MouseReleased(MouseEvent evt) {
        if (tool == 2) {
            currentX = evt.getX();
            currentY = evt.getY();
            System.out.println("line!!!! from" + oldX + "to" + currentX);
        }
    }

    //set ui visible//
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JavaPaintUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private JPanel jPanel2;
    // End of variables declaration

    // This class name is very confusing, since it is also used as the
    // name of an attribute!
    //class jPanel2 extends JPanel {
    class Panel2 extends JPanel {

        Panel2() {
            // set a preferred size for the custom panel.
            setPreferredSize(new Dimension(420,420));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            g.drawString("BLAH", 20, 20);
            g.drawRect(200, 200, 200, 200);
        }
    }
}

Screen Shot

enter image description here

Other examples - more tailored to multiple lines & multiple line segments

HFOE put a good link as the first comment on this thread. Camickr also has a description of active painting vs. drawing to a BufferedImage in the Custom Painting Approaches article.

See also this approach using painting in a BufferedImage.

Clear image on picturebox

clear pictureBox in c# winform Application Simple way to clear pictureBox in c# winform Application

Custom ImageView with drop shadow

If you want to use the custom imageView, I suggest you use this one

View look perfect and dont't use any nine path image

enter image description here

Drawing circles with System.Drawing

     private void DrawEllipseRectangle(PaintEventArgs e)
        {
            Pen p = new Pen(Color.Black, 3);
            Rectangle r = new Rectangle(100, 100, 100, 100);
            e.Graphics.DrawEllipse(p, r);
        }
     private void Form1_Paint(object sender, PaintEventArgs e)
        {
            DrawEllipseRectangle(e);
        }

iPhone UILabel text soft shadow

Subclass UILabel, as stated, then, in drawRect:, do [self drawTextInRect:rect]; to get the text drawn into the current context. Once it is in there, you can start working with it by adding filters and whatnot. If you want to make a drop shadow with what you just drew into the context, you should be able to use:

CGContextSetShadowWithColor()

Look that function up in the docs to learn how to use it.

What is the most robust way to force a UIView to redraw?

I had a problem with a big delay between calling setNeedsDisplay and drawRect: (5 seconds). It turned out I called setNeedsDisplay in a different thread than the main thread. After moving this call to the main thread the delay went away.

Hope this is of some help.

How do I draw a shadow under a UIView?

Simple and clean solution using Interface Builder

Add a file named UIView.swift in your project (or just paste this in any file) :

import UIKit

@IBDesignable extension UIView {

    /* The color of the shadow. Defaults to opaque black. Colors created
    * from patterns are currently NOT supported. Animatable. */
    @IBInspectable var shadowColor: UIColor? {
        set {
            layer.shadowColor = newValue!.CGColor
        }
        get {
            if let color = layer.shadowColor {
                return UIColor(CGColor:color)
            }
            else {
                return nil
            }
        }
    }

    /* The opacity of the shadow. Defaults to 0. Specifying a value outside the
    * [0,1] range will give undefined results. Animatable. */
    @IBInspectable var shadowOpacity: Float {
        set {
            layer.shadowOpacity = newValue
        }
        get {
            return layer.shadowOpacity
        }
    }

    /* The shadow offset. Defaults to (0, -3). Animatable. */
    @IBInspectable var shadowOffset: CGPoint {
        set {
            layer.shadowOffset = CGSize(width: newValue.x, height: newValue.y)
        }
        get {
            return CGPoint(x: layer.shadowOffset.width, y:layer.shadowOffset.height)
        }
    }

    /* The blur radius used to create the shadow. Defaults to 3. Animatable. */
    @IBInspectable var shadowRadius: CGFloat {
        set {
            layer.shadowRadius = newValue
        }
        get {
            return layer.shadowRadius
        }
    }
}

Then this will be available in Interface Builder for every view in the Utilities Panel > Attributes Inspector :

Utilities Panel

You can easily set the shadow now.

Notes:
- The shadow won't appear in IB, only at runtime.
- As Mazen Kasser said

To those who failed in getting this to work [...] make sure Clip Subviews (clipsToBounds) is not enabled

Add data to JSONObject

In order to have this result:

{"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]}

that holds the same data as:

  {
    "aoColumnDefs": [
     { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
     { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
     { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
   ]
  }

you could use this code:

    JSONObject jo = new JSONObject();
    Collection<JSONObject> items = new ArrayList<JSONObject>();

    JSONObject item1 = new JSONObject();
    item1.put("aDataSort", new JSONArray(0, 1));
    item1.put("aTargets", new JSONArray(0));
    items.add(item1);
    JSONObject item2 = new JSONObject();
    item2.put("aDataSort", new JSONArray(1, 0));
    item2.put("aTargets", new JSONArray(1));
    items.add(item2);
    JSONObject item3 = new JSONObject();
    item3.put("aDataSort", new JSONArray(2, 3, 4));
    item3.put("aTargets", new JSONArray(2));
    items.add(item3);

    jo.put("aoColumnDefs", new JSONArray(items));

    System.out.println(jo.toString());

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

Make

Make is the program that’s used to install the program that’s compiled from the source code. It’s not the Linux package manager so it doesn’t keep track of the files it installs. This makes it difficult to uninstall the files afterward.

The Make Install command copies the built program and packages into the library directory and specified locations from the makefile. These locations can vary based on the examination that’s performed by the configure script.

CheckInstall

CheckInstall is the program that’s used to install or uninstall programs that are compiled from the source code. It monitors and copies the files that are installed using the make program. It also installs the files using the Linux package manager which allows it to be uninstalled like any regular package.

The CheckInstall command is used to call the Make Install command. It monitors the files that are installed and creates a binary package from them. It also installs the binary package with the Linux package manager.

Replace "source_location.deb" and "name" with your information from the Screenshot.

Execute the following commands in the source package directory:

  1. Install CheckInstall sudo apt-get install checkinstall
  2. Run the Configure script sudo ./configure
  3. Run the Make command sudo make
  4. Run CheckInstall sudo checkinstall
  5. Reinstall the package sudo dpkg --install --force-overwrite source_location.deb
  6. Remove the package sudo apt remove name

Here's an article article I wrote that covers the whole process with explanations.

How exactly to use Notification.Builder

Notification Builder is strictly for Android API Level 11 and above (Android 3.0 and up).

Hence, if you are not targeting Honeycomb tablets, you should not be using the Notification Builder but rather follow older notification creation methods like the following example.

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

I think create a custom EditorTemplate is not good solution, beause you need to care about many possible tepmlates for different cases: strings, numsers, comboboxes and so on. Other solution is custom extention to HtmlHelper.

Model:

public class MyViewModel
{
    [PlaceHolder("Enter title here")]
    public string Title { get; set; }
}

Html helper extension:

   public static MvcHtmlString BsEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TValue>> expression, string htmlClass = "")
{
    var modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    var metadata = modelMetadata;

    var viewData = new
    {
        HtmlAttributes = new
            {
                @class = htmlClass,
                placeholder = metadata.Watermark,
            }
    };
    return htmlHelper.EditorFor(expression, viewData);

}

A corresponding view:

@Html.BsEditorFor(x => x.Title)

What are the git concepts of HEAD, master, origin?

While this doesn't directly answer the question, there is great book available for free which will help you learn the basics called ProGit. If you would prefer the dead-wood version to a collection of bits you can purchase it from Amazon.

how to download file using AngularJS and calling MVC API?

per various post... you cannot trigger a download via XHR. I needed to implement condition for the download, so, My solution was:

//make the call to the api with the ID to validate
someResource.get( { id: someId }, function(data) {
     //confirm that the ID is validated
     if (data.isIdConfirmed) {
         //get the token from the validation and issue another call
         //to trigger the download
         window.open('someapi/print/:someId?token='+ data.token);
     }
});

I wish that somehow, or someday the download can be triggered using XHR to avoid the second call. // _e

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

How to remove multiple indexes from a list at the same time?

If they're contiguous, you can just do

x[2:6] = []

If you want to remove noncontiguous indexes, it's a little trickier.

x = [v for i,v in enumerate(x) if i not in frozenset((2,3,4,5))] 

How do I make a WinForms app go Full Screen

I don't know if it will work on .NET 2.0, but it worked me on .NET 4.5.2. Here is the code:

using System;
using System.Drawing;
using System.Windows.Forms;

public partial class Your_Form_Name : Form
{
    public Your_Form_Name()
    {
        InitializeComponent();
    }

    // CODE STARTS HERE

    private System.Drawing.Size oldsize = new System.Drawing.Size(300, 300);
    private System.Drawing.Point oldlocation = new System.Drawing.Point(0, 0);
    private System.Windows.Forms.FormWindowState oldstate = System.Windows.Forms.FormWindowState.Normal;
    private System.Windows.Forms.FormBorderStyle oldstyle = System.Windows.Forms.FormBorderStyle.Sizable;
    private bool fullscreen = false;
    /// <summary>
    /// Goes to fullscreen or the old state.
    /// </summary>
    private void UpgradeFullscreen()
    {
        if (!fullscreen)
        {
            oldsize = this.Size;
            oldstate = this.WindowState;
            oldstyle = this.FormBorderStyle;
            oldlocation = this.Location;
            this.WindowState = System.Windows.Forms.FormWindowState.Normal;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
            fullscreen = true;
        }
        else
        {
            this.Location = oldlocation;
            this.WindowState = oldstate;
            this.FormBorderStyle = oldstyle;
            this.Size = oldsize;
            fullscreen = false;
        }
    }

    // CODE ENDS HERE
}

Usage:

UpgradeFullscreen(); // Goes to fullscreen
UpgradeFullscreen(); // Goes back to normal state
// You don't need arguments.

Notice: You MUST place it inside your Form's class (Example: partial class Form1 : Form { /* Code goes here */ } ) or it will not work because if you don't place it on any form, code this will create an exception.

How should I declare default values for instance variables in Python?

You can also declare class variables as None which will prevent propagation. This is useful when you need a well defined class and want to prevent AttributeErrors. For example:

>>> class TestClass(object):
...     t = None
... 
>>> test = TestClass()
>>> test.t
>>> test2 = TestClass()
>>> test.t = 'test'
>>> test.t
'test'
>>> test2.t
>>>

Also if you need defaults:

>>> class TestClassDefaults(object):
...    t = None
...    def __init__(self, t=None):
...       self.t = t
... 
>>> test = TestClassDefaults()
>>> test.t
>>> test2 = TestClassDefaults([])
>>> test2.t
[]
>>> test.t
>>>

Of course still follow the info in the other answers about using mutable vs immutable types as the default in __init__.

Convert laravel object to array

this worked for me in laravel 5.4

$partnerProfileIds = DB::table('partner_profile_extras')->get()->pluck('partner_profile_id');
$partnerProfileIdsArray = $partnerProfileIds->all();

output

array:4 [?
  0 => "8219c678-2d3e-11e8-a4a3-648099380678"
  1 => "28459dcb-2d3f-11e8-a4a3-648099380678"
  2 => "d5190f8e-2c31-11e8-8802-648099380678"
  3 => "6d2845b6-2d3e-11e8-a4a3-648099380678"
]

https://laravel.com/docs/5.4/collections#method-all

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

Executing a batch file in a remote machine through PsExec

Here's my current solution to run any code remotely on a given machine or list of machines asynchronously with logging, too!

@echo off
:: by Ralph Buchfelder, thanks to Mark Russinovich and Rob van der Woude for their work!
:: requires PsExec.exe to be in the same directory (download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx)
:: troubleshoot remote commands with PsExec arguments -i or -s if neccessary (see http://forum.sysinternals.com/pstools_forum8.html)
:: will run *in parallel* on a list of remote pcs (if given); to run serially please remove 'START "" CMD.EXE /C' from the psexec call


:: help
if '%1' =='-h' (
 echo.
 echo %~n0
 echo.
 echo Runs a command on one or many remote machines. If no input parameters
 echo are given you will be asked for a target remote machine.
 echo.
 echo You will be prompted for remote credentials with elevated privileges.
 echo.
 echo UNC paths and local paths can be supplied.
 echo Commands will be executed on the remote side just the way you typed
 echo them, so be sure to mind extensions and the path variable!
 echo.
 echo Please note that PsExec.exe must be allowed on remote machines, i.e.
 echo not blocked by firewall or antivirus solutions.
 echo.
 echo Syntax: %~n0 [^<inputfile^>]
 echo.
 echo     inputfile      = a plain text file ^(one hostname or ip address per line^)
 echo.
 echo.
 echo Example:
 echo %~n0 mylist.txt
 exit /b 0
)


:checkAdmin
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' neq '0' (
 echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
 echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
 "%temp%\getadmin.vbs"
 del "%temp%\getadmin.vbs"
 exit /B
)
set ADMINTESTDIR=%WINDIR%\System32\Test_%RANDOM%
mkdir "%ADMINTESTDIR%" 2>NUL
if errorlevel 1 (
 cls
 echo ERROR: This script requires elevated privileges!
 echo.
 echo Launch by Right-Click / Run as Administrator ...
 pause
 exit /b 1
) else (
 rd /s /q "%ADMINTESTDIR%"
 echo Running with elevated privileges...
)
echo.


:checkRequirements
if not exist "%~dp0PsExec.exe" (
 echo PsExec.exe from Sysinternals/Microsoft not found 
 echo in %~dp0
 echo.
 echo Download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx
 echo.
 pause
 exit /B
)


:environment
setlocal
echo.
echo %~n0
echo _____________________________
echo.
echo Working directory:  %cd%\
echo Script directory:   %~dp0
echo.
SET /P REMOTE_USER=Domain\Administrator : 
SET "psCommand=powershell -Command "$pword = read-host 'Kennwort' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set REMOTE_PASS=%%p
if NOT DEFINED REMOTE_PASS SET /P REMOTE_PASS=Password             : 
echo.
if '%1' =='' goto menu
SET REMOTE_LIST=%1


:inputMultipleTargets
if not exist %REMOTE_LIST% (
 echo File %REMOTE_LIST% not found
 goto menu
)
type %REMOTE_LIST% >nul
if '%errorlevel%' neq '0' (
 echo Access denied %REMOTE_LIST%
 goto menu
)
set batchProcessing=true
echo Batch processing:   %REMOTE_LIST%   ...
ping -n 2 127.0.0.1 >nul
goto runOnce


:menu
if exist "%~dp0last.computer"  set /p LAST_COMPUTER=<"%~dp0last.computer"
if exist "%~dp0last.listing"   set /p LAST_LISTING=<"%~dp0last.listing"
if exist "%~dp0last.directory" set /p LAST_DIRECTORY=<"%~dp0last.directory"
if exist "%~dp0last.command"   set /p LAST_COMMAND=<"%~dp0last.command"
if exist "%~dp0last.timestamp" set /p LAST_TIMESTAMP=<"%~dp0last.timestamp"
echo.
echo.
echo                (1)  select target computer [default]
echo                (2)  select multiple computers
echo                     -----------------------------------
echo                     last target : %LAST_COMPUTER%
echo                     last listing: %LAST_LISTING%
echo                     last path   : %LAST_DIRECTORY%
echo                     last command: %LAST_COMMAND%
echo                     last run    : %LAST_TIMESTAMP%
echo                     -----------------------------------
echo                (0)  exit
echo.
echo ENTER your choice.
echo.
echo.
:mychoice
SET /P mychoice=(0, 1, ...): 
if NOT DEFINED mychoice  goto promptSingleTarget
if "%mychoice%"=="1"     goto promptSingleTarget
if "%mychoice%"=="2"     goto promptMultipleTargets
if "%mychoice%"=="0"     goto end
goto mychoice


:promptMultipleTargets
echo.
echo Please provide an input file
echo [one IP address or hostname per line]
SET /P REMOTE_LIST=Filename             : 
goto inputMultipleTargets


:promptSingleTarget
SET batchProcessing=
echo.
echo Please provide a hostname
SET /P REMOTE_COMPUTER=Target computer      : 
goto runOnce


:runOnce
cls
echo Note: Paths are mandatory for CMD-commands (e.g. dir,copy) to work!
echo       Paths are provided on the remote machine via PUSHD.
echo.
SET /P REMOTE_PATH=UNC-Path or folder : 
SET /P REMOTE_CMD=Command with params: 
SET REMOTE_TIMESTAMP=%DATE% %TIME:~0,8%
echo.
echo Remote command starting (%REMOTE_PATH%\%REMOTE_CMD%) on %REMOTE_TIMESTAMP%...
if not defined batchProcessing goto runOnceSingle


:runOnceMulti
REM do for each line; this circumvents PsExec's @file to have stdouts separately
SET REMOTE_LOG=%~dp0\log\%REMOTE_LIST%
if not exist %REMOTE_LOG% md %REMOTE_LOG%
for /F "tokens=*" %%A in (%REMOTE_LIST%) do (
 if "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "%REMOTE_CMD%" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
 if not "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
)
goto restart


:runOnceSingle
SET REMOTE_LOG=%~dp0\log
if not exist %REMOTE_LOG% md %REMOTE_LOG%
if "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "%REMOTE_CMD%" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
if not "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
goto restart


:restart
echo.
echo.
echo Batch completed. Finished with last errorlevel %errorlevel% .
echo All outputs have been saved to %~dp0log\%REMOTE_TIMESTAMP%\.
echo %REMOTE_PATH% >"%~dp0last.directory"
echo %REMOTE_CMD% >"%~dp0last.command"
echo %REMOTE_LIST% >"%~dp0last.listing"
echo %REMOTE_COMPUTER% >"%~dp0last.computer"
echo %REMOTE_TIMESTAMP% >"%~dp0last.timestamp"
SET REMOTE_PATH=
SET REMOTE_CMD=
SET REMOTE_LIST=
SET REMOTE_COMPUTER=
SET REMOTE_LOG=
SET REMOTE_TIMESTAMP=
ping -n 2 127.0.0.1 >nul
goto menu


:end
SET REMOTE_USER=
SET REMOTE_PASS=

How to send email from MySQL 5.1

If you have an SMTP service running, you can outfile to the drop directory. If you have high volume, you may result with duplicate file names, but there are ways to avoid that.

Otherwise, you will need to create a UDF.

Here's a sample trigger solution:

CREATE TRIGGER test.autosendfromdrop BEFORE INSERT ON test.emaildrop
FOR EACH ROW BEGIN
      /* START THE WRITING OF THE EMAIL FILE HERE*/      
      SELECT  concat("To: ",NEW.To),
              concat("From: ",NEW.From),
              concat("Subject: ",NEW.Subject),
              NEW.Body
          INTO OUTFILE 
                   "C:\\inetpub\\mailroot\\pickup\\mail.txt" 
              FIELDS TERMINATED by '\r\n' ESCAPED BY '';            
END;

To markup the message body you will need something like this...

CREATE FUNCTION `HTMLBody`(Msg varchar(8192)) 
    RETURNS varchar(17408) CHARSET latin1 DETERMINISTIC
BEGIN
  declare tmpMsg varchar(17408);
  set tmpMsg = cast(concat(
      'Date: ',date_format(NOW(),'%e %b %Y %H:%i:%S -0600'),'\r\n',
      'MIME-Version: 1.0','\r\n',
      'Content-Type: multipart/alternative;','\r\n',
      ' boundary=\"----=_NextPart_000_0000_01CA4B3F.8C263EE0\"','\r\n',
      'Content-Class: urn:content-classes:message','\r\n',
      'Importance: normal','\r\n',
      'Priority: normal','\r\n','','\r\n','','\r\n',
      'This is a multi-part message in MIME format.','\r\n','','\r\n',
      '------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
      'Content-Type: text/plain;','\r\n',
      '  charset=\"iso-8859-1\"','\r\n',
      'Content-Transfer-Encoding: 7bit','\r\n','','\r\n','','\r\n',
      Msg,
      '\r\n','','\r\n','','\r\n',
      '------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
      'Content-Type: text/html','\r\n',
      'Content-Transfer-Encoding: 7bit','\r\n','','\r\n',
      Msg,
      '\r\n','------=_NextPart_000_0000_01CA4B3F.8C263EE0--'
      ) as char);
  RETURN tmpMsg;
END ;

What is the difference between .text, .value, and .value2?

target.Value will give you a Variant type

target.Value2 will give you a Variant type as well but a Date is coerced to a Double

target.Text attempts to coerce to a String and will fail if the underlying Variant is not coercable to a String type

The safest thing to do is something like

Dim v As Variant
v = target.Value 'but if you don't want to handle date types use Value2

And check the type of the variant using VBA.VarType(v) before you attempt an explicit coercion.

How to do a https request with bad certificate?

All of these answers are wrong! Do not use InsecureSkipVerify to deal with a CN that doesn't match the hostname. The Go developers unwisely were adamant about not disabling hostname checks (which has legitimate uses - tunnels, nats, shared cluster certs, etc), while also having something that looks similar but actually completely ignores the certificate check. You need to know that the certificate is valid and signed by a cert that you trust. But in common scenarios, you know that the CN won't match the hostname you connected with. For those, set ServerName on tls.Config. If tls.Config.ServerName == remoteServerCN, then the certificate check will succeed. This is what you want. InsecureSkipVerify means that there is NO authentication; and it's ripe for a Man-In-The-Middle; defeating the purpose of using TLS.

There is one legitimate use for InsecureSkipVerify: use it to connect to a host and grab its certificate, then immediately disconnect. If you setup your code to use InsecureSkipVerify, it's generally because you didn't set ServerName properly (it will need to come from an env var or something - don't belly-ache about this requirement... do it correctly).

In particular, if you use client certs and rely on them for authentication, you basically have a fake login that doesn't actually login any more. Refuse code that does InsecureSkipVerify, or you will learn what is wrong with it the hard way!

Custom HTTP headers : naming conventions

The question bears re-reading. The actual question asked is not similar to vendor prefixes in CSS properties, where future-proofing and thinking about vendor support and official standards is appropriate. The actual question asked is more akin to choosing URL query parameter names. Nobody should care what they are. But name-spacing the custom ones is a perfectly valid -- and common, and correct -- thing to do.

Rationale:
It is about conventions among developers for custom, application-specific headers -- "data relevant to their account" -- which have nothing to do with vendors, standards bodies, or protocols to be implemented by third parties, except that the developer in question simply needs to avoid header names that may have other intended use by servers, proxies or clients. For this reason, the "X-Gzip/Gzip" and "X-Forwarded-For/Forwarded-For" examples given are moot. The question posed is about conventions in the context of a private API, akin to URL query parameter naming conventions. It's a matter of preference and name-spacing; concerns about "X-ClientDataFoo" being supported by any proxy or vendor without the "X" are clearly misplaced.

There's nothing special or magical about the "X-" prefix, but it helps to make it clear that it is a custom header. In fact, RFC-6648 et al help bolster the case for use of an "X-" prefix, because -- as vendors of HTTP clients and servers abandon the prefix -- your app-specific, private-API, personal-data-passing-mechanism is becoming even better-insulated against name-space collisions with the small number of official reserved header names. That said, my personal preference and recommendation is to go a step further and do e.g. "X-ACME-ClientDataFoo" (if your widget company is "ACME").

IMHO the IETF spec is insufficiently specific to answer the OP's question, because it fails to distinguish between completely different use cases: (A) vendors introducing new globally-applicable features like "Forwarded-For" on the one hand, vs. (B) app developers passing app-specific strings to/from client and server. The spec only concerns itself with the former, (A). The question here is whether there are conventions for (B). There are. They involve grouping the parameters together alphabetically, and separating them from the many standards-relevant headers of type (A). Using the "X-" or "X-ACME-" prefix is convenient and legitimate for (B), and does not conflict with (A). The more vendors stop using "X-" for (A), the more cleanly-distinct the (B) ones will become.

Example:
Google (who carry a bit of weight in the various standards bodies) are -- as of today, 20141102 in this slight edit to my answer -- currently using "X-Mod-Pagespeed" to indicate the version of their Apache module involved in transforming a given response. Is anyone really suggesting that Google should use "Mod-Pagespeed", without the "X-", and/or ask the IETF to bless its use?

Summary:
If you're using custom HTTP Headers (as a sometimes-appropriate alternative to cookies) within your app to pass data to/from your server, and these headers are, explicitly, NOT intended ever to be used outside the context of your application, name-spacing them with an "X-" or "X-FOO-" prefix is a reasonable, and common, convention.

Why should Java 8's Optional not be used in arguments

I think that is because you usually write your functions to manipulate data, and then lift it to Optional using map and similar functions. This adds the default Optional behavior to it. Of course, there might be cases, when it is necessary to write your own auxilary function that works on Optional.

C# error: Use of unassigned local variable

The compiler doesn't know that Environment.Exit() does not return. Why not just "return" from Main()?

Sort a list of numerical strings in ascending order

The recommended approach in this case is to sort the data in the database, adding an ORDER BY at the end of the query that fetches the results, something like this:

SELECT temperature FROM temperatures ORDER BY temperature ASC;  -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order

If for some reason that is not an option, you can change the sorting order like this in Python:

templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int)               # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]

As has been pointed in the comments, the int key (or float if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.

What steps are needed to stream RTSP from FFmpeg?

Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:

sudo apt install vlc ffmpeg

In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.

I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.

You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:

ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'

For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:

ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554

Including one C source file in another?

Numerous other answers have more than covered how you can do this but why you probably should not in normal circumstances. That said, I will add why I've done it in the past.

In embedded development, it's common to have silicon vendor source code as part of your compiled files. The problem is those vendors likely don't have the same style guides or standard warning/error flag settings as your organization.

So, you can create a local source file that includes the vendor source code and then compile this wrapper C file instead to suppress any issues in the included source as well as any headers included by that source. As an example:

/**
 * @file   vendor_wrap.c
 * @brief  vendor source code wrapper to prevent warnings
 */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnested-externs"
#include "vendor_source_code.c"
#pragma GCC diagnostic pop

This allows you to use less complicated Make scripting with a standard set of compiler flags and settings with specific exceptions in the code rather than have custom flags for some files in the scripting.

gcc main.c vendor_wrap.c -o $(CFLAGS) main.out

Linux command: How to 'find' only text files?

Another way of doing this:

# find . |xargs file {} \; |grep "ASCII text"

If you want empty files too:

#  find . |xargs file {} \; |egrep "ASCII text|empty"

curl error 18 - transfer closed with outstanding read data remaining

I've solved this error by this way.

$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, 'http://www.someurl/' );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 30);
ob_start();
$response = curl_exec ( $ch );
$data = ob_get_clean();
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200 ) success;

Error still occurs, but I can handle response data in variable.

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

I am answering this for android studio 2.3.1. One of the easiest ways to set RelativeLayout as default layout is going to text mode and editing the XML file as follows:

Change this line:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

To

<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

And do check your ending tag changes to this:

</android.widget.RelativeLayout>

Also (optionally) go ahead and delete this line if it's being shown in grey:

xmlns:app="http://schemas.android.com/apk/res-auto"

Edit:

This is an optional change to make in project, I came across this tip while going through Udacity's Android Developer Course

If the constraint layout is not needed in the project remove the following dependency from build.gradle by deleting this line and then doing gradle sync:

    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

You need to set the error_reporting value in a .htaccess file. Since there is a parse error, it never runs the error_reporting() function in your PHP code.

Try this in a .htaccess file (assuming you can use one):

php_flag display_errors 1
php_value error_reporting 30719

I think 30719 corresponds to E_ALL but I may be wrong.

Edit Update: http://php.net/manual/en/errorfunc.constants.php

int error_reporting ([ int $level ] )
---
32767   E_ALL (integer)     
All errors and warnings, as supported, except of   level E_STRICT prior to PHP 5.4.0.   32767 in PHP 5.4.x, 30719 in PHP 5.3.x, 6143 in PHP   5.2.x, 2047 previously

Which Ruby version am I really running?

Run this command:

rvm get stable --auto-dotfiles

and make sure to read all the output. RVM will tell you if something is wrong, which in your case might be because GEM_HOME is set to something different then PATH.

how to call a method in another Activity from Activity

The startActivityForResult pattern is much better suited for what you're trying to achieve : http://developer.android.com/reference/android/app/Activity.html#StartingActivities

Try below code

public class MainActivity extends Activity {  

    Button button1;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        textView1=(TextView)findViewById(R.id.textView1);  
        button1=(Button)findViewById(R.id.button1);  
        button1.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View arg0) {  
                Intent intent=new Intent(MainActivity.this,SecondActivity.class);  
                startActivityForResult(intent, 2);// Activity is started with requestCode 2  
            }  
        });  
    }  
 // Call Back method  to get the Message form other Activity  
    @Override  
       protected void onActivityResult(int requestCode, int resultCode, Intent data)  
       {  
                 super.onActivityResult(requestCode, resultCode, data);  
                  // check if the request code is same as what is passed  here it is 2  
                   if(requestCode==2)  
                         {  
                          //do the things u wanted 
                         }  
     }  

} 

SecondActivity.class

public class SecondActivity extends Activity {  

    Button button1;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_second);  

            button1=(Button)findViewById(R.id.button1);  
            button1.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View arg0) {  
                    String message="hello ";  
                    Intent intent=new Intent();  
                    intent.putExtra("MESSAGE",message);  
                    setResult(2,intent);  
                    finish();//finishing activity  
                }  
            });  
    }  

}  

Let me know if it helped...

SELECT * FROM in MySQLi

You can still use it (mysqli is just another way of communicating with the server, the SQL language itself is expanded, not changed). Prepared statements are safer, though - since you don't need to go through the trouble of properly escaping your values each time. You can leave them as they were, if you want to but the risk of sql piggybacking is reduced if you switch.

PHP header(Location: ...): Force URL change in address bar

you may want to put a break; after your location:

header("HTTP/1.1 301 Moved Permanently");
header('Location:  '.  $YourArrayName["YourURL"]  );
break;

How to randomize (shuffle) a JavaScript array?

bencharks

Let's first see the results then we'll look at each implementation of shuffle below -

  • splice

  • pop

  • inplace


splice is slow

Any solution using splice or shift in a loop is going to be very slow. Which is especially noticeable when we increase the size of the array. In a naive algorithm we -

  1. get a rand position, i, in the input array, t
  2. add t[i] to the output
  3. splice position i from array t

To exaggerate the slow effect, we'll demonstrate this on an array of one million elements. The following script almost 30 seconds -

_x000D_
_x000D_
const shuffle = t =>
  Array.from(sample(t, t.length))

function* sample(t, n)
{ let r = Array.from(t)
  while (n > 0 && r.length)
  { const i = rand(r.length) // 1
    yield r[i]               // 2
    r.splice(i, 1)           // 3
    n = n - 1
  }
}

const rand = n =>
  Math.floor(Math.random() * n)

function swap (t, i, j)
{ let q = t[i]
  t[i] = t[j]
  t[j] = q
  return t
}

const size = 1e6
const bigarray = Array.from(Array(size), (_,i) => i)
console.time("shuffle via splice")
const result = shuffle(bigarray)
console.timeEnd("shuffle via splice")
document.body.textContent = JSON.stringify(result, null, 2)
_x000D_
body::before {
  content: "1 million elements via splice";
  font-weight: bold;
  display: block;
}
_x000D_
_x000D_
_x000D_


pop is fast

The trick is not to splice and instead use the super efficient pop. To do this, in place of the typical splice call, you -

  1. select the position to splice, i
  2. swap t[i] with the last element, t[t.length - 1]
  3. add t.pop() to the result

Now we can shuffle one million elements in less than 100 milliseconds -

_x000D_
_x000D_
const shuffle = t =>
  Array.from(sample(t, t.length))

function* sample(t, n)
{ let r = Array.from(t)
  while (n > 0 && r.length)
  { const i = rand(r.length) // 1
    swap(r, i, r.length - 1) // 2
    yield r.pop()            // 3
    n = n - 1
  }
}

const rand = n =>
  Math.floor(Math.random() * n)

function swap (t, i, j)
{ let q = t[i]
  t[i] = t[j]
  t[j] = q
  return t
}

const size = 1e6
const bigarray = Array.from(Array(size), (_,i) => i)
console.time("shuffle via pop")
const result = shuffle(bigarray)
console.timeEnd("shuffle via pop")
document.body.textContent = JSON.stringify(result, null, 2)
_x000D_
body::before {
  content: "1 million elements via pop";
  font-weight: bold;
  display: block;
}
_x000D_
_x000D_
_x000D_


even faster

The two implementations of shuffle above produce a new output array. The input array is not modified. This is my preferred way of working however you can increase the speed even more by shuffling in place.

Below shuffle one million elements in less than 10 milliseconds -

_x000D_
_x000D_
function shuffle (t)
{ let last = t.length
  let n
  while (last > 0)
  { n = rand(last)
    swap(t, n, --last)
  }
}

const rand = n =>
  Math.floor(Math.random() * n)

function swap (t, i, j)
{ let q = t[i]
  t[i] = t[j]
  t[j] = q
  return t
}

const size = 1e6
const bigarray = Array.from(Array(size), (_,i) => i)
console.time("shuffle in place")
shuffle(bigarray)
console.timeEnd("shuffle in place")
document.body.textContent = JSON.stringify(bigarray, null, 2)
_x000D_
body::before {
  content: "1 million elements in place";
  font-weight: bold;
  display: block;
}
_x000D_
_x000D_
_x000D_

Failed to load ApplicationContext from Unit Test: FileNotFound

Give the below

@ContextConfiguration(locations =  {"classpath*:/spring/test-context.xml"})

And in pom.xml give the following plugin:

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-surefire-plugin</artifactId>
   <version>2.20.1</version>
<configuration>
    <additionalClasspathElements>
       <additionalClasspathElement>${basedir}/src/test/resources</additionalClasspathElement>
    </additionalClasspathElements>
</configuration>

MySQL select with CONCAT condition

The aliases you give are for the output of the query - they are not available within the query itself.

You can either repeat the expression:

SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
FROM users
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"

or wrap the query

SELECT * FROM (
  SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
  FROM users) base 
WHERE firstLast = "Bob Michael Jones"

Length of the String without using length() method

try below code

    public static int Length(String str) {
    str = str + '\0';
    int count = 0;

    for (int i = 0; str.charAt(i) != '\0'; i++) {
        count++;
    }

    return count;
    }

What is the difference between map and flatMap and a good use case for each?

Use test.md as a example:

?  spark-1.6.1 cat test.md
This is the first line;
This is the second line;
This is the last line.

scala> val textFile = sc.textFile("test.md")
scala> textFile.map(line => line.split(" ")).count()
res2: Long = 3

scala> textFile.flatMap(line => line.split(" ")).count()
res3: Long = 15

scala> textFile.map(line => line.split(" ")).collect()
res0: Array[Array[String]] = Array(Array(This, is, the, first, line;), Array(This, is, the, second, line;), Array(This, is, the, last, line.))

scala> textFile.flatMap(line => line.split(" ")).collect()
res1: Array[String] = Array(This, is, the, first, line;, This, is, the, second, line;, This, is, the, last, line.)

If you use map method, you will get the lines of test.md, for flatMap method, you will get the number of words.

The map method is similar to flatMap, they are all return a new RDD. map method often to use return a new RDD, flatMap method often to use split words.

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

It may be application is not uninstall successful. If your device is this case, you can try this method.

First get the package name of the application, e.g 'com.xxx.app', you can use Root Explorer and find it from Manifest file(RE can decode the file). then you can use this script to uninstall it:

adb shell pm uninstall com.xxx.app // replace to package name that you want to remove

Naming convention - underscore in C++ and C# variables

I use the _var naming for member variables of my classes. There are 2 main reasons I do:

1) It helps me keep track of class variables and local function variables when I'm reading my code later.

2) It helps in Intellisense (or other code-completion system) when I'm looking for a class variable. Just knowing the first character is helpful in filtering through the list of available variables and methods.

How should I choose an authentication library for CodeIgniter?

I'm the developer of Redux Auth and some of the issues you mentioned have been fixed in the version 2 beta. You can download this off the offcial website with a sample application too.

  • Requires autoloading (impeding performance)
  • Uses the inherently unsafe concept of 'security questions'. Dealbreaker!

Security questions are now not used and a simpler forgotten password system has been put in place.

  • Return types are a bit of a hodgepodge of true, false, error and success codes

This was fixed in version 2 and returns boolean values. I hated the hodgepodge as much as you.

  • Doesn't hook into CI's validation system

The sample application uses the CI's validation system.

  • Doesn't allow a user to resend a 'lost password' code

Work in progress

I also implemented some other features such as email views, this gives you the choice of being able to use the CodeIgniter helpers in your emails.

It's still a work in progress so if have any more suggestions please keep them coming.

-Popcorn

Ps : Thanks for recommending Redux.

How to replace all double quotes to single quotes using jquery?

Use double quote to enclose the quote or escape it.

newTemp = mystring.replace(/"/g, "'");

or

newTemp = mystring.replace(/"/g, '\'');

Delimiter must not be alphanumeric or backslash and preg_match

You need a delimiter for your pattern. It should be added at the start and end of the pattern like so:

$pattern = "/My name is '(.*)' and im fine/";  // With / as a delimeter 

How do you programmatically set an attribute?

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

How to get store information in Magento?

Magento Store Id : Mage::app()->getStore()->getStoreId();

Magento Store Name : Mage::app()->getStore()->getName();

How to check if mysql database exists

Golang solution

create a test package and add:

import "database/sql"

// testing database creation
func TestCreate(t *testing.T){
    Createdb("*Testdb") // This just calls the **sql.DB obect *Testdb 
    db,err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/*Testdb")
    if err != nil{
        panic(err)
    }
    defer db.Close()
    _, err = db.Exec("USE *Testdb")
    if err != nil{
        t.Error("Database not Created")
    }

} 

Copying data from one SQLite database to another

I needed to move data from a sql server compact database to sqlite, so using sql server 2008 you can right click on the table and select 'Script Table To' and then 'Data to Inserts'. Copy the insert statements remove the 'GO' statements and it executed successfully when applied to the sqlite database using the 'DB Browser for Sqlite' app.

Query for array elements inside JSON type

jsonb in Postgres 9.4+

You can use the same query as below, just with jsonb_array_elements().

But rather use the jsonb "contains" operator @> in combination with a matching GIN index on the expression data->'objects':

CREATE INDEX reports_data_gin_idx ON reports
USING gin ((data->'objects') jsonb_path_ops);

SELECT * FROM reports WHERE data->'objects' @> '[{"src":"foo.png"}]';

Since the key objects holds a JSON array, we need to match the structure in the search term and wrap the array element into square brackets, too. Drop the array brackets when searching a plain record.

More explanation and options:

json in Postgres 9.3+

Unnest the JSON array with the function json_array_elements() in a lateral join in the FROM clause and test for its elements:

SELECT data::text, obj
FROM   reports r, json_array_elements(r.data#>'{objects}') obj
WHERE  obj->>'src' = 'foo.png';

db<>fiddle here
Old sqlfiddle

The CTE (WITH query) just substitutes for a table reports.
Or, equivalent for just a single level of nesting:

SELECT *
FROM   reports r, json_array_elements(r.data->'objects') obj
WHERE  obj->>'src' = 'foo.png';

->>, -> and #> operators are explained in the manual.

Both queries use an implicit JOIN LATERAL.

Closely related:

SVG: text inside rect

Programmatically using D3:

body = d3.select('body')
svg = body.append('svg').attr('height', 600).attr('width', 200)
rect = svg.append('rect').transition().duration(500).attr('width', 150)
                .attr('height', 100)
                .attr('x', 40)
                .attr('y', 100)
                .style('fill', 'white')
                .attr('stroke', 'black')
text = svg.append('text').text('This is some information about whatever')
                .attr('x', 50)
                .attr('y', 150)
                .attr('fill', 'black')

text-align: right on <select> or <option>

I think what you want is:

select {
  direction: rtl;
}

fiddled here: http://jsfiddle.net/neilheinrich/XS3yQ/

How to execute 16-bit installer on 64-bit Win7?

Bottom line at the top: Get newer programs or get an older computer.

The solution is simple. It sucks but it's simple. For old programs keep an old computer up and running. Some times you just can't find the same game experience in the new games as the old ones. Sometimes there are programs that have no new counterparts that do the same thing. You basically have 2 choices at that point. On the bright side. Old computers can run $20 -$100 and that can buy you the whole system; monitor, tower, keyboard, mouse and speakers. If you have the patience to run old programs you should have the patience to find what you are looking for in want ads. I have 4 old computers running; 2 windows 98, 2 windows xp. The my wife and I each have win7 computers.

Select the first row by group

now, for dplyr, adding a distinct counter.

df %>%
    group_by(aa, bb) %>%
    summarise(first=head(value,1), count=n_distinct(value))

You create groups, them summarise within groups.

If data is numeric, you can use:
first(value) [there is also last(value)] in place of head(value, 1)

see: http://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html

Full:

> df
Source: local data frame [16 x 3]

   aa bb value
1   1  1   GUT
2   1  1   PER
3   1  2   SUT
4   1  2   GUT
5   1  3   SUT
6   1  3   GUT
7   1  3   PER
8   2  1   221
9   2  1   224
10  2  1   239
11  2  2   217
12  2  2   221
13  2  2   224
14  3  1   GUT
15  3  1   HUL
16  3  1   GUT

> library(dplyr)
> df %>%
>   group_by(aa, bb) %>%
>   summarise(first=head(value,1), count=n_distinct(value))

Source: local data frame [6 x 4]
Groups: aa

  aa bb first count
1  1  1   GUT     2
2  1  2   SUT     2
3  1  3   SUT     3
4  2  1   221     3
5  2  2   217     3
6  3  1   GUT     2

How to linebreak an svg text within javascript?

I think this does what you want:

function ShowTooltip(evt, mouseovertext){
    // Make tooltip text        
    var tooltip_text = tt.childNodes.item(1);
    var words = mouseovertext.split("\\\n");
    var max_length = 0;

    for (var i=0; i<3; i++){
        tooltip_text.childNodes.item(i).firstChild.data = i<words.length ?  words[i] : " ";
        length = tooltip_text.childNodes.item(i).getComputedTextLength();
        if (length > max_length) {max_length = length;}
    }

    var x = evt.clientX + 14 + max_length/2;
    var y = evt.clientY + 29;
    tt.setAttributeNS(null,"transform", "translate(" + x + " " + y + ")")

    // Make tooltip background
    bg.setAttributeNS(null,"width", max_length+15);
    bg.setAttributeNS(null,"height", words.length*15+6);
    bg.setAttributeNS(null,"x",evt.clientX+8);
    bg.setAttributeNS(null,"y",evt.clientY+14);

    // Show everything
    tt.setAttributeNS(null,"visibility","visible");
    bg.setAttributeNS(null,"visibility","visible");
}

It splits the text on \\\n and for each puts each fragment in a tspan. Then it calculates the size of the box required based on the longest length of text and the number of lines. You will also need to change the tooltip text element to contain three tspans:

<g id="tooltip" visibility="hidden">
    <text><tspan>x</tspan><tspan x="0" dy="15">x</tspan><tspan x="0" dy="15">x</tspan></text>
</g>

This assumes that you never have more than three lines. If you want more than three lines you can add more tspans and increase the length of the for loop.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

It could be that the gradle-2.1 distribution specified by the wrapper was not downloaded properly. This was the root cause of the same problem in my environment.

Look into this directory:

ls -l ~/.gradle/wrapper/dists/

In there you should find a gradle-2.1 folder. Delete it like so:

rm -rf ~/.gradle/wrapper/dists/gradle-2.1-bin/

Restart IntelliJ, after that it will restart the download from the beginning and hopefully work.

Thanks, Ioannis

Convert hexadecimal string (hex) to a binary string

Integer.parseInt(hex,16);    
System.out.print(Integer.toBinaryString(hex));

Parse hex(String) to integer with base 16 then convert it to Binary String using toBinaryString(int) method

example

int num = (Integer.parseInt("A2B", 16));
System.out.print(Integer.toBinaryString(num));

Will Print

101000101011

Max Hex vakue Handled by int is FFFFFFF

i.e. if FFFFFFF0 is passed ti will give error

Sending Windows key using SendKeys

SetForegroundWindow( /* window to gain focus */ );
SendKeys.SendWait("^{ESC}"); // ^{ESC} is code for ctrl + esc which mimics the windows key.

Managing jQuery plugin dependency in webpack

I tried some of the supplied answers but none of them seemed to work. Then I tried this:

new webpack.ProvidePlugin({
    'window.jQuery'    : 'jquery',
    'window.$'         : 'jquery',
    'jQuery'           : 'jquery',
    '$'                : 'jquery'
});

Seems to work no matter which version I'm using

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

How to write a large buffer into a binary file in C++, fast?

If you want to write fast to file streams then you could make stream the read buffer larger:

wfstream f;
const size_t nBufferSize = 16184;
wchar_t buffer[nBufferSize];
f.rdbuf()->pubsetbuf(buffer, nBufferSize);

Also, when writing lots of data to files it is sometimes faster to logically extend the file size instead of physically, this is because when logically extending a file the file system does not zero the new space out before writing to it. It is also smart to logically extend the file more than you actually need to prevent lots of file extentions. Logical file extention is supported on Windows by calling SetFileValidData or xfsctl with XFS_IOC_RESVSP64 on XFS systems.

Catch checked change event of a checkbox

$(document).ready(function(){
    checkUncheckAll("#select_all","[name='check_boxes[]']");
});

var NUM_BOXES = 10;
// last checkbox the user clicked
var last = -1;
function check(event) {
  // in IE, the event object is a property of the window object
  // in Mozilla, event object is passed to event handlers as a parameter
  event = event || window.event;

  var num = parseInt(/box\[(\d+)\]/.exec(this.name)[1]);
  if (event.shiftKey && last != -1) {
    var di = num > last ? 1 : -1;
    for (var i = last; i != num; i += di)
      document.forms.boxes['box[' + i + ']'].checked = true;
  }
  last = num;
}
function init() {
  for (var i = 0; i < NUM_BOXES; i++)
    document.forms.boxes['box[' + i + ']'].onclick = check;
}

HTML:

<body onload="init()">
  <form name="boxes">
    <input name="box[0]" type="checkbox">
    <input name="box[1]" type="checkbox">
    <input name="box[2]" type="checkbox">
    <input name="box[3]" type="checkbox">
    <input name="box[4]" type="checkbox">
    <input name="box[5]" type="checkbox">
    <input name="box[6]" type="checkbox">
    <input name="box[7]" type="checkbox">
    <input name="box[8]" type="checkbox">
    <input name="box[9]" type="checkbox">
  </form>
</body>

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

How can I create a copy of an Oracle table without copying the data?

I used the method that you accepted a lot, but as someone pointed out it doesn't duplicate constraints (except for NOT NULL, I think).

A more advanced method if you want to duplicate the full structure is:

SET LONG 5000
SELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME' ) FROM DUAL;

This will give you the full create statement text which you can modify as you wish for creating the new table. You would have to change the names of the table and all constraints of course.

(You could also do this in older versions using EXP/IMP, but it's much easier now.)

Edited to add If the table you are after is in a different schema:

SELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME', 'OTHER_SCHEMA_NAME' ) FROM DUAL;

Change name of folder when cloning from GitHub?

In case you want to clone a specific branch only, then,

git clone -b <branch-name> <repo-url> <destination-folder-name>

for example,

git clone -b dev https://github.com/sferik/sign-in-with-twitter.git signin

Keyword not supported: "data source" initializing Entity Framework Context

I fixed this by changing EntityClient back to SqlClient, even though I was using Entity Framework.

So my complete connection string was in the format:

<add name="DefaultConnection" connectionString="Data Source=localhost;Initial Catalog=xxx;Persist Security Info=True;User ID=xxx;Password=xxx" providerName="System.Data.SqlClient" />

What is the difference between MOV and LEA?

The instruction MOV reg,addr means read a variable stored at address addr into register reg. The instruction LEA reg,addr means read the address (not the variable stored at the address) into register reg.

Another form of the MOV instruction is MOV reg,immdata which means read the immediate data (i.e. constant) immdata into register reg. Note that if the addr in LEA reg,addr is just a constant (i.e. a fixed offset) then that LEA instruction is essentially exactly the same as an equivalent MOV reg,immdata instruction that loads the same constant as immediate data.

sql query to find the duplicate records

select distinct title, (
               select count(title) 
               from kmovies as sub 
               where sub.title=kmovies.title) as cnt 
from kmovies 
group by title 
order by cnt desc

How to check whether a select box is empty using JQuery/Javascript

To check whether select box has any values:

if( $('#fruit_name').has('option').length > 0 ) {

To check whether selected value is empty:

if( !$('#fruit_name').val() ) { 

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

I use below code to get File Name & File Size from Uri in my project.

/**
 * Used to get file detail from uri.
 * <p>
 * 1. Used to get file detail (name & size) from uri.
 * 2. Getting file details from uri is different for different uri scheme,
 * 2.a. For "File Uri Scheme" - We will get file from uri & then get its details.
 * 2.b. For "Content Uri Scheme" - We will get the file details by querying content resolver.
 *
 * @param uri Uri.
 * @return file detail.
 */
public static FileDetail getFileDetailFromUri(final Context context, final Uri uri) {
    FileDetail fileDetail = null;
    if (uri != null) {
        fileDetail = new FileDetail();
        // File Scheme.
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            File file = new File(uri.getPath());
            fileDetail.fileName = file.getName();
            fileDetail.fileSize = file.length();
        }
        // Content Scheme.
        else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            Cursor returnCursor =
                    context.getContentResolver().query(uri, null, null, null, null);
            if (returnCursor != null && returnCursor.moveToFirst()) {
                int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                fileDetail.fileName = returnCursor.getString(nameIndex);
                fileDetail.fileSize = returnCursor.getLong(sizeIndex);
                returnCursor.close();
            }
        }
    }
    return fileDetail;
}

/**
 * File Detail.
 * <p>
 * 1. Model used to hold file details.
 */
public static class FileDetail {

    // fileSize.
    public String fileName;

    // fileSize in bytes.
    public long fileSize;

    /**
     * Constructor.
     */
    public FileDetail() {

    }
}

What is the proper REST response code for a valid request but an empty data?

I'd say, neither is really appropriate. As has been said – e.g. by @anneb, I, too, think that part of the problems arises from using an HTTP response code to transport a status relating to a RESTful service. Anything the REST service has to say about its own processing should be transported by means of REST specific codes.

1

I'd argue that, if the HTTP server finds any service that is ready to answer a request it was sent, it should not respond with an HTTP 404 – in the end, something was found by the server – unless told so explicitly by the service that processes the request.

Let's assume for a moment the following URL: http://example.com/service/return/test.

  • Case A is that the server is “simply looking for the file on the file system“. If it is not present, 404 is correct. The same is true, if it asks some kind of service to deliver exactly this file and that service tells it that nothing of that name exists.
  • In case B, the server does not work with “real” files but actually the request is processed by some other service – e.g. some kind of templating system. Here, the server cannot make any claim about the existence of the resource as it knows nothing about it (unless told by the service handling it).

Without any response from the service explicitly requiring a different behaviour, the HTTP server can only say 3 things:

  • 503 if the service that is supposed to handle the request is not running or responding;
  • 200 otherwise as the HTTP server can actually satisfy the request – no matter what the service will say later;
  • 400 or 404 to indicate that there is no such service (as opposed to “exists but offline”) and nothing else was found.

2

To get back to the question at hand: I think the cleanest approach would be to not use an HTTP any response code at all other than said before. If the service is present and responding, the HTTP code should be 200. The response should contain the status the service returned in a separate header – here, the service can say

  • REST:EMPTY e.g. if it was asked to search for sth. and that research returned empty;
  • REST:NOT FOUND if it was asked specifically for sth. “ID-like” – be that a file name or a resource by ID or entry No. 24, etc. – and that specific resource was not found (usually, one specific resource was requested and not found);
  • REST:INVALID if any part of the request it was sent is not recognized by the service.

(note that I prefixed these with “REST:” on purpose to mark the fact that while these may have the same values or wording as do HTTP response codes, they are sth. completely different)

3

Let's get back to the URL above and inspect case B where service indicates to the HTTP server that it does not handle this request itself but passes it on to SERVICE. HTTP only serves out what it is handed back by SERVICE, it does not know anything about the return/test portion as that is handeled by SERVICE. If that service is running, HTTP should return 200 as it did indeed find something to handle the request.

The status returned by SERVICE (and which, as said above, would like to see in a separate header) depends on what action is actually expected:

  • if return/test asks for a specific resource: if it exists, return it with a status of REST:FOUND; if that resource does not exist, return REST:NOT FOUND; this could be extended to return REST:GONE if we know it once existed and will not return, and REST:MOVED if we know it has gone hollywood
  • if return/test is considered a search or filter-like operation: if the result set is empty, return an empty set in the type requested and a status of REST:EMPTY; a set of results in the type requested and a status of REST:SUCCESS
  • if return/test is not an operation recogized by SERVICE: return REST:ERROR if it is completely wrong (e.g. a typo like retrun/test), or REST:NOT IMPLEMENTED in case it is planned for later.

4

This distinction is a lot cleaner than mixing the two different things up. It will also make debugging easier and processing only slightly more complex, if at all.

  • If an HTTP 404 is returned, the server tells me, “I have no idea what you're talking about”. While the REST portion of my request might be perectly okay, I'm looking for par'Mach in all the wrong places.
  • On the other hand, HTTP 200 and REST:ERR tells me I got the service but did something wrong in my request to the service.
  • From HTTP 200 and REST:EMPTY, I know that I did nothing wrong – right server, the server found the service, right request to the service – but the search result is empty.

Summary

The problem and discussion arises from the fact that HTTP response codes are being used to denote the state of a service whose results are served by HTTP, or to denote sth. that is not in the scope of the HTTP server itself. Due to this discrepancy, the question cannot be answered and all opinions are subject to a lot of discussion.

The state of a request processed by a service and not the HTTP server REALLY SHOULD NOT (RFC 6919) be given by an HTTP response code. The HTTP code SHOULD (RFC 2119) only contain information the HTTP server can give from its own scope: namely, whether the service was found to process the request or not.

Instead, a different way SHOULD be used to tell a consumer about the state of the request to the service that is actually processing the request. My proposal is to do so via a specific header. Ideally, both the name of the header and its contents follow a standard that makes it easy for consumers to work with theses responses.

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

JavaScript: set dropdown selected item based on option text

var textToFind = 'Google';

var dd = document.getElementById('MyDropDown');
for (var i = 0; i < dd.options.length; i++) {
    if (dd.options[i].text === textToFind) {
        dd.selectedIndex = i;
        break;
    }
}

Vue.js redirection to another page

just use:

window.location.href = "http://siwei.me"

Don't use vue-router, otherwise you will be redirected to "http://yoursite.com/#!/http://siwei.me"

my environment: node 6.2.1, vue 1.0.21, Ubuntu.

jQuery onclick toggle class name

It can even be made dependent to another attribute changes. like this:

$('.classA').toggleClass('classB', $('input').prop('disabled'));

In this case, classB are added each time the input is disabled

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

Problems when trying to load a package in R due to rJava

Its because either one of the Java versions(32 bit/64 bit) is missing from your computer. Try installing both the Jdks and run the code.
After installing the Jdks open R and type the code

system("java -version")

This will give you the version of Jdk installed. Then try loading the rJava package. This worked for me.

Error using eclipse for Android - No resource found that matches the given name

I resolved this kind of issue like this: I went into my XML layout file, cut the line of code that was generating the error. Then I saved the file, and pasted the code back in. The error was gone.

How can I insert data into a MySQL database?

#Server Connection to MySQL:

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
                  user="root",
                  passwd="newpassword",
                  db="engy1")
x = conn.cursor()

try:
   x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
   conn.commit()
except:
   conn.rollback()

conn.close()

edit working for me:

>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>> 
>>> #setup cursor
... cursor = db.cursor()
>>> 
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>> 
>>> sql = """CREATE TABLE anooog1 (
...          COL1 INT,  
...          COL2 INT )"""
>>> cursor.execute(sql)
0L
>>> 
>>> #insert to table
... try:
...     cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
...     db.commit()
... except:     
...     db.rollback()
... 
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>> 
>>> db.close()

table in mysql;

mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
|  188 |   90 |
+------+------+
1 row in set (0.00 sec)

mysql> 

DOS: find a string, if found then run another script

We have two commands, first is "condition_command", second is "result_command". If we need run "result_command" when "condition_command" is successful (errorlevel=0):

condition_command && result_command

If we need run "result_command" when "condition_command" is fail:

condition_command || result_command

Therefore for run "some_command" in case when we have "string" in the file "status.txt":

find "string" status.txt 1>nul && some_command

in case when we have not "string" in the file "status.txt":

find "string" status.txt 1>nul || some_command

Get the list of stored procedures created and / or modified on a particular date?

For SQL Server 2012:

SELECT name, modify_date, create_date, type
FROM sys.procedures
WHERE name like '%XXX%' 
ORDER BY modify_date desc

Retrieve WordPress root directory path?

If you have WordPress bootstrap loaded you can use get_home_path() function to get path to the WordPress root directory.

How do I add an element to a list in Groovy?

From the documentation:

We can add to a list in many ways:

assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
    //equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]

def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]

list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]

list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']

You can also do:

def myNewList = myList << "fifth"

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

Simple way to set it in visual studio IDE.

Project > Properties> Debug > Environment variables

enter image description here

How can I align all elements to the left in JPanel?

The easiest way I've found to place objects on the left is using FlowLayout.

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));

adding a component normally to this panel will place it on the left

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

Build Android Studio app via command line

Cheatsheet for running Gradle from the command line for Android Studio projects on Linux:

cd <project-root>
./gradlew
./gradlew tasks
./gradlew --help

Should get you started..

Creating a thumbnail from an uploaded image

function getExtension($str) 
    {

          $i = strrpos($str,".");
         if (!$i) { return ""; } 

         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
    }

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
    {
        $name = $_FILES['photoimg']['name'];
        $size = $_FILES['photoimg']['size'];

        if(strlen($name))
            {
                 $ext = getExtension($name);
                if(in_array($ext,$valid_formats))
                {
                if($size<(1024*1024))
                    {
                        $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
                        $tmp = $_FILES['photoimg']['tmp_name'];
                        if(move_uploaded_file($tmp, $path.$actual_image_name))
                            {


                            mysql_query("INSERT INTO users (uid, profile_image) VALUES ('$session_id' , '$actual_image_name')");

                                echo "<img src='uploads/".$actual_image_name."'  class='preview'>";
                            }
                        else
                            echo "Fail upload folder with read access.";
                    }
                    else
                    echo "Image file size max 1 MB";                    
                    }
                    else
                    echo "Invalid file format..";   
            }

        else
            echo "Please select image..!";

        exit;
    }

How can I use a JavaScript variable as a PHP variable?

You can do what you want, but not like that. What you need to do is make an AJAX request from JavaScript back to the server where a separate PHP script can do the database operation.

Java getHours(), getMinutes() and getSeconds()

Try this:

Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);

Edit:

hours, minutes, seconds

above will be the hours, minutes and seconds after converting yourdate to System Timezone!

Android Saving created bitmap to directory on sd card

Pass bitmap to the saveImage Method, It will save your bitmap in the name of a saveBitmap, inside created test folder.

private void saveImage(Bitmap data) {
                    File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test");
                    if(!createFolder.exists())
                    createFolder.mkdir();
                    File saveImage = new File(createFolder,"saveBitmap.jpg");
                    try {
                        OutputStream outputStream = new FileOutputStream(saveImage);
                        data.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
                        outputStream.flush();
                        outputStream.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

and use this:

  saveImage(bitmap);

Selecting last element in JavaScript array

This worked:

array.reverse()[0]

How to print to console using swift playground?

move you mouse over the "Hello, playground" on the right side bar, you will see an eye icon and a small circle icon next it. Just click on the circle one to show the detail page and console output!

Drawing circles with System.Drawing

PictureBox circle = new PictureBox();
circle.Paint += new PaintEventHandler(circle_Paint);        

void circle_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawEllipse(Pens.Red, 0, 0, 30, 30);
        }

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

I had a slight different solution to this problem. my PATH and JAVA_HOME were pointing to JDK12 in

C:\Program Files\Java

but execution of the command:

Java -version

gave the error:

Error: could not open `C:\ProgramFiles\Java\jre1.8.0_212\lib\amd64\jvm.cfg'

I had to delete a folder of executables (Java.exe, javaw.exe etc.) in a different directory than System32, as other answers here and blog posts have suggested. Instead I found the problem lied with executables found in:

C:\Program Files\Common Files\Oracle 

as there was nothing Java related in

C:\Windows\System32

If you're having this issue and nothing is in System32, check this "common files" directory mentioned above for an oracle directory and delete it.

After, your PATH references should work fine!

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

You can use:

window.location.href = '/Branch/Details/' + id;

But your Ajax code is incomplete without success or error functions.

Is it possible to make input fields read-only through CSS?

Hope this will help.

    input[readonly="readonly"]
{
    background-color:blue;
}

reference:

http://jsfiddle.net/uzyH5/1/

Difference between InvariantCulture and Ordinal string comparison

Always try to use InvariantCulture in those string methods that accept it as overload. By using InvariantCulture you are on a safe side. Many .NET programmers may not use this functionality but if your software will be used by different cultures, InvariantCulture is an extremely handy feature.

Android custom Row Item for ListView

Step 1:Create a XML File

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


        <ListView
            android:id="@+id/lvItems"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />
    </LinearLayout>

Step 2:Studnet.java

package com.scancode.acutesoft.telephonymanagerapp;


public class Student
{
    String email,phone,address;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Step 3:MainActivity.java

 package com.scancode.acutesoft.telephonymanagerapp;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.ListView;

    import java.util.ArrayList;

    public class MainActivity extends Activity  {

        ListView lvItems;
        ArrayList<Student> studentArrayList ;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            lvItems = (ListView) findViewById(R.id.lvItems);
            studentArrayList = new ArrayList<Student>();
            dataSaving();
            CustomAdapter adapter = new CustomAdapter(MainActivity.this,studentArrayList);
            lvItems.setAdapter(adapter);
        }

        private void dataSaving() {

            Student student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Hyderabad");
            studentArrayList.add(student);


            student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Banglore");
            studentArrayList.add(student);

            student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Banglore");
            studentArrayList.add(student);

            student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Banglore");
            studentArrayList.add(student);
        }


    }

Step 4:CustomAdapter.java

  package com.scancode.acutesoft.telephonymanagerapp;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    import java.util.ArrayList;


    public class CustomAdapter extends BaseAdapter
    {
        ArrayList<Student> studentList;
        Context mContext;


        public CustomAdapter(Context context, ArrayList<Student> studentArrayList) {
            this.mContext = context;
            this.studentList = studentArrayList;

        }

        @Override
        public int getCount() {
            return studentList.size();
        }
        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            Student student = studentList.get(position);
            convertView = LayoutInflater.from(mContext).inflate(R.layout.student_row,null);

            TextView tvStudEmail = (TextView) convertView.findViewById(R.id.tvStudEmail);
            TextView tvStudPhone = (TextView) convertView.findViewById(R.id.tvStudPhone);
            TextView tvStudAddress = (TextView) convertView.findViewById(R.id.tvStudAddress);

            tvStudEmail.setText(student.getEmail());
            tvStudPhone.setText(student.getPhone());
            tvStudAddress.setText(student.getAddress());


            return convertView;
        }
    }

How can I check if a program exists from a Bash script?

There are a ton of options here, but I was surprised no quick one-liners. This is what I used at the beginning of my scripts:

[[ "$(command -v mvn)" ]] || { echo "mvn is not installed" 1>&2 ; exit 1; }
[[ "$(command -v java)" ]] || { echo "java is not installed" 1>&2 ; exit 1; }

This is based on the selected answer here and another source.

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

Delete a row in Excel VBA

Chris Nielsen's solution is simple and will work well. A slightly shorter option would be...

ws.Rows(Rand).Delete

...note there is no need to specify a Shift when deleting a row as, by definition, it's not possible to shift left

Incidentally, my preferred method for deleting rows is to use...

ws.Rows(Rand) = ""

...in the initial loop. I then use a Sort function to push these rows to the bottom of the data. The main reason for this is because deleting single rows can be a very slow procedure (if you are deleting >100). It also ensures nothing gets missed as per Robert Ilbrink's comment

You can learn the code for sorting by recording a macro and reducing the code as demonstrated in this expert Excel video. I have a suspicion that the neatest method (Range("A1:Z10").Sort Key1:=Range("A1"), Order1:=xlSortAscending/Descending, Header:=xlYes/No) can only be discovered on pre-2007 versions of Excel...but you can always reduce the 2007/2010 equivalent code

Couple more points...if your list is not already sorted by a column and you wish to retain the order, you can stick the row number 'Rand' in a spare column to the right of each row as you loop through. You would then sort by that comment and eliminate it

If your data rows contain formatting, you may wish to find the end of the new data range and delete the rows that you cleared earlier. That's to keep the file size down. Note that a single large delete at the end of the procedure will not impair your code's performance in the same way that deleting single rows does

How to tell whether a point is to the right or left side of a line

The vector (y1 - y2, x2 - x1) is perpendicular to the line, and always pointing right (or always pointing left, if you plane orientation is different from mine).

You can then compute the dot product of that vector and (x3 - x1, y3 - y1) to determine if the point lies on the same side of the line as the perpendicular vector (dot product > 0) or not.

How do I iterate through lines in an external file with shell?

One way would be:

while read NAME
do
    echo "$NAME"
done < names.txt

EDIT: Note that the loop gets executed in a sub-shell, so any modified variables will be local, except if you declare them with declare outside the loop.

Dennis Williamson is right. Sorry, must have used piped constructs too often and got confused.

Rails 4 - Strong Parameters - Nested Objects

I found this suggestion useful in my case:

  def product_params
    params.require(:product).permit(:name).tap do |whitelisted|
      whitelisted[:data] = params[:product][:data]
    end
  end

Check this link of Xavier's comment on github.

This approach whitelists the entire params[:measurement][:groundtruth] object.

Using the original questions attributes:

  def product_params
    params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
      whitelisted[:groundtruth] = params[:measurement][:groundtruth]
    end
  end

Get value from text area

use the val() method:

$(document).ready(function () {
    var j = $("textarea");
    if (j.val().length > 0) {
        alert(j.val());
    }
});

Setting the target version of Java in ant javac

You may also set {{ant.build.javac.target=1.5}} ant property to update default target version of task. See http://ant.apache.org/manual/javacprops.html#target

Return rows in random order

This is the simplest solution:

SELECT quote FROM quotes ORDER BY RAND() 

Although it is not the most efficient. This one is a better solution.

How can I print out just the index of a pandas dataframe?

You can access the index attribute of a df using .index:

In [277]:

df = pd.DataFrame({'a':np.arange(10), 'b':np.random.randn(10)})
df
Out[277]:
   a         b
0  0  0.293422
1  1 -1.631018
2  2  0.065344
3  3 -0.417926
4  4  1.925325
5  5  0.167545
6  6 -0.988941
7  7 -0.277446
8  8  1.426912
9  9 -0.114189
In [278]:

df.index
Out[278]:
Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')

Where are Magento's log files located?

You can find them in /var/log within your root Magento installation

There will usually be two files by default, exception.log and system.log.

If the directories or files don't exist, create them and give them the correct permissions, then enable logging within Magento by going to System > Configuration > Developer > Log Settings > Enabled = Yes

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

The way without re-inserting all entries into the new map should be the fastest it won't because HashMap.clone internally performs rehash as well.

Map<String, Column> newColumnMap = originalColumnMap.clone();
newColumnMap.replaceAll((s, c) -> new Column(c));

how to get file path from sd card in android

There are different Names of SD-Cards.

This Code check every possible Name (I don't guarantee that these are all names but the most are included)

It prefers the main storage.

 private String SDPath() {
    String sdcardpath = "";

    //Datas
    if (new File("/data/sdext4/").exists() && new File("/data/sdext4/").canRead()){
        sdcardpath = "/data/sdext4/";
    }
    if (new File("/data/sdext3/").exists() && new File("/data/sdext3/").canRead()){
        sdcardpath = "/data/sdext3/";
    }
    if (new File("/data/sdext2/").exists() && new File("/data/sdext2/").canRead()){
        sdcardpath = "/data/sdext2/";
    }
    if (new File("/data/sdext1/").exists() && new File("/data/sdext1/").canRead()){
        sdcardpath = "/data/sdext1/";
    }
    if (new File("/data/sdext/").exists() && new File("/data/sdext/").canRead()){
        sdcardpath = "/data/sdext/";
    }

    //MNTS

    if (new File("mnt/sdcard/external_sd/").exists() && new File("mnt/sdcard/external_sd/").canRead()){
        sdcardpath = "mnt/sdcard/external_sd/";
    }
    if (new File("mnt/extsdcard/").exists() && new File("mnt/extsdcard/").canRead()){
        sdcardpath = "mnt/extsdcard/";
    }
    if (new File("mnt/external_sd/").exists() && new File("mnt/external_sd/").canRead()){
        sdcardpath = "mnt/external_sd/";
    }
    if (new File("mnt/emmc/").exists() && new File("mnt/emmc/").canRead()){
        sdcardpath = "mnt/emmc/";
    }
    if (new File("mnt/sdcard0/").exists() && new File("mnt/sdcard0/").canRead()){
        sdcardpath = "mnt/sdcard0/";
    }
    if (new File("mnt/sdcard1/").exists() && new File("mnt/sdcard1/").canRead()){
        sdcardpath = "mnt/sdcard1/";
    }
    if (new File("mnt/sdcard/").exists() && new File("mnt/sdcard/").canRead()){
        sdcardpath = "mnt/sdcard/";
    }

    //Storages
    if (new File("/storage/removable/sdcard1/").exists() && new File("/storage/removable/sdcard1/").canRead()){
        sdcardpath = "/storage/removable/sdcard1/";
    }
    if (new File("/storage/external_SD/").exists() && new File("/storage/external_SD/").canRead()){
        sdcardpath = "/storage/external_SD/";
    }
    if (new File("/storage/ext_sd/").exists() && new File("/storage/ext_sd/").canRead()){
        sdcardpath = "/storage/ext_sd/";
    }
    if (new File("/storage/sdcard1/").exists() && new File("/storage/sdcard1/").canRead()){
        sdcardpath = "/storage/sdcard1/";
    }
    if (new File("/storage/sdcard0/").exists() && new File("/storage/sdcard0/").canRead()){
        sdcardpath = "/storage/sdcard0/";
    }
    if (new File("/storage/sdcard/").exists() && new File("/storage/sdcard/").canRead()){
        sdcardpath = "/storage/sdcard/";
    }
    if (sdcardpath.contentEquals("")){
        sdcardpath = Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    Log.v("SDFinder","Path: " + sdcardpath);
    return sdcardpath;
}

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.

You can use the following approach.

$data = [
    ['user_id'=>'Coder 1', 'subject_id'=> 4096],
    ['user_id'=>'Coder 2', 'subject_id'=> 2048],
    //...
];

Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach

In your case you already have the data within the $query variable.

Is there an equivalent for var_dump (PHP) in Javascript?

As the others said, you can use Firebug, and that will sort you out no worries on Firefox. Chrome & Safari both have a built-in developer console which has an almost identical interface to Firebug's console, so your code should be portable across those browsers. For other browsers, there's Firebug Lite.

If Firebug isn't an option for you, then try this simple script:

function dump(obj) {
    var out = '';
    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }

    alert(out);

    // or, if you wanted to avoid alerts...

    var pre = document.createElement('pre');
    pre.innerHTML = out;
    document.body.appendChild(pre)
}

I'd recommend against alerting each individual property: some objects have a LOT of properties and you'll be there all day clicking "OK", "OK", "OK", "O... dammit that was the property I was looking for".

Createuser: could not connect to database postgres: FATAL: role "tom" does not exist

sudo -u postgres createuser -s tom 

this should help you as this will happen if the administrator has not created a PostgreSQL user account for you. It could also be that you were assigned a PostgreSQL user name that is different from your operating system user name, in that case you need to use the -U switch.

Java Object Null Check for method

This question is quite older. The Questioner might have been turned into an experienced Java Developer by this time. Yet I want to add some opinion here which would help beginners.

For JDK 7 users, Here using

Objects.requireNotNull(object[, optionalMessage]);

is not safe. This function throws NullPointerException if it finds null object and which is a RunTimeException.

That will terminate the whole program!!. So better check null using == or !=.

Also, use List instead of Array. Although access speed is same, yet using Collections over Array has some advantages like if you ever decide to change the underlying implementation later on, you can do it flexibly. For example, if you need synchronized access, you can change the implementation to a Vector without rewriting all your code.

public static double calculateInventoryTotal(List<Book> books) {
    if (books == null || books.isEmpty()) {
        return 0;
    }

    double total = 0;

    for (Book book : books) {
        if (book != null) {
            total += book.getPrice();
        }
    }
    return total;
}

Also, I would like to upvote @1ac0 answer. We should understand and consider the purpose of the method too while writing. Calling method could have further logics to implement based on the called method's returned data.

Also if you are coding with JDK 8, It has introduced a new way to handle null check and protect the code from NullPointerException. It defined a new class called Optional. Have a look at this for detail

Finally, Pardon my bad English.

Multithreading in Bash

Sure, just add & after the command:

read_cfg cfgA &
read_cfg cfgB &
read_cfg cfgC &
wait

all those jobs will then run in the background simultaneously. The optional wait command will then wait for all the jobs to finish.

Each command will run in a separate process, so it's technically not "multithreading", but I believe it solves your problem.

How to set TLS version on apache HttpClient

If you are using httpclient 4.2, then you need to write a small bit of extra code. I wanted to be able to customize both the "TLS enabled protocols" (e.g. TLSv1.1 specifically, and neither TLSv1 nor TLSv1.2) as well as the cipher suites.

public class CustomizedSSLSocketFactory
    extends SSLSocketFactory
{
    private String[] _tlsProtocols;
    private String[] _tlsCipherSuites;

    public CustomizedSSLSocketFactory(SSLContext sslContext,
                                      X509HostnameVerifier hostnameVerifier,
                                      String[] tlsProtocols,
                                      String[] cipherSuites)
    {
        super(sslContext, hostnameVerifier);

        if(null != tlsProtocols)
            _tlsProtocols = tlsProtocols;
        if(null != cipherSuites)
            _tlsCipherSuites = cipherSuites;
    }

    @Override
    protected void prepareSocket(SSLSocket socket)
    {
        // Enforce client-specified protocols or cipher suites
        if(null != _tlsProtocols)
            socket.setEnabledProtocols(_tlsProtocols);

        if(null != _tlsCipherSuites)
            socket.setEnabledCipherSuites(_tlsCipherSuites);
    }
}

Then:

    SSLContext sslContext = SSLContext.getInstance("TLS");

    sslContext.init(null, getTrustManagers(), new SecureRandom());

    // NOTE: not javax.net.SSLSocketFactory
    SSLSocketFactory sf = new CustomizedSSLSocketFactory(sslContext,
                                                         null,
                                                         [TLS protocols],
                                                         [TLS cipher suites]);

    Scheme httpsScheme = new Scheme("https", 443, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);

    ConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);

    HttpClient client = new DefaultHttpClient(cmgr);
    ...

You may be able to do this with slightly less code, but I mostly copy/pasted from a custom component where it made sense to build-up the objects in the way shown above.

Stop Visual Studio from launching a new browser window when starting debug?

Open your startup project's properties (Project ? {ProjectName} Properties... from the main menu or right click your project in the Solution Explorer and choose Properties), then navigate to the Web tab and under Start Action choose Don't open a page. Wait for a request from an external application.

You will still be able to use any browser (or Fiddler, whatever) to access the running application, but it won't open the browser window automatically, it'll just start in the background and wait for any requests.

Can an AJAX response set a cookie?

For the record, be advised that all of the above is (still) true only if the AJAX call is made on the same domain. If you're looking into setting cookies on another domain using AJAX, you're opening a totally different can of worms. Reading cross-domain cookies does work, however (or at least the server serves them; whether your client's UA allows your code to access them is, again, a different topic; as of 2014 they do).

Find files with size in Unix

Assuming you have GNU find:

find . -size +10000k -printf '%s %f\n'

If you want a constant width for the size field, you can do something like:

find . -size +10000k -printf '%10s %f\n'

Note that -size +1000k selects files of at least 10,240,000 bytes (k is 1024, not 1000). You said in a comment that you want files bigger than 1M; if that's 1024*1024 bytes, then this:

find . -size +1M ...

will do the trick -- except that it will also print the size and name of files that are exactly 1024*1024 bytes. If that matters, you could use:

find . -size +1048575c ...

You need to decide just what criterion you want.

How to Get Element By Class in JavaScript?

I assume this was not a valid option when this was originally asked, but you can now use document.getElementsByClassName('');. For example:

var elements = document.getElementsByClassName(names); // or:
var elements = rootElement.getElementsByClassName(names);

See the MDN documentation for more.

Breaking out of nested loops

In this particular case, you can merge the loops with a modern python (3.0 and probably 2.6, too) by using itertools.product.

I for myself took this as a rule of thumb, if you nest too many loops (as in, more than 2), you are usually able to extract one of the loops into a different method or merge the loops into one, as in this case.

Google Maps API v3: How do I dynamically change the marker icon?

You can also use a circle as a marker icon, for example:

var oMarker = new google.maps.Marker({
    position: latLng,
    sName: "Marker Name",
    map: map,
    icon: {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 8.5,
        fillColor: "#F00",
        fillOpacity: 0.4,
        strokeWeight: 0.4
    },
});

and then, if you want to change the marker dynamically (like on mouseover), you can, for example:

oMarker.setIcon({
            path: google.maps.SymbolPath.CIRCLE,
            scale: 10,
            fillColor: "#00F",
            fillOpacity: 0.8,
            strokeWeight: 1
        })

How do I exclude all instances of a transitive dependency when using Gradle?

Your approach is correct. (Depending on the circumstances, you might want to use configurations.all { exclude ... }.) If these excludes really exclude more than a single dependency (I haven't ever noticed that when using them), please file a bug at http://forums.gradle.org, ideally with a reproducible example.

adb server version doesn't match this client

It would appear that the ADB daemon on the device (adbd) is disagreeing with the ADB server process on your host computer as to which version of the protocol they are speaking. Which version of the SDK are you running and what is the OS version on the device you are debugging?

What you might need to do is actually downgrade your version of the SDK tools so that the ADB daemon and process are in agreement. I thought the server process was completely backward compatible, but this could be one of those corner cases where it doesn't. Google doesn't advertise the fact that you can get their old SDK tools packages, but they can be found by looking in the archives area at http://developer.android.com.

How to pick element inside iframe using document.getElementById

document.getElementById('myframe1').contentWindow.document.getElementById('x')

Fiddle

contentWindow is supported by all browsers including the older versions of IE.

Note that if the iframe's src is from another domain, you won't be able to access its content due to the Same Origin Policy.

Read/Parse text file line by line in VBA

You Can use this code to read line by line in text file and You could also check about the first character is "*" then you can leave that..

Public Sub Test()

    Dim ReadData as String

    Open "C:\satheesh\myfile\file.txt" For Input As #1

    Do Until EOF(1) 
       Line Input #1, ReadData 'Adding Line to read the whole line, not only first 128 positions
    If Not Left(ReadData, 1) = "*" then
       '' you can write the variable ReadData into the database or file
    End If 

    Loop

    Close #1

End Sub

await vs Task.Wait - Deadlock?

Some important facts were not given in other answers:

"async await" is more complex at CIL level and thus costs memory and CPU time.

Any task can be canceled if the waiting time is unacceptable.

In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.

Using Task is more flexible then "async await".

Any sync functionality can by wrapped by async.

public async Task<ActionResult> DoAsync(long id) 
{ 
    return await Task.Run(() => { return DoSync(id); } ); 
} 

"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:

https://github.com/dotnet/runtime/issues/36063

I do not see why I'm must live with the code duplication for sync and async method or using hacks.

Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:

https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem

Sorry for my english.

Replacing objects in array

function getMatch(elem) {
    function action(ele, val) {
        if(ele === val){ 
            elem = arr2[i]; 
        }
    }

    for (var i = 0; i < arr2.length; i++) {
        action(elem.id, Object.values(arr2[i])[0]);
    }
    return elem;
}

var modified = arr1.map(getMatch);

Set Canvas size using javascript

Try this:

var setCanvasSize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}

What is the cleanest way to get the progress of JQuery ajax request?

jQuery has already implemented promises, so it's better to use this technology and not move events logic to options parameter. I made a jQuery plugin that adds progress promise and now it's easy to use just as other promises:

$.ajax(url)
  .progress(function(){
    /* do some actions */
  })
  .progressUpload(function(){
    /* do something on uploading */
  });

Check it out at github

How are iloc and loc different?

  • DataFrame.loc() : Select rows by index value
  • DataFrame.iloc() : Select rows by rows number

example :

  1. Select first 5 rows of a table, df1 is your dataframe

df1.iloc[:5]

  1. Select first A, B rows of a table, df1 is your dataframe

df1.loc['A','B']

Using pip behind a proxy with CNTLM

A simpler approach might be:

  1. Create a folder named "pip" in your $HOME directory.
  2. Create a file named "pip.ini" (Windows) or "pip.conf" (Linux) in the directory created in step 1
  3. Copy & paste the following lines under the pip.ini/pip.conf:

    [global]
    trusted-host = pypi.python.org
                   pypi.org
                   files.pythonhosted.org 
    

What does a bitwise shift (left or right) do and what is it used for?

Left Shift

x = x * 2^value (normal operation)

x << value (bit-wise operation)


x = x * 16 (which is the same as 2^4)

The left shift equivalent would be x = x << 4

Right Shift

x = x / 2^value (normal arithmetic operation)

x >> value (bit-wise operation)


x = x / 8 (which is the same as 2^3)

The right shift equivalent would be x = x >> 3

Python pandas: how to specify data types when reading an Excel file?

You just specify converters. I created an excel spreadsheet of the following structure:

names   ages
bob     05
tom     4
suzy    3

Where the "ages" column is formatted as strings. To load:

import pandas as pd

df = pd.read_excel('Book1.xlsx',sheetname='Sheet1',header=0,converters={'names':str,'ages':str})
>>> df
       names ages
   0   bob   05
   1   tom   4
   2   suzy  3

How do I find if a string starts with another string in Ruby?

The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.

Have a play with Rubular: http://rubular.com/

But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.

'abcdefg' =~  /\Aabc/ 

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

I'm using OS X v10.11.5 (El Capitan), and I tried setting JAVA_HOME and forcing the "correct" Java version via Maven. Nothing helped.

The problem happened when the OS X account was logged out while the application was still running. After logging in again, OS X opened the old terminal session with greyed-out history. I used the same terminal session to build the project, but failed with the unsupported class version error.

Cleaning the Maven project didn't help at all.

To solve the problem, I simply had to close the auto-opened terminal window and use a new one.

Add a pipe separator after items in an unordered list unless that item is the last on a line

Use :after pseudo selector. Look http://jsfiddle.net/A52T8/1/

<ul>
    <li>Dogs</li>
    <li>Cats</li>
    <li>Lions</li>
    <li>Tigers</li>
    <li>Zebras</li>
    <li>Giraffes</li>
    <li>Bears</li>
    <li>Hippopotamuses</li>
    <li>Antelopes</li>
    <li>Unicorns</li>
    <li>Seagulls</li>
</ul>

ul li { float: left; }
ul li:after { content: "|"; padding: 0 .5em; }

EDIT:

jQuery solution:

html:

<div>
    <ul id="animals">
        <li>Dogs</li>
        <li>Cats</li>
        <li>Lions</li>
        <li>Tigers</li>
        <li>Zebras</li>
        <li>Giraffes</li>
        <li>Bears</li>
        <li>Hippopotamuses</li>
        <li>Antelopes</li>
        <li>Unicorns</li>
        <li>Seagulls</li>
        <li>Monkey</li>
        <li>Hedgehog</li>
        <li>Chicken</li>
        <li>Rabbit</li>
        <li>Gorilla</li>
    </ul>
</div>

css:

div { width: 300px; }
ul li { float: left; border-right: 1px solid black; padding: 0 .5em; }
ul li:last-child { border: 0; }

jQuery

var maxWidth = 300, // Your div max-width
    totalWidth = 0;
$('#animals li').each(function(){
    var currentWidth = $(this).outerWidth(),
        nextWidth = $(this).next().outerWidth();
    totalWidth += currentWidth;
    if ( (totalWidth + nextWidth) > maxWidth ) {
        $(this).css('border', 'none');
        totalWidth = 0;
    }
});

Take a look here. I also added a few more animals. http://jsfiddle.net/A52T8/10/

Must issue a STARTTLS command first

smtp port and socketFactory has to be change

    String to = "[email protected]";
    String subject = "subject"
    String msg ="email text...."
    final String from ="[email protected]"
    final  String password ="senderPassword"


    Properties props = new Properties();  
    props.setProperty("mail.transport.protocol", "smtp");     
    props.setProperty("mail.host", "smtp.gmail.com");  
    props.put("mail.smtp.auth", "true");  
    props.put("mail.smtp.port", "465");  
    props.put("mail.debug", "true");  
    props.put("mail.smtp.socketFactory.port", "465");  
    props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");  
    props.put("mail.smtp.socketFactory.fallback", "false");  
    Session session = Session.getDefaultInstance(props,  
    new javax.mail.Authenticator() {
       protected PasswordAuthentication getPasswordAuthentication() {  
       return new PasswordAuthentication(from,password);  
   }  
   });  

   //session.setDebug(true);  
   Transport transport = session.getTransport();  
   InternetAddress addressFrom = new InternetAddress(from);  

   MimeMessage message = new MimeMessage(session);  
   message.setSender(addressFrom);  
   message.setSubject(subject);  
   message.setContent(msg, "text/plain");  
   message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  

   transport.connect();  
   Transport.send(message);  
   transport.close();
   }  

hope it will work for you..

Best practices to test protected methods with PHPUnit

You can indeed use __call() in a generic fashion to access protected methods. To be able to test this class

class Example {
    protected function getMessage() {
        return 'hello';
    }
}

you create a subclass in ExampleTest.php:

class ExampleExposed extends Example {
    public function __call($method, array $args = array()) {
        if (!method_exists($this, $method))
            throw new BadMethodCallException("method '$method' does not exist");
        return call_user_func_array(array($this, $method), $args);
    }
}

Note that the __call() method does not reference the class in any way so you can copy the above for each class with protected methods you want to test and just change the class declaration. You may be able to place this function in a common base class, but I haven't tried it.

Now the test case itself only differs in where you construct the object to be tested, swapping in ExampleExposed for Example.

class ExampleTest extends PHPUnit_Framework_TestCase {
    function testGetMessage() {
        $fixture = new ExampleExposed();
        self::assertEquals('hello', $fixture->getMessage());
    }
}

I believe PHP 5.3 allows you to use reflection to change the accessibility of methods directly, but I assume you'd have to do so for each method individually.

How to use jQuery Plugin with Angular 4?

You can use webpack to provide it. It will be then injected DOM automatically.

module.exports = {
  context: process.cwd(),
  entry: {
    something: [
      path.join(root, 'src/something.ts')
    ],
    vendor: ['jquery']
  },
  devtool: 'source-map',
  output: {
    path: path.join(root, '/dist/js'),
    sourceMapFilename: "[name].js.map",
    filename: '[name].js'
  },
  module: {
    rules: [
      {test: /\.ts$/, exclude: /node_modules/, loader: 'ts-loader'}
    ]
  },
  resolve: {
    extensions: ['.ts', '.es6', '.js', '.json']
  },
  plugins: [

    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    }),

  ]
};

sending email via php mail function goes to spam

If you are sending this through your own mail server you might need to add a "Sender" header which will contain an email address of from your own domain. Gmail will probably be spamming the email because the FROM address is a gmail address but has not been sent from their own server.

How to silence output in a Bash script?

Useful in scripts:


Get only the STDERR in a file, while hiding any STDOUT even if the program to hide isn't existing at all (does not ever hang parent script), this alone was working:

stty -echo && ./programMightNotExist 2> errors.log && stty echo

Detach completely and silence everything, even killing the parent script won't abort ./prog :

 ./prog </dev/null >/dev/null 2>&1 &

Android statusbar icons color

if you have API level smaller than 23 than you must use it this way. it worked for me declare this under v21/style.

<item name="colorPrimaryDark" tools:targetApi="23">@color/colorPrimary</item>
        <item name="android:windowLightStatusBar" tools:targetApi="23">true</item>

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

I solved the issue by configuring environment.rb as

YourApp::Application.default_url_options = YourApp::Application.config.action_mailer.default_url_options

You need to set default_url_options for action mailer against each environment like development, testing, staging and production etc.

Reference: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

How to plot vectors in python using matplotlib

What did you expect the following to do?

v1 = [0,0],[M[i,0],M[i,1]]
v1 = [M[i,0]],[M[i,1]]

This is making two different tuples, and you overwrite what you did the first time... Anyway, matplotlib does not understand what a "vector" is in the sense you are using. You have to be explicit, and plot "arrows":

In [5]: ax = plt.axes()

In [6]: ax.arrow(0, 0, *v1, head_width=0.05, head_length=0.1)
Out[6]: <matplotlib.patches.FancyArrow at 0x114fc8358>

In [7]: ax.arrow(0, 0, *v2, head_width=0.05, head_length=0.1)
Out[7]: <matplotlib.patches.FancyArrow at 0x115bb1470>

In [8]: plt.ylim(-5,5)
Out[8]: (-5, 5)

In [9]: plt.xlim(-5,5)
Out[9]: (-5, 5)

In [10]: plt.show()

Result:

enter image description here

How to generate a random integer number from within a range

While Ryan is correct, the solution can be much simpler based on what is known about the source of the randomness. To re-state the problem:

  • There is a source of randomness, outputting integer numbers in range [0, MAX) with uniform distribution.
  • The goal is to produce uniformly distributed random integer numbers in range [rmin, rmax] where 0 <= rmin < rmax < MAX.

In my experience, if the number of bins (or "boxes") is significantly smaller than the range of the original numbers, and the original source is cryptographically strong - there is no need to go through all that rigamarole, and simple modulo division would suffice (like output = rnd.next() % (rmax+1), if rmin == 0), and produce random numbers that are distributed uniformly "enough", and without any loss of speed. The key factor is the randomness source (i.e., kids, don't try this at home with rand()).

Here's an example/proof of how it works in practice. I wanted to generate random numbers from 1 to 22, having a cryptographically strong source that produced random bytes (based on Intel RDRAND). The results are:

Rnd distribution test (22 boxes, numbers of entries in each box):     
 1: 409443    4.55%
 2: 408736    4.54%
 3: 408557    4.54%
 4: 409125    4.55%
 5: 408812    4.54%
 6: 409418    4.55%
 7: 408365    4.54%
 8: 407992    4.53%
 9: 409262    4.55%
10: 408112    4.53%
11: 409995    4.56%
12: 409810    4.55%
13: 409638    4.55%
14: 408905    4.54%
15: 408484    4.54%
16: 408211    4.54%
17: 409773    4.55%
18: 409597    4.55%
19: 409727    4.55%
20: 409062    4.55%
21: 409634    4.55%
22: 409342    4.55%   
total: 100.00%

This is as close to uniform as I need for my purpose (fair dice throw, generating cryptographically strong codebooks for WWII cipher machines such as http://users.telenet.be/d.rijmenants/en/kl-7sim.htm, etc). The output does not show any appreciable bias.

Here's the source of cryptographically strong (true) random number generator: Intel Digital Random Number Generator and a sample code that produces 64-bit (unsigned) random numbers.

int rdrand64_step(unsigned long long int *therand)
{
  unsigned long long int foo;
  int cf_error_status;

  asm("rdrand %%rax; \
        mov $1,%%edx; \
        cmovae %%rax,%%rdx; \
        mov %%edx,%1; \
        mov %%rax, %0;":"=r"(foo),"=r"(cf_error_status)::"%rax","%rdx");
        *therand = foo;
  return cf_error_status;
}

I compiled it on Mac OS X with clang-6.0.1 (straight), and with gcc-4.8.3 using "-Wa,q" flag (because GAS does not support these new instructions).

What does the 'u' symbol mean in front of string values?

The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.

You can create a Unicode string multiple ways:

>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'

But the real reason is to represent something like this (translation here):

>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????

For the most part, Unicode and non-Unicode strings are interoperable on Python 2.

There are other symbols you will see, such as the "raw" symbol r for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.

>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'

Unicode and non-Unicode strings can be equal on Python 2:

>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True

but not on Python 3:

>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False

Pandas sum by groupby, but exclude certain columns

If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:

columns = ['Y'+str(i) for year in range(1967, 2011)]

df.groupby('Country')[columns].agg('sum')

mysql select from n last rows

Might be a very late answer, but this is good and simple.

select * from table_name order by id desc limit 5

This query will return a set of last 5 values(last 5 rows) you 've inserted in your table

Does "git fetch --tags" include "git fetch"?

git fetch upstream --tags

works just fine, it will only get new tags and will not get any other code base.

Import CSV file into SQL Server

Because they do not use the SQL import wizard, the steps would be as follows:

enter image description here

  1. Right click on the database in the option tasks to import data,

  2. Once the wizard is open, we select the type of data to be implied. In this case it would be the

Flat file source

We select the CSV file, you can configure the data type of the tables in the CSV, but it is best to bring it from the CSV.

  1. Click Next and select in the last option that is

SQL client

Depending on our type of authentication we select it, once this is done, a very important option comes.

  1. We can define the id of the table in the CSV (it is recommended that the columns of the CSV should be called the same as the fields in the table). In the option Edit Mappings we can see the preview of each table with the column of the spreadsheet, if we want the wizard to insert the id by default we leave the option unchecked.

Enable id insert

(usually not starting from 1), instead if we have a column with the id in the CSV we select the enable id insert, the next step is to end the wizard, we can review the changes here.

On the other hand, in the following window may come alerts, or warnings the ideal is to ignore this, only if they leave error is necessary to pay attention.

This link has images.

DateTime and CultureInfo

Use CultureInfo class to change your culture info.

var dutchCultureInfo = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCultureInfo);

C/C++ check if one bit is set in, i.e. int variable

Why not use something as simple as this?

uint8_t status = 255;
cout << "binary: ";

for (int i=((sizeof(status)*8)-1); i>-1; i--)
{
  if ((status & (1 << i)))
  {
    cout << "1";
  } 
  else
  {
    cout << "0";
  }
}

OUTPUT: binary: 11111111

Detect the Internet connection is offline?

an ajax call to your domain is the easiest way to detect if you are offline

$.ajax({
      type: "HEAD",
      url: document.location.pathname + "?param=" + new Date(),
      error: function() { return false; },
      success: function() { return true; }
   });

this is just to give you the concept, it should be improved.

E.g. error=404 should still mean that you online

Inserting HTML into a div

I using "+" (plus) to insert div to html :

document.getElementById('idParent').innerHTML += '<div id="idChild"> content html </div>';

Hope this help.

Closing Twitter Bootstrap Modal From Angular Controller

You can do it with a simple jquery code.

$('#Mymodal').modal('hide');

What does "export default" do in JSX?

Simplest Understanding for default export is

Export is ES6's feature which is used to Export a module(file) and use it in some other module(file).

Default Export:

  1. default export is the convention if you want to export only one object(variable, function, class) from the file(module).
  2. There could be only one default export per file, but not restricted to only one export.
  3. When importing default exported object we can rename it as well.

Export or Named Export:

  1. It is used to export the object(variable, function, calss) with the same name.

  2. It is used to export multiple objects from one file.

  3. It cannot be renamed when importing in another file, it must have the same name that was used to export it, but we can create its alias by using as operator.

In React, Vue and many other frameworks the Export is mostly used to export reusable components to make modular based applications.

Parse usable Street Address, City, State, Zip from a string

I've done this in the past.

Either do it manually, (build a nice gui that helps the user do it quickly) or have it automated and check against a recent address database (you have to buy that) and manually handle errors.

Manual handling will take about 10 seconds each, meaning you can do 3600/10 = 360 per hour, so 4000 should take you approximately 11-12 hours. This will give you a high rate of accuracy.

For automation, you need a recent US address database, and tweak your rules against that. I suggest not going fancy on the regex (hard to maintain long-term, so many exceptions). Go for 90% match against the database, do the rest manually.

Do get a copy of Postal Addressing Standards (USPS) at http://pe.usps.gov/cpim/ftp/pubs/Pub28/pub28.pdf and notice it is 130+ pages long. Regexes to implement that would be nuts.

For international addresses, all bets are off. US-based workers would not be able to validate.

Alternatively, use a data service. I have, however, no recommendations.

Furthermore: when you do send out the stuff in the mail (that's what it's for, right?) make sure you put "address correction requested" on the envelope (in the right place) and update the database. (We made a simple gui for the front desk person to do that; the person who actually sorts through the mail)

Finally, when you have scrubbed data, look for duplicates.

Altering user-defined table types in SQL Server

You should drop the old table type and create a new one. However if it has any dependencies (any stored procedures using it) you won't be able to drop it. I've posted another answer on how to automate the process of temporary dropping all stored procedures, modifying the table table and then restoring the stored procedures.

How to quickly drop a user with existing privileges

There is no REVOKE ALL PRIVILEGES ON ALL VIEWS, so I ended with:

do $$
DECLARE r record;
begin
  for r in select * from pg_views where schemaname = 'myschem'
  loop
    execute 'revoke all on ' || quote_ident(r.schemaname) ||'.'|| quote_ident(r.viewname) || ' from "XUSER"';
  end loop;
end $$;

and usual:

REVOKE ALL PRIVILEGES ON DATABASE mydb FROM "XUSER";
REVOKE ALL PRIVILEGES ON SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA myschem FROM "XUSER";

for the following to succeed:

drop role "XUSER";

Argument Exception "Item with Same Key has already been added"

This error is fairly self-explanatory. Dictionary keys are unique and you cannot have more than one of the same key. To fix this, you should modify your code like so:

Dictionary<string, string> rct3Features = new Dictionary<string, string>();
Dictionary<string, string> rct4Features = new Dictionary<string, string>();

foreach (string line in rct3Lines) 
{
    string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);

    if (!rct3Features.ContainsKey(items[0]))
    {
        rct3Features.Add(items[0], items[1]);
    }

    ////To print out the dictionary (to see if it works)
    //foreach (KeyValuePair<string, string> item in rct3Features)
    //{
    //    Console.WriteLine(item.Key + " " + item.Value);
    //}
}

This simple if statement ensures that you are only attempting to add a new entry to the Dictionary when the Key (items[0]) is not already present.

background: fixed no repeat not working on mobile

I found maybe best solution for parallax effect which work on all devices.

Main thing is to set all sections with z-index greater than parallax section.

And parallax image element to set fixed with max width and height

_x000D_
_x000D_
body, html { margin: 0px; }_x000D_
section {_x000D_
  position: relative; /* Important */_x000D_
  z-index: 1; /* Important */_x000D_
  width: 100%;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
section.blue { background-color: blue; }_x000D_
section.red { background-color: red; }_x000D_
_x000D_
section.parallax {_x000D_
  z-index: 0; /* Important */_x000D_
}_x000D_
_x000D_
section.parallax .image {_x000D_
  position: fixed; /* Important */_x000D_
  top: 0; /* Important */_x000D_
  left: 0; /* Important */_x000D_
  width: 100%; /* Important */_x000D_
  height: 100%; /* Important */_x000D_
  background-image: url(https://www.w3schools.com/css/img_fjords.jpg);_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center;_x000D_
  -webkit-background-size: cover;_x000D_
  -moz-background-size: cover;_x000D_
  -o-background-size: cover;_x000D_
  background-size: cover;_x000D_
}
_x000D_
<section class="blue"></section>_x000D_
<section class="parallax">_x000D_
  <div class="image"></div>_x000D_
</section>_x000D_
<section class="red"></section>
_x000D_
_x000D_
_x000D_

How to get the current working directory in Java?

What makes you think that c:\windows\system32 is not your current directory? The user.dir property is explicitly to be "User's current working directory".

To put it another way, unless you start Java from the command line, c:\windows\system32 probably is your CWD. That is, if you are double-clicking to start your program, the CWD is unlikely to be the directory that you are double clicking from.

Edit: It appears that this is only true for old windows and/or Java versions.

Serializing with Jackson (JSON) - getting "No serializer found"?

For Jackson to serialize that class, the SomeString field needs to either be public (right now it's package level isolation) or you need to define getter and setter methods for it.

Can you control how an SVG's stroke-width is drawn?

I don’t know how helpful will that be but in my case I just created another circle with border only and placed it “inside” the other shape.

Sending emails in Node.js?

Check out emailjs

After wasting lots of time on trying to make nodemailer work with large attachments, found emailjs and happy ever since.

It supports sending files by using normal File objects, and not huge Buffers as nodemailer requires. Means that you can link it to, f.e., formidable to pass the attachments from an html form to the mailer. It also supports queueing..

All in all, no idea why nodejitsu ppl chose nodemailer to base their version on, emailjs is just much more advanced.

Left join only selected columns in R with the merge() function

I think it's a little simpler to use the dplyr functions select and left_join ; at least it's easier for me to understand. The join function from dplyr are made to mimic sql arguments.

 library(tidyverse)

 DF2 <- DF2 %>%
   select(client, LO)

 joined_data <- left_join(DF1, DF2, by = "Client")

You don't actually need to use the "by" argument in this case because the columns have the same name.

How to correctly represent a whitespace character

Using regular expressions, you can represent any whitespace character with the metacharacter "\s"

MSDN Reference

How to correctly dismiss a DialogFragment?

I found that when my fragment was defined in the navigation graph with a <fragment> tag (for a full screen dialogfragment), the dialogfragment would not dismiss with the dismiss() command. Instead, I had to pop the back stack:

findNavController(getActivity(), R.id.nav_host_fragment).popBackStack();

However, if the same dialogfragment was defined in the navigation graph with a <dialog> tag, dismiss() works fine.

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

The solution is to change the DropDownStyle property to DropDownList. It will help.

Creating a random string with A-Z and 0-9 in Java

RandomStringUtils from Apache commons-lang might help:

RandomStringUtils.randomAlphanumeric(17).toUpperCase()

2017 update: RandomStringUtils has been deprecated, you should now use RandomStringGenerator.

How to identify and switch to the frame in selenium webdriver when frame does not have id

driver.switchTo().frame() has multiple overloads.

  1. driver.switchTo().frame(name_or_id)
    Here your iframe doesn't have id or name, so not for you.

  2. driver.switchTo().frame(index)
    This is the last option to choose, because using index is not stable enough as you could imagine. If this is your only iframe in the page, try driver.switchTo().frame(0)

  3. driver.switchTo().frame(iframe_element)
    The most common one. You locate your iframe like other elements, then pass it into the method.

Here locating it by title attributes seems to be the best.

driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));
// driver.switchTo().frame(driver.findElement(By.xpath(".//iframe[@title='Fill Quote']")));

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

 function convertDatePickerTimeToMySQLTime(str) {
        var month, day, year, hours, minutes, seconds;
        var date = new Date(str),
            month = ("0" + (date.getMonth() + 1)).slice(-2),
            day = ("0" + date.getDate()).slice(-2);
        hours = ("0" + date.getHours()).slice(-2);
        minutes = ("0" + date.getMinutes()).slice(-2);
        seconds = ("0" + date.getSeconds()).slice(-2);

        var mySQLDate = [date.getFullYear(), month, day].join("-");
        var mySQLTime = [hours, minutes, seconds].join(":");
        return [mySQLDate, mySQLTime].join(" ");
    }

How do I animate constraint changes?

Generally, you just need to update constraints and call layoutIfNeeded inside the animation block. This can be either changing the .constant property of an NSLayoutConstraint, adding remove constraints (iOS 7), or changing the .active property of constraints (iOS 8 & 9).

Sample Code:

[UIView animateWithDuration:0.3 animations:^{
    // Move to right
    self.leadingConstraint.active = false;
    self.trailingConstraint.active = true;

    // Move to bottom
    self.topConstraint.active = false;
    self.bottomConstraint.active = true;

    // Make the animation happen
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
}];

Sample Setup:

Xcode Project so sample animation project.

Controversy

There are some questions about whether the constraint should be changed before the animation block, or inside it (see previous answers).

The following is a Twitter conversation between Martin Pilkington who teaches iOS, and Ken Ferry who wrote Auto Layout. Ken explains that though changing constants outside of the animation block may currently work, it's not safe and they should really be change inside the animation block. https://twitter.com/kongtomorrow/status/440627401018466305

Animation:

Sample Project

Here's a simple project showing how a view can be animated. It's using Objective C and animates the view by changing the .active property of several constraints. https://github.com/shepting/SampleAutoLayoutAnimation

How does an SSL certificate chain bundle work?

The original order is in fact backwards. Certs should be followed by the issuing cert until the last cert is issued by a known root per IETF's RFC 5246 Section 7.4.2

This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it.

See also SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch for troubleshooting techniques.

But I still don't know why they wrote the spec so that the order matters.

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

html button to send email

As David notes, his suggestion does not actually fulfill the OP's request, which was an email with subject and message. It doesn't work because most, maybe all, combinations of browsers plus e-mail clients do not accept the subject and body attributes of the mailto: URI when supplied as a <form>'s action.

But here's a working example:

HTML (with Bootstrap styles):

<p><input id="subject" type="text" placeholder="type your subject here" 
    class="form-control"></p>
<p><input id="message" type="text" placeholder="type your message here" 
    class="form-control"></p>
<p><a id="mail-link" class="btn btn-primary">Create email</a></p>

JavaScript (with jQuery):

<script type="text/javascript">
    function loadEvents() {
        var mailString;
        function updateMailString() {
            mailString = '?subject=' + encodeURIComponent($('#subject').val())
                + '&body=' + encodeURIComponent($('#message').val());
            $('#mail-link').attr('href',  'mailto:[email protected]' + mailString);
        }
        $( "#subject" ).focusout(function() { updateMailString(); });
        $( "#message" ).focusout(function() { updateMailString(); });
        updateMailString();
    }
</script>

Notes:

  • The <form> element with associated action attribute is not used.
  • The <input> element of type button is also not used.
    • <a> styled as a button (here using Bootstrap) replaces <input type="button">
    • focusout() with updateMailString() is necessary because the <a> tag's href attribute does not automatically update when the input fields' values change.
    • updateMailString() is also called when document is loaded in case the input fields are prepopulated.
  • Also encodeURIComponent() is used to get characters such as the quotation mark (") across to Outlook.

In this approach, the mailto: URI is supplied (with subject and body attributes) in an a element's href tag. This works in all combinations of browsers and e-mail clients I have tested, which are recent (2015) versions of:

  • Browsers: Firefox/Win&OSX, Chrome/Win&OSX, IE/Win, Safari/OSX&iOS, Opera/OSX
  • E-mail clients: Outlook/Win, Mail.app/OSX&iOS, Sparrow/OSX

Bonus tip: In my use cases, I add some contextual text to the e-mail body. More often than not, I want that text to contain line breaks. %0D%0A (carriage return and linefeed) works in my tests.

Getting all types that implement an interface

There are many valid answers already but I'd like to add anther implementation as a Type extension and a list of unit tests to demonstrate different scenarios:

public static class TypeExtensions
{
    public static IEnumerable<Type> GetAllTypes(this Type type)
    {
        var typeInfo = type.GetTypeInfo();
        var allTypes = GetAllImplementedTypes(type).Concat(typeInfo.ImplementedInterfaces);
        return allTypes;
    }

    private static IEnumerable<Type> GetAllImplementedTypes(Type type)
    {
        yield return type;
        var typeInfo = type.GetTypeInfo();
        var baseType = typeInfo.BaseType;
        if (baseType != null)
        {
            foreach (var foundType in GetAllImplementedTypes(baseType))
            {
                yield return foundType;
            }
        }
    }
}

This algorithm supports the following scenarios:

public static class GetAllTypesTests
{
    public class Given_A_Sample_Standalone_Class_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        protected override void Given()
        {
            _sut = typeof(SampleStandalone);

            _expectedTypes =
                new List<Type>
                {
                    typeof(SampleStandalone),
                    typeof(object)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    public class Given_A_Sample_Abstract_Base_Class_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        protected override void Given()
        {
            _sut = typeof(SampleBase);

            _expectedTypes =
                new List<Type>
                {
                    typeof(SampleBase),
                    typeof(object)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    public class Given_A_Sample_Child_Class_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        protected override void Given()
        {
            _sut = typeof(SampleChild);

            _expectedTypes =
                new List<Type>
                {
                    typeof(SampleChild),
                    typeof(SampleBase),
                    typeof(object)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    public class Given_A_Sample_Base_Interface_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        protected override void Given()
        {
            _sut = typeof(ISampleBase);

            _expectedTypes =
                new List<Type>
                {
                    typeof(ISampleBase)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    public class Given_A_Sample_Child_Interface_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        protected override void Given()
        {
            _sut = typeof(ISampleChild);

            _expectedTypes =
                new List<Type>
                {
                    typeof(ISampleBase),
                    typeof(ISampleChild)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    public class Given_A_Sample_Implementation_Class_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        protected override void Given()
        {
            _sut = typeof(SampleImplementation);

            _expectedTypes =
                new List<Type>
                {
                    typeof(SampleImplementation),
                    typeof(SampleChild),
                    typeof(SampleBase),
                    typeof(ISampleChild),
                    typeof(ISampleBase),
                    typeof(object)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    public class Given_A_Sample_Interface_Instance_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        class Foo : ISampleChild { }

        protected override void Given()
        {
            var foo = new Foo();
            _sut = foo.GetType();

            _expectedTypes =
                new List<Type>
                {
                    typeof(Foo),
                    typeof(ISampleChild),
                    typeof(ISampleBase),
                    typeof(object)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    sealed class SampleStandalone { }
    abstract class SampleBase { }
    class SampleChild : SampleBase { }
    interface ISampleBase { }
    interface ISampleChild : ISampleBase { }
    class SampleImplementation : SampleChild, ISampleChild { }
}

Pyspark: display a spark data frame in a table format

Let's say we have the following Spark DataFrame:

df = sqlContext.createDataFrame(
    [
        (1, "Mark", "Brown"), 
        (2, "Tom", "Anderson"), 
        (3, "Joshua", "Peterson")
    ], 
    ('id', 'firstName', 'lastName')
)

There are typically three different ways you can use to print the content of the dataframe:

Print Spark DataFrame

The most common way is to use show() function:

>>> df.show()
+---+---------+--------+
| id|firstName|lastName|
+---+---------+--------+
|  1|     Mark|   Brown|
|  2|      Tom|Anderson|
|  3|   Joshua|Peterson|
+---+---------+--------+

Print Spark DataFrame vertically

Say that you have a fairly large number of columns and your dataframe doesn't fit in the screen. You can print the rows vertically - For example, the following command will print the top two rows, vertically, without any truncation.

>>> df.show(n=2, truncate=False, vertical=True)
-RECORD 0-------------
 id        | 1        
 firstName | Mark     
 lastName  | Brown    
-RECORD 1-------------
 id        | 2        
 firstName | Tom      
 lastName  | Anderson 
only showing top 2 rows

Convert to Pandas and print Pandas DataFrame

Alternatively, you can convert your Spark DataFrame into a Pandas DataFrame using .toPandas() and finally print() it.

>>> df_pd = df.toPandas()
>>> print(df_pd)
   id firstName  lastName
0   1      Mark     Brown
1   2       Tom  Anderson
2   3    Joshua  Peterson

Note that this is not recommended when you have to deal with fairly large dataframes, as Pandas needs to load all the data into memory. If this is the case, the following configuration will help when converting a large spark dataframe to a pandas one:

spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")

For more details you can refer to my blog post Speeding up the conversion between PySpark and Pandas DataFrames

Set UITableView content inset permanently

automaticallyAdjustsScrollViewInsets is deprecated in iOS11 (and the accepted solution no longer works). use:

if #available(iOS 11.0, *) {
    scrollView.contentInsetAdjustmentBehavior = .never
} else {
    automaticallyAdjustsScrollViewInsets = false
}

How to specify function types for void (not Void) methods in Java8?

Set return type to Void instead of void and return null

// Modify existing method
public static Void displayInt(Integer i) {
    System.out.println(i);
    return null;
}

OR

// Or use Lambda
myForEach(theList, i -> {System.out.println(i);return null;});

XML to CSV Using XSLT

Found an XML transform stylesheet here (wayback machine link, site itself is in german)

The stylesheet added here could be helpful:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1"/>

<xsl:strip-space elements="*" />

<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>",    </xsl:if>
<xsl:if test="position()  = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>&#xD;</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.

What does java:comp/env/ do?

After several attempts and going deep in Tomcat's source code I found out that the simple property useNaming="false" did the trick!! Now Tomcat resolves names java:/liferay instead of java:comp/env/liferay

Reset MySQL root password using ALTER USER statement after install on Mac

UPDATE user SET authentication_string=PASSWORD("MyPassWord") WHERE User='root'; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '("MyPassWord") WHERE User='root'' at line 1

Resolved with

ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';

Reference from below site

https://dev.mysql.com/doc/refman/8.0/en/resetting-permissions.html

req.body empty on posts

I believe this can solve app.use(express.json());

Android Layout Weight

i would suppose to set the EditTexts width to wrap_content and put the two buttons into a LinearLayout whose width is fill_parent and weight set to 1.

static function in C

When there is a need to restrict access to some functions, we'll use the static keyword while defining and declaring a function.

            /* file ab.c */ 
static void function1(void) 
{ 
  puts("function1 called"); 
} 
And store the following code in another file ab1.c

/* file ab1.c  */ 
int main(void) 
{ 
 function1();  
  getchar(); 
  return 0;   
} 
/* in this code, we'll get a "Undefined reference to function1".Because function 1 is declared static in file ab.c and can't be used in ab1.c */

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

How to show and update echo on same line

You can try this.. My own version of it..

funcc() {
while true ; do 
for i in \| \/ \- \\ \| \/ \- \\; do 
  echo -n -e "\r$1  $i  "
sleep 0.5
done  
#echo -e "\r                                                                                      "
[ -f /tmp/print-stat ] && break 2
done
}

funcc "Checking Kubectl" & &>/dev/null
sleep 5
touch /tmp/print-stat
echo -e "\rPrint Success                  "

How to programmatically set drawableLeft on Android button?

Following is the way to change the color of the left icon in edit text and set it in left side.

 Drawable img = getResources().getDrawable( R.drawable.user );
img.setBounds( 0, 0, 60, 60 );
mNameEditText.setCompoundDrawables(img,null, null, null);

int color = ContextCompat.getColor(this, R.color.blackColor);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    DrawableCompat.setTint(img, color);

} else {
    img.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}

Concatenate a list of pandas dataframes together

Given that all the dataframes have the same columns, you can simply concat them:

import pandas as pd
df = pd.concat(list_of_dataframes)

In a URL, should spaces be encoded using %20 or +?

Form data (for GET or POST) is usually encoded as application/x-www-form-urlencoded: this specifies + for spaces.

URLs are encoded as RFC 1738 which specifies %20.

In theory I think you should have %20 before the ? and + after:

example.com/foo%20bar?foo+bar

Getting the HTTP Referrer in ASP.NET

Use the Request.UrlReferrer property.

Underneath the scenes it is just checking the ServerVariables("HTTP_REFERER") property.

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

Sometimes adding a WCF Service Reference generates an empty reference.cs

If you recently added a collection to your project when this started to occur, the problem may be caused by two collections which have the same CollectionDataContract attribute:

[CollectionDataContract(Name="AItems", ItemName="A")]
public class CollectionA : List<A> { }

[CollectionDataContract(Name="AItems", ItemName="A")]  // Wrong
public class CollectionB : List<B> { }

I fixed the error by sweeping through my project and ensuring that every Name and ItemName attribute was unique:

[CollectionDataContract(Name="AItems", ItemName="A")]
public class CollectionA : List<A> { }

[CollectionDataContract(Name="BItems", ItemName="B")]  // Corrected
public class CollectionB : List<B> { }

Then I refreshed the service reference and everything worked again.

Linux command to print directory structure in the form of a tree

Since I was not too happy with the output of other (non-tree) answers (see my comment at Hassou's answer), I tried to mimic trees output a bit more.

It's similar to the answer of Robert but the horizontal lines do not all start at the beginning, but where there are supposed to start. Had to use perl though, but in my case, on the system where I don't have tree, perl is available.

ls -aR | grep ":$" | perl -pe 's/:$//;s/[^-][^\/]*\//    /g;s/^    (\S)/+-- \1/;s/(^    |    (?= ))/¦   /g;s/    (\S)/+-- \1/'

Output (shortened):

.
+-- fd
+-- net
¦   +-- dev_snmp6
¦   +-- nfsfs
¦   +-- rpc
¦   ¦   +-- auth.unix.ip
¦   +-- stat
¦   +-- vlan
+-- ns
+-- task
¦   +-- 1310
¦   ¦   +-- net
¦   ¦   ¦   +-- dev_snmp6
¦   ¦   ¦   +-- rpc
¦   ¦   ¦   ¦   +-- auth.unix.gid
¦   ¦   ¦   ¦   +-- auth.unix.ip
¦   ¦   ¦   +-- stat
¦   ¦   ¦   +-- vlan
¦   ¦   +-- ns

Suggestions to avoid the superfluous vertical lines are welcome :-)

I still like Ben's solution in the comment of Hassou's answer very much, without the (not perfectly correct) lines it's much cleaner. For my use case I additionally removed the global indentation and added the option to also ls hidden files, like so:

ls -aR | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//  /g'

Output (shortened even more):

.
  fd
  net
    dev_snmp6
    nfsfs
    rpc
      auth.unix.ip
    stat
    vlan
  ns

jquery json to string?

Most browsers have a native JSON object these days, which includes parse and stringify methods. So just try JSON.stringify({}) and see if you get "{}". You can even pass in parameters to filter out keys or to do pretty-printing, e.g. JSON.stringify({a:1,b:2}, null, 2) puts a newline and 2 spaces in front of each key.

JSON.stringify({a:1,b:2}, null, 2)

gives

"{\n  \"a\": 1,\n  \"b\": 2\n}"

which prints as

{
  "a": 1,
  "b": 2
}

As for the messing around part of your question, use the second parameter. From http://www.javascriptkit.com/jsref/json.shtml :

The replacer parameter can either be a function or an array of String/Numbers. It steps through each member within the JSON object to let you decide what value each member should be changed to. As a function it can return:

  • A number, string, or Boolean, which replaces the property's original value with the returned one.
  • An object, which is serialized then returned. Object methods or functions are not allowed, and are removed instead.
  • Null, which causes the property to be removed.

As an array, the values defined inside it corresponds to the names of the properties inside the JSON object that should be retained when converted into a JSON object.

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

A real problem often exists because any variables set inside will not be exported when that batch file finishes. So its not possible to export, which caused us issues. As a result, I just set the registry to ALWAYS used delayed expansion (I don't know why it's not the default, could be speed or legacy compatibility issue.)

calling parent class method from child class object in java

NOTE calling parent method via super will only work on parent class, If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();

interface Vehicle {
    //Non abstract method
    public default void printVehicleTypeName() { //default keyword can be used only in interface.
        System.out.println("Vehicle");
    }
}


class FordFigo extends FordImpl implements Vehicle, Ford {
    @Override
    public void printVehicleTypeName() { 
        System.out.println("Figo");
        Vehicle.super.printVehicleTypeName();
    }
}

Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.

Simple CSS: Text won't center in a button

Testing this in Chrome, you need to add

padding: 0px;

To the CSS.

Interfaces vs. abstract classes

Abstract classes and interfaces are semantically different, although their usage can overlap.

An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class.

An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.