Programs & Examples On #Android camera intent

Questions related about calling the camera app from the local device, without the camera permission.

Android camera intent

Try the following I found Here's a link

If your app targets M and above and declares as using the CAMERA permission which is not granted, then attempting to use this action will result in a SecurityException.

EasyImage.openCamera(Activity activity, int type);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
        @Override
        public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
            //Some error handling
        }

        @Override
        public void onImagesPicked(List<File> imagesFiles, EasyImage.ImageSource source, int type) {
            //Handle the images
            onPhotosReturned(imagesFiles);
        }
    });
}

Android ACTION_IMAGE_CAPTURE Intent

to have the camera write to sdcard but keep in a new Album on the gallery app I use this :

 File imageDirectory = new File("/sdcard/signifio");
          String path = imageDirectory.toString().toLowerCase();
           String name = imageDirectory.getName().toLowerCase();


            ContentValues values = new ContentValues(); 
            values.put(Media.TITLE, "Image"); 
            values.put(Images.Media.BUCKET_ID, path.hashCode());
            values.put(Images.Media.BUCKET_DISPLAY_NAME,name);

            values.put(Images.Media.MIME_TYPE, "image/jpeg");
            values.put(Media.DESCRIPTION, "Image capture by camera");
           values.put("_data", "/sdcard/signifio/1111.jpg");
         uri = getContentResolver().insert( Media.EXTERNAL_CONTENT_URI , values);
            Intent i = new Intent("android.media.action.IMAGE_CAPTURE"); 

            i.putExtra(MediaStore.EXTRA_OUTPUT, uri);

            startActivityForResult(i, 0); 

Please note that you will need to generate a unique filename every time and replace teh 1111.jpg that I wrote. This was tested with nexus one. the uri is declared in the private class , so on activity result I am able to load the image from the uri to imageView for preview if needed.

How to compress image size?

Try this is working great with me.

private String decodeFile(String path) {
        String strMyImagePath = null;
        Bitmap scaledBitmap = null;

        try {
            // Part 1: Decode image
            Bitmap unscaledBitmap = ScalingUtilities.decodeFile(path, DESIREDWIDTH, DESIREDHEIGHT, ScalingLogic.FIT);

            if (!(unscaledBitmap.getWidth() <= 800 && unscaledBitmap.getHeight() <= 800)) {
                // Part 2: Scale image
                scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap, DESIREDWIDTH, DESIREDHEIGHT, ScalingLogic.FIT);
            } else {
                unscaledBitmap.recycle();
                return path;
            }

            // Store to tmp file

            String extr = Environment.getExternalStorageDirectory().toString();
            File mFolder = new File(extr + "/myTmpDir");
            if (!mFolder.exists()) {
                mFolder.mkdir();
            }

            String s = "tmp.png";

            File f = new File(mFolder.getAbsolutePath(), s);

            strMyImagePath = f.getAbsolutePath();
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(f);
                scaledBitmap.compress(Bitmap.CompressFormat.PNG, 70, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {

                e.printStackTrace();
            } catch (Exception e) {

                e.printStackTrace();
            }

            scaledBitmap.recycle();
        } catch (Throwable e) {
        }

        if (strMyImagePath == null) {
            return path;
        }
        return strMyImagePath;

    }

Utility Class

public class ScalingUtilities {

    /**
     * Utility function for decoding an image resource. The decoded bitmap will
     * be optimized for further scaling to the requested destination dimensions
     * and scaling logic.
     *
     * @param res The resources object containing the image data
     * @param resId The resource id of the image data
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Decoded bitmap
     */
    public static Bitmap decodeResource(Resources res, int resId, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth,
                dstHeight, scalingLogic);
        Bitmap unscaledBitmap = BitmapFactory.decodeResource(res, resId, options);

        return unscaledBitmap;
    }
    public static Bitmap decodeFile(String path, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth,
                dstHeight, scalingLogic);
        Bitmap unscaledBitmap = BitmapFactory.decodeFile(path, options);

        return unscaledBitmap;
    }

    /**
     * Utility function for creating a scaled version of an existing bitmap
     *
     * @param unscaledBitmap Bitmap to scale
     * @param dstWidth Wanted width of destination bitmap
     * @param dstHeight Wanted height of destination bitmap
     * @param scalingLogic Logic to use to avoid image stretching
     * @return New scaled bitmap object
     */
    public static Bitmap createScaledBitmap(Bitmap unscaledBitmap, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
                dstWidth, dstHeight, scalingLogic);
        Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
                dstWidth, dstHeight, scalingLogic);
        Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(),
                Config.ARGB_8888);
        Canvas canvas = new Canvas(scaledBitmap);
        canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(Paint.FILTER_BITMAP_FLAG));

        return scaledBitmap;
    }

    /**
     * ScalingLogic defines how scaling should be carried out if source and
     * destination image has different aspect ratio.
     *
     * CROP: Scales the image the minimum amount while making sure that at least
     * one of the two dimensions fit inside the requested destination area.
     * Parts of the source image will be cropped to realize this.
     *
     * FIT: Scales the image the minimum amount while making sure both
     * dimensions fit inside the requested destination area. The resulting
     * destination dimensions might be adjusted to a smaller size than
     * requested.
     */
    public static enum ScalingLogic {
        CROP, FIT
    }

    /**
     * Calculate optimal down-sampling factor given the dimensions of a source
     * image, the dimensions of a destination area and a scaling logic.
     *
     * @param srcWidth Width of source image
     * @param srcHeight Height of source image
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Optimal down scaling sample size for decoding
     */
    public static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        if (scalingLogic == ScalingLogic.FIT) {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                return srcWidth / dstWidth;
            } else {
                return srcHeight / dstHeight;
            }
        } else {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                return srcHeight / dstHeight;
            } else {
                return srcWidth / dstWidth;
            }
        }
    }

    /**
     * Calculates source rectangle for scaling bitmap
     *
     * @param srcWidth Width of source image
     * @param srcHeight Height of source image
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Optimal source rectangle
     */
    public static Rect calculateSrcRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        if (scalingLogic == ScalingLogic.CROP) {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                final int srcRectWidth = (int)(srcHeight * dstAspect);
                final int srcRectLeft = (srcWidth - srcRectWidth) / 2;
                return new Rect(srcRectLeft, 0, srcRectLeft + srcRectWidth, srcHeight);
            } else {
                final int srcRectHeight = (int)(srcWidth / dstAspect);
                final int scrRectTop = (int)(srcHeight - srcRectHeight) / 2;
                return new Rect(0, scrRectTop, srcWidth, scrRectTop + srcRectHeight);
            }
        } else {
            return new Rect(0, 0, srcWidth, srcHeight);
        }
    }

    /**
     * Calculates destination rectangle for scaling bitmap
     *
     * @param srcWidth Width of source image
     * @param srcHeight Height of source image
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Optimal destination rectangle
     */
    public static Rect calculateDstRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        if (scalingLogic == ScalingLogic.FIT) {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                return new Rect(0, 0, dstWidth, (int)(dstWidth / srcAspect));
            } else {
                return new Rect(0, 0, (int)(dstHeight * srcAspect), dstHeight);
            }
        } else {
            return new Rect(0, 0, dstWidth, dstHeight);
        }
    }

}

Getting path of captured image in Android using camera intent

try this

String[] projection = { MediaStore.Images.Media.DATA };
            @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(mCapturedImageURI, projection,
                    null, null, null);
            int column_index_data = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            image_path = cursor.getString(column_index_data);
            Log.e("path of image from CAMERA......******************.........",
                    image_path + "");

for capturing image:

    String fileName = "temp.jpg";
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, fileName);
    mCapturedImageURI = getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
    values.clear();

Why does an image captured using camera intent gets rotated on some devices on Android?

I have spent a lot of time looking for solution for this. And finally managed to do this. Don't forget to upvote @Jason Robinson answer because my is based on his.

So first thing, you sholuld know that since Android 7.0 we have to use FileProvider and something called ContentUri, otherwise you will get an annoying error trying to invoke your Intent. This is sample code:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, getUriFromPath(context, "[Your path to save image]"));
startActivityForResult(intent, CAPTURE_IMAGE_RESULT);

Method getUriFromPath(Context, String) basis on user version of Android create FileUri (file://...) or ContentUri (content://...) and there it is:

public Uri getUriFromPath(Context context, String destination) {
    File file =  new File(destination);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        return FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
    } else {
        return Uri.fromFile(file);
    }
}

After onActivityResult you can catch that uri where image is saved by camera, but now you have to detect camera rotation, here we will use moddified @Jason Robinson answer:

First we need to create ExifInterface based on Uri

@Nullable
public ExifInterface getExifInterface(Context context, Uri uri) {
    try {
        String path = uri.toString();
        if (path.startsWith("file://")) {
            return new ExifInterface(path);
        }
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (path.startsWith("content://")) {
                InputStream inputStream = context.getContentResolver().openInputStream(uri);
                return new ExifInterface(inputStream);
            }
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Above code can be simplified, but i want to show everything. So from FileUri we can create ExifInterface based on String path, but from ContentUri we can't, Android doesn't support that.

In that case we have to use other constructor based on InputStream. Remember this constructor isn't available by default, you have to add additional library:

compile "com.android.support:exifinterface:XX.X.X"

Now we can use getExifInterface method to get our angle:

public float getExifAngle(Context context, Uri uri) {
    try {
        ExifInterface exifInterface = getExifInterface(context, uri);
        if(exifInterface == null) {
            return -1f;
        }

        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                return 90f;
            case ExifInterface.ORIENTATION_ROTATE_180:
                return 180f;
            case ExifInterface.ORIENTATION_ROTATE_270:
                return 270f;
            case ExifInterface.ORIENTATION_NORMAL:
                return 0f;
            case ExifInterface.ORIENTATION_UNDEFINED:
                return -1f;
            default:
                return -1f;
        }
    }
    catch (Exception e) {
        e.printStackTrace();
        return -1f;
    }
}

Now you have Angle to properly rotate you image :).

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

 protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {  
        if (requestCode == CAMERE_REQUEST && resultCode == RESULT_OK && data != null) 
        {  
           Bitmap photo = (Bitmap) data.getExtras().get("data"); 
           imageView.setImageBitmap(photo);
        } 
}

You can check if the resultCode equals RESULT_OK this will only be the case if a picture is taken and selected and everything worked. This if clause here should check every condition.

Replace comma with newline in sed on MacOS?

The sed on macOS Mojave was released in 2005, so one solution is to install the gnu-sed,

brew install gnu-sed

then use gsed will do as you wish,

gsed 's/,/\n/g' file

If you prefer sed, just sudo sh -c 'echo /usr/local/opt/gnu-sed/libexec/gnubin > /etc/paths.d/brew', which is suggested by brew info gnu-sed. Restart your term, then your sed in command line is gsed.

Android, How to limit width of TextView (and add three dots at the end of text)?

I take it you want to limit width to one line and not limit it by character? Since singleLine is deprecated, you could try using the following together:

android:maxLines="1"
android:scrollHorizontally="true"
android:ellipsize="end"

Sort a List of Object in VB.NET

If you need a custom string sort, you can create a function that returns a number based on the order you specify.

For example, I had pictures that I wanted to sort based on being front side or clasp. So I did the following:

Private Function sortpictures(s As String) As Integer
    If Regex.IsMatch(s, "FRONT") Then
        Return 0
    ElseIf Regex.IsMatch(s, "SIDE") Then
        Return 1
    ElseIf Regex.IsMatch(s, "CLASP") Then
        Return 2
    Else
        Return 3
    End If
End Function

Then I call the sort function like this:

list.Sort(Function(elA As String, elB As String)
                  Return sortpictures(elA).CompareTo(sortpictures(elB))
              End Function)

Converting a character code to char (VB.NET)

You could use the Chr(int) function

How to get file's last modified date on Windows command line?

you can get a files modified date using vbscript too

Set objFS=CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
strFile= objArgs(0)
WScript.Echo objFS.GetFile(strFile).DateLastModified

save the above as mygetdate.vbs and on command line

c:\test> cscript //nologo mygetdate.vbs myfile

C# DateTime to UTC Time without changing the time

You can use the overloaded constructor of DateTime:

DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);

Is a Python dictionary an example of a hash table?

To expand upon nosklo's explanation:

a = {}
b = ['some', 'list']
a[b] = 'some' # this won't work
a[tuple(b)] = 'some' # this will, same as a['some', 'list']

