Programs & Examples On #Ripple

Ripple is a Chrome plugin that emulates the PhoneGap APIs. It enables testing of applications that target mobile devices.

How to add icon to mat-icon-button

Just add the <mat-icon> inside mat-button or mat-raised-button. See the example below. Note that I am using material icon instead of your svg for demo purpose:

<button mat-button>
    <mat-icon>mic</mat-icon>
    Start Recording
</button>

OR

<button mat-raised-button color="accent">
    <mat-icon>mic</mat-icon>
    Start Recording
</button>

Here is a link to stackblitz demo.

'mat-form-field' is not a known element - Angular 5 & Material2

the problem is in the MatInputModule:

exports: [
    MatInputModule
  ]

mat-form-field must contain a MatFormFieldControl

I had this issue. I imported MatFormFieldModule at my main module, but forgot to add MatInputModule to the imports array, like so:

import { MatFormFieldModule, MatInputModule } from '@angular/material';

@NgModule({
    imports: [
        MatFormFieldModule,
        MatInputModule
    ]
})
export class AppModule { }

More info here.

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

I had a similar issue and solved after running these instructions!

npm install npm -g
npm install --save-dev @angular/cli@latest
npm install
npm start

Add ripple effect to my button with button background color?

setForeground is added in API level 23. Leverage the power of RevealAnimator in case u need to relay on foreground property !

 <View
   android:id="@+id/circular_reveal"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="@color/primaryMilk_22"
   android:elevation="@dimen/margin_20"
   android:visibility="invisible" />

With kotlin ext function, it's way osm !

fun View.circularReveal() {
    val cx: Int = width / 2
    val cy: Int = height / 2
    val finalRadius: Int =
        width.coerceAtLeast(height)
    val anim: Animator = ViewAnimationUtils.createCircularReveal(
        this,
        cx,
        cy,
        0f,
        finalRadius.toFloat()
    )
    anim.interpolator = AccelerateDecelerateInterpolator()
    anim.duration = 400
    isVisible = true
    anim.start()
    anim.doOnEnd {
        isVisible = false
    }
}

Angular2 get clicked element id

For TypeScript users:

    toggle(event: Event): void {
        let elementId: string = (event.target as Element).id;
        // do something with the id... 
    }

MySQL Incorrect datetime value: '0000-00-00 00:00:00'

I had a similar problem but in my case some line had the value NULL.

so first I update the table:

update `my_table`set modified = '1000-01-01 00:00:00' WHERE modified is null

problem solved, at least in my case.

How to set a ripple effect on textview or imageview on Android?

for circle ripple : android:background="?attr/selectableItemBackgroundBorderless"

for rectangle ripple : android:background="?attr/selectableItemBackground"

How to update RecyclerView Adapter Data?

This is a general answer for future visitors. The various ways to update the adapter data are explained. The process includes two main steps every time:

  1. Update the data set
  2. Notify the adapter of the change

#Insert single item

Add "Pig" at index 2.

Insert single item
String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);

#Insert multiple items

Insert three more animals at index 2.

Insert multiple items
ArrayList<String> items = new ArrayList<>();
items.add("Pig");
items.add("Chicken");
items.add("Dog");
int insertIndex = 2;
data.addAll(insertIndex, items);
adapter.notifyItemRangeInserted(insertIndex, items.size());

#Remove a single item

Remove "Pig" from the list.

Remove single item
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);

#Remove multiple items

Remove "Camel" and "Sheep" from the list.

Remove multiple items
int startIndex = 2; // inclusive
int endIndex = 4;   // exclusive
int count = endIndex - startIndex; // 2 items will be removed
data.subList(startIndex, endIndex).clear();
adapter.notifyItemRangeRemoved(startIndex, count);

#Remove all items

Clear the whole list.

Remove all items
data.clear();
adapter.notifyDataSetChanged();

#Replace old list with the new list

Clear the old list then add a new one.

Replace old list with new list
// clear old list
data.clear();

// add new list
ArrayList<String> newList = new ArrayList<>();
newList.add("Lion");
newList.add("Wolf");
newList.add("Bear");
data.addAll(newList);

// notify adapter
adapter.notifyDataSetChanged();

The adapter has a reference to data, so it is important that I didn't set data to a new object. Instead, I cleared the old items from data and then added the new ones.

#Update single item

Change the "Sheep" item so that it says "I like sheep."

Update single item
String newValue = "I like sheep.";
int updateIndex = 3;
data.set(updateIndex, newValue);
adapter.notifyItemChanged(updateIndex);

#Move single item

Move "Sheep" from position 3 to position 1.

Move single item
int fromPosition = 3;
int toPosition = 1;

// update data array
String item = data.get(fromPosition);
data.remove(fromPosition);
data.add(toPosition, item);

// notify adapter
adapter.notifyItemMoved(fromPosition, toPosition);

#Code

Here is the project code for your reference. The RecyclerView Adapter code can be found at this answer.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    List<String> data;
    MyRecyclerViewAdapter adapter;

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

        // data to populate the RecyclerView with
        data = new ArrayList<>();
        data.add("Horse");
        data.add("Cow");
        data.add("Camel");
        data.add("Sheep");
        data.add("Goat");

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvAnimals);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
                layoutManager.getOrientation());
        recyclerView.addItemDecoration(dividerItemDecoration);
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
    }

    public void onButtonClick(View view) {
        insertSingleItem();
    }

    private void insertSingleItem() {
        String item = "Pig";
        int insertIndex = 2;
        data.add(insertIndex, item);
        adapter.notifyItemInserted(insertIndex);
    }

    private void insertMultipleItems() {
        ArrayList<String> items = new ArrayList<>();
        items.add("Pig");
        items.add("Chicken");
        items.add("Dog");
        int insertIndex = 2;
        data.addAll(insertIndex, items);
        adapter.notifyItemRangeInserted(insertIndex, items.size());
    }

    private void removeSingleItem() {
        int removeIndex = 2;
        data.remove(removeIndex);
        adapter.notifyItemRemoved(removeIndex);
    }

    private void removeMultipleItems() {
        int startIndex = 2; // inclusive
        int endIndex = 4;   // exclusive
        int count = endIndex - startIndex; // 2 items will be removed
        data.subList(startIndex, endIndex).clear();
        adapter.notifyItemRangeRemoved(startIndex, count);
    }

    private void removeAllItems() {
        data.clear();
        adapter.notifyDataSetChanged();
    }

    private void replaceOldListWithNewList() {
        // clear old list
        data.clear();

        // add new list
        ArrayList<String> newList = new ArrayList<>();
        newList.add("Lion");
        newList.add("Wolf");
        newList.add("Bear");
        data.addAll(newList);

        // notify adapter
        adapter.notifyDataSetChanged();
    }

    private void updateSingleItem() {
        String newValue = "I like sheep.";
        int updateIndex = 3;
        data.set(updateIndex, newValue);
        adapter.notifyItemChanged(updateIndex);
    }

    private void moveSingleItem() {
        int fromPosition = 3;
        int toPosition = 1;

        // update data array
        String item = data.get(fromPosition);
        data.remove(fromPosition);
        data.add(toPosition, item);

        // notify adapter
        adapter.notifyItemMoved(fromPosition, toPosition);
    }
}

#Notes

  • If you use notifyDataSetChanged(), then no animation will be performed. This can also be an expensive operation, so it is not recommended to use notifyDataSetChanged() if you are only updating a single item or a range of items.
  • Check out DiffUtil if you are making large or complex changes to a list.

#Further study

Android changing Floating Action Button color

If you have a Floating Action Button with no drawable you can change the tint programmatically using:

fab.getBackground().mutate().setTint(ContextCompat.getColor(yourContext, R.color.anyColor));

Adjust icon size of Floating action button (fab)

As your content is 24dp x 24dp you should use 24dp icon. And then set android:scaleType="center" in your ImageButton to avoid auto resize.

Ripple effect on Android Lollipop CardView

For those searching for a solution to the issue of the ripple effect not working on a programmatically created CardView (or in my case custom view which extends CardView) being shown in a RecyclerView, the following worked for me. Basically declaring the XML attributes mentioned in the other answers declaratively in the XML layout file doesn't seem to work for a programmatically created CardView, or one created from a custom layout (even if root view is CardView or merge element is used), so they have to be set programmatically like so:

private class MadeUpCardViewHolder extends RecyclerView.ViewHolder {
    private MadeUpCardView cardView;

    public MadeUpCardViewHolder(View v){
        super(v);

        this.cardView = (MadeUpCardView)v;

        // Declaring in XML Layout doesn't seem to work in RecyclerViews
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int[] attrs = new int[]{R.attr.selectableItemBackground};
            TypedArray typedArray = context.obtainStyledAttributes(attrs);
            int selectableItemBackground = typedArray.getResourceId(0, 0);
            typedArray.recycle();

            this.cardView.setForeground(context.getDrawable(selectableItemBackground));
            this.cardView.setClickable(true);
        }
    }
}

Where MadeupCardView extends CardView Kudos to this answer for the TypedArray part.

Material effect on button with background color

Programmatically applying the colors:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {

    ColorStateList colorStateListRipple = new ColorStateList(
            new int[][] {{0}},
            new int[] {Color.WHITE} // ripple color
            );

    RippleDrawable rippleDrawable = (RippleDrawable) myButton.getBackground();
    rippleDrawable.setColor(colorStateListRipple);
    myButton.setBackground(rippleDrawable); // applying the ripple color
}

ColorStateList colorStateList = new ColorStateList(
        new int[][]{
                new int[]{android.R.attr.state_pressed}, // when pressed
                new int[]{android.R.attr.state_enabled}, // normal state color
                new int[]{} // normal state color
        },
        new int[]{
                Color.CYAN, // when pressed
                Color.RED, // normal state color
                Color.RED // normal state color
        }
);

ViewCompat.setBackgroundTintList(myButton, colorStateList); // applying the state colors

How to achieve ripple animation using support library?

I made a simple class that makes ripple buttons, i never needed it in the end so its not the best, But here it is:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

public class RippleView extends Button
{
    private float duration = 250;

    private float speed = 1;
    private float radius = 0;
    private Paint paint = new Paint();
    private float endRadius = 0;
    private float rippleX = 0;
    private float rippleY = 0;
    private int width = 0;
    private int height = 0;
    private OnClickListener clickListener = null;
    private Handler handler;
    private int touchAction;
    private RippleView thisRippleView = this;

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

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

    public RippleView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init()
    {
        if (isInEditMode())
            return;

        handler = new Handler();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);
    }

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

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

        if(radius > 0 && radius < endRadius)
        {
            canvas.drawCircle(rippleX, rippleY, radius, paint);
            if(touchAction == MotionEvent.ACTION_UP)
                invalidate();
        }
    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event)
    {
        rippleX = event.getX();
        rippleY = event.getY();

        switch(event.getAction())
        {
            case MotionEvent.ACTION_UP:
            {
                getParent().requestDisallowInterceptTouchEvent(false);
                touchAction = MotionEvent.ACTION_UP;

                radius = 1;
                endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
                speed = endRadius / duration * 10;
                handler.postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        if(radius < endRadius)
                        {
                            radius += speed;
                            paint.setAlpha(90 - (int) (radius / endRadius * 90));
                            handler.postDelayed(this, 1);
                        }
                        else
                        {
                            clickListener.onClick(thisRippleView);
                        }
                    }
                }, 10);
                invalidate();
                break;
            }
            case MotionEvent.ACTION_CANCEL:
            {
                getParent().requestDisallowInterceptTouchEvent(false);
                touchAction = MotionEvent.ACTION_CANCEL;
                radius = 0;
                invalidate();
                break;
            }
            case MotionEvent.ACTION_DOWN:
            {
                getParent().requestDisallowInterceptTouchEvent(true);
                touchAction = MotionEvent.ACTION_UP;
                endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
                paint.setAlpha(90);
                radius = endRadius/4;
                invalidate();
                return true;
            }
            case MotionEvent.ACTION_MOVE:
            {
                if(rippleX < 0 || rippleX > width || rippleY < 0 || rippleY > height)
                {
                    getParent().requestDisallowInterceptTouchEvent(false);
                    touchAction = MotionEvent.ACTION_CANCEL;
                    radius = 0;
                    invalidate();
                    break;
                }
                else
                {
                    touchAction = MotionEvent.ACTION_MOVE;
                    invalidate();
                    return true;
                }
            }
        }

        return false;
    }

    @Override
    public void setOnClickListener(OnClickListener l)
    {
        clickListener = l;
    }
}

EDIT

Since many people are looking for something like this i made a class that can make other views have the ripple effect:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

public class RippleViewCreator extends FrameLayout
{
    private float duration = 150;
    private int frameRate = 15;

    private float speed = 1;
    private float radius = 0;
    private Paint paint = new Paint();
    private float endRadius = 0;
    private float rippleX = 0;
    private float rippleY = 0;
    private int width = 0;
    private int height = 0;
    private Handler handler = new Handler();
    private int touchAction;

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

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

