Programs & Examples On #Acts as tree

Variables as commands in bash scripts

eval is not an acceptable practice if your directory names can be generated by untrusted sources. See BashFAQ #48 for more on why eval should not be used, and BashFAQ #50 for more on the root cause of this problem and its proper solutions, some of which are touched on below:

If you need to build up your commands over time, use arrays:

tar_cmd=( tar cv "$directory" )
split_cmd=( split -b 1024m - "$backup_file" )
encrypt_cmd=( openssl des3 -salt )
"${tar_cmd[@]}" | "${encrypt_cmd[@]}" | "${split_cmd[@]}"

Alternately, if this is just about defining your commands in one central place, use functions:

tar_cmd() { tar cv "$directory"; }
split_cmd() { split -b 1024m - "$backup_file"; }
encrypt_cmd() { openssl des3 -salt; }
tar_cmd | split_cmd | encrypt_cmd

How to generate a range of numbers between two numbers?

Nothing new but I rewrote Brian Pressler solution to be easier on the eye, it might be useful to someone (even if it's just future me):

alter function [dbo].[fn_GenerateNumbers]
(   
    @start int,
    @end  int
) returns table
return

with 
b0 as (select n from (values (0),(0x00000001),(0x00000002),(0x00000003),(0x00000004),(0x00000005),(0x00000006),(0x00000007),(0x00000008),(0x00000009),(0x0000000A),(0x0000000B),(0x0000000C),(0x0000000D),(0x0000000E),(0x0000000F)) as b0(n)),
b1 as (select n from (values (0),(0x00000010),(0x00000020),(0x00000030),(0x00000040),(0x00000050),(0x00000060),(0x00000070),(0x00000080),(0x00000090),(0x000000A0),(0x000000B0),(0x000000C0),(0x000000D0),(0x000000E0),(0x000000F0)) as b1(n)),
b2 as (select n from (values (0),(0x00000100),(0x00000200),(0x00000300),(0x00000400),(0x00000500),(0x00000600),(0x00000700),(0x00000800),(0x00000900),(0x00000A00),(0x00000B00),(0x00000C00),(0x00000D00),(0x00000E00),(0x00000F00)) as b2(n)),
b3 as (select n from (values (0),(0x00001000),(0x00002000),(0x00003000),(0x00004000),(0x00005000),(0x00006000),(0x00007000),(0x00008000),(0x00009000),(0x0000A000),(0x0000B000),(0x0000C000),(0x0000D000),(0x0000E000),(0x0000F000)) as b3(n)),
b4 as (select n from (values (0),(0x00010000),(0x00020000),(0x00030000),(0x00040000),(0x00050000),(0x00060000),(0x00070000),(0x00080000),(0x00090000),(0x000A0000),(0x000B0000),(0x000C0000),(0x000D0000),(0x000E0000),(0x000F0000)) as b4(n)),
b5 as (select n from (values (0),(0x00100000),(0x00200000),(0x00300000),(0x00400000),(0x00500000),(0x00600000),(0x00700000),(0x00800000),(0x00900000),(0x00A00000),(0x00B00000),(0x00C00000),(0x00D00000),(0x00E00000),(0x00F00000)) as b5(n)),
b6 as (select n from (values (0),(0x01000000),(0x02000000),(0x03000000),(0x04000000),(0x05000000),(0x06000000),(0x07000000),(0x08000000),(0x09000000),(0x0A000000),(0x0B000000),(0x0C000000),(0x0D000000),(0x0E000000),(0x0F000000)) as b6(n)),
b7 as (select n from (values (0),(0x10000000),(0x20000000),(0x30000000),(0x40000000),(0x50000000),(0x60000000),(0x70000000)) as b7(n))

select s.n
from (
    select
          b7.n
        | b6.n
        | b5.n
        | b4.n
        | b3.n
        | b2.n
        | b1.n
        | b0.n
        + @start
         n
    from b0
    join b1 on b0.n <= @end-@start and b1.n <= @end-@start
    join b2 on b2.n <= @end-@start
    join b3 on b3.n <= @end-@start
    join b4 on b4.n <= @end-@start
    join b5 on b5.n <= @end-@start
    join b6 on b6.n <= @end-@start
    join b7 on b7.n <= @end-@start
) s
where @end >= s.n

GO

How to sum the values of a JavaScript object?

Honestly, given our "modern times" I'd go with a functional programming approach whenever possible, like so:

const sumValues = (obj) => Object.keys(obj).reduce((acc, value) => acc + obj[value], 0);

Our accumulator acc, starting with a value of 0, is accumulating all looped values of our object. This has the added benefit of not depending on any internal or external variables; it's a constant function so it won't be accidentally overwritten... win for ES2015!

nvm is not compatible with the npm config "prefix" option:

Note:
to remove, delete, or uninstall nvm - just remove the $NVM_DIR folder (usually ~/.nvm)
you can try :
rm -rf ~/.nvm

In MySQL, can I copy one row to insert into the same table?

This procedure assumes that:

  • you don't have _duplicate_temp_table
  • your primary key is int
  • you have access to create table

Of course this is not perfect, but in certain (probably most) cases it will work.

DELIMITER $$
CREATE PROCEDURE DUPLICATE_ROW(copytable VARCHAR(255), primarykey VARCHAR(255), copyid INT, out newid INT)
BEGIN
        DECLARE EXIT HANDLER FOR SQLEXCEPTION SET @error=1;
        SET @temptable = '_duplicate_temp_table';
        SET @sql_text = CONCAT('CREATE TABLE ', @temptable, ' LIKE ', copytable);
        PREPARE stmt FROM @sql_text;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SET @sql_text = CONCAT('INSERT INTO ', @temptable, ' SELECT * FROM ', copytable, ' where ', primarykey,'=', copyid);
        PREPARE stmt FROM @sql_text;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SET @sql_text = CONCAT('SELECT max(', primarykey, ')+1 FROM ', copytable, ' INTO @newid');
        PREPARE stmt FROM @sql_text;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SET @sql_text = CONCAT('UPDATE ', @temptable, ' SET ', primarykey, '=@newid');
        PREPARE stmt FROM @sql_text;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SET @sql_text = CONCAT('INSERT INTO ', copytable, ' SELECT * FROM ', @temptable, '');
        PREPARE stmt FROM @sql_text;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SET @sql_text = CONCAT('DROP TABLE ', @temptable);
        PREPARE stmt FROM @sql_text;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SELECT @newid INTO newid;
END $$
DELIMITER ;

CALL DUPLICATE_ROW('table', 'primarykey', 1, @duplicate_id);
SELECT @duplicate_id;

Postgres and Indexes on Foreign Keys and Primary Keys

PostgreSQL automatically creates indexes on primary keys and unique constraints, but not on the referencing side of foreign key relationships.

When Pg creates an implicit index it will emit a NOTICE-level message that you can see in psql and/or the system logs, so you can see when it happens. Automatically created indexes are visible in \d output for a table, too.

The documentation on unique indexes says:

PostgreSQL automatically creates an index for each unique constraint and primary key constraint to enforce uniqueness. Thus, it is not necessary to create an index explicitly for primary key columns.

and the documentation on constraints says:

Since a DELETE of a row from the referenced table or an UPDATE of a referenced column will require a scan of the referencing table for rows matching the old value, it is often a good idea to index the referencing columns. Because this is not always needed, and there are many choices available on how to index, declaration of a foreign key constraint does not automatically create an index on the referencing columns.

Therefore you have to create indexes on foreign-keys yourself if you want them.

Note that if you use primary-foreign-keys, like 2 FK's as a PK in a M-to-N table, you will have an index on the PK and probably don't need to create any extra indexes.

While it's usually a good idea to create an index on (or including) your referencing-side foreign key columns, it isn't required. Each index you add slows DML operations down slightly, so you pay a performance cost on every INSERT, UPDATE or DELETE. If the index is rarely used it may not be worth having.

What is the effect of extern "C" in C++?

When mixing C and C++ (i.e., a. calling C function from C++; and b. calling C++ function from C), the C++ name mangling causes linking problems. Technically speaking, this issue happens only when the callee functions have been already compiled into binary (most likely, a *.a library file) using the corresponding compiler.

So we need to use extern "C" to disable the name mangling in C++.

python how to "negate" value : if true return false, if false return true

Use the not boolean operator:

nyval = not myval

not returns a boolean value (True or False):

>>> not 1
False
>>> not 0
True

If you must have an integer, cast it back:

nyval = int(not myval)

However, the python bool type is a subclass of int, so this may not be needed:

>>> int(not 0)
1
>>> int(not 1)
0
>>> not 0 == 1
True
>>> not 1 == 0
True

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

Where is shared_ptr?

for VS2008 with feature pack update, shared_ptr can be found under namespace std::tr1.

std::tr1::shared_ptr<int> MyIntSmartPtr = new int;

of

if you had boost installation path (for example @ C:\Program Files\Boost\boost_1_40_0) added to your IDE settings:

#include <boost/shared_ptr.hpp>

What does "xmlns" in XML mean?

It defines an XML Namespace.

In your example, the Namespace Prefix is "android" and the Namespace URI is "http://schemas.android.com/apk/res/android"

In the document, you see elements like: <android:foo />

Think of the namespace prefix as a variable with a short name alias for the full namespace URI. It is the equivalent of writing <http://schemas.android.com/apk/res/android:foo /> with regards to what it "means" when an XML parser reads the document.

NOTE: You cannot actually use the full namespace URI in place of the namespace prefix in an XML instance document.

Check out this tutorial on namespaces: http://www.sitepoint.com/xml-namespaces-explained/

How to pause javascript code execution for 2 seconds

This Link might be helpful for you.

Every time I've wanted a sleep in the middle of my function, I refactored to use a setTimeout().

Move view with keyboard using Swift

If you have 2 or more text fields on the same VC, and the user taps on one of them and then taps on the other one, without calling the function keyboardWillHide, the view is going upwards one more time, which is not necessary, because you'll have the keyboard, a blank space which has the height of the keyboard, and then the view, using the code in the answer I edited:

override func viewDidLoad() {       
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        self.view.frame.origin.y -= keyboardSize.height
    }
}

func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        self.view.frame.origin.y += keyboardSize.height
    }
}

To solve this, replace the two functions "KeyboardWillShow/Hide" to these:

func keyboardWillShow(notification: NSNotification) {
 if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
    if view.frame.origin.y == 0{
        self.view.frame.origin.y -= keyboardSize.height
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        if view.frame.origin.y != 0 {
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

How do I get the coordinates of a mouse click on a canvas element?

First, as others have said, you need a function to get the position of the canvas element. Here's a method that's a little more elegant than some of the others on this page (IMHO). You can pass it any element and get its position in the document:

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

Now calculate the current position of the cursor relative to that:

$('#canvas').mousemove(function(e) {
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var coordinateDisplay = "x=" + x + ", y=" + y;
    writeCoordinateDisplay(coordinateDisplay);
});

Notice that I've separated the generic findPos function from the event handling code. (As it should be. We should try to keep our functions to one task each.)

The values of offsetLeft and offsetTop are relative to offsetParent, which could be some wrapper div node (or anything else, for that matter). When there is no element wrapping the canvas they're relative to the body, so there is no offset to subtract. This is why we need to determine the position of the canvas before we can do anything else.

Similary, e.pageX and e.pageY give the position of the cursor relative to the document. That's why we subtract the canvas's offset from those values to arrive at the true position.

An alternative for positioned elements is to directly use the values of e.layerX and e.layerY. This is less reliable than the method above for two reasons:

  1. These values are also relative to the entire document when the event does not take place inside a positioned element
  2. They are not part of any standard

Difference between $(document.body) and $('body')

There should be no difference at all maybe the first is a little more performant but i think it's trivial ( you shouldn't worry about this, really ).

With both you wrap the <body> tag in a jQuery object

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

jQuery OR Selector?

Finally I've found hack how to do it:

div:not(:not(.classA,.classB)) > span

(selects div with class classA OR classB with direct child span)

How to embed a .mov file in HTML?

Had issues using the code in the answer provided by @haynar above (wouldn't play on Chrome), and it seems that one of the more modern ways to ensure it plays is to use the video tag

Example:

<video controls="controls" width="800" height="600" 
       name="Video Name" src="http://www.myserver.com/myvideo.mov"></video>

This worked like a champ for my .mov file (generated from Keynote) in both Safari and Chrome, and is listed as supported in most modern browsers (The video tag is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.)

Note: Will work in IE / etc.. if you use MP4 (Mov is not officially supported by those guys)

How can I get the list of files in a directory using C or C++?

Here is a very simple code in C++11 using boost::filesystem library to get file names in a directory (excluding folder names):

#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;

int main()
{
    path p("D:/AnyFolder");
    for (auto i = directory_iterator(p); i != directory_iterator(); i++)
    {
        if (!is_directory(i->path())) //we eliminate directories
        {
            cout << i->path().filename().string() << endl;
        }
        else
            continue;
    }
}

Output is like:

file1.txt
file2.dat

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Besides the already stated answers about using Vector, Vector also has a bunch of methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don't check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization - with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won't be easy to replace it with a different List implementation.

Update OpenSSL on OS X with Homebrew

If you're using Homebrew /usr/local/bin should already be at the front of $PATH or at least come before /usr/bin. If you now run brew link --force openssl in your terminal window, open a new one and run which openssl in it. It should now show openssl under /usr/local/bin.

Counting repeated elements in an integer array

public class ArrayDuplicate {
private static Scanner sc;
static int totalCount = 0;

    public static void main(String[] args) {
        int n, num;
        sc = new Scanner(System.in);
        System.out.print("Enter the size of array: ");
        n =sc.nextInt();
        int[] a = new int[n];
        for(int i=0;i<n;i++){
            System.out.print("Enter the element at position "+i+": ");
            num = sc.nextInt();
            a[enter image description here][1][i]=num;
        }
        System.out.print("Elements in array are: ");
        for(int i=0;i<a.length;i++)
            System.out.print(a[i]+" ");
        System.out.println();
        duplicate(a);
        System.out.println("There are "+totalCount+" repeated numbers:");
    }

    public static void duplicate(int[] a){
        int j = 0,count, recount, temp;
        for(int i=0; i<a.length;i++){
            count = 0;
            recount = 0;
            j=i+1;
            while(j<a.length){
                if(a[i]==a[j])
                    count++;
                j++;
            }
            if(count>0){
                temp = a[i];
                for(int x=0;x<i;x++){
                    if(a[x]==temp)
                        recount++;
                }
                if(recount==0){                 
                    totalCount++;
                    System.out.println(+a[i]+" : "+count+" times");
                }   
            }

        }
    }

}

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

How to print a dictionary line by line in Python?

for x in cars:
    print (x)
    for y in cars[x]:
        print (y,':',cars[x][y])

output:

A
color : 2
speed : 70
B
color : 3
speed : 60

Changing fonts in ggplot2

To change the font globally for ggplot2 plots.

theme_set(theme_gray(base_size = 20, base_family = 'Font Name' ))

Laravel Eloquent ORM Transactions

If you want to avoid closures, and happy to use facades, the following keeps things nice and clean:

try {
    \DB::beginTransaction();

    $user = \Auth::user();
    $user->fill($request->all());
    $user->push();

    \DB::commit();

} catch (Throwable $e) {
    \DB::rollback();
}

If any statements fail, commit will never hit, and the transaction won't process.

What is the difference between UNION and UNION ALL?

Just to add my two cents to the discussion here: one could understand the UNION operator as a pure, SET-oriented UNION - e.g. set A={2,4,6,8}, set B={1,2,3,4}, A UNION B = {1,2,3,4,6,8}

When dealing with sets, you would not want numbers 2 and 4 appearing twice, as an element either is or is not in a set.

In the world of SQL, though, you might want to see all the elements from the two sets together in one "bag" {2,4,6,8,1,2,3,4}. And for this purpose T-SQL offers the operator UNION ALL.

addClass - can add multiple classes on same div?

$('.page-address-edit').addClass('test1 test2 test3');

Ref- jQuery

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

How to test android apps in a real device with Android Studio?

I can run on my device at last, just I enabled the "USB debugging" and "Allow mock location" options from the Debug Menu of my device.

Single Result from Database by using mySQLi

If you assume just one result you could do this as in Edwin suggested by using specific users id.

$someUserId = 'abc123';

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);

$stmt->execute();

$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.

OR as "Your Common Sense" which selects just one user.

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");

$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

Nothing really different from the above except for PHP v.5

org.hibernate.MappingException: Could not determine type for: java.util.Set

You may just need to add @Transient annotations on roles to not serialize the set.

Why does Java have transient fields?

How to clear Tkinter Canvas?

Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.

To clear a canvas, use the delete method. Give it the special parameter "all" to delete all items on the canvas (the string "all"" is a special tag that represents all items on the canvas):

canvas.delete("all")

If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all", you could supply the name of a tag.

If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.

Type definition in object literal in TypeScript

In TypeScript if we are declaring object then we'd use the following syntax:

[access modifier] variable name : { /* structure of object */ }

For example:

private Object:{ Key1: string, Key2: number }

Where is GACUTIL for .net Framework 4.0 in windows 7?

There is no Gacutil included in the .net 4.0 standard installation. They have moved the GAC too, from %Windir%\assembly to %Windir%\Microsoft.NET\Assembly.

They havent' even bothered adding a "special view" for the folder in Windows explorer, as they have for the .net 1.0/2.0 GAC.

Gacutil is part of the Windows SDK, so if you want to use it on your developement machine, just install the Windows SDK for your current platform. Then you will find it somewhere like this (depending on your SDK version):

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools

There is a discussion on the new GAC here: .NET 4.0 has a new GAC, why?

If you want to install something in GAC on a production machine, you need to do it the "proper" way (gacutil was never meant as a tool for installing stuff on production servers, only as a development tool), with a Windows Installer, or with other tools. You can e.g. do it with PowerShell and the System.EnterpriseServices dll.

On a general note, and coming from several years of experience, I would personally strongly recommend against using GAC at all. Your application will always work if you deploy the DLL with each application in its bin folder as well. Yes, you will get multiple copies of the DLL on your server if you have e.g. multiple web apps on one server, but it's definitely worth the flexibility of being able to upgrade one application without breaking the others (by introducing an incompatible version of the shared DLL in the GAC).

Error - Unable to access the IIS metabase

I resolved this issue by granting IIS AppPool identity permissions to the %systemroot%\inetsrv\config

python replace single backslash with double backslash

Given the source string, manipulation with os.path might make more sense, but here's a string solution;

>>> s=r"C:\Users\Josh\Desktop\\20130216"
>>> '\\\\'.join(filter(bool, s.split('\\')))
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'

Note that split treats the \\ in the source string as a delimited empty string. Using filter gets rid of those empty strings so join won't double the already doubled backslashes. Unfortunately, if you have 3 or more, they get reduced to doubled backslashes, but I don't think that hurts you in a windows path expression.

for each loop in Objective-C for accessing NSMutable dictionary

for (NSString* key in xyz) {
    id value = xyz[key];
    // do stuff
}

This works for every class that conforms to the NSFastEnumeration protocol (available on 10.5+ and iOS), though NSDictionary is one of the few collections which lets you enumerate keys instead of values. I suggest you read about fast enumeration in the Collections Programming Topic.

Oh, I should add however that you should NEVER modify a collection while enumerating through it.

Uninstalling an MSI file from the command line without using msiexec

I'm assuming that when you type int file.msi into the command line, Windows is automatically calling msiexec file.msi for you. I'm assuming this because when you type in picture.png it brings up the default picture viewer.

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

console.log(result) returns [object Object]. How do I get result.name?

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

Iterating through list of list in Python

two nested for loops?

 for a in x:
     print "--------------"
     for b in a:
             print b

It would help if you gave an example of what you want to do with the lists

data.frame rows to a list

A couple of more options :

With asplit

asplit(xy.df, 1)
#[[1]]
#     x      y 
#0.1137 0.6936 

#[[2]]
#     x      y 
#0.6223 0.5450 

#[[3]]
#     x      y 
#0.6093 0.2827 
#....

With split and row

split(xy.df, row(xy.df)[, 1])

#$`1`
#       x      y
#1 0.1137 0.6936

#$`2`
#       x     y
#2 0.6223 0.545

#$`3`
#       x      y
#3 0.6093 0.2827
#....

data

set.seed(1234)
xy.df <- data.frame(x = runif(10),  y = runif(10))

'Connect-MsolService' is not recognized as the name of a cmdlet

This issue can occur if the Azure Active Directory Module for Windows PowerShell isn't loaded correctly.

To resolve this issue, follow these steps.
1.Install the Azure Active Directory Module for Windows PowerShell on the computer (if it isn't already installed). To install the Azure Active Directory Module for Windows PowerShell, go to the following Microsoft website:
Manage Azure AD using Windows PowerShell

2.If the MSOnline module isn't present, use Windows PowerShell to import the MSOnline module.

Import-Module MSOnline 

After it complete, we can use this command to check it.

PS C:\Users> Get-Module -ListAvailable -Name MSOnline*


    Directory: C:\windows\system32\WindowsPowerShell\v1.0\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.1.166.0  MSOnline                            {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
Manifest   1.1.166.0  MSOnlineExtended                    {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}

More information about this issue, please refer to it.


Update:

We should import azure AD powershell to VS 2015, we can add tool and select Azure AD powershell.

enter image description here

FCM getting MismatchSenderId

As per response "MismatchSenderId", this is a mismatch between FireBase and your local "google-services.json", you have to make sure that both manifests matches

In FireBase console you go to "YourProject > Project OverView > Cloud Messaging" you'll see the "SenderID" which MUST match with the "google-services.json" in your Android project.

Best thing you can do is download the final json file from "General" tab and place it in your project.

Protecting cells in Excel but allow these to be modified by VBA script

I don't think you can set any part of the sheet to be editable only by VBA, but you can do something that has basically the same effect -- you can unprotect the worksheet in VBA before you need to make changes:

wksht.Unprotect()

and re-protect it after you're done:

wksht.Protect()

Edit: Looks like this workaround may have solved Dheer's immediate problem, but for anyone who comes across this question/answer later, I was wrong about the first part of my answer, as Joe points out below. You can protect a sheet to be editable by VBA-only, but it appears the "UserInterfaceOnly" option can only be set when calling "Worksheet.Protect" in code.

How do I tell if a regular file does not exist in Bash?

The test command ([ here) has a "not" logical operator which is the exclamation point (similar to many other languages). Try this:

if [ ! -f /tmp/foo.txt ]; then
    echo "File not found!"
fi

Git add all subdirectories

I saw this problem before, when the (sub)folder I was trying to add had its name begin with "_Something_"

I removed the underscores and it worked. Check to see if your folder has characters which may be causing problems.

Can lambda functions be templated?

In C++11, lambda functions can not be templated, but in the next version of the ISO C++ Standard (often called C++14), this feature will be introduced. [Source]

Usage example:

auto get_container_size = [] (auto container) { return container.size(); };

Note that though the syntax uses the keyword auto, the type deduction will not use the rules of auto type deduction, but instead use the rules of template argument deduction. Also see the proposal for generic lambda expressions(and the update to this).

How to use RecyclerView inside NestedScrollView?

RecyclerView with NestedScrollView

    <android.support.v7.widget.RecyclerView
    android:id="@+id/rv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

TestNG ERROR Cannot find class in classpath

i was facing same issue solution is , you need to check testng file,your class created under package in this case class is not found through Test NG. perform below steps just convert your project in to Test NG and over write/rplace with new testNG file.

Again run this TestNG in this case it is working my case,

How to get english language word database?

WordNet database might be helpful. I once worked on a Firefox add-on which deals with words and all kinds of simple to complicated associations between them and stuff. Looks like WordNet will be very much useful to you.

Here it is in MySQL format. And this one (web-archived link) uses Wordnet v3.0 data, rather than the older Wordnet 2.0 data.

CREATE TABLE LIKE A1 as A2

You can use below query to create table and insert distinct values into this table:

Select Distinct Column1, Column2, Column3 into New_Users from Old_Users

Convert date to day name e.g. Mon, Tue, Wed

Your code works for me.

$input = 201308131830; 
echo date("Y-M-d H:i:s",strtotime($input)) . "\n";
echo date("D", strtotime($input)) . "\n";

Output:

2013-Aug-13 18:30:00
Tue

However if you pass 201308131830 as a number it is 50 to 100x larger than can be represented by a 32-bit integer. [dependent on your system's specific implementation] If your server/PHP version does not support 64-bit integers then the number will overflow and probably end up being output as a negative number and date() will default to Jan 1, 1970 00:00:00 GMT.

Make sure whatever source you are retrieving this data from returns that date as a string, and keep it as a string.

Jump into interface implementation in Eclipse IDE

Highlight an interface and use Ctrl+T to open "Quick Type Hierarchy".

Applying Comic Sans Ms font style

You need to use quote marks.

font-family: "Comic Sans MS", cursive, sans-serif;

Although you really really shouldn't use comic sans. The font has massive stigma attached to it's use; it's not seen as professional at all.

How can I get a precise time, for example in milliseconds in Objective-C?

Functions based on mach_absolute_time are good for short measurements.
But for long measurements important caveat is that they stop ticking while device is asleep.

There is a function to get time since boot. It doesn't stop while sleeping. Also, gettimeofday is not monotonic, but in my experiments I've always see that boot time changes when system time changes, so I think it should work fine.

func timeSinceBoot() -> TimeInterval
{
    var bootTime = timeval()
    var currentTime = timeval()
    var timeZone = timezone()

    let mib = UnsafeMutablePointer<Int32>.allocate(capacity: 2)
    mib[0] = CTL_KERN
    mib[1] = KERN_BOOTTIME
    var size = MemoryLayout.size(ofValue: bootTime)

    var timeSinceBoot = 0.0

    gettimeofday(&currentTime, &timeZone)

    if sysctl(mib, 2, &bootTime, &size, nil, 0) != -1 && bootTime.tv_sec != 0 {
        timeSinceBoot = Double(currentTime.tv_sec - bootTime.tv_sec)
        timeSinceBoot += Double(currentTime.tv_usec - bootTime.tv_usec) / 1000000.0
    }
    return timeSinceBoot
}

And since iOS 10 and macOS 10.12 we can use CLOCK_MONOTONIC:

if #available(OSX 10.12, *) {
    var uptime = timespec()
    if clock_gettime(CLOCK_MONOTONIC_RAW, &uptime) == 0 {
        return Double(uptime.tv_sec) + Double(uptime.tv_nsec) / 1000000000.0
    }
}

To sum it up:

  • Date.timeIntervalSinceReferenceDate — changes when system time changes, not monotonic
  • CFAbsoluteTimeGetCurrent() — not monotonic, may go backward
  • CACurrentMediaTime() — stops ticking when device is asleep
  • timeSinceBoot() — doesn't sleep, but might be not monotonic
  • CLOCK_MONOTONIC — doesn't sleep, monotonic, supported since iOS 10

How can I pass arguments to anonymous functions in JavaScript?

Your specific case can simply be corrected to be working:

<script type="text/javascript">
  var myButton = document.getElementById("myButton");
  var myMessage = "it's working";
  myButton.onclick = function() { alert(myMessage); };
</script>

This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.

For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there

Oracle SQL Developer spool output?

I have found that if I save my query(spool_script_file.sql) and call it using this

@c:\client\queries\spool_script_file.sql as script(F5)

My output now is just the results with out the commands at the top.

I found this solution on the oracle forums.

How do I check if PHP is connected to a database already?

Baron Schwartz blogs that due to race conditions, this 'check before write' is a bad practice. He advocates a try/catch pattern with a reconnect in the catch. Here is the pseudo code he recommends:

function query_database(connection, sql, retries=1)
   while true
      try
         result=connection.execute(sql)
         return result
      catch InactiveConnectionException e
         if retries > 0 then
            retries = retries - 1
            connection.reconnect()
         else
            throw e
         end
      end
   end
end

Here is his full blog: https://www.percona.com/blog/2010/05/05/checking-for-a-live-database-connection-considered-harmful/

How to properly stop the Thread in Java?

Typically, a thread is terminated when it's interrupted. So, why not use the native boolean? Try isInterrupted():

Thread t = new Thread(new Runnable(){
        @Override
        public void run() {
            while(!Thread.currentThread().isInterrupted()){
                // do stuff         
            }   
        }});
    t.start();

    // Sleep a second, and then interrupt
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {}
    t.interrupt();

ref- How can I kill a thread? without using stop();

How to change button text or link text in JavaScript?

You can simply use:

document.getElementById(button_id).innerText = 'Your text here';

If you want to use HTML formatting, use the innerHTML property instead.

Change CSS class properties with jQuery

You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.

Dynamically Load CSS from a File

function updateStyleSheet(filename) {
    newstylesheet = "style_" + filename + ".css";

    if ($("#dynamic_css").length == 0) {
        $("head").append("<link>")
        css = $("head").children(":last");

        css.attr({
          id: "dynamic_css",
          rel:  "stylesheet",
          type: "text/css",
          href: newstylesheet
        });
    } else {
        $("#dynamic_css").attr("href",newstylesheet);
    }
}

The example above is copied from:

Dynamically Add a Style Element

$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');

The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

Check if argparse optional argument is set or not

You can check an optionally passed flag with store_true and store_false argument action options:

import argparse

argparser = argparse.ArgumentParser()
argparser.add_argument('-flag', dest='flag_exists', action='store_true')

print argparser.parse_args([])
# Namespace(flag_exists=False)
print argparser.parse_args(['-flag'])
# Namespace(flag_exists=True)

This way, you don't have to worry about checking by conditional is not None. You simply check for True or False. Read more about these options in the docs here

Quicksort with Python

def quicksort(array):
 if len(array) < 2:
  return array
 else:
  pivot = array[0]

 less = [i for i in array[1:] if i <= pivot]
 greater = [i for i in array[1:] if i > pivot]
 return quicksort(less) + [pivot] + quicksort(greater)

How to create the branch from specific commit in different branch

Try

git checkout <commit hash>
git checkout -b new_branch

The commit should only exist once in your tree, not in two separate branches.

This allows you to check out that specific commit and name it what you will.

Multiple Indexes vs Multi-Column Indexes

One item that seems to have been missed is star transformations. Index Intersection operators resolve the predicate by calculating the set of rows hit by each of the predicates before any I/O is done on the fact table. On a star schema you would index each individual dimension key and the query optimiser can resolve which rows to select by the index intersection computation. The indexes on individual columns give the best flexibility for this.

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

How to compare objects by multiple fields

You can implement a Comparator which compares two Person objects, and you can examine as many of the fields as you like. You can put in a variable in your comparator that tells it which field to compare to, although it would probably be simpler to just write multiple comparators.

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

A simple restart fixed it for me. I'm not sure what was the problem since I work with so much software but I have a feeling it was the VPN software or maybe the fact I put my laptop in sleep a lot and some file was corrupted. I really don't know but the restart fixed it.

Dynamically add item to jQuery Select2 control that uses AJAX

Extending on Bumptious Q Bangwhistle's answer:

$('#select2').append($('<option>', { 
    value: item,
    text : item 
})).select2();

This would add the new options into the <select> tags and lets select2 re-render it.

Why won't my PHP app send a 404 error?

You know, in my website i created something like this:

        $uri=$_SERVER['REQUEST_URI'];
        $strpos=strpos($uri, '.php');
        if ($strpos!==false){
        $e404="The page requested by you: &quot".$_SERVER['REQUEST_URI']."&quot, doesn't exists on this server.";
        $maybe=str_replace('.php','',$uri);
        $maybe=str_replace('/','',$maybe);
        die("<center><h1>404</h1><hr><h3>$e404</h3><h3>Maybe try <a href=$maybe>www.leaveyortexthere.p.ht/$maybe</a>?</center>");

}

i hope it helps you.

Using Chrome, how to find to which events are bound to an element

2018 Update - Might be helpful for future readers:

I am not sure when this was originally introduced in Chrome. But another (easy) way this can be done now in Chrome is via console commands.

For example: (in chrome console type)

getEventListeners($0)

Whereas $0 is the selected element in the DOM.

https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#0_-_4

enter image description here

Visual studio code CSS indentation and formatting

Yes, try installing vscode-css-formatter extension.
It just adds the functionality to format .css files and the shortcut stays the same Alt+Shift+F.

How does one generate a random number in Apple's Swift language?

Use arc4random_uniform(n) for a random integer between 0 and n-1.

let diceRoll = Int(arc4random_uniform(6) + 1)

Cast the result to Int so you don't have to explicitly type your vars as UInt32 (which seems un-Swifty).

How can I get the current screen orientation?

int rotation =  getWindowManager().getDefaultDisplay().getRotation();

this will gives all orientation like normal and reverse

and handle it like

int angle = 0;
switch (rotation) {
    case Surface.ROTATION_90:
        angle = -90;
        break;
    case Surface.ROTATION_180:
        angle = 180;
        break;
    case Surface.ROTATION_270:
        angle = 90;
        break;
    default:
        angle = 0;
        break;
}

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

A solution which worked in my case is:
  1. Go to the module having Main class.
  2. Right click on pom.xml under this module.
  3. Select "Run Maven" -> "UpdateSnapshots"

Getting Unexpected Token Export

I got the unexpected token export error also when I was trying to import a local javascript module in my project. I solved it by declaring a type as a module when adding a script tag in my index.html file.

<script src = "./path/to/the/module/" type = "module"></script>

Ruby: Can I write multi-line string with no concatenation?

Other options:

#multi line string
multiline_string = <<EOM
This is a very long string
that contains interpolation
like #{4 + 5} \n\n
EOM

puts multiline_string

#another option for multiline string
message = <<-EOF
asdfasdfsador #{2+2} this month.
asdfadsfasdfadsfad.
EOF

puts message

How to Cast Objects in PHP

There is no built-in method for type casting of user defined objects in PHP. That said, here are several possible solutions:

1) Use a function like the one below to deserialize the object, alter the string so that the properties you need are included in the new object once it's deserialized.

function cast($obj, $to_class) {
  if(class_exists($to_class)) {
    $obj_in = serialize($obj);
    $obj_out = 'O:' . strlen($to_class) . ':"' . $to_class . '":' . substr($obj_in, $obj_in[2] + 7);
    return unserialize($obj_out);
  }
  else
    return false;
}

2) Alternatively, you could copy the object's properties using reflection / manually iterating through them all or using get_object_vars().

This article should enlighten you on the "dark corners of PHP" and implementing typecasting on the user level.

SQL changing a value to upper or lower case

LCASE or UCASE respectively.

Example:

SELECT UCASE(MyColumn) AS Upper, LCASE(MyColumn) AS Lower
FROM MyTable

How do I compare two variables containing strings in JavaScript?

=== is not necessary. You know both values are strings so you dont need to compare types.

_x000D_
_x000D_
function do_check()_x000D_
{_x000D_
  var str1 = $("#textbox1").val();_x000D_
  var str2 = $("#textbox2").val();_x000D_
_x000D_
  if (str1 == str2)_x000D_
  {_x000D_
    $(":text").removeClass("incorrect");_x000D_
    alert("equal");_x000D_
  }_x000D_
  else_x000D_
  {_x000D_
    $(":text").addClass("incorrect");_x000D_
    alert("not equal");_x000D_
  }_x000D_
}
_x000D_
.incorrect_x000D_
{_x000D_
  background: #ff8888;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input id="textbox1" type="text">_x000D_
<input id="textbox2" type="text">_x000D_
_x000D_
<button onclick="do_check()">check</button>
_x000D_
_x000D_
_x000D_

Running Python on Windows for Node.js dependencies

For me, these steps fixed the issue:

1- Running this cmd as admin:

npm install --global --production windows-build-tools

2- Then running npm rebuild after the 1st step is completed (especially completing the python 2.7 installation, which was the main cause of the issue)

Maximum length of HTTP GET request

Technically, I have seen HTTP GET will have issues if the URL length goes beyond 2000 characters. In that case, it's better to use HTTP POST or split the URL.

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class

I have the same problem. I checked my /WEB-INF/classes based on Stephen's recommendation:

the class is not in your webapp's /WEB-INF/classes directory tree or a JAR file in the /WEB-INF/lib directory.

I discovered I have an outdated jar file. Replacing it with the latest jar file solved the issue.

What is the best/simplest way to read in an XML file in Java application?

There are of course a lot of good solutions based on what you need. If it is just configuration, you should have a look at Jakarta commons-configuration and commons-digester.

You could always use the standard JDK method of getting a document :

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

[...]

File file = new File("some/path");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);

CSS pseudo elements in React

Inline styles cannot be used to target pseudo-classes or pseudo-elements. You need to use a stylesheet.

If you want to generate CSS dynamically, then the easiest way is to create a DOM element <style>.

<style dangerouslySetInnerHTML={{
  __html: [
     '.my-special-div:after {',
     '  content: "Hello";',
     '  position: absolute',
     '}'
    ].join('\n')
  }}>
</style>
<div className='my-special-div'></div>

How to display an IFRAME inside a jQuery UI dialog

The problems were:

  1. iframe content comes from another domain
  2. iframe dimensions need to be adjusted for each video

The solution based on omerkirk's answer involves:

  • Creating an iframe element
  • Creating a dialog with autoOpen: false, width: "auto", height: "auto"
  • Specifying iframe source, width and height before opening the dialog

Here is a rough outline of code:

HTML

<div class="thumb">
    <a href="http://jsfiddle.net/yBNVr/show/"   data-title="Std 4:3 ratio video" data-width="512" data-height="384"><img src="http://dummyimage.com/120x90/000/f00&text=Std+4-3+ratio+video" /></a></li>
    <a href="http://jsfiddle.net/yBNVr/1/show/" data-title="HD 16:9 ratio video" data-width="512" data-height="288"><img src="http://dummyimage.com/120x90/000/f00&text=HD+16-9+ratio+video" /></a></li>
</div>

jQuery

$(function () {
    var iframe = $('<iframe frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>');
    var dialog = $("<div></div>").append(iframe).appendTo("body").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        width: "auto",
        height: "auto",
        close: function () {
            iframe.attr("src", "");
        }
    });
    $(".thumb a").on("click", function (e) {
        e.preventDefault();
        var src = $(this).attr("href");
        var title = $(this).attr("data-title");
        var width = $(this).attr("data-width");
        var height = $(this).attr("data-height");
        iframe.attr({
            width: +width,
            height: +height,
            src: src
        });
        dialog.dialog("option", "title", title).dialog("open");
    });
});

Demo here and code here. And another example along similar lines

How to read all rows from huge table?

I think your question is similar to this thread: JDBC Pagination which contains solutions for your need.

In particular, for PostgreSQL, you can use the LIMIT and OFFSET keywords in your request: http://www.petefreitag.com/item/451.cfm

PS: In Java code, I suggest you to use PreparedStatement instead of simple Statements: http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html

what is the difference between XSD and WSDL

XSD is schema for WSDL file. XSD contain datatypes for WSDL. Element declared in XSD is valid to use in WSDL file. We can Check WSDL against XSD to check out web service WSDL is valid or not.

Integrating Dropzone.js into existing HTML form with other fields

I had the exact same problem and found that Varan Sinayee's answer was the only one that actually solved the original question. That answer can be simplified though, so here's a simpler version.

The steps are:

  1. Create a normal form (don't forget the method and enctype args since this is not handled by dropzone anymore).

  2. Put a div inside with the class="dropzone" (that's how Dropzone attaches to it) and id="yourDropzoneName" (used to change the options).

  3. Set Dropzone's options, to set the url where the form and files will be posted, deactivate autoProcessQueue (so it only happens when user presses 'submit') and allow multiple uploads (if you need it).

  4. Set the init function to use Dropzone instead of the default behavior when the submit button is clicked.

  5. Still in the init function, use the "sendingmultiple" event handler to send the form data along wih the files.

Voilà ! You can now retrieve the data like you would with a normal form, in $_POST and $_FILES (in the example this would happen in upload.php)

HTML

<form action="upload.php" enctype="multipart/form-data" method="POST">
    <input type="text" id ="firstname" name ="firstname" />
    <input type="text" id ="lastname" name ="lastname" />
    <div class="dropzone" id="myDropzone"></div>
    <button type="submit" id="submit-all"> upload </button>
</form>

JS

Dropzone.options.myDropzone= {
    url: 'upload.php',
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 5,
    maxFiles: 5,
    maxFilesize: 1,
    acceptedFiles: 'image/*',
    addRemoveLinks: true,
    init: function() {
        dzClosure = this; // Makes sure that 'this' is understood inside the functions below.

        // for Dropzone to process the queue (instead of default form behavior):
        document.getElementById("submit-all").addEventListener("click", function(e) {
            // Make sure that the form isn't actually being sent.
            e.preventDefault();
            e.stopPropagation();
            dzClosure.processQueue();
        });

        //send all the form data along with the files:
        this.on("sendingmultiple", function(data, xhr, formData) {
            formData.append("firstname", jQuery("#firstname").val());
            formData.append("lastname", jQuery("#lastname").val());
        });
    }
}

How to run composer from anywhere?

You can do a simple global install to run it from anywhere

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

The https://getcomposer.org/doc/00-intro.md#globally website recommends this way. Worked well on Ubuntu 14.04 no problem. This way you don't need to do as an example php compomser.phar show , you just do composer show , in any directory you are working with.

Getting "conflicting types for function" in C, why?

A C Function-Declaration Backgrounder

In C, function declarations don't work like they do in other languages: The C compiler itself doesn't search backward and forward in the file to find the function's declaration from the place you call it, and it doesn't scan the file multiple times to figure out the relationships either: The compiler only scans forward in the file exactly once, from top to bottom. Connecting function calls to function declarations is part of the linker's job, and is only done after the file is compiled down to raw assembly instructions.

This means that as the compiler scans forward through the file, the very first time the compiler encounters the name of a function, one of two things have to be the case: It either is seeing the function declaration itself, in which case the compiler knows exactly what the function is and what types it takes as arguments and what types it returns — or it's a call to the function, and the compiler has to guess how the function will eventually be declared.

(There's a third option, where the name is used in a function prototype, but we'll ignore that for now, since if you're seeing this problem in the first place, you're probably not using prototypes.)

History Lesson

In the earliest days of C, the fact that the compiler had to guess types wasn't really an issue: All of the types were more-or-less the same — pretty much everything was either an int or a pointer, and they were the same size. (In fact, in B, the language that preceded C, there were no types at all; everything was just an int or pointer and its type was determined solely by how you used it!) So the compiler could safely guess the behavior of any function just based on the number of parameters that were passed: If you passed two parameters, the compiler would push two things onto the call stack, and presumably the callee would have two arguments declared, and that would all line up. If you passed only one parameter but the function expected two, it would still sort-of work, and the second argument would just be ignored/garbage. If you passed three parameters and the function expected two, it would also still sort-of work, and the third parameter would be ignored and stomped on by the function's local variables. (Some old C code still expects these mismatched-argument rules will work, too.)

But having the compiler let you pass anything to anything isn't really a good way to design a programming language. It worked well in the early days because the early C programmers were mostly wizards, and they knew not to pass the wrong type to functions, and even if they did get the types wrong, there were always tools like lint that could do deeper double-checking of your C code and warn you about such things.

Fast-forward to today, and we're not quite in the same boat. C has grown up, and a lot of people are programming in it who aren't wizards, and to accommodate them (and to accommodate everyone else who regularly used lint anyway), the compilers have taken on many of the abilities that were previously part of lint — especially the part where they check your code to ensure it's type-safe. Early C compilers would let you write int foo = "hello"; and it would just blithely assign the pointer to the integer, and it was up to you to make sure you weren't doing anything stupid. Modern C compilers complain loudly when you get your types wrong, and that's a good thing.

Type Conflicts

So what's all this got to do with the mysterious conflicting-type error on the line of the function declaration? As I said above, C compilers still have to either know or guess what a name means the first time they see that name as they scan forward through the file: They can know what it means it if it's an actual function declaration itself (or a function "prototype," more on that shortly), but if it's just a call to the function, they have to guess. And, sadly, the guess is often wrong.

When the compiler saw your call to do_something(), it looked at how it was invoked, and it concluded that do_something() would eventually be declared like this:

int do_something(char arg1[], char arg2[])
{
    ...
}

Why did it conclude that? Because that's how you called it! (Some C compilers may conclude that it was int do_something(int arg1, int arg2), or simply int do_something(...), both of which are even farther from what you want, but the important point is that regardless of how the compiler guesses the types, it guesses them differently from what your actual function uses.)

Later on, as the compiler scans forward in the file, it sees your actual declaration of char *do_something(char *, char *). That function declaration isn't even close to the declaration that the compiler guessed, which means that the line where the compiler compiled the call was compiled wrong, and the program is just not going to work. So it rightly prints an error telling you that your code isn't going to work as written.

You might be wondering, "Why does it assume I'm returning an int?" Well, it assumes that type because there's no information to the contrary: printf() can take in any type in its variable arguments, so without a better answer, int is as good a guess as any. (Many early C compilers always assumed int for every unspecified type, and assumed you meant ... for the arguments for every function declared f() — not void — which is why many modern code standards recommend always putting void in for the arguments if there really aren't supposed to be any.)

The Fix

There are two common fixes for the function-declaration error.

The first solution, which is recommended by many other answers here, is to put a prototype in the source code above the place where the function is first called. A prototype looks just like the function's declaration, but it has a semicolon where the body should be:

char *do_something(char *dest, const char *src);

By putting the prototype first, the compiler then knows what the function will eventually look like, so it doesn't have to guess. By convention, programmers often put prototypes at the top of the file, just under the #include statements, to ensure that they'll always be defined before any potential usages of them.

The other solution, which also shows up in some real-world code, is to simply reorder your functions so that the function declarations are always before anything that calls them! You could move the entire char *do_something(char *dest, const char *src) { ... } function above the first call to it, and the compiler then would know exactly what the function looks like and wouldn't have to guess.

In practice, most people use function prototypes, because you can also take function prototypes and move them into header (.h) files so that code in other .c files can call those functions. But either solution works, and many codebases use both.

C99 and C11

It is useful to note that the rules are slightly different in the newer versions of the C standard. In the earlier versions (C89 and K&R), the compiler really would guess the types at function-call time (and K&R-era compilers often wouldn't even warn you if they were wrong). C99 and C11 both require that the function declaration/prototype must precede the first call, and it's an error if it doesn't. But many modern C compilers — mainly for backward compatibility with earlier code — will only warn about a missing prototype and not consider it an error.

Pass a string parameter in an onclick function

Also you can use the grave accent symbol ( ` ) in a string

Try:

`<input type="button" onClick="gotoNode('${result.name}')" />`

For more information, visit MDN and Stack Overflow.

By Chrome, Edge, Firefox (Gecko), Opera, Safari support, but it does not support Internet Explorer.

is there a css hack for safari only NOT chrome?

At the end I use a little JavaScript to achieve it:

if (navigator.vendor.startsWith('Apple'))
    document.documentElement.classList.add('on-apple');

then in my CSS to target Apple browser engine the selector will be:

.on-apple .my-class{
    ...
}

How to get the Google Map based on Latitude on Longitude?

Firstly add a div with id.

<div id="my_map_add" style="width:100%;height:300px;"></div>

<script type="text/javascript">
function my_map_add() {
var myMapCenter = new google.maps.LatLng(28.5383866, 77.34916609);
var myMapProp = {center:myMapCenter, zoom:12, scrollwheel:false, draggable:false, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("my_map_add"),myMapProp);
var marker = new google.maps.Marker({position:myMapCenter});
marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=your_key&callback=my_map_add"></script>

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

Difference between using gradlew and gradle

gradlew is a wrapper(w - character) that uses gradle.

Under the hood gradlew performs three main things:

  • Download and install the correct gradle version
  • Parse the arguments
  • Call a gradle task

Using Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.

To create a wrapper run:

gradle wrapper

This command generate:

gradle-wrapper.properties will contain the information about the Gradle distribution

*./ Is used on Unix to specify the current directory

How to use OR condition in a JavaScript IF statement?

|| is the or operator.

if(A || B){ do something }

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

try:

string.decode('utf-8')  # or:
unicode(string, 'utf-8')

edit:

'(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'.decode('utf-8') gives u'(\uff61\uff65\u03c9\uff65\uff61)\uff89', which is correct.

so your problem must be at some oter place, possibly if you try to do something with it were there is an implicit conversion going on (could be printing, writing to a stream...)

to say more we'll need to see some code.

Android - Package Name convention

Android follows normal java package conventions plus here is an important snippet of text to read (this is important regarding the wide use of xml files while developing on android).

The reason for having it in reverse order is to do with the layout on the storage media. If you consider each period ('.') in the application name as a path separator, all applications from a publisher would sit together in the path hierarchy. So, for instance, packages from Adobe would be of the form:

com.adobe.reader (Adobe Reader)

com.adobe.photoshop (Adobe Photoshop)

com.adobe.ideas (Adobe Ideas)

[Note that this is just an illustration and these may not be the exact package names.]

These could internally be mapped (respectively) to:

com/adobe/reader

com/adobe/photoshop

com/adobe/ideas

The concept comes from Package Naming Conventions in Java, more about which can be read here:*

http://en.wikipedia.org/wiki/Java_package#Package_naming_conventions

Source: http://www.quora.com/Why-do-a-majority-of-Android-package-names-begin-with-com

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

Deleting row from datatable in C#

There several different ways to do it. But You can use the following approach:

List<DataRow> RowsToDelete = new List<DataRow>();

for (int i = 0; i < drr.Length; i++) 
{     
   if(condition to delete the row) 
   {  
       RowsToDelete.Add(drr[i]);     
   } 
}

foreach(var dr in RowsToDelete) 
{     
   drr.Rows.Remove(dr); 
} 

How do I get the collection of Model State Errors in ASP.NET MVC?

Here is the VB.

Dim validationErrors As String = String.Join(",", ModelState.Values.Where(Function(E) E.Errors.Count > 0).SelectMany(Function(E) E.Errors).[Select](Function(E) E.ErrorMessage).ToArray())

How do I get a class instance of generic type T?

Actually, I suppose you have a field in your class of type T. If there's no field of type T, what's the point of having a generic Type? So, you can simply do an instanceof on that field.

In my case, I have a

List<T> items;
in my class, and I check if the class type is "Locality" by

if (items.get(0) instanceof Locality) ...

Of course, this only works if the total number of possible classes is limited.

jQuery call function after load

$(document).ready(my_function);

Or

$(document).ready(function () {
  // Function code here.
});

Or the shorter but less readable variant:

$(my_function);

All of these will cause my_function to be called after the DOM loads.

See the ready event documentation for more details.

Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.

Edit:

To simulate a click, use the click() method without arguments:

$('#button').click();

From the docs:

Triggers the click event of each matched element. Causes all of the functions that have been bound to that click event to be executed.

To put it all together, the following code simulates a click when the document finishes loading:

$(function () {
  $('#button').click();
});

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :

SET SQL_SAFE_UPDATES=0; 

Or

close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

maven error: package org.junit does not exist

if you are using Eclipse watch your POM dependencies and your Eclipse buildpath dependency on junit

if you select use Junit4 eclipse create TestCase using org.junit package but your POM use by default Junit3 (junit.framework package) that is the cause, like this picture:

see JUNIT conflict

Just update your Junit dependency in your POM file to Junit4 or your Eclipse BuildPath to Junit3

How to send parameters with jquery $.get()

Try this:

$.ajax({
    type: 'get',
    url: 'manageproducts.do',
    data: 'option=1',
    success: function(data) {

        availableProductNames = data.split(",");

        alert(availableProductNames);

    }
});

Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.

Java/ JUnit - AssertTrue vs AssertFalse

The course contains a logical error:

    assertTrue("Book check in failed", ml.checkIn(b1));

    assertFalse("Book was aleready checked in", ml.checkIn(b1));

In the first assert we expect the checkIn to return True (because checkin is succesful). If this would fail we would print a message like "book check in failed. Now in the second assert we expect the checkIn to fail, because the book was checked in already in the first line. So we expect a checkIn to return a False. If for some reason checkin returns a True (which we don't expect) than the message should never be "Book was already checked in", because the checkin was succesful.

How to convert image file data in a byte array to a Bitmap?

Just try this:

Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();

If bitmapdata is the byte array then getting Bitmap is done like this:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

Returns the decoded Bitmap, or null if the image could not be decoded.

How to stop asynctask thread in android?

declare your asyncTask in your activity:

private YourAsyncTask mTask;

instantiate it like this:

mTask = new YourAsyncTask().execute();

kill/cancel it like this:

mTask.cancel(true);

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

1: Create a class WebMvcConfig and extend it as shown from the WebMvcConfiguration and override addCorsMappings method.

2: Most importantly don't forget to make it @Configuration annotation because it should be loaded with Main Spring class to allow Cross-Origin.

  @Configuration
    public class WebMvcCofig implements WebMvcConfigurer{
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/*")
                    .allowedOrigins("*")
                    .allowedMethods("*")
                    .allowedHeaders("*")
                    .allowCredentials(true);
        }
    }

What's the best way to send a signal to all members of a process group?

Thanks for your wisdom, folks. My script was leaving some child processes on exit and the negation tip made things easier. I wrote this function to be used in other scripts if necessary:

# kill my group's subprocesses:          killGroup
# kill also myself:                      killGroup -x
# kill another group's subprocesses:     killGroup N  
# kill that group all:                   killGroup -x N
# N: PID of the main process (= process group ID).

function killGroup () {
    local prid mainpid
    case $1 in
        -x) [ -n "$2" ] && kill -9 -$2 || kill -9 -$$ ;;
        "") mainpid=$$ ;;
         *) mainpid=$1 ;;
    esac
    prid=$(ps ax -o pid,pgid | grep $mainpid)
    prid=${prid//$mainpid/}
    kill -9 $prid 2>/dev/null
    return
}

Cheers.

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

Provide the :name option to add_index, e.g.:

add_index :studies,
  ["user_id", "university_id", "subject_name_id", "subject_type_id"], 
  unique: true,
  name: 'my_index'

If using the :index option on references in a create_table block, it takes the same options hash as add_index as its value:

t.references :long_name, index: { name: :my_index }

How to find encoding of a file via script on Linux?

I know you're interested in a more general answer, but what's good in ASCII is usually good in other encodings. Here is a Python one-liner to determine if standard input is ASCII. (I'm pretty sure this works in Python 2, but I've only tested it on Python 3.)

python -c 'from sys import exit,stdin;exit()if 128>max(c for l in open(stdin.fileno(),"b") for c in l) else exit("Not ASCII")' < myfile.txt

Creating instance list of different objects

You could create a list of Object like List<Object> list = new ArrayList<Object>(). As all classes implementation extends implicit or explicit from java.lang.Object class, this list can hold any object, including instances of Employee, Integer, String etc.

When you retrieve an element from this list, you will be retrieving an Object and no longer an Employee, meaning you need to perform a explicit cast in this case as follows:

List<Object> list = new ArrayList<Object>();
list.add("String");
list.add(Integer.valueOf(1));
list.add(new Employee());

Object retrievedObject = list.get(2);
Employee employee = (Employee)list.get(2); // explicit cast

get everything between <tag> and </tag> with php

You can use the following:

$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
  • \b ensures that a typo (like <codeS>) is not captured.
  • The first pattern [^>]* captures the content of a tag with attributes (eg a class).
  • Finally, the flag s capture content with newlines.

See the result here : http://lumadis.be/regex/test_regex.php?id=1081

Google Play app description formatting

Currently (June 2016) typing in the link as http://www.example.com will only produce plain text.

You can now however put in an html anchor :

<a href="http://www.example.com">My Example Site</a>

How to Calculate Jump Target Address and Branch Target Address?

(In the diagrams and text below, PC is the address of the branch instruction itself. PC+4 is the end of the branch instruction itself, and the start of the branch delay slot. Except in the absolute jump diagram.)

1. Branch Address Calculation

In MIPS branch instruction has only 16 bits offset to determine next instruction. We need a register added to this 16 bit value to determine next instruction and this register is actually implied by architecture. It is PC register since PC gets updated (PC+4) during the fetch cycle so that it holds the address of the next instruction.

We also limit the branch distance to -2^15 to +2^15 - 1 instruction from the (instruction after the) branch instruction. However, this is not real issue since most branches are local anyway.

So step by step :

  • Sign extend the 16 bit offset value to preserve its value.
  • Multiply resulting value with 4. The reason behind this is that If we are going to branch some address, and PC is already word aligned, then the immediate value has to be word-aligned as well. However, it makes no sense to make the immediate word-aligned because we would be wasting low two bits by forcing them to be 00.
  • Now we have a 32 bit relative offset. Add this value to PC + 4 and that is your branch address.

Branch address calculation


2. Jump Address Calculation

For Jump instruction MIPS has only 26 bits to determine Jump location. Jumps are relative to PC in MIPS. Like branch, immediate jump value needs to be word-aligned; therefore, we need to multiply 26 bit address with four.

Again step by step:

  • Multiply 26 bit value with 4.
  • Since we are jumping relative to PC+4 value, concatenate first four bits of PC+4 value to left of our jump address.
  • Resulting address is the jump value.

In other words, replace the lower 28 bits of the PC + 4 with the lower 26 bits of the fetched instruction shifted left by 2 bits.

enter image description here

Jumps are region-relative to the branch-delay slot, not necessarily the branch itself. In the diagram above, PC has already advanced to the branch delay slot before the jump calculation. (In a classic-RISC 5 stage pipeline, the BD was fetched in the same cycle the jump is decoded, so that PC+4 next instruction address is already available for jumps as well as branches, and calculating relative to the jump's own address would have required extra work to save that address.)

Source: Bilkent University CS 224 Course Slides

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

The accepted answer is through but there is official explanation on this:

The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes (see Using themes), and that it knows which Servlet it is associated with (by having a link to the ServletContext). The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it.

Cited from Spring web framework reference

By the way servlet and root context are both webApplicationContext:

Typical context hierarchy in Spring Web MVC

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

What is the most efficient way of finding all the factors of a number in Python?

Using set(...) makes the code slightly slower, and is only really necessary for when you check the square root. Here's my version:

def factors(num):
    if (num == 1 or num == 0):
        return []
    f = [1]
    sq = int(math.sqrt(num))
    for i in range(2, sq):
        if num % i == 0:
            f.append(i)
            f.append(num/i)
    if sq > 1 and num % sq == 0:
        f.append(sq)
        if sq*sq != num:
            f.append(num/sq)
    return f

The if sq*sq != num: condition is necessary for numbers like 12, where the square root is not an integer, but the floor of the square root is a factor.

Note that this version doesn't return the number itself, but that is an easy fix if you want it. The output also isn't sorted.

I timed it running 10000 times on all numbers 1-200 and 100 times on all numbers 1-5000. It outperforms all the other versions I tested, including dansalmo's, Jason Schorn's, oxrock's, agf's, steveha's, and eryksun's solutions, though oxrock's is by far the closest.

Base64 String throwing invalid character error

You say

The string is exactly what was written to the file (with the addition of a "\0" at the end, but I don't think that even does anything).

In fact, it does do something (it causes your code to throw a FormatException:"Invalid character in a Base-64 string") because the Convert.FromBase64String does not consider "\0" to be a valid Base64 character.

  byte[] data1 = Convert.FromBase64String("AAAA\0"); // Throws exception
  byte[] data2 = Convert.FromBase64String("AAAA");   // Works

Solution: Get rid of the zero termination. (Maybe call .Trim("\0"))

Notes:

The MSDN docs for Convert.FromBase64String say it will throw a FormatException when

The length of s, ignoring white space characters, is not zero or a multiple of 4.

-or-

The format of s is invalid. s contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.

and that

The base 64 digits in ascending order from zero are the uppercase characters 'A' to 'Z', lowercase characters 'a' to 'z', numerals '0' to '9', and the symbols '+' and '/'.

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

You can give dialog box which given by the JavaFX UI Controls Project. I think it will help you

Dialogs.showErrorDialog(Stage object, errorMessage,  "Main line", "Name of Dialog box");
Dialogs.showWarningDialog(Stage object, errorMessage,  "Main line", "Name of Dialog box");

Beautiful way to remove GET-variables with PHP?

basename($_SERVER['REQUEST_URI']) returns everything after and including the '?',

In my code sometimes I need only sections, so separate it out so I can get the value of what I need on the fly. Not sure on the performance speed compared to other methods, but it's really useful for me.

$urlprotocol = 'http'; if ($_SERVER["HTTPS"] == "on") {$urlprotocol .= "s";} $urlprotocol .= "://";
$urldomain = $_SERVER["SERVER_NAME"];
$urluri = $_SERVER['REQUEST_URI'];
$urlvars = basename($urluri);
$urlpath = str_replace($urlvars,"",$urluri);

$urlfull = $urlprotocol . $urldomain . $urlpath . $urlvars;

How to pass values arguments to modal.show() function in Bootstrap

You could do it like this:

<a class="btn btn-primary announce" data-toggle="modal" data-id="107" >Announce</a>

Then use jQuery to bind the click and send the Announce data-id as the value in the modals #cafeId:

$(document).ready(function(){
   $(".announce").click(function(){ // Click to only happen on announce links
     $("#cafeId").val($(this).data('id'));
     $('#createFormId').modal('show');
   });
});

How to link a folder with an existing Heroku app

Use heroku's fork

  1. Use the new "heroku fork" command! It will copy all the environment and you have to update the github repo after!

    heroku fork -a sourceapp targetapp
    
  2. Clone it local

    git clone [email protected]:youamazingapp.git
    
  3. Make a new repo on github and add it

    git remote add origin https://github.com/yourname/your_repo.git
    
  4. Push on github

    git push origin master
    

How to post query parameters with Axios?

As of 2021 insted of null i had to add {} in order to make it work!

axios.post(
        url,
        {},
        {
          params: {
            key,
            checksum
          }
        }
      )
      .then(response => {
        return success(response);
      })
      .catch(error => {
        return fail(error);
      });

Spring Boot application.properties value not populating

Using Environment class we can get application. Properties values

@Autowired,

private Environment env;

and access using

String password =env.getProperty(your property key);

Python's "in" set operator

Sets behave different than dicts, you need to use set operations like issubset():

>>> k
{'ip': '123.123.123.123', 'pw': 'test1234', 'port': 1234, 'debug': True}
>>> set('ip,port,pw'.split(',')).issubset(set(k.keys()))
True
>>> set('ip,port,pw'.split(',')) in set(k.keys())
False

Python regular expressions return true/false

Ignacio Vazquez-Abrams is correct. But to elaborate, re.match() will return either None, which evaluates to False, or a match object, which will always be True as he said. Only if you want information about the part(s) that matched your regular expression do you need to check out the contents of the match object.

how to configuring a xampp web server for different root directory

In case, if anyone prefers a simpler solution, especially on Linux (e.g. Ubuntu), a very easy way out is to create a symbolic link to the intended folder in the htdocs folder. For example, if I want to be able to serve files from a folder called "/home/some/projects/testserver/" and my htdocs is located in "/opt/lampp/htdocs/". Just create a symbolic link like so:

ln -s /home/some/projects/testserver /opt/lampp/htdocs/testserver

The command for symbolic link works like so: ln -s target source where,

target - The existing file/directory you would like to link TO.
source - The file/folder to be created, copying the contents of the target. The LINK itself.

For more help see ln --help Source: Create Symbolic Links in Ubuntu

And that's done. just visit http://localhost/testserver/ In fact, you don't even need to restart your server.

How to select between brackets (or quotes or ...) in Vim?

Use whatever navigation key you want to get inside the parentheses, then you can use either yi( or yi) to copy everything within the matching parens. This also works with square brackets (e.g. yi]) and curly braces. In addition to y, you can also delete or change text (e.g. ci), di]).

I tried this with double and single-quotes and it appears to work there as well. For your data, I do:

write (*, '(a)') 'Computed solution coefficients:'

Move cursor to the C, then type yi'. Move the cursor to a blank line, hit p, and get

Computed solution coefficients:

As CMS noted, this works for visual mode selection as well - just use vi), vi}, vi', etc.

How do I use NSTimer?

there are a couple of ways of using a timer:

1) scheduled timer & using selector

NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
                      target: self
                      selector:@selector(onTick:)
                      userInfo: nil repeats:NO];
  • if you set repeats to NO, the timer will wait 2 seconds before running the selector and after that it will stop;
  • if repeat: YES, the timer will start immediatelly and will repeat calling the selector every 2 seconds;
  • to stop the timer you call the timer's -invalidate method: [t invalidate];

As a side note, instead of using a timer that doesn't repeat and calls the selector after a specified interval, you could use a simple statement like this:

[self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0];

this will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES;

2) self-scheduled timer

NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
                              interval: 1
                              target: self
                              selector:@selector(onTick:)
                              userInfo:nil repeats:YES];

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
  • this will create a timer that will start itself on a custom date specified by you (in this case, after a minute), and repeats itself every one second

3) unscheduled timer & using invocation

NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(onTick:)];

NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
                      invocation:inv 
                      repeats:YES];

and after that, you start the timer manually whenever you need like this:

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];



And as a note, onTick: method looks like this:

-(void)onTick:(NSTimer *)timer {
   //do smth
}

How to set a default row for a query that returns no rows?

One approach for Oracle:

SELECT val
FROM myTable
UNION ALL
SELECT 'DEFAULT'
FROM dual
WHERE NOT EXISTS (SELECT * FROM myTable)

Or alternatively in Oracle:

SELECT NVL(MIN(val), 'DEFAULT')
FROM myTable

Or alternatively in SqlServer:

SELECT ISNULL(MIN(val), 'DEFAULT')
FROM myTable

These use the fact that MIN() returns NULL when there are no rows.

Authenticate Jenkins CI for Github private repository

Perhaps GitHub's support for deploy keys is what you're looking for? To quote that page:

When should I use a deploy key?

Simple, when you have a server that needs pull access to a single private repo. This key is attached directly to the repository instead of to a personal user account.

If that's what you're already trying and it doesn't work, you might want to update your question with more details of the URLs being used, the names and location of the key files, etc.


Now for the technical part: How to use your SSH key with Jenkins?

If you have, say, a jenkins unix user, you can store your deploy key in ~/.ssh/id_rsa. When Jenkins tries to clone the repo via ssh, it will try to use that key.

In some setups, you cannot run Jenkins as an own user account, and possibly also cannot use the default ssh key location ~/.ssh/id_rsa. In such cases, you can create a key in a different location, e.g. ~/.ssh/deploy_key, and configure ssh to use that with an entry in ~/.ssh/config:

Host github-deploy-myproject
    HostName       github.com
    User           git
    IdentityFile   ~/.ssh/deploy_key
    IdentitiesOnly yes

Because all you authenticate to all Github repositories using [email protected] and you don't want the above key to be used for all your connections to Github, we created a host alias github-deploy-myproject. Your clone URL now becomes

git clone github-deploy-myproject:myuser/myproject

and that is also what you put as repository URL into Jenkins.

(Note that you must not put ssh:// in front in order for this to work.)

How can I concatenate a string within a loop in JSTL/JSP?

You're using JSTL 2.0 right? You don't need to put <c:out/> around all variables. Have you tried something like this?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="${myVar}${currentItem}" />
</c:forEach>

Edit: Beaten by the above

Bash or KornShell (ksh)?

For scripts, I always use ksh because it smooths over gotchas.

But I find bash more comfortable for interactive use. For me the emacs key bindings and tab completion are the main benefits. But that's mostly force of habit, not any technical issue with ksh.

Create a .tar.bz2 file Linux

Try this from different folder:

sudo tar -cvjSf folder.tar.bz2 folder/*

React passing parameter via onclick event using ES6 syntax

Use Arrow function like this:

<button onClick={()=>{this.handleRemove(id)}}></button>

Linking a UNC / Network drive on an html page

To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).

file://///server/path/to/file.txt

Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:

For security purposes, Mozilla applications block links to local files (and directories) from remote files.

And less directly, from Google:

Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.

The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.

jQuery click function doesn't work after ajax call?

The problem is that .click only works for elements already on the page. You have to use something like on if you are wiring up future elements

$("#LangTable").on("click",".deletelanguage", function(){
  alert("success");
});

How can I force clients to refresh JavaScript files?

In asp.net mvc you can use @DateTime.UtcNow.ToString() for js file version number. Version number auto change with date and you force clients browser to refresh automatically js file. I using this method and this is work well.

<script src="~/JsFilePath/[email protected]()"></script>

Removing leading zeroes from a field in a SQL statement

select substring(substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), 20), 
    patindex('%[^0]%',substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), 
    20)), 20)

returns N0Z, that is, will get rid of leading zeroes and anything that comes before them.

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

They are both correct. Personally I prefer your approach better for its verbosity but it's really down to personal preference.

Off hand, running if($_POST) would not throw an error - the $_POST array exists regardless if the request was sent with POST headers. An empty array is cast to false in a boolean check.

How to manually include external aar package using new Gradle Android Build System

before(default)

implementation fileTree(include: ['*.jar'], dir: 'libs')

just add '*.aar' in include array.

implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')

it works well on Android Studio 3.x.

if you want ignore some library? do like this.

implementation fileTree(include: ['*.jar', '*.aar'], exclude: 'test_aar*', dir: 'libs')
debugImplementation files('libs/test_aar-debug.aar')
releaseImplementation files('libs/test_aar-release.aar')

Looping through a DataTable

Please try the following code below:

//Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd).
//Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop.

using (reader = cmd.ExecuteReader())
{
// Load the Data table object
  dataTable.Load(reader);
  if (dataTable.Rows.Count > 0)
  {
    DataColumn col = dataTable.Columns["YourColumnName"];  
    foreach (DataRow row in dataTable.Rows)
    {                                   
       strJsonData = row[col].ToString();
    }
  }
}

How to convert a string to lower case in Bash?

To store the transformed string into a variable. Following worked for me - $SOURCE_NAME to $TARGET_NAME

TARGET_NAME="`echo $SOURCE_NAME | tr '[:upper:]' '[:lower:]'`"

Removing ul indentation with CSS

This code will remove the indentation and list bullets.

ul {
    padding: 0;
    list-style-type: none;
}

http://jsfiddle.net/qeqtK/2/

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

JAX-RS implementations automatically support marshalling/unmarshalling of classes based on discoverable JAXB annotations, but because your payload is declared as Object, I think the created JAXBContext misses the Department class and when it's time to marshall it it doesn't know how.

A quick and dirty fix would be to add a XmlSeeAlso annotation to your response class:

@XmlRootElement
@XmlSeeAlso({Department.class})
public class Response implements Serializable {
  ....

or something a little more complicated would be "to enrich" the JAXB context for the Response class by using a ContextResolver:

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

@Provider
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class ResponseResolver implements ContextResolver<JAXBContext> {
    private JAXBContext ctx;

    public ResponseResolver() {
        try {
            this.ctx = JAXBContext.newInstance(

                        Response.class, 
                        Department.class

                    );
        } catch (JAXBException ex) {
            throw new RuntimeException(ex);
        }
    }

    public JAXBContext getContext(Class<?> type) {
        return (type.equals(Response.class) ? ctx : null);
    }
}

CSS to select/style first word

Sadly even with the likes of CSS 3 we still do not have the likes of :first-word :last-word etc using pure CSS. Thankfully there's almost a JavaScript nowadays for everything which brings me to my recommendation. Using nthEverything and jQuery you can expand from the traditional Pseudo elements.

Currently the valid Pseudos are:

  • :first-child
  • :first-of-type
  • :only-child
  • :last-child
  • :last-of-type
  • :only-of-type
  • :nth-child
  • :nth-of-type
  • :nth-last-child
  • :nth-last-of-type

And using nth Everything we can expand this to:

  • ::first-letter
  • ::first-line
  • ::first-word
  • ::last-letter
  • ::last-line
  • ::last-word
  • ::nth-letter
  • ::nth-line
  • ::nth-word
  • ::nth-last-letter
  • ::nth-last-line
  • ::nth-last-word

How do I get the day of week given a date?

A solution whithout imports for dates after 1700/1/1

def weekDay(year, month, day):
    offset = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
    week   = ['Sunday', 
              'Monday', 
              'Tuesday', 
              'Wednesday', 
              'Thursday',  
              'Friday', 
              'Saturday']
    afterFeb = 1
    if month > 2: afterFeb = 0
    aux = year - 1700 - afterFeb
    # dayOfWeek for 1700/1/1 = 5, Friday
    dayOfWeek  = 5
    # partial sum of days betweem current date and 1700/1/1
    dayOfWeek += (aux + afterFeb) * 365                  
    # leap year correction    
    dayOfWeek += aux / 4 - aux / 100 + (aux + 100) / 400     
    # sum monthly and day offsets
    dayOfWeek += offset[month - 1] + (day - 1)               
    dayOfWeek %= 7
    return dayOfWeek, week[dayOfWeek]

print weekDay(2013, 6, 15) == (6, 'Saturday')
print weekDay(1969, 7, 20) == (0, 'Sunday')
print weekDay(1945, 4, 30) == (1, 'Monday')
print weekDay(1900, 1, 1)  == (1, 'Monday')
print weekDay(1789, 7, 14) == (2, 'Tuesday')

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

in Symfony 2.3

/app/config/config.yml

framework:
    # ?????? ??????????????? ???????? ? ???????, json, xml ? ???????
    serializer:
        enabled: true

services:
    object_normalizer:
        class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
        tags:
        # ???????? ? ???? ????????? ???? ??????, ??? ??. ?????, ?.?. ????? ???????? ?? ?????
          - { name: serializer.normalizer }

and example for your controller:

/**
 * ????? ???????? ?? ?? ??????? ? ?? ?????
 * @Route("/search/", name="orgunitSearch")
 */
public function orgunitSearchAction()
{
    $array = $this->get('request')->query->all();

    $entity = $this->getDoctrine()
        ->getRepository('IntranetOrgunitBundle:Orgunit')
        ->findOneBy($array);

    $serializer = $this->get('serializer');
    //$json = $serializer->serialize($entity, 'json');
    $array = $serializer->normalize($entity);

    return new JsonResponse( $array );
}

but the problems with the field type \DateTime will remain.

How to fix Invalid AES key length?

You can verify the key length limit:

int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
System.out.println("MaxAllowedKeyLength=[" + maxKeyLen + "].");

Converting a UNIX Timestamp to Formatted Date String

I found the information in this conversation so helpful that I just wanted to add how I figured it out by using the timestamp from my MySQL database and a little PHP

 <?= date("Y-m-d\TH:i:s\+01:00",strtotime($column['loggedin'])) ?>

The output was: 2017-03-03T08:22:36+01:00

Thanks very much Stewe you answer was a eureka for me.

How to convert int to QString?

In it's simplest form, use the answer of Georg Fritzsche

For a bit advanced, you can use this,

QString QString::arg ( int a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const

Get the documentation and an example here..

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

My server storage was full, this was preventing Mysql from starting. Got the idea from here. Increasing the HD and rebooting fixed the issue.

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

Check the User-Agent and in case it's Mobile Safari, open a myprotocol:// URL to (attempt) to open the iPhone app and have it open Mobile iTunes to the download of the app in case the attempt fails

This sounds a reasonable approach to me, but I don't think you'll be able to get it to open mobile itunes as a second resort. I think you'll have to pick one or the other - either redirect to your app or to itunes.

i.e. if you redirect to myprotocol://, and the app isn't on the phone, you won't get a second chance to redirect to itunes.

You could perhaps first redirect to an (iphone optimised) landing page and give the user the option to click through to your app, or to itunes to get the app if they don't have it? But, you'll be relying on the user to do the right thing there. (Edit: though you could set a cookie so that is a first-time thing only?)

Jquery DatePicker Set default date

For today's Date

$(document).ready(function() {
$('#textboxname').datepicker();
$('#textboxname').datepicker('setDate', 'today');});

JOIN two SELECT statement results

Use UNION:

SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks

Or UNION ALL if you want duplicates:

SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION ALL
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks

What is the difference between 'git pull' and 'git fetch'?

OK, here is some information about git pull and git fetch, so you can understand the actual differences... in few simple words, fetch gets the latest data, but not the code changes and not going to mess with your current local branch code, but pull get the code changes and merge it your local branch, read on to get more details about each:

git fetch

It will download all refs and objects and any new branches to your local Repository...

Fetch branches and/or tags (collectively, "refs") from one or more other repositories, along with the objects necessary to complete their histories. Remote-tracking branches are updated (see the description of below for ways to control this behavior).

By default, any tag that points into the histories being fetched is also fetched; the effect is to fetch tags that point at branches that you are interested in. This default behavior can be changed by using the --tags or --no-tags options or by configuring remote..tagOpt. By using a refspec that fetches tags explicitly, you can fetch tags that do not point into branches you are interested in as well.

git fetch can fetch from either a single named repository or URL or from several repositories at once if is given and there is a remotes. entry in the configuration file. (See git-config1).

When no remote is specified, by default the origin remote will be used, unless there’s an upstream branch configured for the current branch.

The names of refs that are fetched, together with the object names they point at, are written to .git/FETCH_HEAD. This information may be used by scripts or other git commands, such as git-pull.


git pull

It will apply the changes from remote to the current branch in local...

Incorporates changes from a remote repository into the current branch. In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD.

More precisely, git pull runs git fetch with the given parameters and calls git merge to merge the retrieved branch heads into the current branch. With --rebase, it runs git rebase instead of git merge.

should be the name of a remote repository as passed to git-fetch1. can name an arbitrary remote ref (for example, the name of a tag) or even a collection of refs with corresponding remote-tracking branches (e.g., refs/heads/:refs/remotes/origin/), but usually it is the name of a branch in the remote repository.

Default values for and are read from the "remote" and "merge" configuration for the current branch as set by git-branch --track.


I also create the visual below to show you how git fetch and git pull working together...

git pull and git fetch

Compute elapsed time

Try something like this (FIDDLE)

// record start time
var startTime = new Date();

...

// later record end time
var endTime = new Date();

// time difference in ms
var timeDiff = endTime - startTime;

// strip the ms
timeDiff /= 1000;

// get seconds (Original had 'round' which incorrectly counts 0:28, 0:29, 1:30 ... 1:59, 1:0)
var seconds = Math.round(timeDiff % 60);

// remove seconds from the date
timeDiff = Math.floor(timeDiff / 60);

// get minutes
var minutes = Math.round(timeDiff % 60);

// remove minutes from the date
timeDiff = Math.floor(timeDiff / 60);

// get hours
var hours = Math.round(timeDiff % 24);

// remove hours from the date
timeDiff = Math.floor(timeDiff / 24);

// the rest of timeDiff is number of days
var days = timeDiff ;

How to have a drop down <select> field in a rails form?

Or for custom options

<%= f.select :desired_attribute, ['option1', 'option2']%>

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

Did you read https://software.intel.com/en-us/blogs/2014/03/14/troubleshooting-intel-haxm?

It says "Make sure "Hyper-V", a Windows feature, is not installed/enabled on your system. Hyper-V captures the VT virtualization capability of the CPU, and HAXM and Hyper-V cannot run at the same time. Read this blog: Creating a "no hypervisor" boot entry." https://blogs.msdn.microsoft.com/virtual_pc_guy/2008/04/14/creating-a-no-hypervisor-boot-entry/

I've created the boot entry that disables HyperV and it's working

Passing null arguments to C# methods

The OP's question is answered well already, but the title is just broad enough that I think it benefits from the following primer:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace consolePlay
{
    class Program
    {
        static void Main(string[] args)
        {
            Program.test(new DateTime());
            Program.test(null);
            //Program.test(); // <<< Error.  
            // "No overload for method 'test' takes 0 arguments"  
            // So don't mistake nullable to be optional.

            Console.WriteLine("Done.  Return to quit");
            Console.Read();
        }

        static public void test(DateTime? dteIn)
        {
            Console.WriteLine("#" + dteIn.ToString() + "#");
        }
    }
}

output:

#1/1/0001 12:00:00 AM#
##
Done.  Return to quit

How to rollback everything to previous commit

I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.

I generally use this to reset the git to the specific commit in source tree.

  1. select commit to reset on sourcetree.

  2. In dropdowns select the active branch , first Parent Only

  3. And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)

  4. and then go to terminal git push -f

You should be all set!

:: (double colon) operator in Java 8

In older Java versions, instead of "::" or lambd, you can use:

public interface Action {
    void execute();
}

public class ActionImpl implements Action {

    @Override
    public void execute() {
        System.out.println("execute with ActionImpl");
    }

}

public static void main(String[] args) {
    Action action = new Action() {
        @Override
        public void execute() {
            System.out.println("execute with anonymous class");
        }
    };
    action.execute();

    //or

    Action actionImpl = new ActionImpl();
    actionImpl.execute();
}

Or passing to the method:

public static void doSomething(Action action) {
    action.execute();
}

Updating and committing only a file's permissions using git version control

@fooMonster article worked for me

# git ls-tree HEAD
100644 blob 55c0287d4ef21f15b97eb1f107451b88b479bffe    script.sh

As you can see the file has 644 permission (ignoring the 100). We would like to change it to 755:

# git update-index --chmod=+x script.sh

commit the changes

# git commit -m "Changing file permissions"
[master 77b171e] Changing file permissions
0 files changed, 0 insertions(+), 0 deletions(-)
mode change 100644 => 100755 script.sh

Hashset vs Treeset

HashSet implementations are, of course, much much faster -- less overhead because there's no ordering. A good analysis of the various Set implementations in Java is provided at http://java.sun.com/docs/books/tutorial/collections/implementations/set.html.

The discussion there also points out an interesting 'middle ground' approach to the Tree vs Hash question. Java provides a LinkedHashSet, which is a HashSet with an "insertion-oriented" linked list running through it, that is, the last element in the linked list is also the most recently inserted into the Hash. This allows you to avoid the unruliness of an unordered hash without incurring the increased cost of a TreeSet.

How to have a transparent ImageButton: Android

I was already adding something to the background so , This thing worked for me:

   android:backgroundTint="@android:color/transparent"

(Android Studio 3.4.1)

EDIT: only works on android api level 21 and above. for compatibility, use this instead

   android:background="@android:color/transparent"

WindowsError: [Error 126] The specified module could not be found

On the off chance anyone else ever runs into this extremely specific issue.. Something inside PyTorch breaks DLL loading. Once you run import torch, any further DLL loads will fail. So if you're using PyTorch and loading your own DLLs you'll have to rearrange your code to import all DLLs first. Confirmed w/ PyTorch 1.5.0 on Python 3.7

failed to lazily initialize a collection of role

Lazy exceptions occur when you fetch an object typically containing a collection which is lazily loaded, and try to access that collection.

You can avoid this problem by

  • accessing the lazy collection within a transaction.
  • Initalizing the collection using Hibernate.initialize(obj);
  • Fetch the collection in another transaction
  • Use Fetch profiles to select lazy/non-lazy fetching runtime
  • Set fetch to non-lazy (which is generally not recommended)

Further I would recommend looking at the related links to your right where this question has been answered many times before. Also see Hibernate lazy-load application design.

HTTP URL Address Encoding in Java

There is still a problem if you have got an encoded "/" (%2F) in your URL.

RFC 3986 - Section 2.2 says: "If data for a URI component would conflict with a reserved character's purpose as a delimiter, then the conflicting data must be percent-encoded before the URI is formed." (RFC 3986 - Section 2.2)

But there is an Issue with Tomcat:

http://tomcat.apache.org/security-6.html - Fixed in Apache Tomcat 6.0.10

important: Directory traversal CVE-2007-0450

Tomcat permits '\', '%2F' and '%5C' [...] .

The following Java system properties have been added to Tomcat to provide additional control of the handling of path delimiters in URLs (both options default to false):

  • org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH: true|false
  • org.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH: true|false

Due to the impossibility to guarantee that all URLs are handled by Tomcat as they are in proxy servers, Tomcat should always be secured as if no proxy restricting context access was used.

Affects: 6.0.0-6.0.9

So if you have got an URL with the %2F character, Tomcat returns: "400 Invalid URI: noSlash"

You can switch of the bugfix in the Tomcat startup script:

set JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%   -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true 

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

How to define object in array in Mongoose schema correctly with 2d geo index

Thanks for the replies.

I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.

After a while I found the problem: When I was sending the response, I was converting it to a string via .toString().

I fixed that and now it works brilliantly. Sorry for the false alarm.

How to close a GUI when I push a JButton?

You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.

The System.exit(0) will terminates the currently running Java Virtual Machine.

Composer Update Laravel

write this command in your terminal :

composer update

RESTful Authentication

Tips valid for securing any web application

If you want to secure your application, then you should definitely start by using HTTPS instead of HTTP, this ensures a creating secure channel between you & the users that will prevent sniffing the data sent back & forth to the users & will help keep the data exchanged confidential.

You can use JWTs (JSON Web Tokens) to secure RESTful APIs, this has many benefits when compared to the server-side sessions, the benefits are mainly:

1- More scalable, as your API servers will not have to maintain sessions for each user (which can be a big burden when you have many sessions)

2- JWTs are self contained & have the claims which define the user role for example & what he can access & issued at date & expiry date (after which JWT won't be valid)

3- Easier to handle across load-balancers & if you have multiple API servers as you won't have to share session data nor configure server to route the session to same server, whenever a request with a JWT hit any server it can be authenticated & authorized

4- Less pressure on your DB as well as you won't have to constantly store & retrieve session id & data for each request

5- The JWTs can't be tampered with if you use a strong key to sign the JWT, so you can trust the claims in the JWT that is sent with the request without having to check the user session & whether he is authorized or not, you can just check the JWT & then you are all set to know who & what this user can do.

Many libraries provide easy ways to create & validate JWTs in most programming languages, for example: in node.js one of the most popular is jsonwebtoken

Since REST APIs generally aims to keep the server stateless, so JWTs are more compatible with that concept as each request is sent with Authorization token that is self contained (JWT) without the server having to keep track of user session compared to sessions which make the server stateful so that it remembers the user & his role, however, sessions are also widely used & have their pros, which you can search for if you want.

One important thing to note is that you have to securely deliver the JWT to the client using HTTPS & save it in a secure place (for example in local storage).

You can learn more about JWTs from this link

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

Could not load file or assembly 'Microsoft.ReportViewer.Webforms' or

Could not load file or assembly 'Microsoft.ReportViewer.Common'

This issue occured for me in Visual studio 2015.

Reason:

the reference for Microsoft.ReportViewer.Webforms dll is missing.

Possible Fix

Step1:

To add "Microsoft.ReportViewer.Webforms.dll" to the solution.

Navigate to Nuget Package Manager Console as

"Tools-->NugetPackageManager-->Package Manager Console".

Then enter the following command in console as below

PM>Install-Package Microsoft.ReportViewer.Runtime.WebForms

Then it will install the Reportviewer.webforms dll in "..\packages\Microsoft.ReportViewer.Runtime.WebForms.12.0.2402.15\lib" (Your project folder path)

and ReportViewer.Runtime.Common dll in "..\packages\Microsoft.ReportViewer.Runtime.Common.12.0.2402.15\lib". (Your project folder path)

Step2:-

Remove the existing reference of "Microsoft.ReportViewer.WebForms". we need to refer these dll files in our Solution as "Right click Solution >References-->Add reference-->browse ". Add both the dll files from the above paths.

Step3:

Change the web.Config File to point out to Visual Studio 2015. comment out both the Microsoft.ReportViewer.WebForms and Microsoft.ReportViewer.Common version 11.0.0.0 and Uncomment both the Microsoft.ReportViewer.WebForms and Microsoft.ReportViewer.Common Version=12.0.0.0. as attached in screenshot.

Microsoft.ReportViewer.Webforms/Microsoft.ReportViewer.Common

Also refer the link below.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

Getting the last n elements of a vector. Is there a better way than using the length() function?

I just add here something related. I was wanted to access a vector with backend indices, ie writting something like tail(x, i) but to return x[length(x) - i + 1] and not the whole tail.

Following commentaries I benchmarked two solutions:

accessRevTail <- function(x, n) {
    tail(x,n)[1]
}

accessRevLen <- function(x, n) {
  x[length(x) - n + 1]
}

microbenchmark::microbenchmark(accessRevLen(1:100, 87), accessRevTail(1:100, 87))
Unit: microseconds
                     expr    min      lq     mean median      uq     max neval
  accessRevLen(1:100, 87)  1.860  2.3775  2.84976  2.803  3.2740   6.755   100
 accessRevTail(1:100, 87) 22.214 23.5295 28.54027 25.112 28.4705 110.833   100

So it appears in this case that even for small vectors, tail is very slow comparing to direct access

When is assembly faster than C?

Chiming in historically.

When I was a much younger man (1970s) assembler was important, in my experience, more for the size of the code than the speed of the code.

If a module in a higher-level language was, say, 1300 bytes of code, but an assembler version of the module was 300 bytes, that 1K bytes was very important when you were trying to fit the application into 16K or 32K of memory.

Compilers were not great at the time.

In old-timey Fortran

X = (Y - Z)
IF (X .LT. 0) THEN
 ... do something
ENDIF

The compiler at the time did a SUBTRACT instruction, then a TEST instruction on X. In assembler, you would just check the condition code (LT zero, zero, GT zero) after the subtract.

For modern systems and compilers none of that is a concern.

I do think that understanding what the compiler is doing is still important. When you code in a higher-level language, you should understand what allows or prevents the compiler to do loop-unroll.

And with pipe-lining and look-ahead computation involving conditionals, when the compiler does a "branch-likley"

Assembler is still needed when doing things not allowed by a higher-level language, like reading or writing to processor-specific registers.

But largely, it is no longer needed for the general programmer, except to have a basic understanding of how the code might be compiled and executed.

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

I've had this problem. See The Python "Connection Reset By Peer" Problem.

You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.

You can (sometimes) correct this with a time.sleep(0.01) placed strategically.

"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.

How to select all textareas and textboxes using jQuery?

Password boxes are also textboxes, so if you need them too:

$("input[type='text'], textarea, input[type='password']").css({width: "90%"});

and while file-input is a bit different, you may want to include them too (eg. for visual consistency):

$("input[type='text'], textarea, input[type='password'], input[type='file']").css({width: "90%"});

Fixed point vs Floating point number

A fixed point number has a specific number of bits (or digits) reserved for the integer part (the part to the left of the decimal point) and a specific number of bits reserved for the fractional part (the part to the right of the decimal point). No matter how large or small your number is, it will always use the same number of bits for each portion. For example, if your fixed point format was in decimal IIIII.FFFFF then the largest number you could represent would be 99999.99999 and the smallest non-zero number would be 00000.00001. Every bit of code that processes such numbers has to have built-in knowledge of where the decimal point is.

A floating point number does not reserve a specific number of bits for the integer part or the fractional part. Instead it reserves a certain number of bits for the number (called the mantissa or significand) and a certain number of bits to say where within that number the decimal place sits (called the exponent). So a floating point number that took up 10 digits with 2 digits reserved for the exponent might represent a largest value of 9.9999999e+50 and a smallest non-zero value of 0.0000001e-49.

Change a Git remote HEAD to point to something besides master

See: http://www.kernel.org/pub/software/scm/git/docs/git-symbolic-ref.html

This sets the default branch in the git repository. You can run this in bare or mirrored repositories.

Usage:

$ git symbolic-ref HEAD refs/heads/<branch name>

How to list processes attached to a shared memory segment in linux?

Just in case someone is interest only in what kind of process created the shared moeries, call

ls -l /dev/shm

It lists the names that are associated with the shared memories - at least on Ubuntu. Usually the names are quite telling.

SQL join format - nested inner joins

For readability, I restructured the query... starting with the apparent top-most level being Table1, which then ties to Table3, and then table3 ties to table2. Much easier to follow if you follow the chain of relationships.

Now, to answer your question. You are getting a large count as the result of a Cartesian product. For each record in Table1 that matches in Table3 you will have X * Y. Then, for each match between table3 and Table2 will have the same impact... Y * Z... So your result for just one possible ID in table 1 can have X * Y * Z records.

This is based on not knowing how the normalization or content is for your tables... if the key is a PRIMARY key or not..

Ex:
Table 1       
DiffKey    Other Val
1          X
1          Y
1          Z

Table 3
DiffKey   Key    Key2  Tbl3 Other
1         2      6     V
1         2      6     X
1         2      6     Y
1         2      6     Z

Table 2
Key    Key2   Other Val
2      6      a
2      6      b
2      6      c
2      6      d
2      6      e

So, Table 1 joining to Table 3 will result (in this scenario) with 12 records (each in 1 joined with each in 3). Then, all that again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count would be returned.

So, now, take that and expand based on your 1000's of records and you see how a messed-up structure could choke a cow (so-to-speak) and kill performance.

SELECT
      COUNT(*)
   FROM
      Table1 
         INNER JOIN Table3
            ON Table1.DifferentKey = Table3.DifferentKey
            INNER JOIN Table2
               ON Table3.Key =Table2.Key
               AND Table3.Key2 = Table2.Key2 

"NOT IN" clause in LINQ to Entities

Try:

from p in db.Products
where !theBadCategories.Contains(p.Category)
select p;

What's the SQL query you want to translate into a Linq query?

Java Error: illegal start of expression

Methods can only declare local variables. That is why the compiler reports an error when you try to declare it as public.

In the case of local variables you can not use any kind of accessor (public, protected or private).

You should also know what the static keyword means. In method checkYourself, you use the Integer array locations.

The static keyword distinct the elements that are accessible with object creation. Therefore they are not part of the object itself.

public class Test { //Capitalized name for classes are used in Java
   private final init[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later. 

   public Test(int[] locations) {
      this.locations = locations;//To access to class member, when method argument has the same name use `this` key word. 
   }

   public boolean checkYourSelf(int value) { //This method is accessed only from a object.
      for(int location : locations) {
         if(location == value) {
            return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method.
         }
      }
      return false; //Method should be simple and perform one task. So you can get more flexibility. 
   }
   public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it. 

   public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place.
      Test test = new Test(Test.locations); //We declare variable test, and create new instance (object) of class Test.  
      String result;
      if(test.checkYourSelf(2)) {//We moved outside the string
        result = "Hurray";        
      } else {
        result = "Try again"
      }
      System.out.println(result); //We have only one place where write is done. Easy to change in future.
   } 
}

Styling Password Fields in CSS

I found I could improve the situation a little with CSS dedicated to Webkit (Safari, Chrome). However, I had to set a fixed width and height on the field because the font change will resize the field.

@media screen and (-webkit-min-device-pixel-ratio:0){ /* START WEBKIT */
  INPUT[type="password"]{
  font-family:Verdana,sans-serif;
  height:28px;
  font-size:19px;
  width:223px;
  padding:5px;
  }
} /* END WEBKIT */

Which selector do I need to select an option by its text?

This work for me

$('#mySelect option:contains(' + value + ')').attr('selected', 'selected');

VBA Excel - Insert row below with same format including borders and frames

When inserting a row, regardless of the CopyOrigin, Excel will only put vertical borders on the inserted cells if the borders above and below the insert position are the same.

I'm running into a similar (but rotated) situation with inserting columns, but Copy/Paste is too slow for my workbook (tens of thousands of rows, many columns, and complex formatting).

I've found three workarounds that don't require copying the formatting from the source row:

  1. Ensure the vertical borders are the same weight, color, and pattern above and below the insert position so Excel will replicate them in your new row. (This is the "It hurts when I do this," "Stop doing that!" answer.)

  2. Use conditional formatting to establish the border (with a Formula of "=TRUE"). The conditional formatting will be copied to the new row, so you still end up with a border.Caveats:

    • Conditional formatting borders are limited to the thin-weight lines.
    • Works best for sheets where borders are relatively consistent so you don't have to create a bunch of conditional formatting rules.
  3. Set the border on the inserted row in VBA after inserting the row. Setting a border on a range is much faster than copying and pasting all of the formatting just to get a border (assuming you know ahead of time what the border should be or can sample it from the row above without losing performance).

Using an index to get an item, Python

You can use _ _getitem__(key) function.

>>> iterable = ('A', 'B', 'C', 'D', 'E')
>>> key = 4
>>> iterable.__getitem__(key)
'E'

Combining border-top,border-right,border-left,border-bottom in CSS

No, you cannot set them all in a single statement.
At the general case, you need at least three properties:

border-color: red green white blue;
border-style: solid dashed dotted solid;
border-width: 1px 2px 3px 4px;

However, that would be quite messy. It would be more readable and maintainable with four:

border-top:    1px solid  #ff0;
border-right:  2px dashed #f0F;
border-bottom: 3px dotted #f00;
border-left:   5px solid  #09f;

Change background color of iframe issue

JavaScript is what you need. If you are loading iframe when loading the page, insert the test for iframe using the onload event. If iframe is inserted in realtime, then create a callback function on insertion and hook in whatever action you need to take :)