Removing html5 required attribute with jQuery

_x000D_
_x000D_
$('#id').removeAttr('required');?????
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Search an Oracle database for tables with specific column names?

The data you want is in the "cols" meta-data table:

SELECT * FROM COLS WHERE COLUMN_NAME = 'id'

This one will give you a list of tables that have all of the columns you want:

select distinct
  C1.TABLE_NAME
from
  cols c1
  inner join
  cols c2
  on C1.TABLE_NAME = C2.TABLE_NAME
  inner join
  cols c3
  on C2.TABLE_NAME = C3.TABLE_NAME
  inner join
  cols c4
  on C3.TABLE_NAME = C4.TABLE_NAME  
  inner join
  tab t
  on T.TNAME = C1.TABLE_NAME
where T.TABTYPE = 'TABLE' --could be 'VIEW' if you wanted
  and upper(C1.COLUMN_NAME) like upper('%id%')
  and upper(C2.COLUMN_NAME) like upper('%fname%')
  and upper(C3.COLUMN_NAME) like upper('%lname%')
  and upper(C4.COLUMN_NAME) like upper('%address%')  

To do this in a different schema, just specify the schema in front of the table, as in

SELECT * FROM SCHEMA1.COLS WHERE COLUMN_NAME LIKE '%ID%';

If you want to combine the searches of many schemas into one output result, then you could do this:

SELECT DISTINCT
  'SCHEMA1' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA1.COLS
WHERE COLUMN_NAME LIKE '%ID%'
UNION
SELECT DISTINCT
  'SCHEMA2' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA2.COLS
WHERE COLUMN_NAME LIKE '%ID%'

Passing parameters from jsp to Spring Controller method

Your controller method should be like this:

@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    int id = 2323;  // Currently passing static values for testing
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
    return "note";
}

Use the id in your code, call the controller method from your JSP as:

/{your mapping}/{your id}

UPDATE:

Change your jsp code to:

<c:forEach items="${listNotes}" var="notices" varStatus="status">
    <tr>
        <td>${notices.noticesid}</td>
        <td>${notices.notetext}</td>
        <td>${notices.notetag}</td>
        <td>${notices.notecolor}</td>
        <td>${notices.sectionid}</td>
        <td>${notices.canvasid}</td>
        <td>${notices.canvasnName}</td>
        <td>${notices.personid}</td>
        <td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
        <td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
    </tr>
</c:forEach>

How to print Unicode character in Python?

Print a unicode character in Python:

Print a unicode character directly from python interpreter:

el@apollo:~$ python
Python 2.7.3
>>> print u'\u2713'
?

Unicode character u'\u2713' is a checkmark. The interpreter prints the checkmark on the screen.

Print a unicode character from a python script:

Put this in test.py:

#!/usr/bin/python
print("here is your checkmark: " + u'\u2713');

Run it like this:

el@apollo:~$ python test.py
here is your checkmark: ?

If it doesn't show a checkmark for you, then the problem could be elsewhere, like the terminal settings or something you are doing with stream redirection.

Store unicode characters in a file:

Save this to file: foo.py:

#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import codecs
import sys 
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print(u'e with obfuscation: é')

Run it and pipe output to file:

python foo.py > tmp.txt

Open tmp.txt and look inside, you see this:

el@apollo:~$ cat tmp.txt 
e with obfuscation: é

Thus you have saved unicode e with a obfuscation mark on it to a file.

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Some version working

<div class="hidden-xs">Only Mobile hidden</div>
<div class="visible-xs">Only Mobile visible</div>

How to make a copy of an object in C#

You can use MemberwiseClone

obj myobj2 = (obj)myobj.MemberwiseClone();

The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj are of value types.

If you own the source code, you can also implement ICloneable

jQuery deferreds and promises - .then() vs .done()

The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected.

Prior to jQuery 1.8, then() was just syntactic sugar:

promise.then( doneCallback, failCallback )
// was equivalent to
promise.done( doneCallback ).fail( failCallback )

As of 1.8, then() is an alias for pipe() and returns a new promise, see here for more information on pipe().

success() and error() are only available on the jqXHR object returned by a call to ajax(). They are simple aliases for done() and fail() respectively:

jqXHR.done === jqXHR.success
jqXHR.fail === jqXHR.error

Also, done() is not limited to a single callback and will filter out non-functions (though there is a bug with strings in version 1.8 that should be fixed in 1.8.1):

// this will add fn1 to 7 to the deferred's internal callback list
// (true, 56 and "omg" will be ignored)
promise.done( fn1, fn2, true, [ fn3, [ fn4, 56, fn5 ], "omg", fn6 ], fn7 );

Same goes for fail().

AngularJS : When to use service instead of factory

The concept for all these providers is much simpler than it initially appears. If you dissect a provider you and pull out the different parts it becomes very clear.

To put it simply each one of these providers is a specialized version of the other, in this order: provider > factory > value / constant / service.

So long the provider does what you can you can use the provider further down the chain which would result in writing less code. If it doesn't accomplish what you want you can go up the chain and you'll just have to write more code.

This image illustrates what I mean, in this image you will see the code for a provider, with the portions highlighted showing you which portions of the provider could be used to create a factory, value, etc instead.

AngularJS providers, factories, services, etc are all the same thing
(source: simplygoodcode.com)

For more details and examples from the blog post where I got the image from go to: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/

package R does not exist

Just got rid of the error in my project. I had imported a sample project, I had changed the package folders but I had not updated the package in one of the java files.

Most likely cause of this error 'package R does not exist' is that the package name in Java or manifest file is incorrect. Make sure it is correct and in sync and then do a clean build.

get current date with 'yyyy-MM-dd' format in Angular 4

In Controller ,

 var DateObj = new Date();

 $scope.YourParam = DateObj.getFullYear() + '-' + ('0' + (DateObj.getMonth() + 1)).slice(-2) + '-' + ('0' + DateObj.getDate()).slice(-2);

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

How do you read CSS rule values with JavaScript?

This version will go through all of the stylesheets on a page. For my needs, the styles were usually in the 2nd to last of the 20+ stylesheets, so I check them backwards.

    var getStyle = function(className){
        var x, sheets,classes;
        for( sheets=document.styleSheets.length-1; sheets>=0; sheets-- ){
            classes = document.styleSheets[sheets].rules || document.styleSheets[sheets].cssRules;
            for(x=0;x<classes.length;x++) {
                if(classes[x].selectorText===className) {
                    return  (classes[x].cssText ? classes[x].cssText : classes[x].style.cssText);
                }
            }
        }
        return false;
    };

Animate change of view background color on Android

Based on ademar111190's answer, I have created this method the will pulse the background color of a view between any two colors:

private void animateBackground(View view, int colorFrom, int colorTo, int duration) {


    ObjectAnimator objectAnimator = ObjectAnimator.ofObject(view, "backgroundColor", new ArgbEvaluator(), colorFrom, colorTo);
    objectAnimator.setDuration(duration);
    //objectAnimator.setRepeatCount(Animation.INFINITE);
    objectAnimator.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {

        }

        @Override
        public void onAnimationEnd(Animator animation) {
            // Call this method again, but with the two colors switched around.
            animateBackground(view, colorTo, colorFrom, duration);
        }

        @Override
        public void onAnimationCancel(Animator animation) {

        }

        @Override
        public void onAnimationRepeat(Animator animation) {

        }
    });
    objectAnimator.start();
}

SVN Repository Search

I started using this tool

http://www.supose.org/wiki/supose

It works fine just lacking a visual UI, but is fast and somewhat maintained

What is a MIME type?

MIME stands for Multi-purpose Internet Mail Extensions. MIME types form a standard way of classifying file types on the Internet. Internet programs such as Web servers and browsers all have a list of MIME types, so that they can transfer files of the same type in the same way, no matter what operating system they are working in.

A MIME type has two parts: a type and a subtype. They are separated by a slash (/). For example, the MIME type for Microsoft Word files is application and the subtype is msword. Together, the complete MIME type is application/msword.

Although there is a complete list of MIME types, it does not list the extensions associated with the files, nor a description of the file type. This means that if you want to find the MIME type for a certain kind of file, it can be difficult. Sometimes you have to look through the list and make a guess as to the MIME type of the file you are concerned with.

How to recursively find the latest modified file in a directory?

This simple cli will also work:

ls -1t | head -1

You may change the -1 to the number of files you want to list

No value accessor for form control with name: 'recipient'

Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule

How to find the sum of an array of numbers

Use recursion

var sum = (arr) => arr.length === 1 ? arr[0] : arr.shift() + sum(arr);
sum([1,2,3,4]) // 10

How do you select the entire excel sheet with Range using VBA?

Here is what I used, I know it could use some perfecting, but I think it will help others...

''STYLING''

Dim sheet As Range

' Find Number of rows used
Dim Final As Variant
    Final = Range("A1").End(xlDown).Row

' Find Last Column
Dim lCol As Long
    lCol = Cells(1, Columns.Count).End(xlToLeft).Column

Set sheet = ActiveWorkbook.ActiveSheet.Range("A" & Final & "", Cells(1, lCol ))
With sheet
    .Interior.ColorIndex = 1
End With

How do I copy to the clipboard in JavaScript?

This is the best. So much winning.

var toClipboard = function(text) {
    var doc = document;

    // Create temporary element
    var textarea = doc.createElement('textarea');
    textarea.style.position = 'absolute';
    textarea.style.opacity  = '0';
    textarea.textContent    = text;

    doc.body.appendChild(textarea);

    textarea.focus();
    textarea.setSelectionRange(0, textarea.value.length);

    // Copy the selection
    var success;
    try {
        success = doc.execCommand("copy");
    }
    catch(e) {
        success = false;
    }

    textarea.remove();

    return success;
}

Java: How to Indent XML Generated by Transformer

If you want the indentation, you have to specify it to the TransformerFactory.

TransformerFactory tf = TransformerFactory.newInstance();
tf.setAttribute("indent-number", new Integer(2));
Transformer t = tf.newTransformer();

How do I get out of 'screen' without typing 'exit'?

Ctrl+a followed by k will "kill" the current screen session.

How to open URL in Microsoft Edge from the command line?

It will do more or less the same thing in good old dos script fashion

set add=%1
if %add%$ ==$ set add="about:blank" && goto launch

rem http://
set test=%add:~0, 7%
if %test% == http:// goto launch

rem ftp:// 
set test=%add:~0, 6%
if %test% == ftp:// goto launch

rem https://
set test=%add:~0, 8%
if %test% == https:// goto launch

rem add http
set add=http://%add%

:launch
start microsoft-edge:%add%

Node.js get file extension

var fileName = req.files.upload.name;

var arr = fileName.split('.');

var extension = arr[length-1];

Line break in HTML with '\n'

You should consider replacing your line breaks with <br/>. In HTML a line break will only stand for new line in your code.

Alternatively you can use some other HTML markups like placing your lines in paragraphs:

<p>Sample line</p>
<p>Another line</p>

or other wrappers like for instance <div>sample</div> with CSS attribute: display: block.

You can also use <pre>. The content of pre will have its HTML styling ignored. In other words it will display pure HTML with normal \n line breaks.

force browsers to get latest js and css files in asp.net application

ASP.NET MVC will handle this for you if you use bundles for your JS/CSS. It will automatically append a version number in the form of a GUID to your bundles and only update this GUID when the bundle is updated (aka any of the source files have changes).

This also helps if you have a ton of JS/CSS files as it can greatly improve content load times!

See Here

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

For Java 8: You can use inbuilt java.time.format.DateTimeFormatter to reduce any chance of typos, like

DateTimeFormatter formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;

ISO_ZONED_DATE_TIME represents 2011-12-03T10:15:30+01:00[Europe/Paris] is one of the bundled standard DateTime formats provided by Oracle link

How to get complete current url for Cakephp

I use $this->here for the path, to get the whole URL you'll have to do as Juhana said and use the $_SERVER variables. There's no need to use a Cake function for this.

Oracle query execution time

select LAST_LOAD_TIME, ELAPSED_TIME, MODULE, SQL_TEXT elapsed from v$sql
  order by LAST_LOAD_TIME desc