    public RippleViewCreator(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init()
    {
        if (isInEditMode())
            return;

        paint.setStyle(Paint.Style.FILL);
        paint.setColor(getResources().getColor(R.color.control_highlight_color));
        paint.setAntiAlias(true);

        setWillNotDraw(true);
        setDrawingCacheEnabled(true);
        setClickable(true);
    }

    public static void addRippleToView(View v)
    {
        ViewGroup parent = (ViewGroup)v.getParent();
        int index = -1;
        if(parent != null)
        {
            index = parent.indexOfChild(v);
            parent.removeView(v);
        }
        RippleViewCreator rippleViewCreator = new RippleViewCreator(v.getContext());
        rippleViewCreator.setLayoutParams(v.getLayoutParams());
        if(index == -1)
            parent.addView(rippleViewCreator, index);
        else
            parent.addView(rippleViewCreator);
        rippleViewCreator.addView(v);
    }

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

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

        if(radius > 0 && radius < endRadius)
        {
            canvas.drawCircle(rippleX, rippleY, radius, paint);
            if(touchAction == MotionEvent.ACTION_UP)
                invalidate();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event)
    {
        return true;
    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event)
    {
        rippleX = event.getX();
        rippleY = event.getY();

        touchAction = event.getAction();
        switch(event.getAction())
        {
            case MotionEvent.ACTION_UP:
            {
                getParent().requestDisallowInterceptTouchEvent(false);

                radius = 1;
                endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
                speed = endRadius / duration * frameRate;
                handler.postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        if(radius < endRadius)
                        {
                            radius += speed;
                            paint.setAlpha(90 - (int) (radius / endRadius * 90));
                            handler.postDelayed(this, frameRate);
                        }
                        else if(getChildAt(0) != null)
                        {
                            getChildAt(0).performClick();
                        }
                    }
                }, frameRate);
                break;
            }
            case MotionEvent.ACTION_CANCEL:
            {
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
            }
            case MotionEvent.ACTION_DOWN:
            {
                getParent().requestDisallowInterceptTouchEvent(true);
                endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
                paint.setAlpha(90);
                radius = endRadius/3;
                invalidate();
                return true;
            }
            case MotionEvent.ACTION_MOVE:
            {
                if(rippleX < 0 || rippleX > width || rippleY < 0 || rippleY > height)
                {
                    getParent().requestDisallowInterceptTouchEvent(false);
                    touchAction = MotionEvent.ACTION_CANCEL;
                    break;
                }
                else
                {
                    invalidate();
                    return true;
                }
            }
        }
        invalidate();
        return false;
    }

    @Override
    public final void addView(@NonNull View child, int index, ViewGroup.LayoutParams params)
    {
        //limit one view
        if (getChildCount() > 0)
        {
            throw new IllegalStateException(this.getClass().toString()+" can only have one child.");
        }
        super.addView(child, index, params);
    }
}

Node.js: socket.io close client connection

For socket.io version 1.4.5:

On server:

socket.on('end', function (){
    socket.disconnect(0);
});

On client:

var io = io();
io.emit('end');

invalid_grant trying to get oAuth token from google

I had this problem after enabling a new service API on the Google console and trying to use the previously made credentials.

To fix the problem, I had to go back to the credential page, clicking on the credential name, and clicking "Save" again. After that, I could authenticate just fine.

Explanation of BASE terminology

To add to the other answers, I think the acronyms were derived to show a scale between the two terms to distinguish how reliable transactions or requests where between RDMS versus Big Data.

From this article acid vs base

In Chemistry, pH measures the relative basicity and acidity of an aqueous (solvent in water) solution. The pH scale extends from 0 (highly acidic substances such as battery acid) to 14 (highly alkaline substances like lie); pure water at 77° F (25° C) has a pH of 7 and is neutral.

Data engineers have cleverly borrowed acid vs base from chemists and created acronyms that while not exact in their meanings, are still apt representations of what is happening within a given database system when discussing the reliability of transaction processing.

One other point, since I work with Big Data using Elasticsearch. To clarify, an instance of Elasticsearch is a node and a group of nodes form a cluster.

To me from a practical standpoint, BA (Basically Available), in this context, has the idea of multiple master nodes to handle the Elasticsearch cluster and it's operations.

If you have 3 master nodes and the currently directing master node goes down, the system stays up, albeit in a less efficient state, and another master node takes its place as the main directing master node. If two master nodes go down, the system still stays up and the last master node takes over.

Flash CS4 refuses to let go

Flash still has the ASO file, which is the compiled byte code for your classes. On Windows, you can see the ASO files here:

C:\Documents and Settings\username\Local Settings\Application Data\Adobe\Flash CS4\en\Configuration\Classes\aso

On a Mac, the directory structure is similar in /Users/username/Library/Application Support/


You can remove those files by hand, or in Flash you can select Control->Delete ASO files to remove them.

Difference between Visual Basic 6.0 and VBA

VBA stands for Visual Basic For Applications and its a Visual Basic implementation intended to be used in the Office Suite.

The difference between them is that VBA is embedded inside Office documents (its an Office feature). VB is the ide/language for developing applications.

Why Doesn't C# Allow Static Methods to Implement an Interface?

When a class implements an interface,it is creating instance for the interface members. While a static type doesnt have an instance,there is no point in having static signatures in an interface.

I can't install intel HAXM

Note: this is not an answer because I could not find a solution. But I think the information may be useful for others (and it wouldn't be practical as a comment). I have tried all of the steps detailed in the various docs but I could not get Android Emulator to work on my AMD Ryzen 7 :(


Most answers work only for Intel CPUs. If you have an AMD CPU (like me, an AMD Ryzen 7) you need to know about some restrictions and you have to use WHPX instead of HAXM.

I found this on MS's site: Because the Android emulator currently supports AMD hardware acceleration only on Linux, hardware acceleration is not available for AMD-based computers running Windows.

Fortunatelly there is a way to make it work but configuring hardware acceleration for an AMD CPU is a bit more complex:

Requirements and recommendations: - AMD CPU recommendation: AMD Ryzen CPU - Android Studio 3.2 Beta 1 or higher - Android Emulator version 27.3.8 or higher - Windows 10 with April 2018 Update or higher

To use WHPX acceleration on Windows, you must enable the Windows Hypervisor Platform option in the Turn Windows features on or off dialog box. For changes to this option to take effect, restart your computer.

Additionally, the following changes must be made in the BIOS settings: - AMD CPU: Virtualization or SVM must be enabled.

Note that there are further restrictions as well:

  • You can't run a VM-accelerated emulator inside another VM, such as a VM hosted by VirtualBox, VMWare, or Docker. You must run the emulator directly on your system hardware.
  • You can't run software that uses another virtualization technology at the same time that you run the accelerated emulator. For example, VirtualBox, VMWare, and Docker currently use a different virtualization technology, so you can't run them at the same time as the accelerated emulator.

Some more info: Android Emulator - AMD Processor & Hyper-V Support

This recommendation did not help either:

Please note: More recent versions of the emulator (27.2.8, 27.3.0, or later), require an emulator flag while the feature is in the preview. To do this, create or edit the file C:\Users\.android\advancedFeatures.ini and add the line “WindowsHypervisorPlatform = on”, or start the emulator from the command line with “-feature WindowsHypervisorPlatform”.

How to manually update datatables table with new JSON data

You can use:

$('#table').dataTable().fnClearTable();
$('#table').dataTable().fnAddData(myData2);

Jsfiddle

Update. And yes current documentation is not so good but if you are okay using older versions you can refer legacy documentation.

What does it mean by command cd /d %~dp0 in Windows

~dp0 : d=drive, p=path, %0=full path\name of this batch-file.

cd /d %~dp0 will change the path to the same, where the batch file resides.

See for /? or call / for more details about the %~... modifiers.
See cd /? about the /d switch.

Regular expression to extract numbers from a string

we can use \b as a word boundary and then; \b\d+\b

How to apply style classes to td classes?

Simply create a Class Name and define your style there like this :

table.tdfont td {
  font-size: 0.9em;
}

What's the difference between echo, print, and print_r in PHP?

The difference between echo, print, print_r and var_dump is very simple.

echo

echo is actually not a function but a language construct which is used to print output. It is marginally faster than the print.

echo "Hello World";    // this will print Hello World
echo "Hello ","World"; // Multiple arguments - this will print Hello World

$var_1=55;
echo "$var_1";               // this will print 55
echo "var_1=".$var_1;        // this will print var_1=55
echo 45+$var_1;              // this will print 100

$var_2="PHP";
echo "$var_2";                   // this will print PHP

$var_3=array(99,98,97)           // Arrays are not possible with echo (loop or index  value required)
$var_4=array("P"=>"3","J"=>"4"); // Arrays are not possible with echo (loop or index  value required)

You can also use echo statement with or without parenthese

echo ("Hello World");   // this will print Hello World

print

Just like echo construct print is also a language construct and not a real function. The differences between echo and print is that print only accepts a single argument and print always returns 1. Whereas echo has no return value. So print statement can be used in expressions.

print "Hello World";    // this will print Hello World
print "Hello ","World"; // Multiple arguments - NOT POSSIBLE with print
$var_1=55;
print "$var_1";               // this will print 55
print "var_1=".$var_1;        // this will print var_1=55
print 45+$var_1;              // this will print 100

$var_2="PHP";
print "$var_2";                   // this will print PHP

$var_3=array(99,98,97)           // Arrays are not possible with print (loop or index  value required)
$var_4=array("P"=>"3","J"=>"4"); // Arrays are not possible with print (loop or index  value required)

Just like echo, print can be used with or without parentheses.

print ("Hello World");   // this will print Hello World

print_r

The print_r() function is used to print human-readable information about a variable. If the argument is an array, print_r() function prints its keys and elements (same for objects).

print_r ("Hello World");    // this will print Hello World

$var_1=55;
print_r ("$var_1");               // this will print 55
print_r ("var_1=".$var_1);        // this will print var_1=55
print_r (45+$var_1);              // this will print 100

$var_2="PHP";
print_r ("$var_2");                // this will print PHP

$var_3=array(99,98,97)             // this will print Array ( [0] => 1 [1] => 2 [2] => 3 ) 
$var_4=array("P"=>"3","J"=>"4");   // this will print  Array ( [P] => 3 [J] => 4 ) 

var_dump

var_dump function usually used for debugging and prints the information ( type and value) about a variable/array/object.

var_dump($var_1);     // this will print  int(5444) 
var_dump($var_2);     // this will print  string(5) "Hello" 
var_dump($var_3);     // this will print  array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } 
var_dump($var_4);     // this will print  array(2) { ["P"]=> string(1) "3" ["J"]=> string(1) "4" }

How to change Android usb connect mode to charge only?

To change the connect mode selection try Settings -> Wireless & Networks -> USB Connection. You can shoose to Charging, Mass Storage, Tethered, and ask on connection.

How to specify names of columns for x and y when joining in dplyr?

This feature has been added in dplyr v0.3. You can now pass a named character vector to the by argument in left_join (and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:

left_join(test_data, kantrowitz, by = c("first_name" = "name"))

How line ending conversions work with git core.autocrlf between different operating systems

Here is my understanding of it so far, in case it helps someone.

core.autocrlf=true and core.safecrlf = true

You have a repository where all the line endings are the same, but you work on different platforms. Git will make sure your lines endings are converted to the default for your platform. Why does this matter? Let's say you create a new file. The text editor on your platform will use its default line endings. When you check it in, if you don't have core.autocrlf set to true, you've introduced a line ending inconsistency for someone on a platform that defaults to a different line ending. I always set safecrlf too because I would like to know that the crlf operation is reversible. With these two settings, git is modifying your files, but it verifies that the modifications are reversible.

core.autocrlf=false

You have a repository that already has mixed line endings checked in and fixing the incorrect line endings could break other things. Its best not to tell git to convert line endings in this case, because then it will exacerbate the problem it was designed to solve - making diffs easier to read and merges less painful. With this setting, git doesn't modify your files.

core.autocrlf=input

I don't use this because the reason for this is to cover a use case where you created a file that has CRLF line endings on a platform that defaults to LF line endings. I prefer instead to make my text editor always save new files with the platform's line ending defaults.

Fatal error: iostream: No such file or directory in compiling C program using GCC

Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)

TSQL DATETIME ISO 8601

Gosh, NO!!! You're asking for a world of hurt if you store formatted dates in SQL Server. Always store your dates and times and one of the SQL Server "date/time" datatypes (DATETIME, DATE, TIME, DATETIME2, whatever). Let the front end code resolve the method of display and only store formatted dates when you're building a staging table to build a file from. If you absolutely must display ISO date/time formats from SQL Server, only do it at display time. I can't emphasize enough... do NOT store formatted dates/times in SQL Server.

{Edit}. The reasons for this are many but the most obvious are that, even with a nice ISO format (which is sortable), all future date calculations and searches (search for all rows in a given month, for example) will require at least an implicit conversion (which takes extra time) and if the stored formatted date isn't the format that you currently need, you'll need to first convert it to a date and then to the format you want.

The same holds true for front end code. If you store a formatted date (which is text), it requires the same gyrations to display the local date format defined either by windows or the app.

My recommendation is to always store the date/time as a DATETIME or other temporal datatype and only format the date at display time.

How to parse JSON using Node.js?

NodeJs is a JavaScript based server, so you can do the way you do that in pure JavaScript...

Imagine you have this Json in NodeJs...

var details = '{ "name": "Alireza Dezfoolian", "netWorth": "$0" }';
var obj = JSON.parse(details);

And you can do above to get a parsed version of your json...

How to determine if a number is positive or negative?

Try this without the code: (x-SQRT(x^2))/(2*x)

Chart.js v2 - hiding grid lines

The code below removes remove grid lines from chart area only not the ones in x&y axis labels

Chart.defaults.scale.gridLines.drawOnChartArea = false;

Add a new item to recyclerview programmatically?

First add your item to mItems and then use:

mAdapter.notifyItemInserted(mItems.size() - 1);

this method is better than using:

mAdapter.notifyDataSetChanged();

in performance.

convert from Color to brush

This is for Color to Brush....

you can't convert it, you have to make a new brush....

SolidColorBrush brush = new SolidColorBrush( myColor );

now, if you need it in XAML, you COULD make a custom value converter and use that in a binding

How to change the color of a button?

Through Programming:

btn.setBackgroundColor(getResources().getColor(R.color.colorOffWhite));

and your colors.xml must contain...

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <color name="colorOffWhite">#80ffffff</color>
</resources>

How to access at request attributes in JSP?

EL expression:

${requestScope.Error_Message}

There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.

How to reference image resources in XAML?

  1. Add folders to your project and add images to these through "Existing Item".
  2. XAML similar to this: <Image Source="MyRessourceDir\images\addButton.png"/>
  3. F6 (Build)

Grep regex NOT containing string

(?<!1\.2\.3\.4).*Has exploded

You need to run this with -P to have negative lookbehind (Perl regular expression), so the command is:

grep -P '(?<!1\.2\.3\.4).*Has exploded' test.log

Try this. It uses negative lookbehind to ignore the line if it is preceeded by 1.2.3.4. Hope that helps!

What does bundle exec rake mean?

You're running bundle exec on a program. The program's creators wrote it when certain versions of gems were available. The program Gemfile specifies the versions of the gems the creators decided to use. That is, the script was made to run correctly against these gem versions.

Your system-wide Gemfile may differ from this Gemfile. You may have newer or older gems with which this script doesn't play nice. This difference in versions can give you weird errors.

bundle exec helps you avoid these errors. It executes the script using the gems specified in the script's Gemfile rather than the systemwide Gemfile. It executes the certain gem versions with the magic of shell aliases.

See more on the man page.

Here's an example Gemfile:

source 'http://rubygems.org'

gem 'rails', '2.8.3'

Here, bundle exec would execute the script using rails version 2.8.3 and not some other version you may have installed system-wide.

How to count the number of occurrences of an element in a List

In Java 8:

Map<String, Long> counts =
    list.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));

Angular HTML binding

Just to post a little addition to all the great answers so far: If you are using [innerHTML] to render Angular components and are bummed about it not working like me, have a look at the ngx-dynamic-hooks library that I wrote to address this very issue.

With it, you can load components from dynamic strings/html without compromising security. It actually uses Angular's DOMSanitizer just like [innerHTML] does as well, but retains the ability to load components (in a safe manner).

See it in action in this Stackblitz.

HTML entity for the middle dot

Do you mean bulletpoints? • • •

&bull;

How can a Javascript object refer to values in itself?

You can't refer to a property of an object before you have initialized that object; use an external variable.

var key1 = "it";
var obj = {
  key1 : key1,
  key2 : key1 + " works!"
};

Also, this is not a "JSON object"; it is a Javascript object. JSON is a method of representing an object with a string (which happens to be valid Javascript code).

How to create a sticky footer that plays well with Bootstrap 3

What worked for me was adding the position relative to the html tag.

html {
  min-height:100%;
  position:relative;
}
body {
  margin-bottom:60px;
}
footer {
  position:absolute;
  bottom:0;
  height:60px;
}

Put Excel-VBA code in module or sheet?

I would suggest separating your code based on the functionality and purpose specific to each sheet or module. In this manner, you would only put code relative to a sheet's UI inside the sheet's module and only put code related to modules in respective modules. Also, use separate modules to encapsulate code that is shared or reused among several different sheets.

For example, let's say you multiple sheets that are responsible for displaying data from a database in a special way. What kinds of functionality do we have in this situation? We have functionality related to each specific sheet, tasks related to getting data from the database, and tasks related to populating a sheet with data. In this case, I might start with a module for the data access, a module for populating a sheet with data, and within each sheet I'd have code for accessing code in those modules.

It might be laid out like this.

Module: DataAccess:

Function GetData(strTableName As String, strCondition1 As String) As Recordset
    'Code Related to getting data from the database'
End Function

Module: PopulateSheet:

Sub PopulateASheet(wsSheet As Worksheet, rs As Recordset)
    'Code to populate a worksheet '
End Function

Sheet: Sheet1 Code:

Sub GetDataAndPopulate()
    'Sample Code'
     Dim rs As New Recordset
     Dim ws As Worksheet
     Dim strParam As String
     Set ws = ActiveSheet
     strParam = ws.Range("A1").Value

     Set rs = GetData("Orders",strParam)

     PopulateASheet ws, rs
End Sub

Sub Button1_Click()
    Call GetDataAndPopulate
End Sub

Deleting array elements in JavaScript - delete vs splice

Others have already properly compared delete with splice.

Another interesting comparison is delete versus undefined: a deleted array item uses less memory than one that is just set to undefined;

For example, this code will not finish:

let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
    ary.push(y);
    ary[y] = undefined;
    y += 1;
}
console(ary.length);

It produces this error:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.

So, as you can see undefined actually takes up heap memory.

However, if you also delete the ary-item (instead of just setting it to undefined), the code will slowly finish:

let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
    ary.push(x);
    ary[x] = undefined;
    delete ary[x];
    x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);

These are extreme examples, but they make a point about delete that I haven't seen anyone mention anywhere.

How to launch an application from a browser?

You can't really "launch an application" in the true sense. You can as you indicated ask the user to open a document (ie a PDF) and windows will attempt to use the default app for that file type. Many applications have a way to do this.

For example you can save RDP connections as a .rdp file. Putting a link on your site to something like this should allow the user to launch right into an RDP session:

<a href="MyServer1.rdp">Server 1</a>

How to open maximized window with Javascript?

Checkout this jquery window plugin: http://fstoke.me/jquery/window/

// create a window
sampleWnd = $.window({
   .....
});

// resize the window by passed w,h parameter
sampleWnd.resize(screen.width, screen.height);

JavaScript string newline character?

yes use \n, unless you are generating html code, in which you want to use <br />

CSS hide scroll bar, but have element scrollable

work on all major browsers

html {
    overflow: scroll;
    overflow-x: hidden;
}
::-webkit-scrollbar {
    width: 0px;  /* Remove scrollbar space */
    background: transparent;  /* Optional: just make scrollbar invisible */
}

Textarea to resize based on content length

Decide a width and check how many characters one line could hold, and then for each key pressed you call a function that looks something like:

function changeHeight()
{
var chars_per_row = 100;
var pixles_per_row = 16;
this.style.height = Math.round((this.value.length / chars_per_row) * pixles_per_row) + 'px';
}

Havn't tested the code.

Best way to do a PHP switch with multiple values per case?

Switch in combination with variable variables will give you more flexibility:

<?php
$p = 'home'; //For testing

$p = ( strpos($p, 'users') !== false? 'users': $p);
switch ($p) { 
    default:
        $varContainer = 'current_' . $p; //Stores the variable [$current_"xyORz"] into $varContainer
        ${$varContainer} = 'current'; //Sets the VALUE of [$current_"xyORz"] to 'current'
    break;

}
//For testing
echo $current_home;
?>

To learn more, checkout variable variables and the examples I submitted to php manual:
Example 1: http://www.php.net/manual/en/language.variables.variable.php#105293
Example 2: http://www.php.net/manual/en/language.variables.variable.php#105282

PS: This example code is SMALL AND SIMPLE, just the way I like it. It's tested and works too

IntelliJ show JavaDocs tooltip on mouse over

For Intellij 15, use the checkbox in File > Settings > Editor > General option Show quick documentation on mouse move.

enter image description here

You can also get there by typing "quick" or something similar in the search box:

enter image description here

How do you know a variable type in java?

I would like to expand on Martin's answer there...

His solution is rather nice, but it can be tweaked so any "variable type" can be printed like that.(It's actually Value Type, more on the topic). That said, "tweaked" may be a strong word for this. Regardless, it may be helpful.

Martins Solution:

a.getClass().getName()

However, If you want it to work with anything you can do this:

((Object) myVar).getClass().getName()
//OR
((Object) myInt).getClass().getSimpleName()

In this case, the primitive will simply be wrapped in a Wrapper. You will get the Object of the primitive in that case.

I myself used it like this:

private static String nameOf(Object o) {
    return o.getClass().getSimpleName();
}

Using Generics:

public static <T> String nameOf(T o) {
    return o.getClass().getSimpleName();
}

Disable password authentication for SSH

I followed these steps (for Mac).

In /etc/ssh/sshd_config change

#ChallengeResponseAuthentication yes
#PasswordAuthentication yes

to

ChallengeResponseAuthentication no
PasswordAuthentication no

Now generate the RSA key:

ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa

(For me an RSA key worked. A DSA key did not work.)

A private key will be generated in ~/.ssh/id_rsa along with ~/.ssh/id_rsa.pub (public key).

Now move to the .ssh folder: cd ~/.ssh

Enter rm -rf authorized_keys (sometimes multiple keys lead to an error).

Enter vi authorized_keys

Enter :wq to save this empty file

Enter cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

Restart the SSH:

sudo launchctl stop com.openssh.sshd
sudo launchctl start com.openssh.sshd

Can a local variable's memory be accessed outside its scope?

In typical compiler implementations, you can think of the code as "print out the value of the memory block with adress that used to be occupied by a". Also, if you add a new function invocation to a function that constains a local int it's a good chance that the value of a (or the memory address that a used to point to) changes. This happens because the stack will be overwritten with a new frame containing different data.

However, this is undefined behaviour and you should not rely on it to work!

Need to remove href values when printing in Chrome

If you use the following CSS

<link href="~/Content/common/bootstrap.css" rel="stylesheet" type="text/css"    />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" type="text/css" />

just change it into the following style by adding media="screen"

<link href="~/Content/common/bootstrap.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" **media="screen"** type="text/css" />

I think it will work.

the former answers like

    @media print {
  a[href]:after {
    content: none !important;
  }
}

were not worked well in the chrome browse.

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

Try this:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

zzz is the timezone offset.

How can I extract a predetermined range of lines from a text file on Unix?

You could use 'vi' and then the following command:

:16224,16482w!/tmp/some-file

Alternatively:

cat file | head -n 16482 | tail -n 258

EDIT:- Just to add explanation, you use head -n 16482 to display first 16482 lines then use tail -n 258 to get last 258 lines out of the first output.

Pandas: Return Hour from Datetime Column Directly

Now we can use:

sales['time_hour'] = sales['timestamp'].apply(lambda x: x.hour)

Oracle date function for the previous month

Data for last month-

select count(distinct switch_id)
  from [email protected]
 where dealer_name =  'XXXX'
   and to_char(CREATION_DATE,'MMYYYY') = to_char(add_months(trunc(sysdate),-1),'MMYYYY');

C++ performance vs. Java/C#

I like Orion Adrian's answer, but there is another aspect to it.

The same question was posed decades ago about assembly language vs. "human" languages like FORTRAN. And part of the answer is similar.

Yes, a C++ program is capable of being faster than C# on any given (non-trivial?) algorithm, but the program in C# will often be as fast or faster than a "naive" implementation in C++, and an optimized version in C++ will take longer to develop, and might still beat the C# version by a very small margin. So, is it really worth it?

You'll have to answer that question on a one-by-one basis.

That said, I'm a long time fan of C++, and I think it's an incredibly expressive and powerful language -- sometimes underappreciated. But in many "real life" problems (to me personally, that means "the kind I get paid to solve"), C# will get the job done sooner and safer.

The biggest penalty you pay? Many .NET and Java programs are memory hogs. I have seen .NET and Java apps take "hundreds" of megabytes of memory, when C++ programs of similar complexity barely scratch the "tens" of MBs.

BarCode Image Generator in Java

iText is a great Java PDF library. They also have an API for creating barcodes. You don't need to be creating a PDF to use it.

This page has the details on creating barcodes. Here is an example from that site:

BarcodeEAN codeEAN = new BarcodeEAN();
codeEAN.setCodeType(codeEAN.EAN13);
codeEAN.setCode("9780201615883");
Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);

The biggest thing you will need to determine is what type of barcode you need. There are many different barcode formats and iText does support a lot of them. You will need to know what format you need before you can determine if this API will work for you.

Response Content type as CSV