More complicated example (don't forget to delete or to substitute PATTERN):

select * from (
  select LAST_LOAD_TIME, to_char(ELAPSED_TIME/1000, '999,999,999.000') || ' ms' as TIME,
         MODULE, SQL_TEXT from SYS."V_\$SQL"
    where SQL_TEXT like '%PATTERN%'
    order by LAST_LOAD_TIME desc
  ) where ROWNUM <= 5;

How to avoid soft keyboard pushing up my layout?

To solve this simply add android:windowSoftInputMode="stateVisible|adjustPan to that activity in android manifest file. for example

<activity 
    android:name="com.comapny.applicationname.activityname"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateVisible|adjustPan"/>

SecurityException during executing jnlp file (Missing required Permissions manifest attribute in main jar)

If you'd like to set this globally for all users of a machine, you can create the following directory and file structures:

mkdir %windir%\Sun\Java\Deployment

Create a file deployment.config with the content:

deployment.system.config=file:///c:/windows/Sun/Java/Deployment/deployment.properties
deployment.system.config.mandatory=TRUE

Create a file deployment.properties

deployment.user.security.exception.sites=C\:/WINDOWS/Sun/Java/Deployment/exception.sites

Create a file exception.sites

http://example1.com
http://example2.com/path/to/specific/directory/

Reference https://blogs.oracle.com/java-platform-group/entry/upcoming_exception_site_list_in

Set 4 Space Indent in Emacs in Text Mode

This problem isn't caused by missing tab stops; it's that emacs has a (new?) tab method called indent-relative that seems designed to line up tabular data. The TAB key is mapped to the method indent-for-tab-command, which calls whatever method the variable indent-line-function is set to, which is indent-relative method for text mode. I havn't figured out a good way to override the indent-line-function variable (text mode hook isn't working, so maybe it is getting reset after the mode-hooks run?) but one simple way to get rid of this behavior is to just chuck the intent-for-tab-command method by setting TAB to the simpler tab-to-tab-stop method:

(define-key text-mode-map (kbd "TAB") 'tab-to-tab-stop)

Javascript geocoding from address to latitude and longitude numbers not working

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           },
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
           }
        }
     },
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

python: How do I know what type of exception occurred?

The other answers all point out that you should not catch generic exceptions, but no one seems to want to tell you why, which is essential to understanding when you can break the "rule". Here is an explanation. Basically, it's so that you don't hide:

So as long as you take care to do none of those things, it's OK to catch the generic exception. For instance, you could provide information about the exception to the user another way, like:

  • Present exceptions as dialogs in a GUI
  • Transfer exceptions from a worker thread or process to the controlling thread or process in a multithreading or multiprocessing application

So how to catch the generic exception? There are several ways. If you just want the exception object, do it like this:

try:
    someFunction()
except Exception as ex:
    template = "An exception of type {0} occurred. Arguments:\n{1!r}"
    message = template.format(type(ex).__name__, ex.args)
    print message

Make sure message is brought to the attention of the user in a hard-to-miss way! Printing it, as shown above, may not be enough if the message is buried in lots of other messages. Failing to get the users attention is tantamount to swallowing all exceptions, and if there's one impression you should have come away with after reading the answers on this page, it's that this is not a good thing. Ending the except block with a raise statement will remedy the problem by transparently reraising the exception that was caught.

The difference between the above and using just except: without any argument is twofold:

  • A bare except: doesn't give you the exception object to inspect
  • The exceptions SystemExit, KeyboardInterrupt and GeneratorExit aren't caught by the above code, which is generally what you want. See the exception hierarchy.

If you also want the same stacktrace you get if you do not catch the exception, you can get that like this (still inside the except clause):

import traceback
print traceback.format_exc()

If you use the logging module, you can print the exception to the log (along with a message) like this:

import logging
log = logging.getLogger()
log.exception("Message for you, sir!")

If you want to dig deeper and examine the stack, look at variables etc., use the post_mortem function of the pdb module inside the except block:

import pdb
pdb.post_mortem()

I've found this last method to be invaluable when hunting down bugs.

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

BIRT, the Eclipse Business Intelligence and Reporting Tool is open source.

BIRT is an open source Eclipse-based reporting system that integrates with your Java/J2EE application to produce compelling reports. BIRT provides core reporting features such as report layout, data access and scripting.

SQLite select where empty?

It looks like you can simply do:

SELECT * FROM your_table WHERE some_column IS NULL OR some_column = '';

Test case:

CREATE TABLE your_table (id int, some_column varchar(10));

INSERT INTO your_table VALUES (1, NULL);
INSERT INTO your_table VALUES (2, '');
INSERT INTO your_table VALUES (3, 'test');
INSERT INTO your_table VALUES (4, 'another test');
INSERT INTO your_table VALUES (5, NULL);

Result:

SELECT id FROM your_table WHERE some_column IS NULL OR some_column = '';

id        
----------
1         
2         
5    

how to use font awesome in own css?

you can do so by using the :before or :after pseudo. read more about it here http://astronautweb.co/snippet/font-awesome/

change your code to this

.lb-prev:hover {
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
  opacity: 1;
   text-decoration: none;
}

.lb-prev:before {
    font-family: FontAwesome;
    content: "\f053";
    font-size: 30px;
}

do the same for the other icons. you might want to adjust the color and height of the icons too. anyway here is the fiddle hope this helps

Error in eval(expr, envir, enclos) : object not found

I think I got what I was looking for..

data.train <- read.table("Assign2.WineComplete.csv",sep=",",header=T)
fit <- rpart(quality ~ ., method="class",data=data.train)
plot(fit)
text(fit, use.n=TRUE)
summary(fit)

Create a Date with a set timezone without using a string representation

Best Solution I have seen from this came from

http://www.codingforums.com/archive/index.php/t-19663.html

Print Time Function

<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)

function printTime(offset) {
    offset++;
    tempDate = new Date()
    tempDate.setTime(UTCDate.getTime()+3600000*(offset))
    timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
    timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
    timeValue += " hrs."
    return timeValue
    }
    var now = new Date()
    var seed = now.getTime() % 0xfffffff
    var same = rand(12)
</script>

Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>

Full Code Example

<html>

<head>
<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)

function printTime(offset) {
offset++;
tempDate = new Date()
tempDate.setTime(UTCDate.getTime()+3600000*(offset))
timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
timeValue += " hrs."
return timeValue
}
var now = new Date()
var seed = now.getTime() % 0xfffffff
var same = rand(12)
</script>

</head>

<body>
Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>
<br>
Michigan:
<script language="JavaScript">document.write(printTime("-5"))</script>
<br>
Greenwich, England(UTC):
<script language="JavaScript">document.write(printTime("-0"))</script>
<br>
Tokyo, Japan:
<script language="JavaScript">document.write(printTime("+9"))</script>
<br>
Berlin, Germany:
<script language="JavaScript">document.write(printTime("+1"))</script>

</body>
</html>

List<String> to ArrayList<String> conversion issue

Cast works where the actual instance of the list is an ArrayList. If it is, say, a Vector (which is another extension of List) it will throw a ClassCastException.

The error when changing the definition of your HashMap is due to the elements later being processed, and that process expects a method that is defined only in ArrayList. The exception tells you that it did not found the method it was looking for.

Create a new ArrayList with the contents of the old one.

new ArrayList<String>(myList);

Check if a given key already exists in a dictionary

Using ternary operator:

message = "blah" if 'key1' in dict else "booh"
print(message)

Initialise a list to a specific length in Python

list multiplication works.

>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

How do I set Tomcat Manager Application User Name and Password for NetBeans?

One simple way to check your changes to that file in Tomcat 8 + is to open a browser to: http://localhost:8080/manager/text/list

Concatenate multiple files but include filename as section headers

Was looking for the same thing, and found this to suggest:

tail -n +1 file1.txt file2.txt file3.txt

Output:

==> file1.txt <==
<contents of file1.txt>

==> file2.txt <==
<contents of file2.txt>

==> file3.txt <==
<contents of file3.txt>

If there is only a single file then the header will not be printed. If using GNU utils, you can use -v to always print a header.

Spool Command: Do not output SQL statement to file

You can directly export the query result with export option in the result grig. This export has various options to export. I think this will work.

Why isn't textarea an input[type="textarea"]?

It was a limitation of the technology at the time it was created. My answer copied over from Programmers.SE:

From one of the original HTML drafts:

NOTE: In the initial design for forms, multi-line text fields were supported by the Input element with TYPE=TEXT. Unfortunately, this causes problems for fields with long text values. SGML's default (Reference Quantity Set) limits the length of attribute literals to only 240 characters. The HTML 2.0 SGML declaration increases the limit to 1024 characters.

Identifying country by IP address

You can try using https://ip-api.io - geo location api that returns country among other IP information.

For example with Node.js

const request = require('request-promise')

request('http://ip-api.io/api/json/1.2.3.4')
  .then(response => console.log(JSON.parse(response)))
  .catch(err => console.log(err))

Access-Control-Allow-Origin Multiple Origin Domains?

I struggled to set this up for a domain running HTTPS, so I figured I would share the solution. I used the following directive in my httpd.conf file:

    <FilesMatch "\.(ttf|otf|eot|woff)$">
            SetEnvIf Origin "^http(s)?://(.+\.)?example\.com$" AccessControlAllowOrigin=$0
            Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    </FilesMatch>

Change example.com to your domain name. Add this inside <VirtualHost x.x.x.x:xx> in your httpd.conf file. Notice that if your VirtualHost has a port suffix (e.g. :80) then this directive will not apply to HTTPS, so you will need to also go to /etc/apache2/sites-available/default-ssl and add the same directive in that file, inside of the <VirtualHost _default_:443> section.

Once the config files are updated, you will need to run the following commands in the terminal:

a2enmod headers
sudo service apache2 reload

How to log cron jobs?

There are at least three different types of logging:

  1. The logging BEFORE the program is executed, which only logs IF the cronjob TRIED to execute the command. That one is located in /var/log/syslog, as already mentioned by @Matthew Lock.

  2. The logging of errors AFTER the program tried to execute, which can be sent to an email or to a file, as mentioned by @Spliffster. I prefer logging to a file, because with email THEN you have a NEW source of problems, and its checking if email sending and reception is working perfectly. Sometimes it is, sometimes it's not. For example, in a simple common desktop machine in which you are not interested in configuring an smtp, sometimes you will prefer logging to a file:

     * * * *  COMMAND_ABSOLUTE_PATH > /ABSOLUTE_PATH_TO_LOG 2>&1
    
    • I would also consider checking the permissions of /ABSOLUTE_PATH_TO_LOG, and run the command from that user's permissions. Just for verification, while you test whether it might be a potential source of problems.
  3. The logging of the program itself, with its own error-handling and logging for tracking purposes.

There are some common sources of problems with cronjobs: * The ABSOLUTE PATH of the binary to be executed. When you run it from your shell, it might work, but the cron process seems to use another environment, and hence it doesn't always find binaries if you don't use the absolute path. * The LIBRARIES used by a binary. It's more or less the same previous point, but make sure that, if simply putting the NAME of the command, is referring to exactly the binary which uses the very same library, or better, check if the binary you are referring with the absolute path is the very same you refer when you use the console directly. The binaries can be found using the locate command, for example:

$locate python

Be sure that the binary you will refer, is the very same the binary you are calling in your shell, or simply test again in your shell using the absolute path that you plan to put in the cronjob.

  • Another common source of problems is the syntax in the cronjob. Remember that there are special characters you can use for lists (commas), to define ranges (dashes -), to define increment of ranges (slashes), etc. Take a look: http://www.softpanorama.org/Utilities/cron.shtml

list all files in the folder and also sub folders

Use FileUtils from Apache commons.

listFiles