Try one of these other mime-types (from here: http://filext.com/file-extension/CSV )

  • text/comma-separated-values
  • text/csv
  • application/csv
  • application/excel
  • application/vnd.ms-excel
  • application/vnd.msexcel

Also, the mime-type might be case sensitive...

Restore a postgres backup file using the command line?

Try to see if the following commands can help you:

sudo su - yourdbuser
psql
\i yourbackupfile

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

I think that you can bind the load event of the iframe, the event fires when the iframe content is fully loaded.

At the same time you can start a setTimeout, if the iFrame is loaded clear the timeout alternatively let the timeout fire.

Code:

var iframeError;

function change() {
    var url = $("#addr").val();
    $("#browse").attr("src", url);
    iframeError = setTimeout(error, 5000);
}

function load(e) {
    alert(e);
}

function error() {
    alert('error');
}

$(document).ready(function () {
    $('#browse').on('load', (function () {
        load('ok');
        clearTimeout(iframeError);
    }));

});

Demo: http://jsfiddle.net/IrvinDominin/QXc6P/

Second problem

It is because you miss the parens in the inline function call; try change this:

<iframe id="browse" style="width:100%;height:100%" onload="load" onerror="error"></iframe>

into this:

<iframe id="browse" style="width:100%;height:100%" onload="load('Done func');" onerror="error('failed function');"></iframe>

Demo: http://jsfiddle.net/IrvinDominin/ALBXR/4/

Using Sockets to send and receive data

the easiest way to do this is to wrap your sockets in ObjectInput/OutputStreams and send serialized java objects. you can create classes which contain the relevant data, and then you don't need to worry about the nitty gritty details of handling binary protocols. just make sure that you flush your object streams after you write each object "message".

Excel - Sum column if condition is met by checking other column in same table

This should work, but there is a little trick. After you enter the formula, you need to hold down Ctrl+Shift while you press Enter. When you do, you'll see that the formula bar has curly-braces around your formula. This is called an array formula.

For example, if the Months are in cells A2:A100 and the amounts are in cells B2:B100, your formula would look like {=SUM(If(A2:A100="January",B2:B100))}. You don't actually type the curly-braces though.

You could also do something like =SUM((A2:A100="January")*B2:B100). You'd still need to use the trick to get it to work correctly.

How to delete a stash created with git stash create?

Git stash clear will clear complete stash,

cmd: git stash clear

If you want to delete a particular stash with a stash index, you can use the drop.

cmd: git stash drop 4

(4 is stash id or stash index)

Editing in the Chrome debugger

Just like @mark 's answer, we can create a Snippets in Chrome DevTools, to override the default JavaScript. Finally, we can see what effects they have on the page.

Image

How can I remove file extension from a website address?

For those who are still looking for a simple answer to this; You can remove your file extension by using .htaccessbut this solution is just saving the day maybe even not. Because when user copies the URL from address bar or tries to reload or even coming back from history, your standart Apache Router will not be able to realize what are you looking for and throw you a 404 Error. You need a dedicated Router for this purpose to make your app understand what does the URL actually means by saying something Server and File System has no idea about.

I leave here my solution for this. This is tested and used many times for my clients and for my projects too. It supports multi language and language detection too. Read Readme file is recommended. It also provides you a good structure to have a tidy project with differenciated language files (you can even have different designs for each language) and separated css,js and phpfiles even more like images or whatever you have.

Cr8Router - Simple PHP Router

How to debug a Flask app

with virtual env activate

export FLASK_DEBUG=true

you can configure

export FLASK_APP=app.py  # run.py
export FLASK_ENV = "development"

to start

flask run

the result

 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: xxx-xxx-xxx

and if you change

export FLASK_DEBUG=false

 * Environment: development
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Why can I not switch branches?

You need to commit or destroy any unsaved changes before you switch branch.

Git won't let you switch branch if it means unsaved changes would be removed.

How to apply filters to *ngFor?

There is a dynamic filter pipe that I use

Source data:

items = [{foo: 'hello world'}, {foo: 'lorem ipsum'}, {foo: 'foo bar'}];

In the template you can dinamically set the filter in any object attr:

<li *ngFor="let item of items | filter:{foo:'bar'}">

The pipe:

  import { Pipe, PipeTransform } from '@angular/core';

  @Pipe({
    name: 'filter',
  })
  export class FilterPipe implements PipeTransform {
    transform(items: any[], filter: Record<string, any>): any {
      if (!items || !filter) {
        return items;
      }

      const key = Object.keys(filter)[0];
      const value = filter[key];

      return items.filter((e) => e[key].indexOf(value) !== -1);
    }
  }

Don't forget to register the pipe in your app.module.ts declarations

Detect all changes to a <input type="text"> (immediately) using JQuery

Can't you just use <span contenteditable="true" spellcheck="false"> element in place of <input type="text">?

<span> (with contenteditable="true" spellcheck="false" as attributes) distincts by <input> mainly because:

  • It's not styled like an <input>.
  • It doesn't have a value property, but the text is rendered as innerText and makes part of its inner body.
  • It's multiline whereas <input> isn't although you set the attribute multiline="true".

To accomplish the appearance you can, of course, style it in CSS, whereas writing the value as innerText you can get for it an event:

Here's a fiddle.

Unfortunately there's something that doesn't actually work in IE and Edge, which I'm unable to find.

Count with IF condition in MySQL query

Use sum() in place of count()

Try below:

SELECT
    ccc_news . * , 
    SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments
FROM
    ccc_news
    LEFT JOIN
        ccc_news_comments
    ON
        ccc_news_comments.news_id = ccc_news.news_id
WHERE
    `ccc_news`.`category` = 'news_layer2'
    AND `ccc_news`.`status` = 'Active'
GROUP BY
    ccc_news.news_id
ORDER BY
    ccc_news.set_order ASC
LIMIT 20 

dpi value of default "large", "medium" and "small" text views android

See in the android sdk directory.

In \platforms\android-X\data\res\values\themes.xml:

    <item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
    <item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
    <item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>

In \platforms\android-X\data\res\values\styles.xml:

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>
</style>

<style name="TextAppearance.Medium">
    <item name="android:textSize">18sp</item>
</style>

<style name="TextAppearance.Small">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?textColorSecondary</item>
</style>

TextAppearance.Large means style is inheriting from TextAppearance style, you have to trace it also if you want to see full definition of a style.

Link: http://developer.android.com/design/style/typography.html

Retrieving Data from SQL Using pyodbc

you could try using Pandas to retrieve information and get it as dataframe

import pyodbc as cnn
import pandas as pd

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')

# Copy to Clipboard for paste in Excel sheet
def copia (argumento):
    df=pd.DataFrame(argumento)
    df.to_clipboard(index=False,header=True)


tableResult = pd.read_sql("SELECT * FROM YOURTABLE", cnxn) 

# Copy to Clipboard
copia(tableResult)

# Or create a Excel file with the results
df=pd.DataFrame(tableResult)
df.to_excel("FileExample.xlsx",sheet_name='Results')

I hope this helps! Cheers!

I cannot start SQL Server browser

If it is disabled, go to Control Panel->Administrative Tools->Services, and look for the SQL Server Agent. Right-click, and select Properties From the Startup Type dropdown, change from Disabled to Automatic.

Animate element transform rotate

In my opinion, jQuery's animate is a bit overused, compared to the CSS3 transition, which performs such animation on any 2D or 3D property. Also I'm afraid, that leaving it to the browser and by forgetting the layer called JavaScript could lead to spare CPU juice - specially, when you wish to blast with the animations. Thus, I like to have animations where the style definitions are, since you define functionality with JavaScript. The more presentation you inject into JavaScript, the more problems you'll face later on.

All you have to do is to use addClass to the element you wish to animate, where you set a class that has CSS transition properties. You just "activate" the animation, which stays implemented on the pure presentation layer.

.js

// with jQuery
$("#element").addClass("Animate");

// without jQuery library
document.getElementById("element").className += "Animate";

One could easly remove a class with jQuery, or remove a class without library.

.css

#element{
    color      : white;
}

#element.Animate{
    transition        : .4s linear;
    color             : red;
    /** 
     * Not that ugly as the JavaScript approach.
     * Easy to maintain, the most portable solution.
     */
    -webkit-transform : rotate(90deg);
}

.html

<span id="element">
    Text
</span>

This is a fast and convenient solution for most use cases.

I also use this when I want to implement a different styling (alternative CSS properties), and wish to change the style on-the-fly with a global .5s animation. I add a new class to the BODY, while having alternative CSS in a form like this:

.js

$("BODY").addClass("Alternative");

.css

BODY.Alternative #element{
    color      : blue;
    transition : .5s linear;
}

This way you can apply different styling with animations, without loading different CSS files. You only involve JavaScript to set a class.

How to control font sizes in pgf/tikz graphics in latex?

You can also use:

\usepackage{anyfontsize}

The huge advantage of the anyfontsize package over scalefnt is that one does not need to enclose the entire {tikzpicture} with a \scalefont environment.

Just adding \usepackage{anyfontsize} to the preamble is all that is required for the font scaling magic to happen.

Delete statement in SQL is very slow

If the table you are deleting from has BEFORE/AFTER DELETE triggers, something in there could be causing your delay.

Additionally, if you have foreign keys referencing that table, additional UPDATEs or DELETEs may be occurring.

Is there any good dynamic SQL builder library in Java?

I can recommend jOOQ. It provides a lot of great features, also a intuitive DSL for SQL and a extremly customable reverse-engineering approach.

jOOQ effectively combines complex SQL, typesafety, source code generation, active records, stored procedures, advanced data types, and Java in a fluent, intuitive DSL.

Add a link to an image in a css style sheet

I stumbled upon this old listing pondering this same question. My band-aid for this same question was to make my header text into a link. I then changed the color and removed text decoration with CSS. Now to make the entire header picture a link, I expanded the padding of the anchor tag until it reached close to the edge of the header image.... This worked to my satisfaction, and I figured i would share.

Code coverage with Mocha

Blanket.js works perfect too.

npm install --save-dev blanket

in front of your test/tests.js

require('blanket')({
    pattern: function (filename) {
        return !/node_modules/.test(filename);
    }
});

run mocha -R html-cov > coverage.html

Use a loop to plot n charts Python

Use a dictionary!!

You can also use dictionaries that allows you to have more control over the plots:

import matplotlib.pyplot as plt
#   plot 0     plot 1    plot 2   plot 3
x=[[1,2,3,4],[1,4,3,4],[1,2,3,4],[9,8,7,4]]
y=[[3,2,3,4],[3,6,3,4],[6,7,8,9],[3,2,2,4]]

plots = zip(x,y)
def loop_plot(plots):
    figs={}
    axs={}
    for idx,plot in enumerate(plots):
        figs[idx]=plt.figure()
        axs[idx]=figs[idx].add_subplot(111)
        axs[idx].plot(plot[0],plot[1])
return figs, axs

figs, axs = loop_plot(plots)

Now you can select the plot that you want to modify easily:

axs[0].set_title("Now I can control it!")

Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx) or show them plt.show(). Use the argument block=False only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot function or in a separate loop using the dictionaries that the function provided.

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Android error: Failed to install *.apk on device *: timeout

I get this a lot. I'm on a Galaxy S too. I unplug the cable from the phone, plug it back in and try launching the app again from Eclipse, and it usually does the trick. Eclipse seems to lose the connection to the phone occasionally but this seems to kick it back to life.

Passing 'this' to an onclick event

Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.

check this fiddle

http://jsfiddle.net/8cvBM/

Check if an array contains any element of another array in JavaScript

You can use a nested Array.prototype.some call. This has the benefit that it will bail at the first match instead of other solutions that will run through the full nested loop.

eg.

var arr = [1, 2, 3];
var match = [2, 4];

var hasMatch = arr.some(a => match.some(m => a === m));

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Django download a file

When you upload a file using FileField, the file will have a URL that you can use to point to the file and use HTML download attribute to download that file you can simply do this.

models.py

The model.py looks like this

class CsvFile(models.Model):
    csv_file = models.FileField(upload_to='documents')

views.py

#csv upload

class CsvUploadView(generic.CreateView):

   model = CsvFile
   fields = ['csv_file']
   template_name = 'upload.html'

#csv download

class CsvDownloadView(generic.ListView):

    model = CsvFile
    fields = ['csv_file']
    template_name = 'download.html'

Then in your templates.

#Upload template

upload.html

<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.media }}
    {{ form.as_p }}
    <button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>

#download template

download.html

  {% for document in object_list %}

     <a href="{{ document.csv_file.url }}" download  class="btn btn-dark float-right">Download</a>

  {% endfor %}

I did not use forms, just rendered model but either way, FileField is there and it will work the same.

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

Turn out to be some SQL service was stopped somehow on server. Restarting SQL Server service manually was the solution.

I know this is foolish but worked anyway. Thanks @PareshJ for the useful comment.

How can I write data in YAML format in a file?

import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

Good afternoon, you could always use a little LINQ to get the selected list items and then do what you want with the results:

var selected = CBLGold.Items.Cast<ListItem>().Where(x => x.Selected);
// work with selected...

mysql is not recognised as an internal or external command,operable program or batch

MYSQL_HOME:

C:\Program Files\MySQL\MySQL Server 5.0

Path:

%MYSQL_HOME%\bin;

Android - drawable with rounded corners at the top only

You may need read this https://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

and below there is a Note.

Note Every corner must (initially) be provided a corner radius greater than 1, or else no corners are rounded. If you want specific corners to not be rounded, a work-around is to use android:radius to set a default corner radius greater than 1, but then override each and every corner with the values you really want, providing zero ("0dp") where you don't want rounded corners.

How can I present a file for download from an MVC controller?

Although standard action results FileContentResult or FileStreamResult may be used for downloading files, for reusability, creating a custom action result might be the best solution.

As an example let's create a custom action result for exporting data to Excel files on the fly for download.

ExcelResult class inherits abstract ActionResult class and overrides the ExecuteResult method.

We are using FastMember package for creating DataTable from IEnumerable object and ClosedXML package for creating Excel file from the DataTable.

public class ExcelResult<T> : ActionResult
{
    private DataTable dataTable;
    private string fileName;

    public ExcelResult(IEnumerable<T> data, string filename, string[] columns)
    {
        this.dataTable = new DataTable();
        using (var reader = ObjectReader.Create(data, columns))
        {
            dataTable.Load(reader);
        }
        this.fileName = filename;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context != null)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            response.AddHeader("content-disposition", string.Format(@"attachment;filename=""{0}""", fileName));
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dataTable, "Sheet1");
                using (MemoryStream stream = new MemoryStream())
                {
                    wb.SaveAs(stream);
                    response.BinaryWrite(stream.ToArray());
                }
            }
        }
    }
}

In the Controller use the custom ExcelResult action result as follows

[HttpGet]
public async Task<ExcelResult<MyViewModel>> ExportToExcel()
{
    var model = new Models.MyDataModel();
    var items = await model.GetItems();
    string[] columns = new string[] { "Column1", "Column2", "Column3" };
    string filename = "mydata.xlsx";
    return new ExcelResult<MyViewModel>(items, filename, columns);
}

Since we are downloading the file using HttpGet, create an empty View without model and empty layout.

Blog post about custom action result for downloading files that are created on the fly:

https://acanozturk.blogspot.com/2019/03/custom-actionresult-for-files-in-aspnet.html

How to add custom method to Spring Data JPA

Considering your code snippet, please note that you can only pass Native objects to the findBy### method, lets say you want to load a list of accounts that belongs certain costumers, one solution is to do this,