public static Collection<File> listFiles(File directory,
                                         String[] extensions,
                                         boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files

How to add Button over image using CSS?

<div class="content"> 
  Counter-Strike 1.6 Steam 
     <img src="images/CSsteam.png">
     <a href="#">Koupit</a>
</div>

/*Use this css*/
content {
width: 182px; /*328 co je 1/3 - 20margin left*/
height: 121px;
line-height: 20px;
margin-top: 0px;
margin-left: 9px;
margin-right:0px;
display:inline-block;
position:relative;
}
content a{
display:inline-block;
padding:10px;
position:absolute;
bottom:10px;
right:10px;
}

Getting full URL of action in ASP.NET MVC

I was having an issue with this, my server was running behind a load balancer. The load balancer was terminating the SSL/TLS connection. It then passed the request to the web servers using http.

Using the Url.Action() method with Request.Url.Schema, it kept creating a http url, in my case to create a link in an automated email (which my PenTester didn't like).

I may have cheated a little, but it is exactly what I needed to force a https url:

<a href="@Url.Action("Action", "Controller", new { id = Model.Id }, "https")">Click Here</a>

I actually use a web.config AppSetting so I can use http when debugging locally, but all test and prod environments use transformation to set the https value.

How do I create a crontab through a script

I have written a crontab deploy tool in python: https://github.com/monklof/deploycron

pip install deploycron

Install your crontab is very easy, this will merge the crontab into the system's existing crontab.

from deploycron import deploycron
deploycron(content="* * * * * echo hello > /tmp/hello")

Where are the python modules stored?

  1. Is there a way to obtain a list of Python modules available (i.e. installed) on a machine?

This works for me:

help('modules')
  1. Where is the module code actually stored on my machine?

Usually in /lib/site-packages in your Python folder. (At least, on Windows.)

You can use sys.path to find out what directories are searched for modules.

Apply CSS rules if browser is IE

I prefer using a separate file for ie rules, as described earlier.

<!--[if IE]><link rel="stylesheet" type="text/css" href="ie-style.css"/><![endif]-->

And inside it you can set up rules for different versions of ie using this:

.abc {...} /* ALL MSIE */
*html *.abc {...} /* MSIE 6 */
*:first-child+html .abc {...} /* MSIE 7 */

How can I stop .gitignore from appearing in the list of untracked files?

If someone has already added a .gitignore to your repo, but you want to make some changes to it and have those changes ignored do the following:

git update-index --assume-unchanged .gitignore

Source.

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

In the latest Bootstrap 3 version (bootstrap-datepicker.js) beforeShowDay expects a result in this format:

{ enabled: false, classes: "class-name", tooltip: "Holiday!" }

Alternatively, if you don't care about the CSS and tooltip then simply return a boolean false to make the date unselectable.

Also, there is no $.datepicker.noWeekends, so you need to do something along the lines of this:

var HOLIDAYS = {  // Ontario, Canada holidays
    2017: {
        1: { 1: "New Year's Day"},
        2: { 20: "Family Day" },
        4: { 17: "Easter Monday" },
        5: { 22: "Victoria Day" },
        7: { 1: "Canada Day" },
        8: { 7: "Civic Holiday" },
        9: { 4: "Labour Day" },
        10: { 9: "Thanksgiving" },
        12: { 25: "Christmas", 26: "Boxing Day"}
    }
};

function filterNonWorkingDays(date) {
    // Is it a weekend?
    if ([ 0, 6 ].indexOf(date.getDay()) >= 0)
        return { enabled: false, classes: "weekend" };
    // Is it a holiday?
    var h = HOLIDAYS;
    $.each(
        [ date.getYear() + 1900, date.getMonth() + 1, date.getDate() ], 
        function (i, x) {
            h = h[x];
            if (typeof h === "undefined")
                return false;
        }
    );
    if (h)
        return { enabled: false, classes: "holiday", tooltip: h };
    // It's a regular work day.
    return { enabled: true };
}

$("#datePicker").datepicker({ beforeShowDay: filterNonWorkingDays });

UnicodeEncodeError: 'latin-1' codec can't encode character

Latin-1 (aka ISO 8859-1) is a single octet character encoding scheme, and you can't fit \u201c () into a byte.

Did you mean to use UTF-8 encoding?

Where Is Machine.Config?

It semi-depends though... mine is:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG

and

C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG

Permanently hide Navigation Bar in an activity

There is a solution starting with KitKat (4.4.2), called Immersive Mode: https://developer.android.com/training/system-ui/immersive.html

Basically, you should add this code to your onResume() method:

View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                              | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                              | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                              | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                              | View.SYSTEM_UI_FLAG_FULLSCREEN
                              | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

Vertical Align Center in Bootstrap 4

In Bootstrap 4 (beta), use align-middle. Refer to Bootstrap 4 Documentation on Vertical alignment:

Change the alignment of elements with the vertical-alignment utilities. Please note that vertical-align only affects inline, inline-block, inline-table, and table cell elements.

Choose from .align-baseline, .align-top, .align-middle, .align-bottom, .align-text-bottom, and .align-text-top as needed.

reducing number of plot ticks

Alternatively, if you want to simply set the number of ticks while allowing matplotlib to position them (currently only with MaxNLocator), there is pyplot.locator_params,

pyplot.locator_params(nbins=4)

You can specify specific axis in this method as mentioned below, default is both:

# To specify the number of ticks on both or any single axes
pyplot.locator_params(axis='y', nbins=6)
pyplot.locator_params(axis='x', nbins=10)

How can I read the client's machine/computer name from the browser?

It is not possible to get the users computer name with Javascript. You can get all details about the browser and network. But not more than that.

Like some one answered in one of the previous question today.

I already did a favor of visiting your website, May be I will return or refer other friends.. I also told you where I am and what OS, Browser and screen resolution I use Why do you want to know the color of my underwear? ;-)

You cannot do it using asp.net as well.

How to hide a mobile browser's address bar?

You can go to fullscreen when user allows it :)

<button id="goFS">Go fullscreen</button>
<script>
  var goFS = document.getElementById("goFS");
  goFS.addEventListener("click", function() {
      
   const elem = document.documentElement;
   if (elem.requestFullscreen) {elem.requestFullscreen()}
   
  }, false);
</script>

Can a foreign key refer to a primary key in the same table?

Sure, why not? Let's say you have a Person table, with id, name, age, and parent_id, where parent_id is a foreign key to the same table. You wouldn't need to normalize the Person table to Parent and Child tables, that would be overkill.

Person
| id |  name | age | parent_id |
|----|-------|-----|-----------|
|  1 |   Tom |  50 |      null |
|  2 | Billy |  15 |         1 |

Something like this.

I suppose to maintain consistency, there would need to be at least 1 null value for parent_id, though. The one "alpha male" row.

EDIT: As the comments show, Sam found a good reason not to do this. It seems that in MySQL when you attempt to make edits to the primary key, even if you specify CASCADE ON UPDATE it won’t propagate the edit properly. Although primary keys are (usually) off-limits to editing in production, it is nevertheless a limitation not to be ignored. Thus I change my answer to:- you should probably avoid this practice unless you have pretty tight control over the production system (and can guarantee no one will implement a control that edits the PKs). I haven't tested it outside of MySQL.

How do I select a sibling element using jQuery?

If you want to select a specific sibling:

var $sibling = $(this).siblings('.bidbutton')[index];

where 'index' is the index of the specific sibling within the parent container.

Jquery each - Stop loop and return object

modified $.each function

$.fn.eachReturn = function(arr, callback) {
   var result = null;
   $.each(arr, function(index, value){
       var test = callback(index, value);
       if (test) {
           result = test;
           return false;
       }
   });
   return result ;
}

it will break loop on non-false/non-empty result and return it back, so in your case it would be

return $.eachReturn(someArray, function(i){
    ...

Android Facebook style slide

I found a simplest way for it and its working. Use simple Navigation drawer and call drawer.setdrawerListner() and use mainView.setX() method in on drawerSlide method below or copy my code.

xml file

 <android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000" >

<RelativeLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff">

  <ImageView
      android:layout_width="40dp"
      android:layout_height="40dp"
      android:id="@+id/menu"
      android:layout_alignParentTop="true"
      android:layout_alignParentLeft="true"
      android:layout_marginTop="10dp"
      android:layout_marginLeft="10dp"
      android:src="@drawable/black_line"
      />
</RelativeLayout>


<RelativeLayout
    android:id="@+id/left_drawer"
    android:layout_width="200dp"
    android:background="#181D21"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    >
    </RelativeLayout>
 </android.support.v4.widget.DrawerLayout>

java file

   public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
RelativeLayout mainView;
ImageView menu;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    menu=(ImageView)findViewById(R.id.menu);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mainView=(RelativeLayout)findViewById(R.id.content_frame);

    menu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            drawerLayout.openDrawer(Gravity.LEFT);
        }
    });

    drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            mainView.setX(slideOffset * 300);
        }

        @Override
        public void onDrawerOpened(View drawerView) {

        }

        @Override
        public void onDrawerClosed(View drawerView) {

        }

        @Override
        public void onDrawerStateChanged(int newState) {

        }
    });
 }
}

enter image description here

Thank You

How do I get the path and name of the file that is currently executing?

You can use inspect.stack()

import inspect,os
inspect.stack()[0]  => (<frame object at 0x00AC2AC0>, 'g:\\Python\\Test\\_GetCurrentProgram.py', 15, '<module>', ['print inspect.stack()[0]\n'], 0)
os.path.abspath (inspect.stack()[0][1]) => 'g:\\Python\\Test\\_GetCurrentProgram.py'

What's the fastest algorithm for sorting a linked list?

Not a direct answer to your question, but if you use a Skip List, it is already sorted and has O(log N) search time.

Run a JAR file from the command line and specify classpath

When you specify -jar then the -cp parameter will be ignored.

From the documentation:

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)

You have two options:

  1. include all jar files from the lib directory into the manifest (you can use relative paths there)
  2. Specify everything (including your jar) on the commandline using -cp:
    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

How to round the double value to 2 decimal points?

This would do it.

     public static void main(String[] args) {
        double d = 12.349678;
        int r = (int) Math.round(d*100);
        double f = r / 100.0;
       System.out.println(f);
     }

You can short this method, it's easy to understand that's why I have written like this.

Show a div with Fancybox

As far as I know, an input element may not have a href attribute, which is where Fancybox gets its information about the content. The following code uses an a element instead of the input element. Also, this is what I would call the "standard way".

<html>
<head>
  <script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script type="text/javascript" src="http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js?v=2.0.5"></script>
  <link rel="stylesheet" type="text/css" href="http://fancyapps.com/fancybox/source/jquery.fancybox.css?v=2.0.5" media="screen" />
</head>
<body>

<a href="#divForm" id="btnForm">Load Form</a>

<div id="divForm" style="display:none">
  <form action="tbd">
    File: <input type="file" /><br /><br />
    <input type="submit" />
  </form>
</div>

<script type="text/javascript">
  $(function(){
    $("#btnForm").fancybox();
  });
</script>

</body>
</html>

See it in action on JSBin

Matplotlib - global legend and title aside subplots

Global title: In newer releases of matplotlib one can use Figure.suptitle() method of Figure:

import matplotlib.pyplot as plt
fig = plt.gcf()
fig.suptitle("Title centered above all subplots", fontsize=14)

Alternatively (based on @Steven C. Howell's comment below (thank you!)), use the matplotlib.pyplot.suptitle() function:

 import matplotlib.pyplot as plt
 # plot stuff
 # ...
 plt.suptitle("Title centered above all subplots", fontsize=14)

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

Two solutions for this error:

1. add this permission in your androidManifest.xml of your Android project

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

2. Turn on the Internet Connection of your device first.

Signing a Windows EXE file

And yet another option, if you're developing on Windows 10 but don't have Microsoft's signtool.exe installed, you can use Bash on Ubuntu on Windows to sign your app. Here is a run down:

https://blog.synapp.nz/2017/06/16/code-signing-a-windows-application-on-linux-on-windows/

How to filter an array from all elements of another array

The following examples use new Set() to create a filtered array that has only unique elements:

Array with primitive data types: string, number, boolean, null, undefined, symbol:

const a = [1, 2, 3, 4];
const b = [3, 4, 5];
const c = Array.from(new Set(a.concat(b)));

Array with objects as items:

const a = [{id:1}, {id: 2}, {id: 3}, {id: 4}];
const b = [{id: 3}, {id: 4}, {id: 5}];
const stringifyObject = o => JSON.stringify(o);
const parseString = s => JSON.parse(s);
const c = Array.from(new Set(a.concat(b).map(stringifyObject)), parseString);

Test if registry value exists

One-liner:

$valueExists = (Get-Item $regKeyPath -EA Ignore).Property -contains $regValueName

Absolute position of an element on the screen using jQuery

BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:

function getOffsetTop (el) {
    if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
    return el.offsetTop || 0
}
function getOffsetLeft (el) {
    if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
    return el.offsetleft || 0
}
function coordinates(el) {
    var y1 = getOffsetTop(el) - window.scrollY;
    var x1 = getOffsetLeft(el) - window.scrollX; 
    var y2 = y1 + el.offsetHeight;
    var x2 = x1 + el.offsetWidth;
    return {
        x1: x1, x2: x2, y1: y1, y2: y2
    }
}

How to parse JSON using Node.js?

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

Imagine you have this Json in NodeJs...

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

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

Running CMD command in PowerShell

Try this:

& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME

To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.

Clear all fields in a form upon going back with browser back button

Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).