@Query("Select a from Account a where a."#nameoffield"=?1")
List<Account> findByCustomer(String "#nameoffield");

Make sue the name of the table to be queried is thesame as the Entity class. For further implementations please take a look at this

How to make Python speak

This is what you are looking for. A complete TTS solution for the Mac. You can use this standalone or as a co-location Mac server for web apps:

http://wolfpaulus.com/jounal/mac/ttsserver/

Why is "except: pass" a bad programming practice?

So, what output does this code produce?

fruits = [ 'apple', 'pear', 'carrot', 'banana' ]

found = False
try:
     for i in range(len(fruit)):
         if fruits[i] == 'apple':
             found = true
except:
     pass

if found:
    print "Found an apple"
else:
    print "No apples in list"

Now imagine the try-except block is hundreds of lines of calls to a complex object hierarchy, and is itself called in the middle of large program's call tree. When the program goes wrong, where do you start looking?

Pass request headers in a jQuery AJAX GET call

As of jQuery 1.5, there is a headers hash you can pass in as follows:

$.ajax({
    url: "/test",
    headers: {"X-Test-Header": "test-value"}
});

From http://api.jquery.com/jQuery.ajax:

headers (added 1.5): A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

Python set to list

Your code works with Python 3.2.1 on Win7 x64

a = set(["Blah", "Hello"])
a = list(a)
type(a)
<class 'list'>

check for null date in CASE statement, where have I gone wrong?

select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
  'Awaiting'
Else
  'Approved'
END AS StartDateStatus
From MyTable

Angular 2 Show and Hide an element

There are two options depending what you want to achieve :

  1. You can use the hidden directive to show or hide an element

    <div [hidden]="!edited" class="alert alert-success box-msg" role="alert">
      <strong>List Saved!</strong> Your changes has been saved.
    </div>
    
  2. You can use the ngIf control directive to add or remove the element. This is different of the hidden directive because it does not show / hide the element, but it add / remove from the DOM. You can loose unsaved data of the element. It can be the better choice for an edit component that is cancelled.

    <div *ngIf="edited" class="alert alert-success box-msg" role="alert"> 
      <strong>List Saved!</strong> Your changes has been saved.
    </div>
    

For you problem of change after 3 seconds, it can be due to incompatibility with setTimeout. Did you include angular2-polyfills.js library in your page ?

XSLT - How to select XML Attribute by Attribute?

Just remove the slash after Data and prepend the root:

<xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>

What is the most efficient way to get first and last line of a text file?

Here is an extension of @Trasp's answer that has additional logic for handling the corner case of a file that has only one line. It may be useful to handle this case if you repeatedly want to read the last line of a file that is continuously being updated. Without this, if you try to grab the last line of a file that has just been created and has only one line, IOError: [Errno 22] Invalid argument will be raised.

def tail(filepath):
    with open(filepath, "rb") as f:
        first = f.readline()      # Read the first line.
        f.seek(-2, 2)             # Jump to the second last byte.
        while f.read(1) != b"\n": # Until EOL is found...
            try:
                f.seek(-2, 1)     # ...jump back the read byte plus one more.
            except IOError:
                f.seek(-1, 1)
                if f.tell() == 0:
                    break
        last = f.readline()       # Read last line.
    return last

Check an integer value is Null in c#

Simply you can do this:

    public void CheckNull(int? item)
    {
        if (item != null)
        {
            //Do Something
        }

    }

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

The strings that contain \xF0 are simply characters encoded as multiple bytes using UTF-8.

Although your collation is set to utf8_general_ci, I suspect that the character encoding of the database, table or even column may be different. They are independent settings. Try:

ALTER TABLE database.table MODIFY COLUMN col VARCHAR(255)  
    CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;

Substitute whatever your actual data type is for VARCHAR(255)

HTML if image is not found

This one worked for me. using the srcset. I have just learnt about it so i dont know if browsers support it but it has worked for me. Try it and later give me your feed back.

 <img src="smiley.gif" srcset="alternatve.gif" width="32" height="32" />

Split a large pandas dataframe

I guess now we can use plain iloc with range for this.

chunk_size = int(df.shape[0] / 4)
for start in range(0, df.shape[0], chunk_size):
    df_subset = df.iloc[start:start + chunk_size]
    process_data(df_subset)
    ....

How do I dump the data of some SQLite3 tables?

You can specify one or more table arguments to the .dump special command, e.g.sqlite3 db ".dump 'table1' 'table2'".

Get a resource using getResource()

Instead of explicitly writing the class name you could use

this.getClass().getResource("/unibo/lsb/res/dice.jpg");

SDK Manager.exe doesn't work

I solved this problem, which occured for me after manually installing the ADT (4.2/api 17) bundle on Windows 7 64 bit in C:\Program Files.

The steps I had to take:

  1. Set the JAVA_HOME environment variable to the installation directory of the (64 bit) JDK, C:\Program Files\Java\jdk1.7.0_11 in my case.
  2. Run SDK Manager as administrator at least once. SDK Manager allows you to change files in Program Files, so you should give it the proper access rights.

How to add button tint programmatically

In properly extending dimsuz's answer by providing a real code situation, see the following code snippet:

    Drawable buttonDrawable = button.getBackground();
    buttonDrawable = DrawableCompat.wrap(buttonDrawable);
    //the color is a direct color int and not a color resource
    DrawableCompat.setTint(buttonDrawable, Color.RED);
    button.setBackground(buttonDrawable);

This solution is for the scenario where a drawable is used as the button's background. It works on pre-Lollipop devices as well.

Div width 100% minus fixed amount of pixels

You can make use of Flexbox layout. You need to set flex: 1 on the element that needs to have dynamic width or height for flex-direction: row and column respectively.

Dynamic width:

HTML

<div class="container">
  <div class="fixed-width">
    1
  </div>
  <div class="flexible-width">
    2
  </div>
  <div class="fixed-width">
    3
  </div>
</div>

CSS

.container {
  display: flex;
}
.fixed-width {
  width: 200px; /* Fixed width or flex-basis: 200px */
}
.flexible-width {
  flex: 1; /* Stretch to occupy remaining width i.e. flex-grow: 1 and flex-shrink: 1*/
}

Output:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  width: 100%;_x000D_
  color: #fff;_x000D_
  font-family: Roboto;_x000D_
}_x000D_
.fixed-width {_x000D_
  background: #9BCB3C;_x000D_
  width: 200px; /* Fixed width */_x000D_
  text-align: center;_x000D_
}_x000D_
.flexible-width {_x000D_
  background: #88BEF5;_x000D_
  flex: 1; /* Stretch to occupy remaining width */_x000D_
  text-align: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="fixed-width">_x000D_
    1_x000D_
  </div>_x000D_
  <div class="flexible-width">_x000D_
    2_x000D_
  </div>_x000D_
  <div class="fixed-width">_x000D_
    3_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_


Dynamic height:

HTML

<div class="container">
  <div class="fixed-height">
    1
  </div>
  <div class="flexible-height">
    2
  </div>
  <div class="fixed-height">
    3
  </div>
</div>

CSS

.container {
  display: flex;
}
.fixed-height {
  height: 200px; /* Fixed height or flex-basis: 200px */
}
.flexible-height {
  flex: 1; /* Stretch to occupy remaining height i.e. flex-grow: 1 and flex-shrink: 1*/
}

Output:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 100vh;_x000D_
  color: #fff;_x000D_
  font-family: Roboto;_x000D_
}_x000D_
.fixed-height {_x000D_
  background: #9BCB3C;_x000D_
  height: 50px; /* Fixed height or flex-basis: 100px */_x000D_
  text-align: center;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
}_x000D_
.flexible-height {_x000D_
  background: #88BEF5;_x000D_
  flex: 1; /* Stretch to occupy remaining width */_x000D_
  text-align: center;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="fixed-height">_x000D_
    1_x000D_
  </div>_x000D_
  <div class="flexible-height">_x000D_
    2_x000D_
  </div>_x000D_
  <div class="fixed-height">_x000D_
    3_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

bash: npm: command not found?

If you already installed npm globally on your system, and you are still getting the above error message by using VSCode terminal. Just close your VSCode application and reopen again, that should resolve the issue.

Android: I am unable to have ViewPager WRAP_CONTENT

I just bumped into the same issue. I had a ViewPager and I wanted to display an ad at the button of it. The solution I found was to get the pager into a RelativeView and set it's layout_above to the view id i want to see below it. that worked for me.

here is my layout XML:

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

    <LinearLayout
        android:id="@+id/AdLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical" >
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/mainpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/AdLayout" >
    </android.support.v4.view.ViewPager>
</RelativeLayout>

How do I get a substring of a string in Python?

Using hardcoded indexes itself can be a mess.

In order to avoid that, Python offers a built-in object slice().

string = "my company has 1000$ on profit, but I lost 500$ gambling."

If we want to know how many money I got left.

Normal solution:

final = int(string[15:19]) - int(string[43:46])
print(final)
>>>500

Using slices:

EARNINGS = slice(15, 19)
LOSSES = slice(43, 46)
final = int(string[EARNINGS]) - int(string[LOSSES])
print(final)
>>>500

Using slice you gain readability.

Laravel: Using try...catch with DB::transaction()

I've decided to give an answer to this question because I think it can be solved using a simpler syntax than the convoluted try-catch block. The Laravel documentation is pretty brief on this subject.

Instead of using try-catch, you can just use the DB::transaction(){...} wrapper like this:

// MyController.php
public function store(Request $request) {
    return DB::transaction(function() use ($request) {
        $user = User::create([
            'username' => $request->post('username')
        ]);

        // Add some sort of "log" record for the sake of transaction:
        $log = Log::create([
            'message' => 'User Foobar created'
        ]);

        // Lets add some custom validation that will prohibit the transaction:
        if($user->id > 1) {
            throw AnyException('Please rollback this transaction');
        }

        return response()->json(['message' => 'User saved!']);
    });
};

You should then see that the User and the Log record cannot exist without eachother.

Some notes on the implementation above:

  • Make sure to return the transaction, so that you can use the response() you return within its callback.
  • Make sure to throw an exception if you want the transaction to be rollbacked (or have a nested function that throws the exception for you automatically, like an SQL exception from within Eloquent).
  • The id, updated_at, created_at and any other fields are AVAILABLE AFTER CREATION for the $user object (for the duration of this transaction). The transaction will run through any of the creation logic you have. HOWEVER, the whole record is discarded when the AnyException is thrown. This means that for instance an auto-increment column for id does get incremented on failed transactions.

Tested on Laravel 5.8

How do I block comment in Jupyter notebook?

I have not yet managed to find the best way possible. Since I am using a keyboard with Finnish layout, some of the answers do not work for me (e.g. user5036413's answer).

However, in the meantime, I have come up with a solution that at least helps me not to comment each and every line one by one. I am using Chrome browser in MS Windows and I have not checked other possibilities though.

The solution:
It uses the fact that you can have multiple line cursors in an Ipython Notebook.

Press the Alt button and keep holding it. The cursor should change its shape into a big plus sign. The next step is, using your mouse, to point to the beginning of the first line you want to comment and while holding the Alt button pull down your mouse until the last line you want to comment. Finally, you can release the Alt button and then use the # character to comment. Voila! You have now commented multiple lines.

Missing maven .m2 folder

If the default .m2 is unable to find, maybe someone changed the default path. Issue the following command to find out where is the Maven local repository,

mvn help:evaluate -Dexpression=settings.localRepository

The above command will scan for projects and run some tasks. Final outcome will be like below

enter image description here

As you can see in the picture the maven local repository is C:\Users\INOVA\.m2\repository

PG COPY error: invalid input syntax for integer

I think it's better to change your csv file like:

"age","first_name","last_name"
23,Ivan,Poupkine
,Eugene,Pirogov

It's also possible to define your table like

CREATE TABLE people (
  age        varchar(20),
  first_name varchar(20),
  last_name  varchar(20)
);

and after copy, you can convert empty strings:

select nullif(age, '')::int as age, first_name, last_name
from people

adding to window.onload event?

If you are using jQuery, you don't have to do anything special. Handlers added via $(document).ready() don't overwrite each other, but rather execute in turn:

$(document).ready(func1)
...
$(document).ready(func2)

If you are not using jQuery, you could use addEventListener, as demonstrated by Karaxuna, plus attachEvent for IE<9.

Note that onload is not equivalent to $(document).ready() - the former waits for CSS, images... as well, while the latter waits for the DOM tree only. Modern browsers (and IE since IE9) support the DOMContentLoaded event on the document, which corresponds to the jQuery ready event, but IE<9 does not.

if(window.addEventListener){
  window.addEventListener('load', func1)
}else{
  window.attachEvent('onload', func1)
}
...
if(window.addEventListener){
  window.addEventListener('load', func2)
}else{
  window.attachEvent('onload', func2)
}

If neither option is available (for example, you are not dealing with DOM nodes), you can still do this (I am using onload as an example, but other options are available for onload):

var oldOnload1=window.onload;
window.onload=function(){
  oldOnload1 && oldOnload1();
  func1();
}
...
var oldOnload2=window.onload;
window.onload=function(){
  oldOnload2 && oldOnload2();
  func2();
}

or, to avoid polluting the global namespace (and likely encountering namespace collisions), using the import/export IIFE pattern:

window.onload=(function(oldLoad){
  return function(){
    oldLoad && oldLoad();
    func1();
  }
})(window.onload)
...
window.onload=(function(oldLoad){
  return function(){
    oldLoad && oldLoad();
    func2();
  }
})(window.onload)

Full-screen iframe with a height of 100%

_x000D_
_x000D_
body {_x000D_
    margin: 0;            /* Reset default margin */_x000D_
}_x000D_
iframe {_x000D_
    display: block;       /* iframes are inline by default */_x000D_
    background: #000;_x000D_
    border: none;         /* Reset default border */_x000D_
    height: 100vh;        /* Viewport-relative units */_x000D_
    width: 100vw;_x000D_
}
_x000D_
<iframe></iframe>
_x000D_
_x000D_
_x000D_

How to set up ES cluster?

Elastic Search 7 changed the configurations for cluster initialisation. What is important to note is the ES instances communicate internally using the Transport layer(TCP) and not the HTTP protocol which is normally used to perform ops on the indices. Below is sample config for 2 machines cluster.

cluster.name: cluster-new
node.name: node-1
node.master: true
node.data: true
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
transport.host: 102.123.322.211
transport.tcp.port: 9300
discovery.seed_hosts: [“102.123.322.211:9300”,"102.123.322.212:9300”]
cluster.initial_master_nodes: 
        - "node-1"
        - "node-2”

Machine 2 config:-

cluster.name: cluster-new
node.name: node-2
node.master: true
node.data: true
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
transport.host: 102.123.322.212
transport.tcp.port: 9300
discovery.seed_hosts: [“102.123.322.211:9300”,"102.123.322.212:9300”]
cluster.initial_master_nodes: 
        - "node-1"
        - "node-2”

cluster.name: This has be same across all the machines that are going to be part of a cluster.

node.name : Identifier for the ES instance. Defaults to machine name if not given.

node.master: specifies whether this ES instance is going to be master or not

node.data: specifies whether this ES instance is going to be data node or not(hold data)

bootsrap.memory_lock: disable swapping.You can start the cluster without setting this flag. But its recommended to set the lock.More info: https://www.elastic.co/guide/en/elasticsearch/reference/master/setup-configuration-memory.html

network.host: 0.0.0.0 if you want to expose the ES instance over network. 0.0.0.0 is different from 127.0.0.1( aka localhost or loopback address). It means all IPv4 addresses on the machine. If machine has multiple ip addresses with a server listening on 0.0.0.0, the client can reach the machine from any of the IPv4 addresses.

http.port: port on which this ES instance will listen to for HTTP requests

transport.host: The IPv4 address of the host(this will be used to communicate with other ES instances running on different machines). More info: https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-transport.html

transport.tcp.port: 9300 (the port where the machine will accept the tcp connections)

discovery.seed_hosts: This was changed in recent versions. Initialise all the IPv4 addresses with TCP port(important) of ES instances that are going to be part of this cluster. This is going to be same across all ES instances that are part of this cluster.

cluster.initial_master_nodes: node names(node.name) of the ES machines that are going to participate in master election.(Quorum based decision making :- https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-quorums.html#modules-discovery-quorums)

How do I share a global variable between c files?

Use extern keyword in another .c file.

How to count items in JSON object using command line?

A simple solution is to install jshon library :

jshon -l < /tmp/test.json
2

Converting String array to java.util.List

List<String> strings = Arrays.asList(new String[]{"one", "two", "three"});

This is a list view of the array, the list is partly unmodifiable, you can't add or delete elements. But the time complexity is O(1).

If you want a modifiable a List:

List<String> strings = 
     new ArrayList<String>(Arrays.asList(new String[]{"one", "two", "three"}));

This will copy all elements from the source array into a new list (complexity: O(n))

How can I center a div within another div?

Everyone said it, but I guess it won't hurt saying it again.

You need to set the width to some value. Here is something simpler to understand.

http://jsfiddle.net/XUxEC/

How to add line break for UILabel?

NSCharacterSet *charSet = NSCharacterSet.newlineCharacterSet;
NSString *formatted = [[unformatted componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@"\n"];

How do I set browser width and height in Selenium WebDriver?

Try something like this:

IWebDriver _driver = new FirefoxDriver();
_driver.Manage().Window.Position = new Point(0, 0);
_driver.Manage().Window.Size = new Size(1024, 768);

Not sure if it'll resize after being launched though, so maybe it's not what you want

Remove NA values from a vector

You can call max(vector, na.rm = TRUE). More generally, you can use the na.omit() function.

Access POST values in Symfony2 request object

I think that in order to get the request data, bound and validated by the form object, you must use :

$form->getClientData();

Execute multiple command lines with the same process using .NET

As another answer alludes to under newer versions of Windows it seems to be necessary to read the standard output and/or standard error streams otherwise it will stall between commands. A neater way to do that instead of using delays is to use an async callback to consume output from the stream:

static void RunCommands(List<string> cmds, string workingDirectory = "")
{
    var process = new Process();
    var psi = new ProcessStartInfo();
    psi.FileName = "cmd.exe";
    psi.RedirectStandardInput = true;
    psi.RedirectStandardOutput = true;
    psi.RedirectStandardError = true;
    psi.UseShellExecute = false;
    psi.WorkingDirectory = workingDirectory;
    process.StartInfo = psi;
    process.Start();
    process.OutputDataReceived += (sender, e) => { Console.WriteLine(e.Data); };
    process.ErrorDataReceived += (sender, e) => { Console.WriteLine(e.Data); };
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    using (StreamWriter sw = process.StandardInput)
    {
        foreach (var cmd in cmds)
        {
            sw.WriteLine (cmd);
        }
    }
    process.WaitForExit();
}

How to calculate age (in years) based on Date of Birth and getDate()

Here is a technique which seems to work around the edge cases: the end of the year and leap Februaries.

The problem with datediff(year,…,…) is that it only finds the difference between the years, and not the actual dates, which is a bit naïve in my opinion. This is only reliable if the date of birth is 1st Jan.

The solution is to time warp the date of birth to the first of January, and the asking date by the same amount.

Because of the leap year problem using the day of year is also unreliable, so I use the month and day to do the time warp:

CREATE FUNCTION age(@then AS date,@now AS date) RETURNS int AS
BEGIN
    DECLARE @month INT = month(@then)-1;
    DECLARE @day INT = day(@then)-1;

    SET @then=dateadd(month,-@month,@then);
    SET @then=dateadd(day,-@day,@then);

    SET @now=dateadd(month,-@month,@now;)
    SET @now=dateadd(day,-@day,@now);

    RETURN datediff(year,@then,@now);
END;

You can write this more compactly, of course. You can even write it in one line, if that’s your idea of having a good time:

CREATE FUNCTION age(@then AS date,@now AS date) RETURNS int AS
BEGIN
    RETURN  datediff(
        year,
        dateadd(day,-day(@then)+1,dateadd(month,-month(@then)+1,@then)),
        dateadd(day,-day(@then)+1,dateadd(month,-month(@then)+1,@now))
    );
END;

but that’s only showing off, and it’s less efficient as it needs to recalculate the offsets.

append to url and refresh page

this should work (not tested!)

var url = window.location.href;    
if (url.indexOf('?') > -1){
   url += '&param=1'
}else{
   url += '?param=1'
}
window.location.href = url;

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

How to clear basic authentication details in chrome

In Chrome, on the right-hand side of the URL bar when you are at a password protected URL, you should see a small key symbol. Click the symbol and it will take you directly to the Password Management area where you can remove the entry. That will ensure you receive future prompts or have an opportunity to enter a new password and save it.

If you do not see the key symbol, that same Password Management area can be accessed by going to Chrome -> Settings -> Passwords and forms -> Manage Passwords. Or more simply, this URL – chrome://settings/passwords.

How to delete stuff printed to console by System.out.println()?

For intellij console the 0x08 character worked for me!

System.out.print((char) 8);

Set and Get Methods in java?

this is the code for set method

public void setAge(int age){
  this.age = age;
}

What is the Python equivalent for a case/switch statement?

The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

How do I remove a submodule?

I just found the .submodule (forgot exact name) hidden file, it has a list... you can erase them individually that way. I just had one, so I deleted it. Simple, but it might mess up Git, since I don't know if anything's attached to the submodule. Seems ok so far, aside from libetpan's usual upgrade issue, but that's (hopefully) unrelated.

Noticed nobody posted manual erasing, so added

Convert string to number and add one

Parse the Id as it would be string and then add.

e.g.

$('.load_more').live("click",function() { //When user clicks
    var newcurrentpageTemp = parseInt($(this).attr("id")) + 1;//Get the id from the hyperlink
    alert(newcurrentpageTemp);
    dosomething();
});

Git: How to commit a manually deleted file?

It says right there in the output of git status:

#   (use "git add/rm <file>..." to update what will be committed)

so just do:

git rm <filename>

Parse HTML in Android

Maybe you can use WebView, but as you can see in the doc WebView doesn't support javascript and other stuff like widgets by default.

http://developer.android.com/reference/android/webkit/WebView.html

I think that you can enable javascript if you need it.

Convert time span value to format "hh:mm Am/Pm" using C#

At first, you need to convert time span to DateTime structure:

var dt = new DateTime(2000, 12, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)

Then you need to convert the value to string with Short Time format

var result = dt.ToString("t"); // Convert to string using Short Time format

XML Serialize generic list of serializable objects

You can't serialize a collection of objects without specifying the expected types. You must pass the list of expected types to the constructor of XmlSerializer (the extraTypes parameter) :

List<object> list = new List<object>();
list.Add(new Foo());
list.Add(new Bar());

XmlSerializer xs = new XmlSerializer(typeof(object), new Type[] {typeof(Foo), typeof(Bar)});
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
    xs.Serialize(streamWriter, list);
}

If all the objects of your list inherit from the same class, you can also use the XmlInclude attribute to specify the expected types :

[XmlInclude(typeof(Foo)), XmlInclude(typeof(Bar))]
public class MyBaseClass
{
}

How can I parse a JSON file with PHP?

Try it:

foreach ($json_a as $key => $value)
 {
   echo $key, ' : ';
   foreach($value as $v)
   {
       echo $v."  ";
   }
}

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Directly from the Windows.h header file:

#ifndef WIN32_LEAN_AND_MEAN
    #include <cderr.h>
    #include <dde.h>
    #include <ddeml.h>
    #include <dlgs.h>
    #ifndef _MAC
        #include <lzexpand.h>
        #include <mmsystem.h>
        #include <nb30.h>
        #include <rpc.h>
    #endif
    #include <shellapi.h>
    #ifndef _MAC
        #include <winperf.h>
        #include <winsock.h>
    #endif
    #ifndef NOCRYPT
        #include <wincrypt.h>
        #include <winefs.h>
        #include <winscard.h>
    #endif

    #ifndef NOGDI
        #ifndef _MAC
            #include <winspool.h>
            #ifdef INC_OLE1
                #include <ole.h>
            #else
                #include <ole2.h>
            #endif /* !INC_OLE1 */
        #endif /* !MAC */
        #include <commdlg.h>
    #endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */

if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.

Also, from Microsoft's support page:

To speed the build process, Visual C++ and the Windows Headers provide the following new defines:

VC_EXTRALEAN
WIN32_LEAN_AND_MEAN

You can use them to reduce the size of the Win32 header files.

Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.

Transform DateTime into simple Date in Ruby on Rails

Try converting the entry to a string first. As long as the database column type is a date it will be formated as a date.

self.date || self.exif_date_time_original.to_s

Display date in dd/mm/yyyy format in vb.net

Like this ..

MsgBox(format(dt,"dd/MM/yyyy"))

Stacked bar chart

Building on Roland's answer, using tidyr to reshape the data from wide to long:

library(tidyr)
library(ggplot2)

df <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

df %>% 
  gather(variable, value, F1:F3) %>% 
  ggplot(aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

enter image description here

Visual Studio Expand/Collapse keyboard shortcuts

As you can see, there are several ways to achieve this.

I personally use:

Expand all: CTRL + M + L

Collapse all: CTRL + M + O

Bonus:

Expand/Collapse on cursor location: CTRL + M + M

How do I open port 22 in OS X 10.6.7

I'm using OSX 10.11.6 and this article works for me.

enter image description here

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

In my case, the issue was with a new class not being recognized. I solved the issue by deleting the class and re-adding it but this time checking the Watch App Extension option when creating the new class.

enter image description here

Please note that I do have a Watch App Extension in my Application.

Understanding the ngRepeat 'track by' expression

You can track by $index if your data source has duplicate identifiers

e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]

You can't iterate this collection while using 'id' as identifier (duplicate id:1).

WON'T WORK:

<element ng-repeat="item.id as item.name for item in dataSource">
  // something with item ...
</element>

but you can, if using track by $index:

<element ng-repeat="item in dataSource track by $index">
  // something with item ...
</element>

get an element's id

In events handler you can get id as follows

_x000D_
_x000D_
function show(btn) {_x000D_
  console.log('Button id:',btn.id);_x000D_
}
_x000D_
<button id="myButtonId" onclick="show(this)">Click me</button>
_x000D_
_x000D_
_x000D_

how to sort order of LEFT JOIN in SQL query?

This will get you the most expensive car for the user:

SELECT users.userName, MAX(cars.carPrice)
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName

However, this statement makes me think that you want all of the cars prices sorted, descending:

So question: How do I set the LEFT JOIN table to be ordered by carPrice, DESC ?

So you could try this:

SELECT users.userName, cars.carPrice
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
ORDER BY users.userName ASC, cars.carPrice DESC

How to extract filename.tar.gz file

Check to make sure that the file is complete. This error message can occur if you only partially downloaded a file or if it has major issues. Check the MD5sum.

How to create a GUID/UUID in Python

Check this post, helped me a lot. In short, the best option for me was:

import random 
import string 

# defining function for random 
# string id with parameter 
def ran_gen(size, chars=string.ascii_uppercase + string.digits): 
    return ''.join(random.choice(chars) for x in range(size)) 

# function call for random string 
# generation with size 8 and string  
print (ran_gen(8, "AEIOSUMA23")) 

Because I needed just 4-6 random characters instead of bulky GUID.

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

The located assembly's manifest definition does not match the assembly reference

In my case it was an old version of the DLL in C:\WINDOWS\Microsoft.NET\Framework\~\Temporary ASP.NET Files\ directory. You can either delete or replace the old version, or you can remove and add back the reference to the DLL in your project. Basically, either way will create a new pointer to the temporary ASP.NET Files.

How to vertically align label and input in Bootstrap 3?

This works perfectly for me in Bootstrap 4.

<div class="form-row align-items-center">
   <div class="col-md-2">
     <label for="FirstName" style="margin-bottom:0rem !important;">First Name</label>
 </div>
 <div class="col-md-10">
    <input type="text" id="FirstName" name="FirstName" class="form-control" val=""/>
  /div>
</div>

POSTing JSON to URL via WebClient in C#

The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:

var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");

PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.

jQuery .search() to any string

Ah, that would be because RegExp is not jQuery. :)

Try this page. jQuery.attr doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text() to return the String representation.

Something like:

$("li").val("title").search(/sometext/i));

adb command for getting ip address assigned by operator

Try this command for Version <= Marshmallow,

adb devices

List of devices attached 38ccdc87 device

adb tcpip 5555

restarting in TCP mode port: 5555

adb shell ip addr show wlan0

24: wlan0: mtu 1500 qdisc mq state UP qlen 1000 link/ether ac:c1:ee:6b:22:f1 brd ff:ff:ff:ff:ff:ff inet 192.168.0.18/24 brd 192.168.0.255 scope global wlan0 valid_lft forever preferred_lft forever inet6 fd01::1d45:6b7a:a3b:5f4d/64 scope global temporary dynamic valid_lft 287sec preferred_lft 287sec inet6 fd01::aec1:eeff:fe6b:22f1/64 scope global dynamic valid_lft 287sec preferred_lft 287sec inet6 fe80::aec1:eeff:fe6b:22f1/64 scope link valid_lft forever preferred_lft forever

To connect to your device run this

adb connect 192.168.0.18

connected to 192.168.0.18:5555

Make sure you have adb inside this location android-sdk\platform-tools

How do I get the last day of a month?

If you want the date, given a month and a year, this seems about right:

public static DateTime GetLastDayOfMonth(this DateTime dateTime)
{
    return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month));
}

How to run Conda?

If you installed Anaconda with Visual Studio 2017 for Windows, conda executable is in this path or similar.

In my case path is this: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\Scripts

Steps to add it to your PATH:

  • On the Windows desktop, right-click My Computer.
  • In the pop-up menu, click Properties.
  • In the System Properties window, click the Advanced tab, and then click Environment Variables.
  • In the System Variables window, highlight Path, and click Edit.
  • Add your path and restart your cmd.

You will be able to execute conda

Happy coding!

Fixed point vs Floating point number

Take the number 123.456789

  • As an integer, this number would be 123
  • As a fixed point (2), this number would be 123.46 (Assuming you rounded it up)
  • As a floating point, this number would be 123.456789

Floating point lets you represent most every number with a great deal of precision. Fixed is less precise, but simpler for the computer..

Generating random strings with T-SQL

For SQL Server 2016 and later, here is a really simple and relatively efficient expression to generate cryptographically random strings of a given byte length:

--Generates 36 bytes (48 characters) of base64 encoded random data
select r from OpenJson((select Crypt_Gen_Random(36) r for json path)) 
  with (r varchar(max))

Note that the byte length is not the same as the encoded size; use the following from this article to convert:

Bytes = 3 * (LengthInCharacters / 4) - Padding

Programmatically Creating UILabel

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = @"Your Text";
[self.view addSubview:label];

Python: get key of index in dictionary

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

The view or its master was not found or no view engine supports the searched locations

In my case, I needed to use RedirectToAction to solve the problem.

[HttpGet]
[ControleDeAcessoAuthorize("Report/ExportToPDF")]
public ActionResult ExportToPDF(int id, string month, string output)
{
    try
    {
        // Validate
        if (output != "PDF")
        {
            throw new Exception("Invalid output.");
        }
        else
        {
            ...// code to generate report in PDF format
        }
    }
    catch (Exception ex)
    {
        return RedirectToAction("Error");
    }
}

[ControleDeAcessoAuthorize("Report/Error")]
public ActionResult Error()
{
    return View();
}

How to change letter spacing in a Textview?

As android doesn't support such a thing, you can do it manually with FontCreator. It has good options for font modifying. I used this tool to build a custom font, even if it takes some times but you can always use it in your projects.

SQL How to remove duplicates within select query?

here is the solution for your query returning only one row for each date in that table here in the solution 'tony' will occur twice as two different start dates are there for it

SELECT * FROM 
(
    SELECT T1.*, ROW_NUMBER() OVER(PARTITION BY TRUNC(START_DATE),OWNER_NAME ORDER BY 1,2 DESC )  RNM
    FROM TABLE T1
)
WHERE RNM=1

Handling errors in Promise.all

You can always wrap your promise returning functions in a way that they catches failure and returning instead an agreed value (e.g. error.message), so the exception won't roll all the way up to the Promise.all function and disable it.

async function resetCache(ip) {

    try {

        const response = await axios.get(`http://${ip}/resetcache`);
        return response;

    }catch (e) {

        return {status: 'failure', reason: 'e.message'};
    }

}

How do I create a foreign key in SQL Server?

This script is about creating tables with foreign key and I added referential integrity constraint sql-server.

create table exams
(  
    exam_id int primary key,
    exam_name varchar(50),
);

create table question_bank 
(
    question_id int primary key,
    question_exam_id int not null,
    question_text varchar(1024) not null,
    question_point_value decimal,
    constraint question_exam_id_fk
       foreign key references exams(exam_id)
               ON DELETE CASCADE
);

jQuery count number of divs with a certain class?

And for the plain js answer if anyone might be interested;

var count = document.getElementsByClassName("item");

Cheers.

Reference: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp

rails bundle clean

Just remove the obsolete gems from your Gemfile. If you're talking about Heroku (you didn't mention that) then the slug is compiled each new release, just using the current contents of that file.

Best practices for SQL varchar column length

VARCHAR(255) and VARCHAR(2) take exactly the same amount of space on disk! So the only reason to limit it is if you have a specific need for it to be smaller. Otherwise make them all 255.

Specifically, when doing sorting, larger column do take up more space, so if that hurts performance, then you need to worry about it and make them smaller. But if you only ever select 1 row from that table, then you can just make them all 255 and it won't matter.

See: What are the optimum varchar sizes for MySQL?

How to open a file / browse dialog using javascript?

How about make clicking the a tag, to click on the file button?

There is more browser support for this, but I use ES6, so if you really want to make it work in older and any browser, try to transpile it using babel, or just simply use ES5:

_x000D_
_x000D_
const aTag = document.getElementById("open-file-uploader");_x000D_
const fileInput = document.getElementById("input-button");_x000D_
aTag.addEventListener("click", () => fileInput.click());
_x000D_
#input-button {_x000D_
  position: abosulte;_x000D_
  width: 1px;_x000D_
  height: 1px;_x000D_
  clip: rect(1px 1px 1px 1px);_x000D_
  clip: rect(1px, 1px, 1px, 1px);_x000D_
}
_x000D_
<a href="#" id="open-file-uploader">Open file uploader</a>_x000D_
<input type="file" id="input-button" />
_x000D_
_x000D_
_x000D_