If you have to do something in case of user hitting back/forward keys - listen for BFCache pageshow and pagehide events:

window.addEventListener("pageshow", () => {
  // update hidden input field
});

See more details for Gecko and WebKit implementations.

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

Many thanks to David Walsh, here is a vanilla version of underscore debounce.

Code:

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

Simple usage:

var myEfficientFn = debounce(function() {
    // All the taxing stuff you do
}, 250);

$(window).on('resize', myEfficientFn);

Ref: http://davidwalsh.name/javascript-debounce-function

How can I undo a mysql statement that I just executed?

You can stop a query which is being processed by this

Find the Id of the query process by => show processlist;

Then => kill id;

How to validate date with format "mm/dd/yyyy" in JavaScript?

function fdate_validate(vi)
{
  var parts =vi.split('/');
  var result;
  var mydate = new Date(parts[2],parts[1]-1,parts[0]);
  if (parts[2] == mydate.getYear() && parts[1]-1 == mydate.getMonth() && parts[0] == mydate.getDate() )
  {result=0;}
  else
  {result=1;}
  return(result);
}

How to merge specific files from Git branches

None of the other current answers will actually "merge" the files, as if you were using the merge command. (At best they'll require you to manually pick diffs.) If you actually want to take advantage of merging using the information from a common ancestor, you can follow a procedure based on one found in the "Advanced Merging" section of the git Reference Manual.

For this protocol, I'm assuming you're wanting to merge the file 'path/to/file.txt' from origin/master into HEAD - modify as appropriate. (You don't have to be in the top directory of your repository, but it helps.)

# Find the merge base SHA1 (the common ancestor) for the two commits:
git merge-base HEAD origin/master

# Get the contents of the files at each stage
git show <merge-base SHA1>:path/to/file.txt > ./file.common.txt
git show HEAD:path/to/file.txt > ./file.ours.txt
git show origin/master:path/to/file.txt > ./file.theirs.txt

# You can pre-edit any of the files (e.g. run a formatter on it), if you want.

# Merge the files
git merge-file -p ./file.ours.txt ./file.common.txt ./file.theirs.txt > ./file.merged.txt

# Resolve merge conflicts in ./file.merged.txt
# Copy the merged version to the destination
# Clean up the intermediate files

git merge-file should use all of your default merge settings for formatting and the like.

Also note that if your "ours" is the working copy version and you don't want to be overly cautious, you can operate directly on the file:

git merge-base HEAD origin/master
git show <merge-base SHA1>:path/to/file.txt > ./file.common.txt
git show origin/master:path/to/file.txt > ./file.theirs.txt
git merge-file path/to/file.txt ./file.common.txt ./file.theirs.txt

Flutter command not found

flutter document tell us

cd ~/development
unzip ~/Downloads/flutter_macos_1.17.5-stable.zip

directory like this

/development/flutter_macos_1.17.5-stable/bin/

Then he told us to do this

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

Then the problem is coming, the file path name does not correspond

wtf?

you need change file name like this

/development/flutter/bin/

or change export path

export PATH="$PATH:`pwd`/flutter_macos_1.17.5-stable/bin"

Finding multiple occurrences of a string within a string in Python

For your list example:

In [1]: x = ['ll','ok','ll']

In [2]: for idx, value in enumerate(x):
   ...:     if value == 'll':
   ...:         print idx, value       
0 ll
2 ll

If you wanted all the items in a list that contained 'll', you could also do that.

In [3]: x = ['Allowed','Hello','World','Hollow']

In [4]: for idx, value in enumerate(x):
   ...:     if 'll' in value:
   ...:         print idx, value
   ...:         
   ...:         
0 Allowed
1 Hello
3 Hollow

Random string generation with upper case letters and digits

this is a take on Anurag Uniyal 's response and something that i was working on myself.

import random
import string

oneFile = open('?Numbers.txt', 'w')
userInput = 0
key_count = 0
value_count = 0
chars = string.ascii_uppercase + string.digits + string.punctuation

for userInput in range(int(input('How many 12 digit keys do you want?'))):
    while key_count <= userInput:
        key_count += 1
        number = random.randint(1, 999)
        key = number

        text = str(key) + ": " + str(''.join(random.sample(chars*6, 12)))
        oneFile.write(text + "\n")
oneFile.close()

Is true == 1 and false == 0 in JavaScript?

with == you are essentially comparing whether a variable is falsey when comparing to false or truthey when comparing to true. If you use ===, it will compare the exact value of the variables so true will not === 1

How to use Tomcat 8 in Eclipse?

In addition to @Jason's answer I had to do a bit more to get my app to run.

Is there a way to automatically generate getters and setters in Eclipse?

Sure.

Use Generate Getters and Setters from the Source menu or the context menu on a selected field or type, or a text selection in a type to open the dialog. The Generate Getters and Setters dialog shows getters and setters for all fields of the selected type. The methods are grouped by the type's fields.

Take a look at the help documentation for more information.

Docker expose all ports or range of ports from 7000 to 8000

For anyone facing this issue and ending up on this post...the issue is still open - https://github.com/moby/moby/issues/11185

HTML5 Video Stop onClose

The problem may be with jquery selector you've chosen $("video") is not a selector

The right selector may be putting an id element for video tag i.e.
Let's say your video element looks like this:

<video id="vid1" width="480" height="267" oster="example.jpg" durationHint="33"> 
    <source src="video1.ogv" /> 
    <source src="video2.ogv" /> 
</video> 

Then you can select it via $("#vid1") with hash mark (#), id selector in jquery. If a video element is exposed in function,then you have access to HtmlVideoElement (HtmlMediaElement).This elements has control over video element,in your case you can use pause() method for your video element.

Check reference for VideoElement here.
Also check that there is a fallback reference here.

How to create a new object instance from a Type

Given this problem the Activator will work when there is a parameterless ctor. If this is a constraint consider using

System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject()

HTTP Error 404.3-Not Found in IIS 7.5

In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".

addID in jQuery?

ID is an attribute, you can set it with the attr function:

$(element).attr('id', 'newID');

I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique.

How to hide columns in an ASP.NET GridView with auto-generated columns?

Try this to hide columns in an ASP.NET GridView with auto-generated columns, both RowDataBound/RowCreated work too.

Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound

    If e.Row.RowType = DataControlRowType.DataRow Or _
        e.Row.RowType = DataControlRowType.Header Then   // apply to datarow and header 

        e.Row.Cells(e.Row.Cells.Count - 1).Visible = False // last column
        e.Row.Cells(0).Visible = False  // first column

    End If
End Sub

Protected Sub GridView1_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowCreated

    If e.Row.RowType = DataControlRowType.DataRow Or _
        e.Row.RowType = DataControlRowType.Header Then

        e.Row.Cells(e.Row.Cells.Count - 1).Visible = False
        e.Row.Cells(0).Visible = False

    End If
End Sub

Check if string is in a pandas dataframe

I bumped into the same problem, I used:

if "Mel" in a["Names"].values:
    print("Yep")

But this solution may be slower since internally pandas create a list from a Series.

Resize height with Highcharts

You must set the height of the container explicitly

#container {
    height:100%;
    width:100%;
    position:absolute; 
}

See other Stackoverflow answer

Highcharts documentation

Where does the slf4j log file get saved?

It does not write to a file by default. You would need to configure something like the RollingFileAppender and have the root logger write to it (possibly in addition to the default ConsoleAppender).

Sending Email in Android using JavaMail API without using the default/built-in app

I found a shorter alternative for others who need help. The code is:

package com.example.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailTLS {

    public static void main(String[] args) {

        final String username = "[email protected]";
        final String password = "password";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("username", "password");
            }
          });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

Source: Sending Email via JavaMail API

Hope this Helps! Good Luck!

How to capture no file for fs.readFileSync()?

You have to catch the error and then check what type of error it is.

try {
  var data = fs.readFileSync(...)
} catch (err) {
  // If the type is not what you want, then just throw the error again.
  if (err.code !== 'ENOENT') throw err;

  // Handle a file-not-found error
}

JQuery - Call the jquery button click event based on name property

You can use the name property for that particular element. For example to set a border of 2px around an input element with name xyz, you can use;

$(function() {
    $("input[name = 'xyz']").css("border","2px solid red");
})

DEMO

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.

How do I convert an integer to binary in JavaScript?

This is my code:

var x = prompt("enter number", "7");
var i = 0;
var binaryvar = " ";

function add(n) {
    if (n == 0) {
        binaryvar = "0" + binaryvar; 
    }
    else {
        binaryvar = "1" + binaryvar;
    }
}

function binary() {
    while (i < 1) {
        if (x == 1) {
            add(1);
            document.write(binaryvar);
            break;
        }
        else {
            if (x % 2 == 0) {
                x = x / 2;
                add(0);
            }
            else {
                x = (x - 1) / 2;
                add(1);
            }
        }
    }
}

binary();

Why is "using namespace std;" considered bad practice?

It doesn't make your software or project performance worse. The inclusion of the namespace at the beginning of your source code isn't bad. The inclusion of the using namespace std instruction varies according to your needs and the way you are developing the software or project.

The namespace std contains the C++ standard functions and variables. This namespace is useful when you often would use the C++ standard functions.

As is mentioned in this page:

The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.

And see this opinion:

There is no problem using "using namespace std" in your source file when you make heavy use of the namespace and know for sure that nothing will collide.

Some people had said that is a bad practice to include the using namespace std in your source files because you're invoking from that namespace all the functions and variables. When you would like to define a new function with the same name as another function contained in the namespace std you would overload the function and it could produce problems due to compile or execute. It will not compile or executing as you expect.

As is mentioned in this page:

Although the statement saves us from typing std:: whenever we wish to access a class or type defined in the std namespace, it imports the entirety of the std namespace into the current namespace of the program. Let us take a few examples to understand why this might not be such a good thing

...

Now at a later stage of development, we wish to use another version of cout that is custom implemented in some library called “foo” (for example)

...

Notice how there is an ambiguity, to which library does cout point to? The compiler may detect this and not compile the program. In the worst case, the program may still compile but call the wrong function, since we never specified to which namespace the identifier belonged.

Any way to write a Windows .bat file to kill processes?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess%.exe'" Call Terminate

wmic offer even more flexibility than taskkill with its SQL-like matchers .With wmic Path win32_process get you can see the available fileds you can filter (and % can be used as a wildcard).

Open link in new tab or window

You can simply do that by setting target="_blank", w3schools has an example.

Calculate age given the birth date in the format YYYYMMDD

function getAge(dateString) {

    var dates = dateString.split("-");
    var d = new Date();

    var userday = dates[0];
    var usermonth = dates[1];
    var useryear = dates[2];

    var curday = d.getDate();
    var curmonth = d.getMonth()+1;
    var curyear = d.getFullYear();

    var age = curyear - useryear;

    if((curmonth < usermonth) || ( (curmonth == usermonth) && curday < userday   )){

        age--;

    }

    return age;
}

To get the age when european date has entered:

getAge('16-03-1989')

Format a datetime into a string with milliseconds

In python 3.6 and above using python f-strings:

from datetime import datetime 

i = datetime.utcnow()

print(f"""{i:%Y-%m-%d %H:%M:%S}.{"{:03d}".format(i.microsecond // 1000)}""")

The code specific to format milliseconds is:

{"{:03d}".format(i.microsecond // 1000)}

The format string {:03d} and microsecond to millisecond conversion // 1000 is from def _format_time in https://github.com/python/cpython/blob/master/Lib/datetime.py that is used for datetime.datetime.isoformat().

How to center HTML5 Videos?

@snowBlind In the first example you gave, your style rules should go in a <style> tag, not a <script> tag:

<style type="text/css">
  .center {
    margin: 0 auto;
  }
</style>

Also, I tried the changes that were mentioned in this answer (see results at http://jsfiddle.net/8cXqQ/7/), but they still don't appear to work.

You can surround the video with a div and apply width and auto margins to the div to center the video (along with specifying width attribute for video, see results at http://jsfiddle.net/8cXqQ/9/).

But that doesn't seem like the simplest solution...shouldn't we be able to center a video without having to wrap it in a container div?

PHP foreach loop key value

You can access your array keys like so:

foreach ($array as $key => $value)

Place a button right aligned

_x000D_
_x000D_
<div style = "display: flex; justify-content:flex-end">
    <button>Click me!</button>
</div>
_x000D_
_x000D_
_x000D_

<div style = "display: flex; justify-content: flex-end">
    <button>Click me!</button>
</div>

Giving graphs a subtitle in matplotlib

Although this doesn't give you the flexibility associated with multiple font sizes, adding a newline character to your pyplot.title() string can be a simple solution;

plt.title('Really Important Plot\nThis is why it is important')

Bootstrap 4 - Responsive cards in card-columns

I have created a Cards Layout - 3 cards in a row using Bootstrap 4 / CSS3 (of course its responsive). The following example uses basic Bootstrap 4 classes such as container, row, col-x, list-group and list-group-item. Thought to share here if someone is interested in this sort of a layout.

enter image description here

HTML

<div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">        
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
  </div>
</div>

CSS / SCSS

$primary-color: #ccc;
$col-bg-color: #eee;
$col-footer-bg-color: #eee;
$col-header-bg-color: #007bff;
$col-content-bg-color: #fff;

body {
  background-color: $primary-color;
}  

.custom-column {  
  background-color: $col-bg-color;
  border: 5px solid $col-bg-color;    
  padding: 10px;
  box-sizing: border-box;  
}

.custom-column-header {
  font-size: 24px;
  background-color: #007bff;  
  color: white;
  padding: 15px;  
  text-align: center;
}

.custom-column-content {
  background-color: $col-content-bg-color;
  border: 2px solid white;  
  padding: 20px;  
}

.custom-column-footer {
  background-color: $col-footer-bg-color;   
  padding-top: 20px;
  text-align: center;
}

Link :- https://codepen.io/anjanasilva/pen/JmdOpb

How can I format DateTime to web UTC format?

Why don't just use The Round-trip ("O", "o") Format Specifier?

The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information and emits a result string that complies with ISO 8601. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind.

The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values. In this string, the pairs of single quotation marks that delimit individual characters, such as the hyphens, the colons, and the letter "T", indicate that the individual character is a literal that cannot be changed. The apostrophes do not appear in the output string.

The O" or "o" standard format specifier (and the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string) takes advantage of the three ways that ISO 8601 represents time zone information to preserve the Kind property of DateTime values:

public class Example
{
   public static void Main()
   {
       DateTime dat = new DateTime(2009, 6, 15, 13, 45, 30, 
                                   DateTimeKind.Unspecified);
       Console.WriteLine("{0} ({1}) --> {0:O}", dat, dat.Kind); 

       DateTime uDat = new DateTime(2009, 6, 15, 13, 45, 30, 
                                    DateTimeKind.Utc);
       Console.WriteLine("{0} ({1}) --> {0:O}", uDat, uDat.Kind);

       DateTime lDat = new DateTime(2009, 6, 15, 13, 45, 30, 
                                    DateTimeKind.Local);
       Console.WriteLine("{0} ({1}) --> {0:O}\n", lDat, lDat.Kind);

       DateTimeOffset dto = new DateTimeOffset(lDat);
       Console.WriteLine("{0} --> {0:O}", dto);
   }
}
// The example displays the following output: 
//    6/15/2009 1:45:30 PM (Unspecified) --> 2009-06-15T13:45:30.0000000 
//    6/15/2009 1:45:30 PM (Utc) --> 2009-06-15T13:45:30.0000000Z 
//    6/15/2009 1:45:30 PM (Local) --> 2009-06-15T13:45:30.0000000-07:00 
//     
//    6/15/2009 1:45:30 PM -07:00 --> 2009-06-15T13:45:30.0000000-07:00

How can I get a vertical scrollbar in my ListBox?

I added a "Height" to my ListBox and it added the scrollbar nicely.

Java : Sort integer array without using Arrays.sort()

Bubble sort can be used here:

 //Time complexity: O(n^2)
public static int[] bubbleSort(final int[] arr) {

    if (arr == null || arr.length <= 1) {
        return arr;
    }

    for (int i = 0; i < arr.length; i++) {
        for (int j = 1; j < arr.length - i; j++) {
            if (arr[j - 1] > arr[j]) {
                arr[j] = arr[j] + arr[j - 1];
                arr[j - 1] = arr[j] - arr[j - 1];
                arr[j] = arr[j] - arr[j - 1];
            }
        }
    }

    return arr;
}

Storing integer values as constants in Enum manner in java

You could store that const value in the enum like so. But why even use the const? Are you persisting the enum's?

public class SO3990319 {
   public static enum PAGE {
      SIGN_CREATE(1);
      private final int constValue;

      private PAGE(int constValue) {
         this.constValue = constValue;
      }

      public int constValue() {
         return constValue;
      }
   }

   public static void main(String[] args) {
      System.out.println("Name:    " + PAGE.SIGN_CREATE.name());
      System.out.println("Ordinal: " + PAGE.SIGN_CREATE.ordinal());
      System.out.println("Const:   " + PAGE.SIGN_CREATE.constValue());

      System.out.println("Enum: " + PAGE.valueOf("SIGN_CREATE"));
   }
}

Edit:

It depends on what you're using the int's for whether to use EnumMap or instance field.

How to get param from url in angular 4?

The accepted answer uses the observable to retrieve the parameter which can be useful in the parameter will change throughtout the component lifecycle.

If the parameter will not change, one can consider using the params object on the snapshot of the router url.

snapshot.params returns all the parameters in the URL in an object.

constructor(private route: ActivateRoute){}

ngOnInit() {
   const allParams = this.route.snapshot.params // allParams is an object
   const param1 = allParams.param1 // retrieve the parameter "param1"
}

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

In xamarin form project. I deleted

.VS Project folder.
ProjectName.Android.csProj.User
ProjectName.Android.csProj.bak

What is a callback in java

In Java, callback methods are mainly used to address the "Observer Pattern", which is closely related to "Asynchronous Programming".

Although callbacks are also used to simulate passing methods as a parameter, like what is done in functional programming languages.

Determine if running on a rooted device

Forget all that detecting root apps and su binaries. Check for the root daemon process. This can be done from the terminal and you can run terminal commands within an app. Try this one-liner.

if [ ! -z "$(/system/bin/ps -A | grep -v grep | grep -c daemonsu)" ]; then echo "device is rooted"; else echo "device is not rooted"; fi

You don't need root permission to achieve this either.

Best way to display data via JSON using jQuery

Perfect! Thank you Jay, below is my HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facebook like ajax post - jQuery - ryancoughlin.com</title>
<link rel="stylesheet" href="../css/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="../css/print.css" type="text/css" media="print" />
<!--[if IE]><link rel="stylesheet" href="../css/ie.css" type="text/css" media="screen, projection"><![endif]-->
<link href="../css/highlight.css" rel="stylesheet" type="text/css" media="screen" />
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
    $.getJSON("readJSON.php",function(data){
        $.each(data.post, function(i,post){
            content += '<p>' + post.post_author + '</p>';
            content += '<p>' + post.post_content + '</p>';
            content += '<p' + post.date + '</p>';
            content += '<br/>';
            $(content).appendTo("#posts");
        });
    });   
});
/* ]]> */
</script>
</head>
<body>
        <div class="container">
                <div class="span-24">
                       <h2>Check out the following posts:</h2>
                        <div id="posts">
                        </di>
                </div>
        </div>
</body>
</html>

And my JSON outputs:

{ posts: [{"id":"1","date_added":"0001-02-22 00:00:00","post_content":"This is a post","author":"Ryan Coughlin"}]}

I get this error, when I run my code:

object is undefined
http://localhost:8888/rks/post/js/jquery.js
Line 19

MySQL: determine which database is selected?

Another way for filtering the database with specific word.

SHOW DATABASES WHERE `Database` LIKE '<yourDatabasePrefixHere>%'
or
SHOW DATABASES LIKE '<yourDatabasePrefixHere>%';

Example:

SHOW DATABASES WHERE `Database` LIKE 'foobar%'
foobar_animal
foobar_humans_gender
foobar_objects

Parameter in like clause JPQL

Use JpaRepository or CrudRepository as repository interface:

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {

    @Query("SELECT t from Customer t where LOWER(t.name) LIKE %:name%")
    public List<Customer> findByName(@Param("name") String name);

}


@Service(value="customerService")
public class CustomerServiceImpl implements CustomerService {

    private CustomerRepository customerRepository;
    
    //...

    @Override
    public List<Customer> pattern(String text) throws Exception {
        return customerRepository.findByName(text.toLowerCase());
    }
}

Importing two classes with same name. How to handle?

Another way to do it is subclass it:

package my.own;

public class FQNDate extends Date {

}

And then import my.own.FQNDate in packages that have java.util.Date.

Pandas - replacing column values

You can also try using apply with get method of dictionary, seems to be little faster than replace:

data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Testing with timeit:

%%timeit
data['sex'].replace([0,1],['Female','Male'],inplace=True)

Result:

The slowest run took 5.83 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 510 µs per loop

Using apply:

%%timeit
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Result:

The slowest run took 5.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 331 µs per loop

Note: apply with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.

The model backing the 'ApplicationDbContext' context has changed since the database was created

Everybody getting a headache from this error: Make absolutely sure all your projetcs have a reference to the same Entity Framework assembly.

Short story long:

My model and my application were in different assemblies. These assemblies were referencing a different version of Entity framework. I guess that the two versions generated a different id for the same modell. So when my application ran the id of the model didn't match the one of the latest migration in __MigrationHistory. After updating all references to the latest EF release the error never showed up again.

Removing a Fragment from the back stack

I created a code to jump to the desired back stack index, it worked fine to my purpose.

ie. I have Fragment1, Fragment2 and Fragment3, I want to jump from Fragment3 to Fragment1

I created a method called onBackPressed in Fragment3 that jumps to Fragment1

Fragment3:

public void onBackPressed() {
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.popBackStack(fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-2).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}

In the activity, I need to know if my current fragment is the Fragment3, so I call the onBackPressed of my fragment instead calling super

FragmentActivity:

@Override
public void onBackPressed() {
    Fragment f = getSupportFragmentManager().findFragmentById(R.id.my_fragment_container);
    if (f instanceof Fragment3)
    {
        ((Fragment3)f).onBackPressed();
    } else {
        super.onBackPressed();
    }
}

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

You're trying to access a JSON, not JSONP.

Notice the difference between your source:

https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59&callback=?

And actual JSONP (a wrapping function):

http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=processJSON&tags=monkey&tagmode=any&format=json

Search for JSON + CORS/Cross-domain policy and you will find hundreds of SO threads on this very topic.

Find html label associated with a given input

It is actually far easier to add an id to the label in the form itself, for example:

<label for="firstName" id="firstNameLabel">FirstName:</label>

<input type="text" id="firstName" name="firstName" class="input_Field" 
       pattern="^[a-zA-Z\s\-]{2,25}$" maxlength="25"
       title="Alphabetic, Space, Dash Only, 2-25 Characters Long" 
       autocomplete="on" required
/>

Then, you can simply use something like this:

if (myvariableforpagelang == 'es') {
   // set field label to spanish
   document.getElementById("firstNameLabel").innerHTML = "Primer Nombre:";
   // set field tooltip (title to spanish
   document.getElementById("firstName").title = "Alfabética, espacio, guión Sólo, 2-25 caracteres de longitud";
}

The javascript does have to be in a body onload function to work.

Just a thought, works beautifully for me.

What is The difference between ListBox and ListView

Listview derives from listbox control. One most important difference is listview uses the extended selection mode by default . listview also adds a property called view which enables you to customize the view in a richer way than a custom itemspanel. One real life example of listview with gridview is file explorer's details view. Listview with grid view is a less powerful data grid. After the introduction of datagrid control listview lost its importance.

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);

Using CSS td width absolute, position

The reason it doesn't work in the link your provided is because you are trying to display a 300px column PLUS 52 columns the span 7 columns each. Shrink the number of columns and it works. You can't fit that many on the screen.

If you want to force the columns to fit try setting:

body {min-width:4150px;}

see my jsfiddle: http://jsfiddle.net/Mkq8L/6/ @mike I can't comment yet.

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

The COLLATE keyword specify what kind of character set and rules (order, confrontation rules) you are using for string values.

For example in your case you are using Latin rules with case insensitive (CI) and accent sensitive (AS)

You can refer to this Documentation

Using wget to recursively fetch a directory with arbitrary files in it

You have to pass the -np/--no-parent option to wget (in addition to -r/--recursive, of course), otherwise it will follow the link in the directory index on my site to the parent directory. So the command would look like this:

wget --recursive --no-parent http://example.com/configs/.vim/

To avoid downloading the auto-generated index.html files, use the -R/--reject option:

wget -r -np -R "index.html*" http://example.com/configs/.vim/

How do I find the last column with data?

I know this is old, but I've tested this in many ways and it hasn't let me down yet, unless someone can tell me otherwise.

Row number

Row = ws.Cells.Find(What:="*", After:=[A1] , SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

Column Letter

ColumnLetter = Split(ws.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Cells.Address(1, 0), "$")(0)

Column Number

ColumnNumber = ws.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

Loop through files in a directory using PowerShell

If you need to loop inside a directory recursively for a particular kind of file, use the below command, which filters all the files of doc file type

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc

If you need to do the filteration on multiple types, use the below command.

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc,*.pdf

Now $fileNames variable act as an array from which you can loop and apply your business logic.

Is Visual Studio Community a 30 day trial?

I had this problem. Signing in or pressing the "Check for an updated license" link did not work for me. My solution was to restart Visual Studio, try again (sign in and check for license). Restart Visual Studio, try again. I had to do this several times and then it worked! (I also tried pressing the "File" menu that is available for a short period of time before the annoying request window appears again.) Maybe you just don't get connected to the server or the server itself doesn't update its database fast enough.

PYTHONPATH on Linux

1) PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. e.g.:

# make python look in the foo subdirectory of your home directory for
# modules and packages 
export PYTHONPATH=${PYTHONPATH}:${HOME}/foo 

Here I use the sh syntax. For other shells (e.g. csh,tcsh), the syntax would be slightly different. To make it permanent, set the variable in your shell's init file (usually ~/.bashrc).

2) Ubuntu comes with python already installed. There may be reasons for installing other (independent) python versions, but I've found that to be rarely necessary.

3) The folder where your modules live is dependent on PYTHONPATH and where the directories were set up when python was installed. For the most part, the installed stuff you shouldn't care about where it lives -- Python knows where it is and it can find the modules. Sort of like issuing the command ls -- where does ls live? /usr/bin? /bin? 99% of the time, you don't need to care -- Just use ls and be happy that it lives somewhere on your PATH so the shell can find it.

4) I'm not sure I understand the question. 3rd party modules usually come with install instructions. If you follow the instructions, python should be able to find the module and you shouldn't have to care about where it got installed.

5) Configure PYTHONPATH to include the directory where your module resides and python will be able to find your module.

bash: shortest way to get n-th column of output

Note, that file path does not have to be in second column of svn st output. For example if you modify file, and modify it's property, it will be 3rd column.

See possible output examples in:

svn help st

Example output:

 M     wc/bar.c
A  +   wc/qax.c

I suggest to cut first 8 characters by:

svn st | cut -c8- | while read FILE; do echo whatever with "$FILE"; done

If you want to be 100% sure, and deal with fancy filenames with white space at the end for example, you need to parse xml output:

svn st --xml | grep -o 'path=".*"' | sed 's/^path="//; s/"$//'

Of course you may want to use some real XML parser instead of grep/sed.

Is there a pretty print for PHP?

Since I found this via google searching for how to format json to make it more readable for troubleshooting.

ob_start() ;  print_r( $json ); $ob_out=ob_get_contents(); ob_end_clean(); echo "\$json".str_replace( '}', "}\n", $ob_out );

Ellipsis for overflow text in dropdown boxes

You can use this:

select {
    width:100px; 
    overflow:hidden; 
    white-space:nowrap; 
    text-overflow:ellipsis;
}
select option {
    width:100px;
    text-overflow:ellipsis;
    overflow:hidden;
}
div {
    border-style:solid; 
    width:100px; 
    overflow:hidden; 
    white-space:nowrap; 
    text-overflow:ellipsis;
}