iFrame Height Auto (CSS)

 <div id="content" >
    <h1>Update Information</h1>
    <div id="support-box">
        <div id="wrapper">
            <iframe name="frame" id="frame" src="http://website.org/update.php" allowtransparency="true" frameborder="0"></iframe>
        </div>
    </div>
  </div>
 #support-box {
        width: 50%;
        float: left;
        display: block;
        height: 20rem; /* is support box height you can change as per your requirement*/
        background-color:#000;
    }
    #wrapper {
        width: 90%;
        display: block;
        position: relative;
        top: 50%;
        transform: translateY(-50%);
         background:#ddd;
       margin:auto;
       height:100px; /* here the height values are automatic you can leave this if you can*/

    }
    #wrapper iframe {
        width: 100%;
        display: block;
        padding:10px;
        margin:auto;
    }

https://jsfiddle.net/umd2ahce/1/

Display only date and no time

Just had to deal with this scenario myself - found a really easy way to do this, simply annotate your property in the model like this:

[DataType(DataType.Date)]
public DateTime? SomeDateProperty { get; set; }

It will hide the time button from the date picker too.

Sorry if this answer is a little late ;)

Set value to currency in <input type="number" />

Add step="0.01" to the <input type="number" /> parameters:

<input type="number" min="0.01" step="0.01" max="2500" value="25.67" />

Demo: http://jsfiddle.net/uzbjve2u/

But the Dollar sign must stay outside the textbox... every non-numeric or separator charachter will be cropped automatically.

Otherwise you could use a classic textbox, like described here.

Select unique values with 'select' function in 'dplyr' library

The dplyr select function selects specific columns from a data frame. To return unique values in a particular column of data, you can use the group_by function. For example:

library(dplyr)

# Fake data
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE))

# Return the distinct values of x
dat %>%
  group_by(x) %>%
  summarise() 

    x
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10

If you want to change the column name you can add the following:

dat %>%
  group_by(x) %>%
  summarise() %>%
  select(unique.x=x)

This both selects column x from among all the columns in the data frame that dplyr returns (and of course there's only one column in this case) and changes its name to unique.x.

You can also get the unique values directly in base R with unique(dat$x).

If you have multiple variables and want all unique combinations that appear in the data, you can generalize the above code as follows:

set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE), 
                 y=sample(letters[1:5], 100, replace=TRUE))

dat %>% 
  group_by(x,y) %>%
  summarise() %>%
  select(unique.x=x, unique.y=y)

Python way to clone a git repository

Github's libgit2 binding, pygit2 provides a one-liner cloning a remote directory:

clone_repository(url, path, 
    bare=False, repository=None, remote=None, checkout_branch=None, callbacks=None)

Facebook Open Graph not clearing cache

Years later and this is still a common problem, but its not always facebook's cache: It is very often human error (allow me to elaborate)

OG:TYPE effects your image scrape:

  1. https://ogp.me/#type_article not the same as https://ogp.me/#type_website

Be aware that og:type=website will cause any /sub-pages/ of that url to become "canonical". This means you will have trouble getting your images to update using the scraper no matter what you do.

Consider this "assumption and common mistake"

-<meta property="og:type" content="website" /> => https://www.example.org (parent)
-<meta property="og:type" content="website" /> => https://www.example.org/sub-page/
-<meta property="og:type" content="website" /> => https://www.example.org/sub-page/child-2/
- Ergo: /sub-page/ and /child-2/ will inherit the og:image of the parent

Those are not "all websites", 1 is a website, the others are articles.

If you do that Facebook will think all of those are canonical and it will put the FIRST og:image into all of them. (try it, you'll see) - if you set the og:url to be your root or parent domain you've told facebook they are all canonical. (there is good reason for that, but its off topic)

Consider this solution (which is what most people "really want")

-<meta property="og:type" content="article" /> => https://www.example.org/sub-page/
-<meta property="og:type" content="article" /> => https://www.example.org/sub-page/child-2/

If you do that now Facebook will give you far far less problems with scraping your NEW images.

In closing, YES the cache busters, random vars, changing urls and suggestions here can work, but they will seem like "intermittent voodoo" if the og:type is not specified correctly.

PS: remember that a CDN or serverside cache will serve to Facebook's scraper even if you "think" you can see the most recent version. (I wont spend any time on this other than to point out it will waste colossal amounts of your time if not double checked.)

C++ pointer to objects

if you want the object on the stack, try this:

MyClass myclass;
myclass.DoSomething();

If you need a pointer to that object:

MyClass* myclassptr = &myclass;
myclassptr->DoSomething();

Redirect HTTP to HTTPS on default virtual host without ServerName

I have use mkcert to create infinites *.dev.net subdomains & localhost with valid HTTPS/SSL certs (Windows 10 XAMPP & Linux Debian 10 Apache2)

I create the certs on Windows with mkcert v1.4.0 (execute CMD as Administrator):

mkcert -install
mkcert localhost "*.dev.net"

This create in Windows 10 this files (I will install it first in Windows 10 XAMPP)

localhost+1.pem
localhost+1-key.pem

Overwrite the XAMPP default certs:

copy "localhost+1.pem" C:\xampp\apache\conf\ssl.crt\server.crt
copy "localhost+1-key.pem"  C:\xampp\apache\conf\ssl.key\server.key

Now, in Apache2 for Debian 10, activate SSL & vhost_alias

a2enmod vhosts_alias
a2enmod ssl
a2ensite default-ssl
systemctl restart apache2

For vhost_alias add this Apache2 config:

nano /etc/apache2/sites-available/999-vhosts_alias.conf

With this content:

<VirtualHost *:80>
   UseCanonicalName Off
   ServerAlias *.dev.net
   VirtualDocumentRoot "/var/www/html/%0/"
</VirtualHost>

Add the site:

a2ensite 999-vhosts_alias

Copy the certs to /root/mkcert by SSH and let overwrite the Debian ones:

systemctl stop apache2

mv /etc/ssl/certs/ssl-cert-snakeoil.pem /etc/ssl/certs/ssl-cert-snakeoil.pem.bak
mv /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/private/ssl-cert-snakeoil.key.bak

cp "localhost+1.pem" /etc/ssl/certs/ssl-cert-snakeoil.pem
cp "localhost+1-key.pem" /etc/ssl/private/ssl-cert-snakeoil.key

chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key
chmod 640 /etc/ssl/private/ssl-cert-snakeoil.key

systemctl start apache2

Edit the SSL config

nano /etc/apache2/sites-enabled/default-ssl.conf

At the start edit the file with this content:

<IfModule mod_ssl.c>
    <VirtualHost *:443>

            UseCanonicalName Off
            ServerAlias *.dev.net
            ServerAdmin webmaster@localhost

            # DocumentRoot /var/www/html/
            VirtualDocumentRoot /var/www/html/%0/

...

Last restart:

systemctl restart apache2

NOTE: don´t forget to create the folders for your subdomains in /var/www/html/

/var/www/html/subdomain1.dev.net
/var/www/html/subdomain2.dev.net
/var/www/html/subdomain3.dev.net

How do I register a .NET DLL file in the GAC?

Just drag and drop the DLL file into folder C:\Windows\assembly using Windows Explorer.

Caveat:

In earlier versions of the .NET Framework, the Shfusion.dll Windows shell extension let you install assemblies by dragging them to File Explorer. Beginning with .NET Framework 4, Shfusion.dll is obsolete.

Source: How to: Install an assembly into the global assembly cache

How to get an element by its href in jquery?

Yes, you can use jQuery's attribute selector for that.

var linksToGoogle = $('a[href="http://google.com"]');

Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:

var allLinksToGoogle = $('a[href^="http://google.com"]');

Count indexes using "for" in Python

This?

for i in range(0,5): 
 print(i)

Run parallel multiple commands at once in the same terminal

Use GNU Parallel:

(echo command1; echo command2) | parallel
parallel ::: command1 command2

To kill:

parallel ::: command1 command2 &
PID=$!
kill -TERM $PID
kill -TERM $PID

illegal use of break statement; javascript

I have a function next() which will maybe inspire you.

function queue(target) {
        var array = Array.prototype;

        var queueing = [];

        target.queue = queue;
        target.queued = queued;

        return target;

        function queued(action) {
            return function () {
                var self = this;
                var args = arguments;

                queue(function (next) {
                    action.apply(self, array.concat.apply(next, args));
                });
            };
        }

        function queue(action) {
            if (!action) {
                return;
            }

            queueing.push(action);

            if (queueing.length === 1) {
                next();
            }
        }

        function next() {
            queueing[0](function (err) {
                if (err) {
                    throw err;
                }

                queueing = queueing.slice(1);

                if (queueing.length) {
                    next();
                }
            });
        }
    }

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

Believe or not, keytool does not provide such basic functionality like importing private key to keystore. You can try this workaround with merging PKSC12 file with private key to a keystore:

keytool -importkeystore \
  -deststorepass storepassword \
  -destkeypass keypassword \
  -destkeystore my-keystore.jks \
  -srckeystore cert-and-key.p12 \
  -srcstoretype PKCS12 \
  -srcstorepass p12password \
  -alias 1

Or just use more user-friendly KeyMan from IBM for keystore handling instead of keytool.

PyCharm shows unresolved references error for valid code

I closed all the other projects and run my required project in isolation in Pycharm. I created a separate virtualenv from pycharm and added all the required modules in it by using pip. I added this virtual environment in project's interpreter. This solved my problem.

CUDA incompatible with my gcc version

For CUDA7.5 these lines work:

sudo ln -s /usr/bin/gcc-4.9 /usr/local/cuda/bin/gcc 
sudo ln -s /usr/bin/g++-4.9 /usr/local/cuda/bin/g++

Java: Best way to iterate through a Collection (here ArrayList)

All of them have there own uses:

  1. If you have an iterable and need to traverse unconditionally to all of them:

    for (iterable_type iterable_element : collection)

  2. If you have an iterable but need to conditionally traverse:

    for (Iterator iterator = collection.iterator(); iterator.hasNext();)

  3. If data-structure does not implement iterable:

    for (int i = 0; i < collection.length; i++)

How to dump a dict to a json file?

If you're using Path:

example_path = Path('/tmp/test.json')
example_dict = {'x': 24, 'y': 25}
json_str = json.dumps(example_dict, indent=4) + '\n'
example_path.write_text(json_str, encoding='utf-8')

Using 'sudo apt-get install build-essentials'

To auto-generate the "source.list" file I suggest to use:

https://debgen.simplylinux.ch/

Where you can select the country, the distribution, ..etc After that, all you need to do is to replace (take a backup of the file first) your original source.list file with the generated one and do as mentioned in other answers:

sudo apt-get update
sudo apt-get install build-essential

Ajax post request in laravel 5 return error 500 (Internal Server Error)

Laravel 7.X In bootstrap.js, in axios related code, add:

window.axios.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');

Solved lot of unexplained 500 ajax errors. Of course it's for those who use axios

jQuery hover and class selector

If someone reads the original question to mean that they want to dynamically change the hover css and not just change the base css rule for the element, I've found this to work:

I have a dynamically loaded page that requires me to find out how high the container becomes after data is loaded. Once loaded, I want to change the hover effect of the css so that an element covers the resulting container. I need to change the css .daymark:hover rule to have a new height. This is how...

function changeAttr(attrName,changeThis,toThis){
    var mysheet=document.styleSheets[1], targetrule;
    var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules;

    for (i=0; i<myrules.length; i++){
        if(myrules[i].selectorText.toLowerCase()==".daymark:hover"){ //find "a:hover" rule
            targetrule=myrules[i];
            break;
        }
    }
    switch(changeThis)
    {
        case "height":
            targetrule.style.height=toThis+"px";
            break;
        case "width":
            targetrule.style.width=toThis+"px";
            break;
    }

}

What is a "slug" in Django?

In short slug help get rid of those ugly looking urls with valid-urls for examples in an ecommerec site instead of showing the url as www.myecom.com/product/5432156 i can show it like www.myecom.com/product/iphone11 with the help of slug

How to find the length of a string in R

nchar(YOURSTRING)

you may need to convert to a character vector first;

nchar(as.character(YOURSTRING))

How to layout multiple panels on a jFrame? (java)

The JPanel is actually only a container where you can put different elements in it (even other JPanels). So in your case I would suggest one big JPanel as some sort of main container for your window. That main panel you assign a Layout that suits your needs ( here is an introduction to the layouts).

After you set the layout to your main panel you can add the paint panel and the other JPanels you want (like those with the text in it..).

  JPanel mainPanel = new JPanel();
  mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

  JPanel paintPanel = new JPanel();
  JPanel textPanel = new JPanel();

  mainPanel.add(paintPanel);
  mainPanel.add(textPanel);

This is just an example that sorts all sub panels vertically (Y-Axis). So if you want some other stuff at the bottom of your mainPanel (maybe some icons or buttons) that should be organized with another layout (like a horizontal layout), just create again a new JPanel as a container for all the other stuff and set setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS).