Get Cell Value from Excel Sheet with Apache Poi

May be by:-

    for(Row row : sheet) {          
        for(Cell cell : row) {              
            System.out.print(cell.getStringCellValue());

        }
    }       

For specific type of cell you can try:

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
    cellValue = cell.getStringCellValue();
    break;

case Cell.CELL_TYPE_FORMULA:
    cellValue = cell.getCellFormula();
    break;

case Cell.CELL_TYPE_NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
        cellValue = cell.getDateCellValue().toString();
    } else {
        cellValue = Double.toString(cell.getNumericCellValue());
    }
    break;

case Cell.CELL_TYPE_BLANK:
    cellValue = "";
    break;

case Cell.CELL_TYPE_BOOLEAN:
    cellValue = Boolean.toString(cell.getBooleanCellValue());
    break;

}

How to set TLS version on apache HttpClient

Using -Dhttps.protocols=TLSv1.2 JVM argument didn't work for me. What worked is the following code

RequestConfig.Builder requestBuilder = RequestConfig.custom();
//other configuration, for example
requestBuilder = requestBuilder.setConnectTimeout(1000);

SSLContext sslContext = SSLContextBuilder.create().useProtocol("TLSv1.2").build();

HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(requestBuilder.build());
builder.setProxy(new HttpHost("your.proxy.com", 3333)); //if you have proxy
builder.setSSLContext(sslContext);

HttpClient client = builder.build();

Use the following JVM argument to verify

-Djavax.net.debug=all

Getting Unexpected Token Export

Install the babel packages @babel/core and @babel/preset which will convert ES6 to a commonjs target as node js doesn't understand ES6 targets directly

npm install --save-dev @babel/core @babel/preset-env

Then you need to create one configuration file with name .babelrc in your project's root directory and add this code there

{ "presets": ["@babel/preset-env"] }

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

My +1 to mata's comment at https://stackoverflow.com/a/10561979/1346705 and to the Nick Craig-Wood's demonstration. You have decoded the string correctly. The problem is with the print command as it converts the Unicode string to the console encoding, and the console is not capable to display the string. Try to write the string into a file and look at the result using some decent editor that supports Unicode:

import codecs

s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
s1 = s.decode('utf-8')
f = codecs.open('out.txt', 'w', encoding='utf-8')
f.write(s1)
f.close()

Then you will see (?????)?.

Making a list of evenly spaced numbers in a certain range in python

Similar to Howard's answer but a bit more efficient:

def my_func(low, up, leng):
    step = ((up-low) * 1.0 / leng)
    return [low+i*step for i in xrange(leng)]

What is the HTML unicode character for a "tall" right chevron?

From the description and from the reference to the search box in the Ubuntu site, I gather that you actually want an arrowhead character pointing to the right. There are no Unicode characters designed to be used as arrowheads, but some of them may visually resemble an arrowhead.

In particular, if you draw your idea of the character at Shapecatcher.com, you will find many suggestions, such as “>” RIGHT-POINTING ANGLE BRACKET' (U+232A) and “?” MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT (U+276D).

Such characters generally have limited support in fonts, so you would need to carefully write a longish font-family list or to use a downloadable font. See my Guide to using special characters in HTML.

Especially if the intended use is as a symbol in a search box, as the reference to the Ubuntu page suggests, it is questionable whether you should use a character at all. It’s not really an element of text here; rather, a graphic symbol that accompanies text but isn’t a part of it. So why take all the trouble with using a character (safely), when it isn’t really a character?

How do you fadeIn and animate at the same time?

Another way to do simultaneous animations if you want to call them separately (eg. from different code) is to use queue. Again, as with Tinister's answer you would have to use animate for this and not fadeIn:

$('.tooltip').css('opacity', 0);
$('.tooltip').show();
...

$('.tooltip').animate({opacity: 1}, {queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

Run Jquery function on window events: load, resize, and scroll?

You can bind listeners to one common functions -

$(window).bind("load resize scroll",function(e){
  // do stuff
});

Or another way -

$(window).bind({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

Alternatively, instead of using .bind() you can use .on() as bind directly maps to on(). And maybe .bind() won't be there in future jquery versions.

$(window).on({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

When we are going to migrate JQuery from 1.x to 2x or 3.x in our old existing application , then we will use .done,.fail instead of success,error as JQuery up gradation is going to be deprecated these methods.For example when we make a call to server web methods then server returns promise objects to the calling methods(Ajax methods) and this promise objects contains .done,.fail..etc methods.Hence we will the same for success and failure response. Below is the example(it is for POST request same way we can construct for request type like GET...)

 $.ajax({
            type: "POST",
            url: url,
            data: '{"name" :"sheo"}',
            contentType: "application/json; charset=utf-8",
            async: false,
            cache: false
            }).done(function (Response) {
                  //do something when get response            })
           .fail(function (Response) {
                    //do something when any error occurs.
                });

DELETE ... FROM ... WHERE ... IN

Try adding parentheses around the row in table1 e.g.

DELETE 
  FROM table1
 WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);

The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.

Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:

MERGE INTO table1 AS t1
   USING table2 AS s1
      ON t1.stn = s1.stn
         AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;

R: "Unary operator error" from multiline ggplot2 command

It's the '+' operator at the beginning of the line that trips things up (not just that you are using two '+' operators consecutively). The '+' operator can be used at the end of lines, but not at the beginning.

This works:

ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
geom_boxplot() 

The does not:

ggplot(combined.data, aes(x = region, y = expression, fill = species))
+ geom_boxplot() 

*Error in + geom_boxplot():
invalid argument to unary operator*

You also can't use two '+' operators, which in this case you've done. But to fix this, you'll have to selectively remove those at the beginning of lines.

AngularJS - difference between pristine/dirty and touched/untouched

It's worth mentioning that the validation properties are different for forms and form elements (note that touched and untouched are for fields only):

Input fields have the following states:

$untouched The field has not been touched yet
$touched The field has been touched
$pristine The field has not been modified yet
$dirty The field has been modified
$invalid The field content is not valid
$valid The field content is valid

They are all properties of the input field, and are either true or false.

Forms have the following states:

$pristine No fields have been modified yet
$dirty One or more have been modified
$invalid The form content is not valid
$valid The form content is valid
$submitted The form is submitted

They are all properties of the form, and are either true or false.

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

Anyone using Jenkins, might get it useful

You need to define a global variable name ANDROID_HOME with the value of the path to android sdk.

For mac, it is /Users/YOUR_USER_NAME/Library/Android/sdk

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

Try using a callback like this with the catch block.

document.getElementById("audio").play().catch(function() {
    // do something
});

How to Get Element By Class in JavaScript?

When some elements lack ID, I use jQuery like this:

$(document).ready(function()
{
    $('.myclass').attr('id', 'myid');
});

This might be a strange solution, but maybe someone find it useful.

Angularjs on page load call function

<section ng-controller="testController as ctrl" class="test_cls"  data-ng-init="fn_load()">

$scope.fn_load = function () {
  console.log("page load")
};

Chrome Extension - Get DOM content

For those who tried gkalpak answer and it did not work,

be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes

Error when using scp command "bash: scp: command not found"

Issue is with remote server, can you login to the remote server and check if "scp" works

probable causes: - scp is not in path - openssh client not installed correctly

for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/

Angular 4.3 - HttpClient set params

Just wanted to add that if you want to add several parameters with the same key name for example: www.test.com/home?id=1&id=2

let params = new HttpParams();
params = params.append(key, value);

Use append, if you use set, it will overwrite the previous value with the same key name.

remove item from array using its name / value

You can do it with _.pullAllBy.

_x000D_
_x000D_
var countries = {};_x000D_
_x000D_
countries.results = [_x000D_
    {id:'AF',name:'Afghanistan'},_x000D_
    {id:'AL',name:'Albania'},_x000D_
    {id:'DZ',name:'Algeria'}_x000D_
];_x000D_
_x000D_
// Remove element by id_x000D_
_.pullAllBy(countries.results , [{ 'id': 'AL' }], 'id');_x000D_
_x000D_
// Remove element by name_x000D_
// _.pullAllBy(countries.results , [{ 'name': 'Albania' }], 'name');_x000D_
console.log(countries);
_x000D_
.as-console-wrapper {_x000D_
  max-height: 100% !important;_x000D_
  top: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Checkbox for nullable boolean

When making an EditorTemplate for a model which contains a nullable bool...

  • Split the nullable bool into 2 booleans:

    // Foo is still a nullable boolean.
    public bool? Foo 
    {
        get 
        { 
            if (FooIsNull)
                return null;
    
            return FooCheckbox;  
        }
        set
        {
            FooIsNull   = (value == null);
            FooCheckbox = (value ?? false);
        }
    }
    
    // These contain the value of Foo. Public only so they are visible in Razor views.
    public bool FooIsNull { get; set; }
    public bool FooCheckbox { get; set; }
    
  • Within the editor template:

    @Html.HiddenFor(m => m.FooIsNull)
    
    @if (Model.FooIsNull)
    {
        // Null means "checkbox is hidden"
        @Html.HiddenFor(m => m.FooCheckbox)
    }
    else
    {
        @Html.CheckBoxFor(m => m.FooCheckbox)
    }
    
  • Do not postback the original property Foo, because that is now calculated from FooIsNull and FooCheckbox.

Powershell 2 copy-item which creates a folder if doesn't exist

My favorite is to use the .Net [IO.DirectoryInfo] class, which takes care of some of the logic. I actually use this for a lot of similar scripting challenges. It has a .Create() method that creates directories that don't exist, without errors if they do.

Since this is still a two step problem, I use the foreach alias to keep it simple. For single files:

[IO.DirectoryInfo]$to |% {$_.create(); cp $from $_}

As far as your multi file/directory match, I would use RoboCopy over xcopy. Remove the "*" from your from and just use:

RoboCopy.exe $from $to *

You can still add the /r (Recurse), /e (Recurse including Empty), and there are 50 other useful switches.

Edit: Looking back at this it is terse, but not very readable if you are not using the code often. Usually I have it split into two, like so:

([IO.DirectoryInfo]$to).Create()
cp $from $to

Also, DirectoryInfo is the type of the Parent property of FileInfo, so if your $to is a file, you can use them together:

([IO.FileInfo]$to).Parent.Create()
cp $from $to

how to get selected row value in the KendoUI

One way is to use the Grid's select() and dataItem() methods.

In single selection case, select() will return a single row which can be passed to dataItem()

var entityGrid = $("#EntitesGrid").data("kendoGrid");
var selectedItem = entityGrid.dataItem(entityGrid.select());
// selectedItem has EntityVersionId and the rest of your model

For multiple row selection select() will return an array of rows. You can then iterate through the array and the individual rows can be passed into the grid's dataItem().

var entityGrid = $("#EntitesGrid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function(index, row) {
  var selectedItem = entityGrid.dataItem(row);
  // selectedItem has EntityVersionId and the rest of your model
});

No such keg: /usr/local/Cellar/git

Had a similar issue while installing "Lua" in OS X using homebrew. I guess it could be useful for other users facing similar issue in homebrew.

On running the command:

$ brew install lua

The command returned an error:

Error: /usr/local/opt/lua is not a valid keg
(in general the error can be of /usr/local/opt/ is not a valid keg

FIXED it by deleting the file/directory it is referring to, i.e., deleting the "/usr/local/opt/lua" file.

root-user # rm -rf /usr/local/opt/lua

And then running the brew install command returned success.

How to find the unclosed div tag

If you use Dreamweaver you could easily note to unclosed div. In the left pane of the code view you can see there <> highlight invalid code button, click this button and you will notice the unclosed div highlighted and then close your unclosed div. Press F5 to refresh the page to see that any other unclosed div are there.

You can also validate your page in Dreamweaver too. File>Check Page>Browser Compatibility, then task-pane will appear Click on Validation, on the left side there you'll see ? button click this to validate.

Enjoy!

Java: method to get position of a match in a String?

Finding a single index

As others have said, use text.indexOf(match) to find a single match.

String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10

Finding multiple indexes

Because of @StephenC's comment about code maintainability and my own difficulty in understanding @polygenelubricants' answer, I wanted to find another way to get all the indexes of a match in a text string. The following code (which is modified from this answer) does so:

String text = "0123hello9012hello8901hello7890";
String match = "hello";

int index = text.indexOf(match);
int matchLength = match.length();
while (index >= 0) {  // indexOf returns -1 if no match found
    System.out.println(index);
    index = text.indexOf(match, index + matchLength);
}

Is it possible to run .APK/Android apps on iPad/iPhone devices?

There is another option not mentioned previously:

  • Pieceable Viewer has unfortunately stopped its service at December 31, 2012 but open-sourced its software. You need to compile your iOS application for the emulator and Pieceable's software will embed it in a webpage which hosts the application. This webpage can be used to run the iOS application. See Pieceable's for more details.

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

everyone comment about SQL, but what hapend in EntityFramework? I spent reading the whole post and no one solved EF. So after a few days a found solution: EF Core in the context to create the model there is an instruction like this: modelBuilder.Entity<Cliente>(entity => { entity.Property(e => e.Id).ValueGeneratedNever();

this produces the error too, solution: you have to change by ValueGeneratedOnAdd() and its works!

how to dynamically add options to an existing select in vanilla javascript

.add() also works.

var daySelect = document.getElementById("myDaySelect");
var myOption = document.createElement("option");
myOption.text = "test";
myOption.value = "value";
daySelect.add(option);

W3 School - try

How to remove an id attribute from a div using jQuery?

I'm not sure what jQuery api you're looking at, but you should only have to specify id.

$('#thumb').removeAttr('id');

Changing background color of text box input not working when empty

Don't add styles to value of input so use like

function checkFilled() {
    var inputElem = document.getElementById("subEmail");
    if (inputElem.value == "") {
        inputElem.style.backgroundColor = "yellow";
                }
        }

Make an image width 100% of parent div, but not bigger than its own width

Setting a width of 100% is the full width of the div it's in, not the original full-sized image. There is no way to do that without JavaScript or some other scripting language that can measure the image. If you can have a fixed width or fixed height of the div (like 200px wide) then it shouldn't be too hard to give the image a range to fill. But if you put a 20x20 pixel image in a 200x300 pixel box it will still be distorted.

How to alter a column and change the default value?

Try this

ALTER TABLE `table_name` CHANGE `column_name` `column_name` data_type  NULL DEFAULT '';

like this

ALTER TABLE `drivers_meta` CHANGE `driving_license` `driving_license` VARCHAR(30) NULL DEFAULT '';

What exactly are DLL files, and how do they work?

DLLs (dynamic link libraries) and SLs (shared libraries, equivalent under UNIX) are just libraries of executable code which can be dynamically linked into an executable at load time.

Static libraries are inserted into an executable at compile time and are fixed from that point. They increase the size of the executable and cannot be shared.

Dynamic libraries have the following advantages:

1/ They are loaded at run time rather than compile time so they can be updated independently of the executable (all those fancy windows and dialog boxes you see in Windows come from DLLs so the look-and-feel of your application can change without you having to rewrite it).

2/ Because they're independent, the code can be shared across multiple executables - this saves memory since, if you're running 100 apps with a single DLL, there may only be one copy of the DLL in memory.

Their main disadvantage is advantage #1 - having DLLs change independent your application may cause your application to stop working or start behaving in a bizarre manner. DLL versioning tend not to be managed very well under Windows and this leads to the quaintly-named "DLL Hell".

MySQL Workbench Edit Table Data is read only

enter image description here

Uncheck the marked check, it will enable the grid edit

How do I call an Angular.js filter with multiple arguments?

In templates, you can separate filter arguments by colons.

{{ yourExpression | yourFilter: arg1:arg2:... }}

From Javascript, you call it as

$filter('yourFilter')(yourExpression, arg1, arg2, ...)

There is actually an example hidden in the orderBy filter docs.


Example:

Let's say you make a filter that can replace things with regular expressions:

myApp.filter("regexReplace", function() { // register new filter

  return function(input, searchRegex, replaceRegex) { // filter arguments

    return input.replace(RegExp(searchRegex), replaceRegex); // implementation

  };
});

Invocation in a template to censor out all digits:

<p>{{ myText | regexReplace: '[0-9]':'X' }}</p>

Reusing output from last command in Bash

The answer is no. Bash doesn't allocate any output to any parameter or any block on its memory. Also, you are only allowed to access Bash by its allowed interface operations. Bash's private data is not accessible unless you hack it.

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

Where is the Microsoft.IdentityModel dll

In Windows 8.1 64bit, look under C:\Windows\ADFS

How to convert unsigned long to string

Try using sprintf:

unsigned long x=1000000;
char buffer[21];
sprintf(buffer,"%lu", x);

Edit:

Notice that you have to allocate a buffer in advance, and have no idea how long the numbers will actually be when you do so. I'm assuming 32bit longs, which can produce numbers as big as 10 digits.

See Carl Smotricz's answer for a better explanation of the issues involved.

Make div scrollable

I know this is an older question and that the original question needed the div to have a fixed height, but I thought I would share that this can also be accomplished without a fixed pixel height for those looking for that kind of answer.

What I mean is that you can use something like:

.itemconfiguration
{
    // ...style rules...
    height: 25%; //or whatever percentage is needed
    overflow-y: scroll;
    // ...maybe more style rules...
}

This method works better for fluid layouts that need to adapt to the height of the screen they are being viewed on and also works for the overflow-x property.


I also thought it would be worth mentioning the differences in the values for the overflow style property as I've seen some people using auto and others using scroll:

visible = The overflowing content is not clipped and will make the div larger than the set height.

hidden = The overflowing content is clipped, and the rest of the content that is outside the set height of the div will be invisible

scroll = The overflowing content is clipped, but a scroll-bar is added to see the rest of the content within the set height of the div

auto = If there is overflowing content, it is clipped and a scroll-bar should be added to see the rest of the content within the set height of the div

Is it possible to access an SQLite database from JavaScript?

You could use SQL.js which is the SQLlite lib compiled to JavaScript and store the database in the local storage introduced in HTML5.

How do I get the first element from an IEnumerable<T> in .net?

Just in case you're using .NET 2.0 and don't have access to LINQ:

 static T First<T>(IEnumerable<T> items)
 {
     using(IEnumerator<T> iter = items.GetEnumerator())
     {
         iter.MoveNext();
         return iter.Current;
     }
 }

This should do what you're looking for...it uses generics so you to get the first item on any type IEnumerable.

Call it like so:

List<string> items = new List<string>() { "A", "B", "C", "D", "E" };
string firstItem = First<string>(items);

Or

int[] items = new int[] { 1, 2, 3, 4, 5 };
int firstItem = First<int>(items);

You could modify it readily enough to mimic .NET 3.5's IEnumerable.ElementAt() extension method:

static T ElementAt<T>(IEnumerable<T> items, int index)
{
    using(IEnumerator<T> iter = items.GetEnumerator())
    {
        for (int i = 0; i <= index; i++, iter.MoveNext()) ;
        return iter.Current;
    }
} 

Calling it like so:

int[] items = { 1, 2, 3, 4, 5 };
int elemIdx = 3;
int item = ElementAt<int>(items, elemIdx);

Of course if you do have access to LINQ, then there are plenty of good answers posted already...

Looping over a list in Python

Do this instead:

values = [[1,2,3],[4,5]]
for x in values:
    if len(x) == 3:
       print(x)

Always show vertical scrollbar in <select>

I guess you cant, this maybe a limitation or not included in the IE browser. I have tried your jsfiddle with IE6-8 and all of it doesn't show the scrollbar and not sure with IE9. While in FF and chrome the scrollbar is shown. I also want to see how to do it in IE if possible.

If you really want to show the scrollbar, you can add a fake scrollbar. If you are familiar with some of the js library which use in RIA. Like in jquery/dojo some of the select is editable, because it is a combination of textbox + select or it can also be a textbox + div.

As an example, see it here a JavaScript that make select like editable.

What is the use of rt.jar file in java?

rt.jar contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.

For MacOS it is called classes.jar and located under /System/Library/Frameworks/<java_version>/Classes . Same not messing with it rule applies there as well :).

http://javahowto.blogspot.com/2006/05/what-does-rtjar-stand-for-in.html

How to use absolute path in twig functions

You probably want to use the assets_base_urls configuration.

framework:
    templating:
        assets_base_urls:
            http:   [http://www.website.com]
            ssl:   [https://www.website.com]

http://symfony.com/doc/current/reference/configuration/framework.html#assets


Note that the configuration is different since Symfony 2.7:

framework:
    # ...
    assets:
        base_urls:
            - 'http://cdn.example.com/'