As you will find out, the layouts are quite rigid and it may be difficult to find the best layout for your panels. So don't give up, read the introduction (the link above) and look at the pictures – this is how I do it :)

Or you can just use NetBeans to write your program. There you have a pretty easy visual editor (drag and drop) to create all sorts of Windows and Frames. (only understanding the code afterwards is ... tricky sometimes.)

EDIT

Since there are some many people interested in this question, I wanted to provide a complete example of how to layout a JFrame to make it look like OP wants it to.

The class is called MyFrame and extends swings JFrame

public class MyFrame extends javax.swing.JFrame{

    // these are the components we need.
    private final JSplitPane splitPane;  // split the window in top and bottom
    private final JPanel topPanel;       // container panel for the top
    private final JPanel bottomPanel;    // container panel for the bottom
    private final JScrollPane scrollPane; // makes the text scrollable
    private final JTextArea textArea;     // the text
    private final JPanel inputPanel;      // under the text a container for all the input elements
    private final JTextField textField;   // a textField for the text the user inputs
    private final JButton button;         // and a "send" button

    public MyFrame(){

        // first, lets create the containers:
        // the splitPane devides the window in two components (here: top and bottom)
        // users can then move the devider and decide how much of the top component
        // and how much of the bottom component they want to see.
        splitPane = new JSplitPane();

        topPanel = new JPanel();         // our top component
        bottomPanel = new JPanel();      // our bottom component

        // in our bottom panel we want the text area and the input components
        scrollPane = new JScrollPane();  // this scrollPane is used to make the text area scrollable
        textArea = new JTextArea();      // this text area will be put inside the scrollPane

        // the input components will be put in a separate panel
        inputPanel = new JPanel();
        textField = new JTextField();    // first the input field where the user can type his text
        button = new JButton("send");    // and a button at the right, to send the text

        // now lets define the default size of our window and its layout:
        setPreferredSize(new Dimension(400, 400));     // let's open the window with a default size of 400x400 pixels
        // the contentPane is the container that holds all our components
        getContentPane().setLayout(new GridLayout());  // the default GridLayout is like a grid with 1 column and 1 row,
        // we only add one element to the window itself
        getContentPane().add(splitPane);               // due to the GridLayout, our splitPane will now fill the whole window

        // let's configure our splitPane:
        splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);  // we want it to split the window verticaly
        splitPane.setDividerLocation(200);                    // the initial position of the divider is 200 (our window is 400 pixels high)
        splitPane.setTopComponent(topPanel);                  // at the top we want our "topPanel"
        splitPane.setBottomComponent(bottomPanel);            // and at the bottom we want our "bottomPanel"

        // our topPanel doesn't need anymore for this example. Whatever you want it to contain, you can add it here
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS)); // BoxLayout.Y_AXIS will arrange the content vertically

        bottomPanel.add(scrollPane);                // first we add the scrollPane to the bottomPanel, so it is at the top
        scrollPane.setViewportView(textArea);       // the scrollPane should make the textArea scrollable, so we define the viewport
        bottomPanel.add(inputPanel);                // then we add the inputPanel to the bottomPanel, so it under the scrollPane / textArea

        // let's set the maximum size of the inputPanel, so it doesn't get too big when the user resizes the window
        inputPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75));     // we set the max height to 75 and the max width to (almost) unlimited
        inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));   // X_Axis will arrange the content horizontally

        inputPanel.add(textField);        // left will be the textField
        inputPanel.add(button);           // and right the "send" button

        pack();   // calling pack() at the end, will ensure that every layout and size we just defined gets applied before the stuff becomes visible
    }

    public static void main(String args[]){
        EventQueue.invokeLater(new Runnable(){
            @Override
            public void run(){
                new MyFrame().setVisible(true);
            }
        });
    }
}

Please be aware that this is only an example and there are multiple approaches to layout a window. It all depends on your needs and if you want the content to be resizable / responsive. Another really good approach would be the GridBagLayout which can handle quite complex layouting, but which is also quite complex to learn.

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

I started with Lua but, then I found that I wanted to see the results instead of just the good old command line flash. So i just added the following line to my file and hey presto, the standard:

please press any key to continue...

os.execute("PAUSE")

My example file is only a print and then a pause statment so I am sure you don't need that posted here.

I am not sure of the CPU implications of a running a process for a full script. However stopping the code mid flow in debugging could be useful.

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

I dug deeper into this and found the best solutions are here.

http://blog.notdot.net/2010/07/Getting-unicode-right-in-Python

In my case I solved "UnicodeEncodeError: 'charmap' codec can't encode character "

original code:

print("Process lines, file_name command_line %s\n"% command_line))

New code:

print("Process lines, file_name command_line %s\n"% command_line.encode('utf-8'))  

better way to drop nan rows in pandas

Use dropna:

dat.dropna()

You can pass param how to drop if all labels are nan or any of the labels are nan

dat.dropna(how='any')    #to drop if any value in the row has a nan
dat.dropna(how='all')    #to drop if all values in the row are nan

Hope that answers your question!

Edit 1: In case you want to drop rows containing nan values only from particular column(s), as suggested by J. Doe in his answer below, you can use the following:

dat.dropna(subset=[col_list])  # col_list is a list of column names to consider for nan values.

How to install a specific JDK on Mac OS X?

As the message says, you have to go to Apple, not Sun, for Java on the Mac. As far as I know, Apple JDK 6 is installed by default on Mac OS X 10.6 (Snow Leopard). Maybe you need to install the developer tools from your Mac OS X installation DVD (the dev tools are an optional install from the OS DVD).

See: http://developer.apple.com/java/

NOTE This answer from 16 Oct 2009 is now outdated; you can get the JDK for Mac OS X from the regular JDK download page on Oracle's website now.

How can I use optional parameters in a T-SQL stored procedure?

Dynamically changing searches based on the given parameters is a complicated subject and doing it one way over another, even with only a very slight difference, can have massive performance implications. The key is to use an index, ignore compact code, ignore worrying about repeating code, you must make a good query execution plan (use an index).

Read this and consider all the methods. Your best method will depend on your parameters, your data, your schema, and your actual usage:

Dynamic Search Conditions in T-SQL by by Erland Sommarskog

The Curse and Blessings of Dynamic SQL by Erland Sommarskog

If you have the proper SQL Server 2008 version (SQL 2008 SP1 CU5 (10.0.2746) and later), you can use this little trick to actually use an index:

Add OPTION (RECOMPILE) onto your query, see Erland's article, and SQL Server will resolve the OR from within (@LastName IS NULL OR LastName= @LastName) before the query plan is created based on the runtime values of the local variables, and an index can be used.

This will work for any SQL Server version (return proper results), but only include the OPTION(RECOMPILE) if you are on SQL 2008 SP1 CU5 (10.0.2746) and later. The OPTION(RECOMPILE) will recompile your query, only the verison listed will recompile it based on the current run time values of the local variables, which will give you the best performance. If not on that version of SQL Server 2008, just leave that line off.

CREATE PROCEDURE spDoSearch
    @FirstName varchar(25) = null,
    @LastName varchar(25) = null,
    @Title varchar(25) = null
AS
    BEGIN
        SELECT ID, FirstName, LastName, Title
        FROM tblUsers
        WHERE
                (@FirstName IS NULL OR (FirstName = @FirstName))
            AND (@LastName  IS NULL OR (LastName  = @LastName ))
            AND (@Title     IS NULL OR (Title     = @Title    ))
        OPTION (RECOMPILE) ---<<<<use if on for SQL 2008 SP1 CU5 (10.0.2746) and later
    END

Bootstrap radio button "checked" flag

A javascript fix to apply the 'active' class to all labels that are parents of checked inputs:

$(':input:checked').parent('.btn').addClass('active');

insert right after

$('.btn').button();

How can I generate a random number in a certain range?

To extend what Rahul Gupta said:

You can use Java function int random = Random.nextInt(n).
This returns a random int in the range [0, n-1].

I.e., to get the range [20, 80] use:

final int random = new Random().nextInt(61) + 20; // [0, 60] + 20 => [20, 80]

To generalize more:

final int min = 20;
final int max = 80;
final int random = new Random().nextInt((max - min) + 1) + min;

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

The problem is that POST method is forbidden for Nginx server's static files requests. Here is the workaround:

# Pass 405 as 200 for requested address:

server {
listen       80;
server_name  localhost;

location / {
    root   html;
    index  index.html index.htm;
}

error_page  404     /404.html;
error_page  403     /403.html;

error_page  405     =200 $uri;
}

If using proxy:

# If Nginx is like proxy for Apache:

error_page 405 =200 @405; 

location @405 { 
    root /htdocs; 
    proxy_pass http://localhost:8080; 
}

If using FastCGI:

location ~\.php(.*) {
fastcgi_pass 127.0.0.1:9000;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include /etc/nginx/fastcgi_params;
}

Browsers usually use GET, so you can use online tools like ApiTester to test your requests.

Source

Code for best fit straight line of a scatter plot in python

Have implemented @Micah 's solution to generate a trendline with a few changes and thought I'd share:

  • Coded as a function
  • Option for a polynomial trendline (input order=2)
  • Function can also just return the coefficient of determination (R^2, input Rval=True)
  • More Numpy array optimisations

Code:

def trendline(xd, yd, order=1, c='r', alpha=1, Rval=False):
    """Make a line of best fit"""

    #Calculate trendline
    coeffs = np.polyfit(xd, yd, order)

    intercept = coeffs[-1]
    slope = coeffs[-2]
    power = coeffs[0] if order == 2 else 0

    minxd = np.min(xd)
    maxxd = np.max(xd)

    xl = np.array([minxd, maxxd])
    yl = power * xl ** 2 + slope * xl + intercept

    #Plot trendline
    plt.plot(xl, yl, c, alpha=alpha)

    #Calculate R Squared
    p = np.poly1d(coeffs)

    ybar = np.sum(yd) / len(yd)
    ssreg = np.sum((p(xd) - ybar) ** 2)
    sstot = np.sum((yd - ybar) ** 2)
    Rsqr = ssreg / sstot

    if not Rval:
        #Plot R^2 value
        plt.text(0.8 * maxxd + 0.2 * minxd, 0.8 * np.max(yd) + 0.2 * np.min(yd),
                 '$R^2 = %0.2f$' % Rsqr)
    else:
        #Return the R^2 value:
        return Rsqr

Setting up a websocket on Apache?

The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.

http://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html

How can I easily add storage to a VirtualBox machine with XP installed?

Adding a second drive is probably easiest. That would only take a few minutes, and it wouldn't require any configuration, really.

Alternatively, you could create the second, bigger drive, then run a disk imaging utility to copy all data on disk1 to disk2. That certainly shouldn't take a few hours, but it would take longer than just living with two drives.