Programs & Examples On #Landscape

A page or device orientation in which the horizontal axis is longer than the vertical axis.

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

I have fixed the by this way:

Create a folder in your resource directory name "drawable-nodpi" and then move yours all resources in this directory from others drawable directory.

Now clean your project and then rebuilt. Run again hopefully it will work this time without any resource not found exception.

Force an Android activity to always use landscape mode

The following is the code which I used to display all activity in landscape mode:

<activity android:screenOrientation="landscape"
          android:configChanges="orientation|keyboardHidden"
          android:name="abcActivty"/>

How do I specify different layouts for portrait and landscape orientations?

Create a layout-land directory and put the landscape version of your layout XML file in that directory.

Force "portrait" orientation mode

Don't apply the orientation to the application element, instead you should apply the attribute to the activity element, and you must also set configChanges as noted below.

Example:

<activity
   android:screenOrientation="portrait"
   android:configChanges="orientation|keyboardHidden">
</activity>

This is applied in the manifest file AndroidManifest.xml.

Get UserDetails object from Security Context in Spring MVC controller

Let Spring 3 injection take care of this.

Thanks to tsunade21 the easiest way is:

 @RequestMapping(method = RequestMethod.GET)   
 public ModelAndView anyMethodNameGoesHere(Principal principal) {
        final String loggedInUserName = principal.getName();

 }

How to determine if object is in array

Use something like this:

function containsObject(obj, list) {
    var i;
    for (i = 0; i < list.length; i++) {
        if (list[i] === obj) {
            return true;
        }
    }

    return false;
}

In this case, containsObject(car4, carBrands) is true. Remove the carBrands.push(car4); call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead:

function containsObject(obj, list) {
    var x;
    for (x in list) {
        if (list.hasOwnProperty(x) && list[x] === obj) {
            return true;
        }
    }

    return false;
}

This approach will work for arrays too, but when used on arrays it will be a tad slower than the first option.

SQLiteDatabase.query method

Where clause and args work together to form the WHERE statement of the SQL query. So say you looking to express

WHERE Column1 = 'value1' AND Column2 = 'value2'

Then your whereClause and whereArgs will be as follows

String whereClause = "Column1 =? AND Column2 =?";
String[] whereArgs = new String[]{"value1", "value2"};

If you want to select all table columns, i believe a null string passed to tableColumns will suffice.

How to preview an image before and after upload?

meVeekay's answer was good and am just making it more improvised by doing 2 things.

  1. Check whether browser supports HTML5 FileReader() or not.

  2. Allow only image file to be upload by checking its extension.

HTML :

<div id="wrapper">
    <input id="fileUpload" type="file" />
    <br />
    <div id="image-holder"></div>
</div> 

jQuery :

$("#fileUpload").on('change', function () {

    var imgPath = $(this)[0].value;
    var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();

    if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
        if (typeof (FileReader) != "undefined") {

            var image_holder = $("#image-holder");
            image_holder.empty();

            var reader = new FileReader();
            reader.onload = function (e) {
                $("<img />", {
                    "src": e.target.result,
                        "class": "thumb-image"
                }).appendTo(image_holder);

            }
            image_holder.show();
            reader.readAsDataURL($(this)[0].files[0]);
        } else {
            alert("This browser does not support FileReader.");
        }
    } else {
        alert("Pls select only images");
    }
});

For detail understanding of FileReader()

Check this Article : Using FileReader() preview image before uploading.

SQL Server CASE .. WHEN .. IN statement

It might be easier to read when written out in longhand using the 'simple case' e.g.

CASE DeviceID 
   WHEN '7  ' THEN '01'
   WHEN '10 ' THEN '01'
   WHEN '62 ' THEN '01'
   WHEN '58 ' THEN '01'
   WHEN '60 ' THEN '01'
   WHEN '46 ' THEN '01'
   WHEN '48 ' THEN '01'
   WHEN '50 ' THEN '01'
   WHEN '137' THEN '01'
   WHEN '139' THEN '01'
   WHEN '142' THEN '01'
   WHEN '143' THEN '01'
   WHEN '164' THEN '01'
   WHEN '8  ' THEN '02'
   WHEN '9  ' THEN '02'
   WHEN '63 ' THEN '02'
   WHEN '59 ' THEN '02'
   WHEN '61 ' THEN '02'
   WHEN '47 ' THEN '02'
   WHEN '49 ' THEN '02'
   WHEN '51 ' THEN '02'
   WHEN '138' THEN '02'
   WHEN '140' THEN '02'
   WHEN '141' THEN '02'
   WHEN '144' THEN '02'
   WHEN '165' THEN '02'
   ELSE 'NA' 
END AS clocking

...which kind makes me thing that perhaps you could benefit from a lookup table to which you can JOIN to eliminate the CASE expression entirely.

How to add a file to the last commit in git?

If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^. Then add all files and commit again.

document.getElementById(id).focus() is not working for firefox or chrome

For getting back focus to retype password text box in javascript:

window.setTimeout(function() { document.forms["reg"]["retypepwd"].focus(); },0);

Here, reg is the registration form name.

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

class Program
{
    static void Main(string[] args)
    {
        a a1 = new b();  
        a1.print();  
    }
}
class a
{
    public a()
    {
        Console.WriteLine("base class object initiated");
    }
    public void print()
    {
        Console.WriteLine("base");
    }
}
class b:a
{
    public b()
    {
        Console.WriteLine("child class object");
    }
    public void print1()
    {
        Console.WriteLine("derived");
    }
}

}

when we create a child class object,the base class object is auto initiated so base class reference variable can point to child class object.

but not vice versa because a child class reference variable can not point to base class object because no child class object is created.

and also notice that base class reference variable can only call base class member.

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

Just add the parameter "origin" with the URL of your site in the paramVars attribute of the player, like this:

this.player = new window['YT'].Player('player', {
    videoId: this.mediaid,
    width: '100%',
    playerVars: { 
        'autoplay': 1,
        'controls': 0,
        'autohide': 1,
        'wmode': 'opaque',
        'origin': 'http://localhost:8100' 
    },
}

Purpose of installing Twitter Bootstrap through npm?

  1. Use npm/bower to install bootstrap if you want to recompile it/change less files/test. With grunt it would be easier to do this, as shown on http://getbootstrap.com/getting-started/#grunt. If you only want to add precompiled libraries feel free to manually include files to project.

  2. No, you have to do this by yourself or use separate grunt tool. For example 'grunt-contrib-concat' How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

Where can I find a list of Mac virtual key codes?

Below is a list of the common key codes for quick reference, taken from Events.h.

If you need to use these keycodes in an application, you should include the Carbon framework:

Objective-C:
#include <Carbon/Carbon.h>

Swift:
import Carbon.HIToolbox

You can then use the kVK_ANSI_A constants directly.


WARNING

The key constants reference physical keys on the keyboard. Their output changes if the typist is using a different keyboard layout. The letters in the constants correspond only to the U.S. QWERTY keyboard layout.

For example, the left ring-finger key on the homerow:

QWERTY keyboard layout > s > kVK_ANSI_S > "s"
Dvorak keyboard layout > o > kVK_ANSI_S > "o"

Strategies for layout-agnostic conversion of keycode to string, and vice versa, are discussed here:

How to convert ASCII character to CGKeyCode?


From Events.h:

/*
 *  Summary:
 *    Virtual keycodes
 *  
 *  Discussion:
 *    These constants are the virtual keycodes defined originally in
 *    Inside Mac Volume V, pg. V-191. They identify physical keys on a
 *    keyboard. Those constants with "ANSI" in the name are labeled
 *    according to the key position on an ANSI-standard US keyboard.
 *    For example, kVK_ANSI_A indicates the virtual keycode for the key
 *    with the letter 'A' in the US keyboard layout. Other keyboard
 *    layouts may have the 'A' key label on a different physical key;
 *    in this case, pressing 'A' will generate a different virtual
 *    keycode.
 */
enum {
  kVK_ANSI_A                    = 0x00,
  kVK_ANSI_S                    = 0x01,
  kVK_ANSI_D                    = 0x02,
  kVK_ANSI_F                    = 0x03,
  kVK_ANSI_H                    = 0x04,
  kVK_ANSI_G                    = 0x05,
  kVK_ANSI_Z                    = 0x06,
  kVK_ANSI_X                    = 0x07,
  kVK_ANSI_C                    = 0x08,
  kVK_ANSI_V                    = 0x09,
  kVK_ANSI_B                    = 0x0B,
  kVK_ANSI_Q                    = 0x0C,
  kVK_ANSI_W                    = 0x0D,
  kVK_ANSI_E                    = 0x0E,
  kVK_ANSI_R                    = 0x0F,
  kVK_ANSI_Y                    = 0x10,
  kVK_ANSI_T                    = 0x11,
  kVK_ANSI_1                    = 0x12,
  kVK_ANSI_2                    = 0x13,
  kVK_ANSI_3                    = 0x14,
  kVK_ANSI_4                    = 0x15,
  kVK_ANSI_6                    = 0x16,
  kVK_ANSI_5                    = 0x17,
  kVK_ANSI_Equal                = 0x18,
  kVK_ANSI_9                    = 0x19,
  kVK_ANSI_7                    = 0x1A,
  kVK_ANSI_Minus                = 0x1B,
  kVK_ANSI_8                    = 0x1C,
  kVK_ANSI_0                    = 0x1D,
  kVK_ANSI_RightBracket         = 0x1E,
  kVK_ANSI_O                    = 0x1F,
  kVK_ANSI_U                    = 0x20,
  kVK_ANSI_LeftBracket          = 0x21,
  kVK_ANSI_I                    = 0x22,
  kVK_ANSI_P                    = 0x23,
  kVK_ANSI_L                    = 0x25,
  kVK_ANSI_J                    = 0x26,
  kVK_ANSI_Quote                = 0x27,
  kVK_ANSI_K                    = 0x28,
  kVK_ANSI_Semicolon            = 0x29,
  kVK_ANSI_Backslash            = 0x2A,
  kVK_ANSI_Comma                = 0x2B,
  kVK_ANSI_Slash                = 0x2C,
  kVK_ANSI_N                    = 0x2D,
  kVK_ANSI_M                    = 0x2E,
  kVK_ANSI_Period               = 0x2F,
  kVK_ANSI_Grave                = 0x32,
  kVK_ANSI_KeypadDecimal        = 0x41,
  kVK_ANSI_KeypadMultiply       = 0x43,
  kVK_ANSI_KeypadPlus           = 0x45,
  kVK_ANSI_KeypadClear          = 0x47,
  kVK_ANSI_KeypadDivide         = 0x4B,
  kVK_ANSI_KeypadEnter          = 0x4C,
  kVK_ANSI_KeypadMinus          = 0x4E,
  kVK_ANSI_KeypadEquals         = 0x51,
  kVK_ANSI_Keypad0              = 0x52,
  kVK_ANSI_Keypad1              = 0x53,
  kVK_ANSI_Keypad2              = 0x54,
  kVK_ANSI_Keypad3              = 0x55,
  kVK_ANSI_Keypad4              = 0x56,
  kVK_ANSI_Keypad5              = 0x57,
  kVK_ANSI_Keypad6              = 0x58,
  kVK_ANSI_Keypad7              = 0x59,
  kVK_ANSI_Keypad8              = 0x5B,
  kVK_ANSI_Keypad9              = 0x5C
};

/* keycodes for keys that are independent of keyboard layout*/
enum {
  kVK_Return                    = 0x24,
  kVK_Tab                       = 0x30,
  kVK_Space                     = 0x31,
  kVK_Delete                    = 0x33,
  kVK_Escape                    = 0x35,
  kVK_Command                   = 0x37,
  kVK_Shift                     = 0x38,
  kVK_CapsLock                  = 0x39,
  kVK_Option                    = 0x3A,
  kVK_Control                   = 0x3B,
  kVK_RightShift                = 0x3C,
  kVK_RightOption               = 0x3D,
  kVK_RightControl              = 0x3E,
  kVK_Function                  = 0x3F,
  kVK_F17                       = 0x40,
  kVK_VolumeUp                  = 0x48,
  kVK_VolumeDown                = 0x49,
  kVK_Mute                      = 0x4A,
  kVK_F18                       = 0x4F,
  kVK_F19                       = 0x50,
  kVK_F20                       = 0x5A,
  kVK_F5                        = 0x60,
  kVK_F6                        = 0x61,
  kVK_F7                        = 0x62,
  kVK_F3                        = 0x63,
  kVK_F8                        = 0x64,
  kVK_F9                        = 0x65,
  kVK_F11                       = 0x67,
  kVK_F13                       = 0x69,
  kVK_F16                       = 0x6A,
  kVK_F14                       = 0x6B,
  kVK_F10                       = 0x6D,
  kVK_F12                       = 0x6F,
  kVK_F15                       = 0x71,
  kVK_Help                      = 0x72,
  kVK_Home                      = 0x73,
  kVK_PageUp                    = 0x74,
  kVK_ForwardDelete             = 0x75,
  kVK_F4                        = 0x76,
  kVK_End                       = 0x77,
  kVK_F2                        = 0x78,
  kVK_PageDown                  = 0x79,
  kVK_F1                        = 0x7A,
  kVK_LeftArrow                 = 0x7B,
  kVK_RightArrow                = 0x7C,
  kVK_DownArrow                 = 0x7D,
  kVK_UpArrow                   = 0x7E
};

Macintosh Toolbox Essentials illustrates the physical locations of these virtual key codes for the Apple Extended Keyboard II in Figure 2-10:

Virtual key codes for the Apple Extended Keyboard II

Groovy - Convert object to JSON string

I couldn't get the other answers to work within the evaluate console in Intellij so...

groovy.json.JsonOutput.toJson(myObject)

This works quite well, but unfortunately

groovy.json.JsonOutput.prettyString(myObject)

didn't work for me.

To get it pretty printed I had to do this...

groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(myObject))

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

What is in your .vimrc?

My 242-line .vimrc is not that interesting, but since nobody mentioned it, I felt like I must share the two most important mappings that have enhanced my workflow besides the default mappings:

map <C-j> :bprev<CR>
map <C-k> :bnext<CR>
set hidden " this will go along

Seriously, switching buffers is the thing to do very often. Windows, sure, but everything doesn't fit the screen so nicely.

Similar set of maps for quick browsing of errors (see quickfix) and grep results:

map <C-n> :cn<CR>
map <C-m> :cp<CR>

Simple, effortless and efficient.

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

Moment JS - check if a date is today or in the future

function isTodayOrFuture(date){
  date = stripTime(date);
  return date.diff(stripTime(moment.now())) >= 0;
}

function stripTime(date){
  date = moment(date);
  date.hours(0);
  date.minutes(0);
  date.seconds(0);
  date.milliseconds(0);
  return date;
}

And then just use it line this :

isTodayOrFuture(YOUR_TEST_DATE_HERE)

Transform char array into String

I have search it again and search this question in baidu. Then I find 2 ways:

1,

_x000D_
_x000D_
char ch[]={'a','b','c','d','e','f','g','\0'};_x000D_
string s=ch;_x000D_
cout<<s;
_x000D_
_x000D_
_x000D_

Be aware to that '\0' is necessary for char array ch.

2,

_x000D_
_x000D_
#include<iostream>_x000D_
#include<string>_x000D_
#include<strstream>_x000D_
using namespace std;_x000D_
_x000D_
int main()_x000D_
{_x000D_
 char ch[]={'a','b','g','e','d','\0'};_x000D_
 strstream s;_x000D_
 s<<ch;_x000D_
 string str1;_x000D_
 s>>str1;_x000D_
 cout<<str1<<endl;_x000D_
 return 0;_x000D_
}
_x000D_
_x000D_
_x000D_

In this way, you also need to add the '\0' at the end of char array.

Also, strstream.h file will be abandoned and be replaced by stringstream

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

Removing the mongodb.lock file was not the issue in my case. I did so and got an error about the port being in use: [initandlisten] listen(): bind() failed errno:98 Address already in use for socket: 0.0.0.0:27017. I found another solution here: unable to start mongodb local server with instructions to kill the process:

  1. Find out from netstat which process is running mongodb port (27017)

    sudo netstat -tulpn | grep :27017

    Output will be: tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 1412/mongod

  2. Kill the appropriate process.

    sudo kill 1412 (replace 1412 with your process ID found in step 1)

And I was able to successfully start mongodb again. I believe mine was still running from an improper shut down.

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

you can try in this way if you are using thymeleaf

sec:authorize="hasAnyRole(T(com.orsbv.hcs.model.SystemRole).ADMIN.getName(),
               T(com.orsbv.hcs.model.SystemRole).SUPER_USER.getName(),'ROLE_MANAGEMENT')"

this will return true if the user has the mentioned roles,false otherwise.

Please note you have to use sec tag in your html declaration tag like this

<html xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

Scale Image to fill ImageView width and keep aspect ratio

I did something similar to the above and then banged my head against the wall for a few hours because it did not work inside a RelativeLayout. I ended up with the following code:

package com.example;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class ScaledImageView extends ImageView {
    public ScaledImageView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        final Drawable d = getDrawable();

        if (d != null) {
            int width;
            int height;
            if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) {
                height = MeasureSpec.getSize(heightMeasureSpec);
                width = (int) Math.ceil(height * (float) d.getIntrinsicWidth() / d.getIntrinsicHeight());
            } else {
                width = MeasureSpec.getSize(widthMeasureSpec);
                height = (int) Math.ceil(width * (float) d.getIntrinsicHeight() / d.getIntrinsicWidth());
            }
            setMeasuredDimension(width, height);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}

And then to prevent RelativeLayout from ignoring the measured dimension I did this:

    <FrameLayout
        android:id="@+id/image_frame"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/something">

        <com.example.ScaledImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="150dp"/>
    </FrameLayout>

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

Declare a constant array

There is no such thing as array constant in Go.

Quoting from the Go Language Specification: Constants:

There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.

A Constant expression (which is used to initialize a constant) may contain only constant operands and are evaluated at compile time.

The specification lists the different types of constants. Note that you can create and initialize constants with constant expressions of types having one of the allowed types as the underlying type. For example this is valid:

func main() {
    type Myint int
    const i1 Myint = 1
    const i2 = Myint(2)
    fmt.Printf("%T %v\n", i1, i1)
    fmt.Printf("%T %v\n", i2, i2)
}

Output (try it on the Go Playground):

main.Myint 1
main.Myint 2

If you need an array, it can only be a variable, but not a constant.

I recommend this great blog article about constants: Constants

Is it possible to declare two variables of different types in a for loop?

You can't declare multiple types in the initialization, but you can assign to multiple types E.G.

{
   int i;
   char x;
   for(i = 0, x = 'p'; ...){
      ...
   }
}

Just declare them in their own scope.

UITableViewCell, show delete button on swipe

If you're adopting diffable data sources, you'll have to move the delegate callbacks to a UITableViewDiffableDataSource subclass. For example:

class DataSource: UITableViewDiffableDataSource<SectionType, ItemType> {

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            if let identifierToDelete = itemIdentifier(for: indexPath) {
                var snapshot = self.snapshot()
                snapshot.deleteItems([identifierToDelete])
                apply(snapshot)
            }
        }
    }
}

How to convert a file to utf-8 in Python?

Thanks for the replies, it works!

And since the source files are in mixed formats, I added a list of source formats to be tried in sequence (sourceFormats), and on UnicodeDecodeError I try the next format:

from __future__ import with_statement

import os
import sys
import codecs
from chardet.universaldetector import UniversalDetector

targetFormat = 'utf-8'
outputDir = 'converted'
detector = UniversalDetector()

def get_encoding_type(current_file):
    detector.reset()
    for line in file(current_file):
        detector.feed(line)
        if detector.done: break
    detector.close()
    return detector.result['encoding']

def convertFileBestGuess(filename):
   sourceFormats = ['ascii', 'iso-8859-1']
   for format in sourceFormats:
     try:
        with codecs.open(fileName, 'rU', format) as sourceFile:
            writeConversion(sourceFile)
            print('Done.')
            return
      except UnicodeDecodeError:
        pass

def convertFileWithDetection(fileName):
    print("Converting '" + fileName + "'...")
    format=get_encoding_type(fileName)
    try:
        with codecs.open(fileName, 'rU', format) as sourceFile:
            writeConversion(sourceFile)
            print('Done.')
            return
    except UnicodeDecodeError:
        pass

    print("Error: failed to convert '" + fileName + "'.")


def writeConversion(file):
    with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:
        for line in file:
            targetFile.write(line)

# Off topic: get the file list and call convertFile on each file
# ...

(EDIT by Rudro Badhon: this incorporates the original try multiple formats until you don't get an exception as well as an alternate approach that uses chardet.universaldetector)

How to append data to a json file?

json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it.

Fortunately, there are lots of other options. A particularly simple one is CSV; which is supported well by python's standard library. The biggest downside is that it only works well for text; it requires additional action on the part of the programmer to convert the values to numbers or other formats, if needed.

Another option which does not have this limitation is to use a sqlite database, which also has built-in support in python. This would probably be a bigger departure from the code you already have, but it more naturally supports the 'modify a little bit' model you are apparently trying to build.

file path Windows format to java format

Java 7 and up supports the Path class (in java.nio package). You can use this class to convert a string-path to one that works for your current OS.

Using:

Paths.get("\\folder\\subfolder").toString()

on a Unix machine, will give you /folder/subfolder. Also works the other way around.

https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

How to add a class to body tag?

This should do it:

var newClass = window.location.href;
newClass = newClass.substring(newClass.lastIndexOf('/')+1, 5);
$('body').addClass(newClass);

The whole "five characters" thing is a little worrisome; that kind of arbitrary cutoff is usually a red flag. I'd recommend catching everything until an _ or .:

newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/);

That pattern should yield the following:

  • ../about_us.html : about
  • ../something.html : something
  • ../has_two_underscores.html : has

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

Java: String - add character n-times

 String toAdd = "toAdd";
 StringBuilder s = new StringBuilder();
 for(int count = 0; count < MAX; count++) {
     s.append(toAdd);
  }
  String output = s.toString();

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):
    time.sleep(4)

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
    def __exit__(self, type, value, traceback):
        signal.alarm(0)

Best way to get application folder path

If you know to get the root directory:

string rootPath = Path.GetPathRoot(Application.StartupPath)

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.

Source: http://www.albeesonline.com/blog/2008/11/29/warning-setpropertiesruleserverserviceenginehostcontext-setting-property/

Integer.toString(int i) vs String.valueOf(int i)

my openion is valueof() always called tostring() for representaion and so for rpresentaion of primtive type valueof is generalized.and java by default does not support Data type but it define its work with objaect and class its made all thing in cllas and made object .here Integer.toString(int i) create a limit that conversion for only integer.

Body set to overflow-y:hidden but page is still scrollable in Chrome

Find out the element which is larger than the body (element which is causing the page to scroll) and just set it's position to fixed. NOTE: I'm not talking to change the position of draggable elements. Draggable elements can be dragged out of body only when there's an element larger than body (mostly in width).

Proper way to set response status and JSON content in a REST API made with nodejs and express

status of 200 will be the default when using res.send, res.json, etc.

You can set the status like res.status(500).json({ error: 'something is wrong' });

Often I'll do something like...

router.get('/something', function(req, res, next) {
  // Some stuff here
  if(err) {
    res.status(500);
    return next(err);
  }
  // More stuff here
});

Then have my error middleware send the response, and do anything else I need to do when there is an error.

Additionally: res.sendStatus(status) has been added as of version 4.9.0 http://expressjs.com/4x/api.html#res.sendStatus

Creating a recursive method for Palindrome

public class chkPalindrome{

public static String isPalindrome(String pal){

if(pal.length() == 1){

return pal;
}
else{

String tmp= "";

tmp = tmp + pal.charAt(pal.length()-1)+isPalindrome(pal.substring(0,pal.length()-1));

return tmp;
}


}
     public static void main(String []args){

         chkPalindrome hwObj = new chkPalindrome();
         String palind = "MADAM";

       String retVal= hwObj.isPalindrome(palind);
      if(retVal.equals(palind))
       System.out.println(palind+" is Palindrome");
       else
       System.out.println(palind+" is Not Palindrome");
     }
}

Redirect to a page/URL after alert button is pressed

if (window.confirm('Really go to another page?'))
{
    alert('message');
    window.location = '/some/url';
}
else
{
    die();
}

How to get the first element of an array?

var ary = ['first', 'second', 'third', 'fourth', 'fifth'];

console.log(Object.keys(ary)[0]);

Make any Object array (req), then simply do Object.keys(req)[0] to pick the first key in the Object array.

Android: ScrollView vs NestedScrollView

In addition to the nested scrolling NestedScrollView added one major functionality, which could even make it interesting outside of nested contexts: It has build in support for OnScrollChangeListener. Adding a OnScrollChangeListener to the original ScrollView below API 23 required subclassing ScrollView or messing around with the ViewTreeObserver of the ScrollView which often means even more work than subclassing. With NestedScrollView it can be done using the build-in setter.

sequelize findAll sort order in nodejs

You can accomplish this in a very back-handed way with the following code:

exports.getStaticCompanies = function () {
    var ids = [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
    return Company.findAll({
        where: {
            id: ids
        },
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],
        order: sequelize.literal('(' + ids.map(function(id) {
            return '"Company"."id" = \'' + id + '\'');
        }).join(', ') + ') DESC')
    });
};

This is somewhat limited because it's got very bad performance characteristics past a few dozen records, but it's acceptable at the scale you're using.

This will produce a SQL query that looks something like this:

[...] ORDER BY ("Company"."id"='46128', "Company"."id"='2865', "Company"."id"='49569', [...])

How to set custom favicon in Express?

If you have you static path set, then just use the <link rel="icon" href="/images/favicon.ico" type="image/x-icon"> in your views. No need for anything else. Please make sure that you have your images folder inside the public folder.

How to get Database Name from Connection String using SqlConnectionStringBuilder

You can use the provider-specific ConnectionStringBuilder class (within the appropriate namespace), or System.Data.Common.DbConnectionStringBuilder to abstract the connection string object if you need to. You'd need to know the provider-specific keywords used to designate the information you're looking for, but for a SQL Server example you could do either of these two things:

System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);

string server = builder.DataSource;
string database = builder.InitialCatalog;

or

System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();

builder.ConnectionString = connectionString;

string server = builder["Data Source"] as string;
string database = builder["Initial Catalog"] as string;

Java for loop multiple variables

  1. It is cards.length(), not cards.length (length is a method of java.lang.String, not an attribute).

  2. It is System.out (capital 's'), not system.out. See java.lang.System.

  3. It is

    for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++){
    

    not

    for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){
    
  4. Syntactically, it is if(rank == cards.substring(a,b)){, not if(rank===cards.substring(a,b){ (double equals, not triple equals; missing closing parenthesis), but to compare if two Strings are equal you need to use equals(): if(rank.equals(cards.substring(a,b))){

You should probably consider downloading Eclipse, which is an integrated development environment (not only) for Java development. Eclipse shows you the errors while you type and also provides help in fixing these. This makes it much easier to get started with Java development.

Uncaught TypeError: Cannot read property 'appendChild' of null

There isn't an element on your page with the id "mainContent" when your callback is being executed.

In the line:

document.getElementById("mainContent").appendChild(p);

the section document.getElementById("mainContent") is returning null

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

a:hover{text-decoration: underline !important}
a{text-decoration: none !important}

Finding the source code for built-in Python functions?

Here is a cookbook answer to supplement @Chris' answer, CPython has moved to GitHub and the Mercurial repository will no longer be updated:

  1. Install Git if necessary.
  2. git clone https://github.com/python/cpython.git

  3. Code will checkout to a subdirectory called cpython -> cd cpython

  4. Let's say we are looking for the definition of print()...
  5. egrep --color=always -R 'print' | less -R
  6. Aha! See Python/bltinmodule.c -> builtin_print()

Enjoy.

Compiling C++11 with g++

You can refer to following link for which features are supported in particular version of compiler. It has an exhaustive list of feature support in compiler. Looks GCC follows standard closely and implements before any other compiler.

Regarding your question you can compile using

  1. g++ -std=c++11 for C++11
  2. g++ -std=c++14 for C++14
  3. g++ -std=c++17 for C++17
  4. g++ -std=c++2a for C++20, although all features of C++20 are not yet supported refer this link for feature support list in GCC.

The list changes pretty fast, keep an eye on the list, if you are waiting for particular feature to be supported.

How do you monitor network traffic on the iPhone?

A man-in-the-middle proxy, like suggested by other answers, is a good solution if you only want to see HTTP/HTTPS traffic.

The best solution for packet sniffing (though it only works for actual iOS devices, not the simulator) I've found is to use rvictl. This blog post has a nice writeup. Basically you do:

rvictl -s <iphone-uid-from-xcode-organizer>

Then you sniff the interface it creates with with Wireshark (or your favorite tool), and when you're done shut down the interface with:

rvictl -x <iphone-uid-from-xcode-organizer>

This is nice because if you want to packet sniff the simulator, you're having to wade through traffic to your local Mac as well, but rvictl creates a virtual interface that just shows you the traffic from the iOS device you've plugged into your USB port.

Note: this only works on a Mac.

Best Regular Expression for Email Validation in C#

Email Validation Regex

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+.)+[a-z]{2,5}$

Or

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+[.])+[a-z]{2,5}$

Demo Link:

https://regex101.com/r/kN4nJ0/53

Capture key press (or keydown) event on DIV element

(1) Set the tabindex attribute:

<div id="mydiv" tabindex="0" />

(2) Bind to keydown:

 $('#mydiv').on('keydown', function(event) {
    //console.log(event.keyCode);
    switch(event.keyCode){
       //....your actions for the keys .....
    }
 });

To set the focus on start:

$(function() {
   $('#mydiv').focus();
});

To remove - if you don't like it - the div focus border, set outline: none in the CSS.

See the table of keycodes for more keyCode possibilities.

All of the code assuming you use jQuery.

#

How to format a phone number with jQuery

Don't forget to ensure you are working with purely integers.

var separator = '-';
$( ".phone" ).text( function( i, DATA ) {
    DATA
        .replace( /[^\d]/g, '' )
        .replace( /(\d{3})(\d{3})(\d{4})/, '$1' + separator + '$2' + separator + '$3' );
    return DATA;
});

Sending HTTP POST with System.Net.WebClient

Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:

Using client As New Net.WebClient
    Dim reqparm As New Specialized.NameValueCollection
    reqparm.Add("param1", "somevalue")
    reqparm.Add("param2", "othervalue")
    Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
    Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using

The key part is this:

client.UploadValues(someurl, "POST", reqparm)

It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.

Can you blur the content beneath/behind a div?

you can do this with css3, this blurs the whole element

div (or whatever element) {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

Fiddle: http://jsfiddle.net/H4DU4/

Determine if a String is an Integer in Java

The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.

public static boolean isInteger(String s) {
    return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
    if(s.isEmpty()) return false;
    for(int i = 0; i < s.length(); i++) {
        if(i == 0 && s.charAt(i) == '-') {
            if(s.length() == 1) return false;
            else continue;
        }
        if(Character.digit(s.charAt(i),radix) < 0) return false;
    }
    return true;
}

Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.

public static boolean isInteger(String s, int radix) {
    Scanner sc = new Scanner(s.trim());
    if(!sc.hasNextInt(radix)) return false;
    // we know it starts with a valid int, now make sure
    // there's nothing left!
    sc.nextInt(radix);
    return !sc.hasNext();
}

If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    } catch(NullPointerException e) {
        return false;
    }
    // only got here if we didn't return false
    return true;
}

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

In my maven project this error occurs, after i closed my projects and reopens them. The dependencys wasn´t build correctly at that time. So for me the solution was just to update the Maven Dependencies of the projects!

How do I handle newlines in JSON?

JSON.stringify

JSON.stringify(`{ 
  a:"a"
}`)

would convert the above string to

"{ \n      a:\"a\"\n    }"

as mentioned here

json stringify

This function adds double quotes at the beginning and end of the input string and escapes special JSON characters. In particular, a newline is replaced by the \n character, a tab is replaced by the \t character, a backslash is replaced by two backslashes \, and a backslash is placed before each quotation mark.

How to push objects in AngularJS between ngRepeat arrays

Try this one also...

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <p>Click the button to join two arrays.</p>_x000D_
_x000D_
  <button onclick="myFunction()">Try it</button>_x000D_
_x000D_
  <p id="demo"></p>_x000D_
  <p id="demo1"></p>_x000D_
  <script>_x000D_
    function myFunction() {_x000D_
      var hege = [{_x000D_
        1: "Cecilie",_x000D_
        2: "Lone"_x000D_
      }];_x000D_
      var stale = [{_x000D_
        1: "Emil",_x000D_
        2: "Tobias"_x000D_
      }];_x000D_
      var hege = hege.concat(stale);_x000D_
      document.getElementById("demo1").innerHTML = hege;_x000D_
      document.getElementById("demo").innerHTML = stale;_x000D_
    }_x000D_
  </script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to set Status Bar Style in Swift 3

To add to the great asnwer by @Krunal https://stackoverflow.com/a/49552326/4697535

In case you are using a UINavigationController, the preferredStatusBarStyle will have no effect on the UIViewController.

Xcode 10 and Swift 4.

Set a custom UINavigationController

Example:

class LightNavigationController: UINavigationController {

   open override var preferredStatusBarStyle: UIStatusBarStyle {
       return .lightContent
   }
}

Use an extension for an app level solution:

extension UINavigationController {

  open override var preferredStatusBarStyle: UIStatusBarStyle {
      guard let index = tabBarController?.selectedIndex else { return .default }
      switch index {
      case 0, 1, 2: return .lightContent // set lightContent for tabs 0-2
      default: return .default // set dark for tab 3
      }
  }
}

What is __gxx_personality_v0 for?

The answers above are correct: it is used in exception handling. The manual for GCC version 6 has more information (which is no longer present in the version 7 manual). The error can arise when linking an external function that - unknown to GCC - throws Java exceptions.

Split an integer into digits to compute an ISBN checksum

Use the body of this loop to do whatever you want to with the digits

for digit in map(int, str(my_number)):

How to format x-axis time scale values in Chart.js v2

I had a different use case, I want different formats based how long between start and end time of data in graph. I found this to be simplest approach

    xAxes = {
        type: "time",
        time: {
            displayFormats: {
                hour: "hA"
            }
        },
        display: true,
        ticks: {
            reverse: true
        },
        gridLines: {display: false}
    }
    // if more than two days between start and end of data,  set format to show date,  not hrs
    if ((parseInt(Cookies.get("epoch_max")) - parseInt(Cookies.get("epoch_min"))) > (1000*60*60*24*2)) {
        xAxes.time.displayFormats.hour = "MMM D";
    }

Apple Mach-O Linker Error when compiling for device

I got the same issue when i export FMDB module in xcode 4.6. Later i found a fmdb.m in my my file list which was causing this issue. After i removed from the project it works fine

How to load property file from classpath?

If you use the static method and load the properties file from the classpath folder so you can use the below code :

//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));

Insert ellipsis (...) into HTML tag if content too wide

This is similar to Alex's but does it in log time instead of linear, and takes a maxHeight parameter.

jQuery.fn.ellipsis = function(text, maxHeight) {
  var element = $(this);
  var characters = text.length;
  var step = text.length / 2;
  var newText = text;
  while (step > 0) {
    element.html(newText);
    if (element.outerHeight() <= maxHeight) {
      if (text.length == newText.length) {
        step = 0;
      } else {
        characters += step;
        newText = text.substring(0, characters);
      }
    } else {
      characters -= step;
      newText = newText.substring(0, characters);
    }
    step = parseInt(step / 2);
  }
  if (text.length > newText.length) {
    element.html(newText + "...");
    while (element.outerHeight() > maxHeight && newText.length >= 1) {
      newText = newText.substring(0, newText.length - 1);
      element.html(newText + "...");
    }
  }
};

How to insert text at beginning of a multi-line selection in vi/Vim

And yet another way:

  • Move to the beginning of a line
  • enter Visual Block mode (CTRL-v)
  • select the lines you want (moving up/down with j/k, or jumping to a line with [line]G)
  • press I (that's capital i)
  • type the comment character(s)
  • press ESC

How to embed YouTube videos in PHP?

You have to ask users to store the 11 character code from the youtube video.

For e.g. http://www.youtube.com/watch?v=Ahg6qcgoay4

The eleven character code is : Ahg6qcgoay4

You then take this code and place it in your database. Then wherever you want to place the youtube video in your page, load the character from the database and put the following code:-

e.g. for Ahg6qcgoay4 it will be :

<object width="425" height="350" data="http://www.youtube.com/v/Ahg6qcgoay4" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/Ahg6qcgoay4" /></object>

What is LD_LIBRARY_PATH and how to use it?

LD_LIBRARY_PATH is the predefined environmental variable in Linux/Unix which sets the path which the linker should look in to while linking dynamic libraries/shared libraries.

LD_LIBRARY_PATH contains a colon separated list of paths and the linker gives priority to these paths over the standard library paths /lib and /usr/lib. The standard paths will still be searched, but only after the list of paths in LD_LIBRARY_PATH has been exhausted.

The best way to use LD_LIBRARY_PATH is to set it on the command line or script immediately before executing the program. This way the new LD_LIBRARY_PATH isolated from the rest of your system.

Example Usage:

$ export LD_LIBRARY_PATH="/list/of/library/paths:/another/path"
$ ./program

Since you talk about .dll you are on a windows system and a .dll must be placed at a path which the linker searches at link time, in windows this path is set by the environmental variable PATH, So add that .dll to PATH and it should work fine.

How to set specific window (frame) size in java swing?

Well, you are using both frame.setSize() and frame.pack().

You should use one of them at one time.

Using setSize() you can give the size of frame you want but if you use pack(), it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.

Try removing frame.pack() from your code or putting it before setting size and then run it.

Whitespace Matching Regex - Java

You can’t use \s in Java to match white space on its own native character set, because Java doesn’t support the Unicode white space property — even though doing so is strictly required to meet UTS#18’s RL1.2! What it does have is not standards-conforming, alas.

Unicode defines 26 code points as \p{White_Space}: 20 of them are various sorts of \pZ GeneralCategory=Separator, and the remaining 6 are \p{Cc} GeneralCategory=Control.

White space is a pretty stable property, and those same ones have been around virtually forever. Even so, Java has no property that conforms to The Unicode Standard for these, so you instead have to use code like this:

String whitespace_chars =  ""       /* dummy empty string for homogeneity */
                        + "\\u0009" // CHARACTER TABULATION
                        + "\\u000A" // LINE FEED (LF)
                        + "\\u000B" // LINE TABULATION
                        + "\\u000C" // FORM FEED (FF)
                        + "\\u000D" // CARRIAGE RETURN (CR)
                        + "\\u0020" // SPACE
                        + "\\u0085" // NEXT LINE (NEL) 
                        + "\\u00A0" // NO-BREAK SPACE
                        + "\\u1680" // OGHAM SPACE MARK
                        + "\\u180E" // MONGOLIAN VOWEL SEPARATOR
                        + "\\u2000" // EN QUAD 
                        + "\\u2001" // EM QUAD 
                        + "\\u2002" // EN SPACE
                        + "\\u2003" // EM SPACE
                        + "\\u2004" // THREE-PER-EM SPACE
                        + "\\u2005" // FOUR-PER-EM SPACE
                        + "\\u2006" // SIX-PER-EM SPACE
                        + "\\u2007" // FIGURE SPACE
                        + "\\u2008" // PUNCTUATION SPACE
                        + "\\u2009" // THIN SPACE
                        + "\\u200A" // HAIR SPACE
                        + "\\u2028" // LINE SEPARATOR
                        + "\\u2029" // PARAGRAPH SEPARATOR
                        + "\\u202F" // NARROW NO-BREAK SPACE
                        + "\\u205F" // MEDIUM MATHEMATICAL SPACE
                        + "\\u3000" // IDEOGRAPHIC SPACE
                        ;        
/* A \s that actually works for Java’s native character set: Unicode */
String     whitespace_charclass = "["  + whitespace_chars + "]";    
/* A \S that actually works for  Java’s native character set: Unicode */
String not_whitespace_charclass = "[^" + whitespace_chars + "]";

Now you can use whitespace_charclass + "+" as the pattern in your replaceAll.


Sorry ’bout all that. Java’s regexes just don’t work very well on its own native character set, and so you really have to jump through exotic hoops to make them work.

And if you think white space is bad, you should see what you have to do to get \w and \b to finally behave properly!

Yes, it’s possible, and yes, it’s a mindnumbing mess. That’s being charitable, even. The easiest way to get a standards-comforming regex library for Java is to JNI over to ICU’s stuff. That’s what Google does for Android, because OraSun’s doesn’t measure up.

If you don’t want to do that but still want to stick with Java, I have a front-end regex rewriting library I wrote that “fixes” Java’s patterns, at least to get them conform to the requirements of RL1.2a in UTS#18, Unicode Regular Expressions.

Remove stubborn underline from link

While the other answers are correct, there is an easy way to get rid of the underline on all those pesky links:

a {
   text-decoration:none;
}

This will remove the underline from EVERY SINGLE LINK on your page!

How to get an element by its href in jquery?

If you want to get any element that has part of a URL in their href attribute you could use:

$( 'a[href*="google.com"]' );

This will select all elements with a href that contains google.com, for example:

As stated by @BalusC in the comments below, it will also match elements that have google.com at any position in the href, like blahgoogle.com.

How do I get the key at a specific index from a Dictionary in Swift?

Here is a small extension for accessing keys and values in dictionary by index:

extension Dictionary {
    subscript(i: Int) -> (key: Key, value: Value) {
        return self[index(startIndex, offsetBy: i)]
    }
}

.gitignore and "The following untracked working tree files would be overwritten by checkout"

I had the same problem when checking out to a branch based on an earlier commit. Git refused to checkout because of untracked files.

I've found a solution and I hope it will help you too.

Adding the affected directories to .gitignore and issuing $ git rm -r --cached on them is apparently not enough.

Assume you want to make a branch based an earlier commit K to test some stuff and come back to the current version. I would do it in the following steps:

  1. Setup the untracked files: edit the .gitignore and apply $ git rm -r --cached on the files and directories you want the git to ignore. Add also the file .gitignore itself to .gitignoreand don't forget to issue $ git rm -r --cached .gitignore. This will ensure the the ignore behavior of git leaves the same in the earlier commits.

  2. Commit the changes you just made:

    $ git add -A
    $ git commit
    
  3. Save the current log, otherwise you may get problems coming back to the current version

    $ git log > ../git.log

  4. Hard reset to the commit K

    $ git reset --hard version_k

  5. Create a branch based on the commit K

    $ git branch commit_k_branch

  6. Checkout into that branch

    $ git checkout commit_k_branch

  7. Do your stuff and commit it

  8. Checkout back into master again

    $ git checkout master

  9. Reset to the current Version again

    $ git reset current_version or $ git reset ORIG_HEAD

  10. Now you can reset hard to the HEAD

    git reset --hard HEAD

NOTE! Do not skip the next-to-last step (like e. g. $ git reset --hard ORIG_HEAD ) otherwise the untracked files git complained above will get lost.

I also made sure the files git complained about were not deleted. I copied them to a text-file and issued the command $ for i in $(cat ../test.txt); do ls -ahl $i; done

If you checkout to the branch mentioned above again, do not forget to issue $ git status to ensure no unwanted changes appear.

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

Create a tar.xz in one command

Use the -J compression option for xz. And remember to man tar :)

tar cfJ <archive.tar.xz> <files>

Edit 2015-08-10:

If you're passing the arguments to tar with dashes (ex: tar -cf as opposed to tar cf), then the -f option must come last, since it specifies the filename (thanks to @A-B-B for pointing that out!). In that case, the command looks like:

tar -cJf <archive.tar.xz> <files>

How to map with index in Ruby?

I often do this:

arr = ["a", "b", "c"]

(0...arr.length).map do |int|
  [arr[int], int + 2]
end

#=> [["a", 2], ["b", 3], ["c", 4]]

Instead of directly iterating over the elements of the array, you're iterating over a range of integers and using them as the indices to retrieve the elements of the array.

How to clear/delete the contents of a Tkinter Text widget?

from Tkinter import *

app = Tk()

# Text Widget + Font Size
txt = Text(app, font=('Verdana',8))
txt.pack()

# Delete Button
btn = Button(app, text='Delete', command=lambda: txt.delete(1.0,END))
btn.pack()

app.mainloop()

Here's an example of txt.delete(1.0,END) as mentioned.

The use of lambda makes us able to delete the contents without defining an actual function.

Submit two forms with one button

The currently chosen best answer is too fuzzy to be reliable.

This feels to me like a fairly safe way to do it:

(Javascript: using jQuery to write it simpler)

$('#form1').submit(doubleSubmit);

function doubleSubmit(e1) {
    e1.preventDefault();
    e1.stopPropagation();
    var post_form1 = $.post($(this).action, $(this).serialize());

    post_form1.done(function(result) {
            // would be nice to show some feedback about the first result here
            $('#form2').submit();
        });
};

Post the first form without changing page, wait for the process to complete. Then post the second form. The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).

I didn't test the code, though.

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

No process is on the other end of the pipe (SQL Server 2012)

I face this issue for the second time and all previous answers failed, fortunately the following request do the job:

Alter login [user] with CHECK_POLICY = OFF
go

Alter login [user] with CHECK_POLICY = ON
go

"Missing return statement" within if / for / while

This will return the string only if the condition is true.

public String myMethod()
{
    if(condition)
    {
       return x;
    }
    else
       return "";
}

Test if string begins with a string?

The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.

The expensive regex method and the css attribute selector with starts with ^ operator

Option Explicit

Public Sub test()

    Debug.Print StartWithSubString("ab", "abc,d")

End Sub

Regex:

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft VBScript Regular Expressions
    Dim re As VBScript_RegExp_55.RegExp
    Set re = New VBScript_RegExp_55.RegExp

    re.Pattern = "^" & substring

    StartWithSubString = re.test(testString)

End Function

Css attribute selector with starts with operator

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft HTML Object Library
    Dim html As MSHTML.HTMLDocument
    Set html = New MSHTML.HTMLDocument

    html.body.innerHTML = "<div test=""" & testString & """></div>"

    StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0

End Function

Angularjs - Pass argument to directive

Here is how I solved my problem:

Directive

app.directive("directive_name", function(){
    return {
        restrict: 'E',
        transclude: true,
        template: function(elem, attr){
           return '<div><h2>{{'+attr.scope+'}}</h2></div>';
        },
        replace: true
    };
})

Controller

$scope.building = function(data){
    var chart = angular.element(document.createElement('directive_name'));
    chart.attr('scope', data);
    $compile(chart)($scope);
    angular.element(document.getElementById('wrapper')).append(chart);
  }

I now can use different scopes through the same directive and append them dynamically.

Bulk Insert to Oracle using .NET

I guess that OracleBulkCopy is one of the fastest ways. I had some trouble to learn, that I needed a new ODAC version. Cf. Where is type [Oracle.DataAccess.Client.OracleBulkCopy] ?

Here is the complete PowerShell code to copy from a query into a suited existing Oracle table. I tried Sql-Server a datasource, but other valid OLE-DB sources will go to.

if ($ora_dll -eq $null)
{
    "Load Oracle dll"
    $ora_dll = [System.Reflection.Assembly]::LoadWithPartialName("Oracle.DataAccess") 
    $ora_dll
}

# sql-server or Oracle source example is sql-server
$ConnectionString ="server=localhost;database=myDatabase;trusted_connection=yes;Provider=SQLNCLI10;"

# Oracle destination
$oraClientConnString = "Data Source=myTNS;User ID=myUser;Password=myPassword"

$tableName = "mytable"
$sql = "select * from $tableName"

$OLEDBConn = New-Object System.Data.OleDb.OleDbConnection($ConnectionString)
$OLEDBConn.open()
$readcmd = New-Object system.Data.OleDb.OleDbCommand($sql,$OLEDBConn)
$readcmd.CommandTimeout = '300'
$da = New-Object system.Data.OleDb.OleDbDataAdapter($readcmd)
$dt = New-Object system.Data.datatable
[void]$da.fill($dt)
$OLEDBConn.close()
#Write-Output $dt

if ($dt)
{
    try
    {
        $bulkCopy = new-object ("Oracle.DataAccess.Client.OracleBulkCopy") $oraClientConnString
        $bulkCopy.DestinationTableName = $tableName
        $bulkCopy.BatchSize = 5000
        $bulkCopy.BulkCopyTimeout = 10000
        $bulkCopy.WriteToServer($dt)
        $bulkcopy.close()
        $bulkcopy.Dispose()
    }
    catch
    {
        $ex = $_.Exception
        Write-Error "Write-DataTable$($connectionName):$ex.Message"
        continue
    }
}

BTW: I use this to copy table with CLOB columns. I didn't get that to work using linked servers cf. question on dba. I didn't retry linked serves with the new ODAC.

Default Activity not found in Android Studio

I have tried all solutions, but not working at all. than I have tried to disable Instant run in my android studio.

Go to Android Studio Settings or Preferences (for MAC) -> Build,Execution,Deployment -> Instant Run.

uncheck the Instant run functionality and than after click sync project with gradle files from file menu

now run your build...

Command to find information about CPUs on a UNIX machine

The nproc command shows the number of processing units available:
$ nproc

Sample outputs: 4

lscpu gathers CPU architecture information form /proc/cpuinfon in human-read-able format:
$ lscpu

Sample outputs:

Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 8
On-line CPU(s) list: 0-7
Thread(s) per core: 1
Core(s) per socket: 4
CPU socket(s): 2
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 15
Stepping: 7
CPU MHz: 1866.669
BogoMIPS: 3732.83
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 4096K
NUMA node0 CPU(s): 0-7

How to find the files that are created in the last hour in unix

Check out this link for more details.

To find files which are created in last one hour in current directory, you can use -amin

find . -amin -60 -type f

This will find files which are created with in last 1 hour.

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

Here is how to build a function that returns a result set that can be queried as if it were a table:

SQL> create type emp_obj is object (empno number, ename varchar2(10));
  2  /

Type created.

SQL> create type emp_tab is table of emp_obj;
  2  /

Type created.

SQL> create or replace function all_emps return emp_tab
  2  is
  3     l_emp_tab emp_tab := emp_tab();
  4     n integer := 0;
  5  begin
  6     for r in (select empno, ename from emp)
  7     loop
  8        l_emp_tab.extend;
  9        n := n + 1;
 10       l_emp_tab(n) := emp_obj(r.empno, r.ename);
 11     end loop;
 12     return l_emp_tab;
 13  end;
 14  /

Function created.

SQL> select * from table (all_emps);

     EMPNO ENAME
---------- ----------
      7369 SMITH
      7499 ALLEN
      7521 WARD
      7566 JONES
      7654 MARTIN
      7698 BLAKE
      7782 CLARK
      7788 SCOTT
      7839 KING
      7844 TURNER
      7902 FORD
      7934 MILLER

Convert DOS line endings to Linux line endings in Vim

With the following command:

:%s/^M$//g

To get the ^M to appear, type CtrlV and then CtrlM. CtrlV tells Vim to take the next character entered literally.

Generating random integer from a range

If your compiler supports C++0x and using it is an option for you, then the new standard <random> header is likely to meet your needs. It has a high quality uniform_int_distribution which will accept minimum and maximum bounds (inclusive as you need), and you can choose among various random number generators to plug into that distribution.

Here is code that generates a million random ints uniformly distributed in [-57, 365]. I've used the new std <chrono> facilities to time it as you mentioned performance is a major concern for you.

#include <iostream>
#include <random>
#include <chrono>

int main()
{
    typedef std::chrono::high_resolution_clock Clock;
    typedef std::chrono::duration<double> sec;
    Clock::time_point t0 = Clock::now();
    const int N = 10000000;
    typedef std::minstd_rand G;
    G g;
    typedef std::uniform_int_distribution<> D;
    D d(-57, 365);
    int c = 0;
    for (int i = 0; i < N; ++i) 
        c += d(g);
    Clock::time_point t1 = Clock::now();
    std::cout << N/sec(t1-t0).count() << " random numbers per second.\n";
    return c;
}

For me (2.8 GHz Intel Core i5) this prints out:

2.10268e+07 random numbers per second.

You can seed the generator by passing in an int to its constructor:

    G g(seed);

If you later find that int doesn't cover the range you need for your distribution, this can be remedied by changing the uniform_int_distribution like so (e.g. to long long):

    typedef std::uniform_int_distribution<long long> D;

If you later find that the minstd_rand isn't a high enough quality generator, that can also easily be swapped out. E.g.:

    typedef std::mt19937 G;  // Now using mersenne_twister_engine

Having separate control over the random number generator, and the random distribution can be quite liberating.

I've also computed (not shown) the first 4 "moments" of this distribution (using minstd_rand) and compared them to the theoretical values in an attempt to quantify the quality of the distribution:

min = -57
max = 365
mean = 154.131
x_mean = 154
var = 14931.9
x_var = 14910.7
skew = -0.00197375
x_skew = 0
kurtosis = -1.20129
x_kurtosis = -1.20001

(The x_ prefix refers to "expected")

Is it .yaml or .yml?

After reading a bunch of people's comments online about this, my first reaction was that this is basically one of those really unimportant debates. However, my initial interest was to find out the right format so I could be consistent with my file naming practice.

Long story short, the creator of YAML are saying .yaml, but personally I keep doing .yml. That just makes more sense to me. So I went on the journey to find affirmation and soon enough, I realise that docker uses .yml everywhere. I've been writing docker-compose.yml files all this time, while you keep seeing in kubernetes' docs kubectl apply -f *.yaml...

So, in conclusion, both formats are obviously accepted and if you are on the other end, (ie: writing systems that receive a YAML file as input) you should allow for both. That seems like another snake case versus camel case thingy...

Add or change a value of JSON key with jquery or javascript

var y_axis_name=[];

 for(var point in jsonData[0].data)
              { 
                y_axis_name.push(point);

              }

y_axis_name is having all the key name

try on jsfiddle

Searching in a ArrayList with custom objects for certain strings

The easy way is to make a for where you verify if the atrrtibute name of the custom object have the desired string

    for(Datapoint d : dataPointList){
        if(d.getName() != null && d.getName().contains(search))
           //something here
    }

I think this helps you.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

If you have error the origin "server did not find a current representation for the target resource or is not willing to disclose that one exists."

Then check the file position given here:

Reference image

bundle install returns "Could not locate Gemfile"

When I had similar problem gem update --system helped me. Run this before bundle install

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

what if you use

Map<String, ? extends Class<? extends Serializable>> expected = null;

How to serve static files in Flask

If you are just trying to open a file, you could use app.open_resource(). So reading a file would look something like

with app.open_resource('/static/path/yourfile'):
      #code to read the file and do something

String format currency

I strongly suspect the problem is simply that the current culture of the thread handling the request isn't set appropriately.

You can either set it for the whole request, or specify the culture while formatting. Either way, I would suggest not use string.Format with a composite format unless you really have more than one thing to format (or a wider message). Instead, I'd use:

@price.ToString("C", culture)

It just makes it somewhat simpler.

EDIT: Given your comment, it sounds like you may well want to use a UK culture regardless of the culture of the user. So again, either set the UK culture as the thread culture for the whole request, or possibly introduce your own helper class with a "constant":

public static class Cultures
{
    public static readonly CultureInfo UnitedKingdom = 
        CultureInfo.GetCultureInfo("en-GB");
}

Then:

@price.ToString("C", Cultures.UnitedKingdom)

In my experience, having a "named" set of cultures like this makes the code using it considerably simpler to read, and you don't need to get the string right in multiple places.

"python" not recognized as a command

You can do it in python installer: enter image description here

Angular 2 optional route parameter

It's recommended to use a query parameter when the information is optional.

Route Parameters or Query Parameters?

There is no hard-and-fast rule. In general,

prefer a route parameter when

  • the value is required.
  • the value is necessary to distinguish one route path from another.

prefer a query parameter when

  • the value is optional.
  • the value is complex and/or multi-variate.

from https://angular.io/guide/router#optional-route-parameters

You just need to take out the parameter from the route path.

@RouteConfig([
{
    path: '/user/',
    component: User,
    as: 'User'
}])

cURL POST command line on WINDOWS RESTful service

Another Alternative for the command line that is easier than fighting with quotation marks is to put the json into a file, and use the @ prefix of curl parameters, e.g. with the following in json.txt:

{ "syncheader" : {
    "servertimesync" : "20131126121749",
    "deviceid" : "testDevice"
  }
}

then in my case I issue:

curl localhost:9000/sync -H "Content-type:application/json" -X POST -d @json.txt

Keeps the json more readable too.

Hibernate Annotations - Which is better, field or property access?

I prefer field access, because that way I'm not forced to provide getter/setter for each property.

A quick survey via Google suggests that field access is the majority (e.g., http://java.dzone.com/tips/12-feb-jpa-20-why-accesstype).

I believe field access is the idiom recommended by Spring, but I can't find a reference to back that up.

There's a related SO question that tried to measure performance and came to the conclusion that there's "no difference".

CSS transition effect makes image blurry / moves image 1px, in Chrome?

filter: blur(0)
transition: filter .3s ease-out
transition-timing-function: steps(3, end) // add this string with steps equal duration

I was helped by setting the value of transition duration .3s equal transition timing steps .3s

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

If you have a proper cors header in place. Your corporate network may be stripping off the cors header. If the website is externally accessible, try accessing it from outside your network to verify whether the network is causing the problem--a good idea regardless of the cause.

Using grep to search for a string that has a dot in it

You need to escape the . as "0\.49".

A . is a regex meta-character to match any character(except newline). To match a literal period, you need to escape it.

TypeError: Cannot read property "0" from undefined

Under normal circumstances,out of bound of array when you encounter the error. So,check uo your array subscript.

Quick way to list all files in Amazon S3 bucket?

In PHP you can get complete list of AWS-S3 objects inside specific bucket using following call

$S3 = \Aws\S3\S3Client::factory(array('region' => $region,));
$iterator = $S3->getIterator('ListObjects', array('Bucket' => $bucket));
foreach ($iterator as $obj) {
    echo $obj['Key'];
}

You can redirect output of the above code in to a file to get list of keys.

Matlab: Running an m-file from command-line

I think that one important point that was not mentioned in the previous answers is that, if not explicitly indicated, the matlab interpreter will remain open. Therefore, to the answer of @hkBattousai I will add the exit command:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m');exit;"

How to create unique keys for React elements?

Keys helps React identify which items have changed/added/removed and should be given to the elements inside the array to give the elements a stable identity.

With that in mind, there are basically three different strategies as described bellow:

  1. Static Elements (when you don't need to keep html state (focus, cursor position, etc)
  2. Editable and sortable elements
  3. Editable but not sortable elements

As React Documentation explains, we need to give stable identity to the elements and because of that, carefully choose the strategy that best suits your needs:

STATIC ELEMENTS

As we can see also in React Documentation, is not recommended the use of index for keys "if the order of items may change. This can negatively impact performance and may cause issues with component state".

In case of static elements like tables, lists, etc, I recommend using a tool called shortid.

1) Install the package using NPM/YARN:

npm install shortid --save

2) Import in the class file you want to use it:

import shortid from 'shortid';

2) The command to generate a new id is shortid.generate().

3) Example:

  renderDropdownItems = (): React.ReactNode => {
    const { data, isDisabled } = this.props;
    const { selectedValue } = this.state;
    const dropdownItems: Array<React.ReactNode> = [];

    if (data) {
      data.forEach(item => {
        dropdownItems.push(
          <option value={item.value} key={shortid.generate()}>
            {item.text}
          </option>
        );
      });
    }

    return (
      <select
        value={selectedValue}
        onChange={this.onSelectedItemChanged}
        disabled={isDisabled}
      >
        {dropdownItems}
      </select>
    );
  };

IMPORTANT: As React Virtual DOM relies on the key, with shortid every time the element is re-rendered a new key will be created and the element will loose it's html state like focus or cursor position. Consider this when deciding how the key will be generated as the strategy above can be useful only when you are building elements that won't have their values changed like lists or read only fields.

EDITABLE (sortable) FIELDS

If the element is sortable and you have a unique ID of the item, combine it with some extra string (in case you need to have the same information twice in a page). This is the most recommended scenario.

Example:

  renderDropdownItems = (): React.ReactNode => {
    const elementKey:string = 'ddownitem_'; 
    const { data, isDisabled } = this.props;
    const { selectedValue } = this.state;
    const dropdownItems: Array<React.ReactNode> = [];

    if (data) {
      data.forEach(item => {
        dropdownItems.push(
          <option value={item.value} key={${elementKey}${item.id}}>
            {item.text}
          </option>
        );
      });
    }

    return (
      <select
        value={selectedValue}
        onChange={this.onSelectedItemChanged}
        disabled={isDisabled}
      >
        {dropdownItems}
      </select>
    );
  };

EDITABLE (non sortable) FIELDS (e.g. INPUT ELEMENTS)

As a last resort, for editable (but non sortable) fields like input, you can use some the index with some starting text as element key cannot be duplicated.

Example:

  renderDropdownItems = (): React.ReactNode => {
    const elementKey:string = 'ddownitem_'; 
    const { data, isDisabled } = this.props;
    const { selectedValue } = this.state;
    const dropdownItems: Array<React.ReactNode> = [];

    if (data) {
      data.forEach((item:any index:number) => {
        dropdownItems.push(
          <option value={item.value} key={${elementKey}${index}}>
            {item.text}
          </option>
        );
      });
    }

    return (
      <select
        value={selectedValue}
        onChange={this.onSelectedItemChanged}
        disabled={isDisabled}
      >
        {dropdownItems}
      </select>
    );
  };

Hope this helps.

Skip first entry in for loop in python?

To skip the first element in Python you can simply write

for car in cars[1:]:
    # Do What Ever you want

or to skip the last elem

for car in cars[:-1]:
    # Do What Ever you want

You can use this concept for any sequence.

Dynamically add data to a javascript map

Well any Javascript object functions sort-of like a "map"

randomObject['hello'] = 'world';

Typically people build simple objects for the purpose:

var myMap = {};

// ...

myMap[newKey] = newValue;

edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.

13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.

Copy file(s) from one project to another using post build event...VS2010

xcopy "your-source-path" "your-destination-path" /D /y /s /r /exclude:path-to-txt- file\ExcludedFilesList.txt

Notice the quotes in source path and destination path, but not in path to exludelist txt file.

Content of ExcludedFilesList.txt is the following: .cs\

I'm using this command to copy file from one project in my solution, to another and excluding .cs files.

/D Copy only files that are modified in sourcepath
/y Suppresses prompting to confirm you want to overwrite an existing destination file.
/s Copies directories and subdirectories except empty ones.
/r Overwrites read-only files.

Executing a batch script on Windows shutdown

Programatically this can be achieved with SCHTASKS:

SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=1074)]]" /EC Security /tn on_shutdown_normal /tr "c:\some.bat" 

SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6006)]]" /EC Security /tn on_shutdown_6006 /tr "c:\some.bat" 

SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6008)]]" /EC Security /tn on_shutdown_6008 /tr "c:\some.bat" 

postgres default timezone

Choose a timezone from:

SELECT * FROM pg_timezone_names;

And set as below given example:

ALTER DATABASE postgres SET timezone TO 'Europe/Berlin';

Use your DB name in place of postgres in above statement.

Implement Stack using Two Queues

The easiest (and maybe only) way of doing this is by pushing new elements into the empty queue, and then dequeuing the other and enqeuing into the previously empty queue. With this way the latest is always at the front of the queue. This would be version B, for version A you just reverse the process by dequeuing the elements into the second queue except for the last one.

Step 0:

"Stack"
+---+---+---+---+---+
|   |   |   |   |   |
+---+---+---+---+---+

Queue A                Queue B
+---+---+---+---+---+  +---+---+---+---+---+
|   |   |   |   |   |  |   |   |   |   |   |
+---+---+---+---+---+  +---+---+---+---+---+

Step 1:

"Stack"
+---+---+---+---+---+
| 1 |   |   |   |   |
+---+---+---+---+---+

Queue A                Queue B
+---+---+---+---+---+  +---+---+---+---+---+
| 1 |   |   |   |   |  |   |   |   |   |   |
+---+---+---+---+---+  +---+---+---+---+---+

Step 2:

"Stack"
+---+---+---+---+---+
| 2 | 1 |   |   |   |
+---+---+---+---+---+

Queue A                Queue B
+---+---+---+---+---+  +---+---+---+---+---+
|   |   |   |   |   |  | 2 | 1 |   |   |   |
+---+---+---+---+---+  +---+---+---+---+---+

Step 3:

"Stack"
+---+---+---+---+---+
| 3 | 2 | 1 |   |   |
+---+---+---+---+---+

Queue A                Queue B
+---+---+---+---+---+  +---+---+---+---+---+
| 3 | 2 | 1 |   |   |  |   |   |   |   |   |
+---+---+---+---+---+  +---+---+---+---+---+

How to 'insert if not exists' in MySQL?

Update or insert without known primary key

If you already have a unique or primary key, the other answers with either INSERT INTO ... ON DUPLICATE KEY UPDATE ... or REPLACE INTO ... should work fine (note that replace into deletes if exists and then inserts - thus does not partially update existing values).

But if you have the values for some_column_id and some_type, the combination of which are known to be unique. And you want to update some_value if exists, or insert if not exists. And you want to do it in just one query (to avoid using a transaction). This might be a solution:

INSERT INTO my_table (id, some_column_id, some_type, some_value)
SELECT t.id, t.some_column_id, t.some_type, t.some_value
FROM (
    SELECT id, some_column_id, some_type, some_value
    FROM my_table
    WHERE some_column_id = ? AND some_type = ?
    UNION ALL
    SELECT s.id, s.some_column_id, s.some_type, s.some_value
    FROM (SELECT NULL AS id, ? AS some_column_id, ? AS some_type, ? AS some_value) AS s
) AS t
LIMIT 1
ON DUPLICATE KEY UPDATE
some_value = ?

Basically, the query executes this way (less complicated than it may look):

  • Select an existing row via the WHERE clause match.
  • Union that result with a potential new row (table s), where the column values are explicitly given (s.id is NULL, so it will generate a new auto-increment identifier).
  • If an existing row is found, then the potential new row from table s is discarded (due to LIMIT 1 on table t), and it will always trigger an ON DUPLICATE KEY which will UPDATE the some_value column.
  • If an existing row is not found, then the potential new row is inserted (as given by table s).

Note: Every table in a relational database should have at least a primary auto-increment id column. If you don't have this, add it, even when you don't need it at first sight. It is definitely needed for this "trick".

Using port number in Windows host file

What you want can be achieved by modifying the hosts file through Fiddler 2 application.

Follow these steps:

  1. Install Fiddler2

  2. Navigate to Fiddler2 menu:- Tools > HOSTS.. (Click to select)

  3. Add a line like this:-

    localhost:8080 www.mydomainname.com

  4. Save the file & then checkout www.mydomainname.com in browser.

Excel Define a range based on a cell value

Say you have number 1,2,3,4,5,6, in cell A1,A2,A3,A4,A5,A6 respectively. in cell A7 we calculate the sum of A1:Ax. x is specified in cell B1 (in this case, x can be any number from 1 to 6). in cell A7, you can write the following formular:

=SUM(A1:INDIRECT(CONCATENATE("A",B1)))

CONCATENATE will give you the index of the cell Ax(if you put 3 in B1, CONCATENATE("A",B1)) gives A3).

INDIRECT convert "A3" to a index.

see this link Using the value in a cell as a cell reference in a formula?

Android lollipop change navigation bar color

You can add the following line in the values-v21/style.xml folder:

<item name="android:navigationBarColor">@color/theme_color</item>

How to calculate the bounding box for a given lat/lng location?

You're looking for an ellipsoid formula.

The best place I've found to start coding is based on the Geo::Ellipsoid library from CPAN. It gives you a baseline to create your tests off of and to compare your results with its results. I used it as the basis for a similar library for PHP at my previous employer.

Geo::Ellipsoid

Take a look at the location method. Call it twice and you've got your bbox.

You didn't post what language you were using. There may already be a geocoding library available for you.

Oh, and if you haven't figured it out by now, Google maps uses the WGS84 ellipsoid.

Using cut command to remove multiple columns

You are able to cut all odd/even columns by using seq:

This would print all odd columns

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 1 2 10)

To print all even columns you could use

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 2 2 10)

By changing the second number of seq you can specify which columns to be printed.

If the specification which columns to print is more complex you could also use a "one-liner-if-clause" like

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(for i in $(seq 1 10); do if [[ $i -lt 10 && $i -lt 5 ]];then echo -n $i,; else echo -n $i;fi;done)

This would print all columns from 1 to 5 - you can simply modify the conditions to create more complex conditions to specify weather a column shall be printed.

laravel foreach loop in controller

Is sku just a property of the Product model? If so:

$products = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();

foreach ($products as $product ) {
  // Access $product->sku here...
}

Or is sku a relationship to another model? If that is the case, then, as long as your relationship is setup properly, you code should work.

How to convert AAR to JAR

 The 'aar' bundle is the binary distribution of an Android Library Project. .aar file 
 consists a JAR file and some resource files. You can convert it
 as .jar file using this steps

1) Copy the .aar file in a separate folder and Rename the .aar file to .zip file using 
 any winrar or zip Extractor software.

2) Now you will get a .zip file. Right click on the .zip file and select "Extract files". 
 Will get a folder which contains "classes.jar, resource, manifest, R.java,
 proguard(optional), libs(optional), assets(optional)".

3) Rename the classes.jar file as yourjarfilename.jar and use this in your project.

Note: If you want to get only .jar file from your .aar file use the above way. Suppose If you want to include the manifest.xml and resources with your .jar file means you can just right click on your .aar file and save it as .jar file directly instead of saving it as a .zip. To view the .jar file which you have extracted, download JD-GUI(Java Decompiler). Then drag and drop your .jar file into this JD_GUI, you can see the .class file in readable formats like a .java file.

enter image description here enter image description here

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

This one is good example for Swift 4 about async:

DispatchQueue.global(qos: .background).async {
    // Background Thread
    DispatchQueue.main.async {
        // Run UI Updates or call completion block
    }
}

How to link to a named anchor in Multimarkdown?

Here is my solution (derived from SaraubhM's answer)

**Jump To**: [Hotkeys & Markers](#hotkeys-markers) / [Radii](#radii) / [Route Wizard 2.0](#route-wizard-2-0)

Which gives you:

Jump To: Hotkeys & Markers / Radii / Route Wizard 2.0

Note the changes from and . to - and also the loss of the & in the links.

Import / Export database with SQL Server Server Management Studio

I tried the answers above but the generated script file was very large and I was having problems while importing the data. I ended up Detaching the database, then copying .mdf to my new machine, then Attaching it to my new version of SQL Server Management Studio.

I found instructions for how to do this on the Microsoft Website:
https://msdn.microsoft.com/en-us/library/ms187858.aspx

NOTE: After Detaching the database I found the .mdf file within this directory:
C:\Program Files\Microsoft SQL Server\

PostgreSQL next value of the sequences?

To answer your question literally, here's how to get the next value of a sequence without incrementing it:

SELECT
 CASE WHEN is_called THEN
   last_value + 1
 ELSE
   last_value
 END
FROM sequence_name

Obviously, it is not a good idea to use this code in practice. There is no guarantee that the next row will really have this ID. However, for debugging purposes it might be interesting to know the value of a sequence without incrementing it, and this is how you can do it.

How to export DataTable to Excel

Excel Interop:

This method prevents Dates getting flipped from dd-mm-yyyy to mm-dd-yyyy

public bool DataTableToExcelFile(DataTable dt, string targetFile)
{
    const bool dontSave = false;
    bool success = true;

    //Exit if there is no rows to export
    if (dt.Rows.Count == 0) return false;

    object misValue = System.Reflection.Missing.Value;
    List<int> dateColIndex = new List<int>();
    Excel.Application excelApp = new Excel.Application();
    Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(misValue);
    Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets("sheet1");

    //Iterate through the DataTable and populate the Excel work sheet
    try {
        for (int i = -1; i <= dt.Rows.Count - 1; i++) {
            for (int j = 0; j <= dt.Columns.Count - 1; j++) {
                if (i < 0) {
                    //Take special care with Date columns
                    if (dt.Columns(j).DataType is typeof(DateTime)) {
                        excelWorkSheet.Cells(1, j + 1).EntireColumn.NumberFormat = "d-MMM-yyyy;@";
                        dateColIndex.Add(j);
                    } 
                    //else if ... Feel free to add more Formats

                    else {
                        //Otherwise Format the column as text
                        excelWorkSheet.Cells(1, j + 1).EntireColumn.NumberFormat = "@";
                    }
                    excelWorkSheet.Cells(1, j + 1) = dt.Columns(j).Caption;
                } 
                else if (dateColIndex.IndexOf(j) > -1) {
                    excelWorkSheet.Cells(i + 2, j + 1) = Convert.ToDateTime(dt.Rows(i).ItemArray(j)).ToString("d-MMM-yyyy");
                } 
                else {
                    excelWorkSheet.Cells(i + 2, j + 1) = dt.Rows(i).ItemArray(j).ToString();
                }
            }
        }

        //Add Autofilters to the Excel work sheet  
        excelWorkSheet.Cells.AutoFilter(1, Type.Missing, Excel.XlAutoFilterOperator.xlAnd, Type.Missing, true);
        //Autofit columns for neatness
        excelWorkSheet.Columns.AutoFit();
        if (File.Exists(exportFile)) File.Delete(exportFile);
        excelWorkSheet.SaveAs(exportFile);
    } catch {
        success = false;
    } finally {
        //Do this irrespective of whether there was an exception or not. 
        excelWorkBook.Close(dontSave);
        excelApp.Quit();
        releaseObject(excelWorkSheet);
        releaseObject(excelWorkBook);
        releaseObject(excelApp);
    }
    return success;
}

If you dont care about Dates being flipped, then use see link that shows how to populate all the cells in the Excel spreadsheet in one line of code:

Excel Interop - Efficiency and performance

CSV:

public string DataTableToCSV(DataTable dt, bool includeHeader, string rowFilter, string sortFilter, bool useCommaDelimiter = false, bool truncateTimesFromDates = false)
{
    dt.DefaultView.RowFilter = rowFilter;
    dt.DefaultView.Sort = sortFilter;
    DataView dv = dt.DefaultView;
    string csv = DataTableToCSV(dv.ToTable, includeHeader, useCommaDelimiter, truncateTimesFromDates);
    //reset the Filtering
    dt.DefaultView.RowFilter = string.Empty;
    return csv;
}

public string DataTableToCsv(DataTable dt, bool includeHeader, bool useCommaDelimiter = false, bool truncateTimesFromDates = false)
{
    StringBuilder sb = new StringBuilder();
    string delimter = Constants.vbTab;
    if (useCommaDelimiter)
        delimter = ",";

    if (includeHeader) {
        foreach (DataColumn dc in dt.Columns) {
            sb.AppendFormat("{0}" + Constants.vbTab, dc.ColumnName);
        }

        //remove the last Tab
        sb.Remove(sb.ToString.Length - 1, 1);
        sb.Append(Environment.NewLine);
    }

    foreach (DataRow dr in dt.Rows) {
        foreach (DataColumn dc in dt.Columns) {
            if (Information.IsDate(dr(dc.ColumnName).ToString()) & dr(dc.ColumnName).ToString().Contains(".") == false & truncateTimesFromDates) {
                sb.AppendFormat("{0}" + delimter, Convert.ToDateTime(dr(dc.ColumnName).ToString()).Date.ToShortDateString());
            } else {
                sb.AppendFormat("{0}" + delimter, CheckDBNull(dr(dc.ColumnName).ToString().Replace(",", "")));
            }
        }
        //remove the last Tab
        sb.Remove(sb.ToString.Length - 1, 1);
        sb.Append(Environment.NewLine);
    }
    return sb.ToString;
}

public enum enumObjectType
{
    StrType = 0,
    IntType = 1,
    DblType = 2
}

public object CheckDBNull(object obj, enumObjectType ObjectType = enumObjectType.StrType)
{
    object objReturn = null;
    objReturn = obj;
    if (ObjectType == enumObjectType.StrType & Information.IsDBNull(obj)) {
        objReturn = "";
    } else if (ObjectType == enumObjectType.IntType & Information.IsDBNull(obj)) {
        objReturn = 0;
    } else if (ObjectType == enumObjectType.DblType & Information.IsDBNull(obj)) {
        objReturn = 0.0;
    }
    return objReturn;
}

What's the difference between RANK() and DENSE_RANK() functions in oracle?

This article here nicely explains it. Essentially, you can look at it as such:

CREATE TABLE t AS
SELECT 'a' v FROM dual UNION ALL
SELECT 'a'   FROM dual UNION ALL
SELECT 'a'   FROM dual UNION ALL
SELECT 'b'   FROM dual UNION ALL
SELECT 'c'   FROM dual UNION ALL
SELECT 'c'   FROM dual UNION ALL
SELECT 'd'   FROM dual UNION ALL
SELECT 'e'   FROM dual;

SELECT
  v,
  ROW_NUMBER() OVER (ORDER BY v) row_number,
  RANK()       OVER (ORDER BY v) rank,
  DENSE_RANK() OVER (ORDER BY v) dense_rank
FROM t
ORDER BY v;

The above will yield:

+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a |          1 |    1 |          1 |
| a |          2 |    1 |          1 |
| a |          3 |    1 |          1 |
| b |          4 |    4 |          2 |
| c |          5 |    5 |          3 |
| c |          6 |    5 |          3 |
| d |          7 |    7 |          4 |
| e |          8 |    8 |          5 |
+---+------------+------+------------+

In words

  • ROW_NUMBER() attributes a unique value to each row
  • RANK() attributes the same row number to the same value, leaving "holes"
  • DENSE_RANK() attributes the same row number to the same value, leaving no "holes"

How do I print a datetime in the local timezone?

Think your should look around: datetime.astimezone()

http://docs.python.org/library/datetime.html#datetime.datetime.astimezone

Also see pytz module - it's quite easy to use -- as example:

eastern = timezone('US/Eastern')

http://pytz.sourceforge.net/

Example:

from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal

utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00

How to change value of object which is inside an array using JavaScript or jQuery?

We can also use Array's map function to modify object of an array using Javascript.

function changeDesc(value, desc){
   projects.map((project) => project.value == value ? project.desc = desc : null)
}

changeDesc('jquery', 'new description')

Display TIFF image in all web browser

This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:

http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support

Where are you getting the tiff images from? Is it possible for them to be generated in a different format?

If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.

If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.

angular 2 ngIf and CSS transition/animation

One way is to use a setter for the ngIf property and set the state as part of updating the value.

StackBlitz example

fade.component.ts

 import {
    animate,
    AnimationEvent,
    state,
    style,
    transition,
    trigger
  } from '@angular/animations';
  import { ChangeDetectionStrategy, Component, Input } from '@angular/core';

  export type FadeState = 'visible' | 'hidden';

  @Component({
    selector: 'app-fade',
    templateUrl: './fade.component.html',
    styleUrls: ['./fade.component.scss'],
    animations: [
      trigger('state', [
        state(
          'visible',
          style({
            opacity: '1'
          })
        ),
        state(
          'hidden',
          style({
            opacity: '0'
          })
        ),
        transition('* => visible', [animate('500ms ease-out')]),
        transition('visible => hidden', [animate('500ms ease-out')])
      ])
    ],
    changeDetection: ChangeDetectionStrategy.OnPush
  })
  export class FadeComponent {
    state: FadeState;
    // tslint:disable-next-line: variable-name
    private _show: boolean;
    get show() {
      return this._show;
    }
    @Input()
    set show(value: boolean) {
      if (value) {
        this._show = value;
        this.state = 'visible';
      } else {
        this.state = 'hidden';
      }
    }

    animationDone(event: AnimationEvent) {
      if (event.fromState === 'visible' && event.toState === 'hidden') {
        this._show = false;
      }
    }
  }

fade.component.html

 <div
    *ngIf="show"
    class="fade"
    [@state]="state"
    (@state.done)="animationDone($event)"
  >
    <button mat-raised-button color="primary">test</button>
  </div>

example.component.css

:host {
  display: block;
}
.fade {
  opacity: 0;
}

Check a radio button with javascript

I was able to select (check) a radio input button by using this Javascript code in Firefox 72, within a Web Extension option page to LOAD the value:

var reloadItem = browser.storage.sync.get('reload_mode');
reloadItem.then((response) => {
    if (response["reload_mode"] == "Periodic") {
        document.querySelector('input[name=reload_mode][value="Periodic"]').click();
    } else if (response["reload_mode"] == "Page Bottom") {
        document.querySelector('input[name=reload_mode][value="Page Bottom"]').click();
    } else {
        document.querySelector('input[name=reload_mode][value="Both"]').click();
    }
});

Where the associated code to SAVE the value was:

reload_mode: document.querySelector('input[name=reload_mode]:checked').value

Given HTML like the following:

    <input type="radio" id="periodic" name="reload_mode" value="Periodic">
    <label for="periodic">Periodic</label><br>
    <input type="radio" id="bottom" name="reload_mode" value="Page Bottom">
    <label for="bottom">Page Bottom</label><br>
    <input type="radio" id="both" name="reload_mode" value="Both">
    <label for="both">Both</label></br></br>

Segmentation Fault - C

Catastrophically bad:

int main(void){
      char *s;
      int ln;
      puts("Enter String");
      // scanf("%s", s);
      gets(s);
      ln = strlen(s); // remove this line to end seg fault
      char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome
      dyn_s = s;
      dyn_s[strlen(s)] = '\0';
      puts(dyn_s);
      return 0;
    }

Better:

#include <stdio.h>
#define BUF_SIZE 80

int 
main(int argc, char *argv[])
{
      char s[BUF_SIZE];
      int ln;
      puts("Enter String");
      // scanf("%s", s);
      gets(s);
      ln = strlen(s); // remove this line to end seg fault
      char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome
      dyn_s = s;
      dyn_s[strlen(s)] = '\0';
      puts(dyn_s);
      return 0;
    }

Best:

#include <stdio.h>
#define BUF_SIZE 80

int 
main(int argc, char *argv[])
{
      char s[BUF_SIZE];
      int ln;
      puts("Enter String");
      fgets(s, BUF_SIZE, stdin); // Use fgets (our "cin"): NEVER "gets()"

      int ln = strlen(s); 
      char *dyn_s = (char*) malloc (ln+1);
      strcpy (dyn_s, s);
      puts(dyn_s);
      return 0;
    }

How to make a machine trust a self-signed Java application

I was having the same issue. So I went to the Java options through Control Panel. Copied the web address that I was having an issue with to the exceptions and it was fixed.

What's the difference between SCSS and Sass?

Difference between SASS and SCSS article explains the difference in details. Don’t be confused by the SASS and SCSS options, although I also was initially, .scss is Sassy CSS and is the next generation of .sass.

If that didn’t make sense you can see the difference in code below.

/* SCSS */
$blue: #3bbfce;
$margin: 16px;

.content-navigation {
  border-color: $blue;
  color: darken($blue, 9%);
}

.border {
  padding: $margin / 2; margin: $margin / 2; border-color: $blue;
}

In the code above we use ; to separate the declarations. I’ve even added all the declarations for .border onto a single line to illustrate this point further. In contrast, the SASS code below must be on different lines with indentation and there is no use of the ;.

/* SASS */
$blue: #3bbfce
$margin: 16px

.content-navigation
  border-color: $blue
  color: darken($blue, 9%)

.border
  padding: $margin / 2
  margin: $margin / 2
  border-color: $blue

You can see from the CSS below that the SCSS style is a lot more similar to regular CSS than the older SASS approach.

/* CSS */
.content-navigation {
  border-color: #3bbfce;
  color: #2b9eab;
}

.border {
  padding: 8px;
  margin: 8px;
  border-color: #3bbfce;
}

I think most of the time these days if someone mentions that they are working with Sass they are referring to authoring in .scss rather than the traditional .sass way.

How to achieve pagination/table layout with Angular.js?

I use this solution:

It's a bit more concise since I use: ng-repeat="obj in objects | filter : paginate" to filter the rows. Also made it working with $resource:

http://plnkr.co/edit/79yrgwiwvan3bAG5SnKx?p=preview

Truncate/round whole number in JavaScript?

Math.trunc() function removes all the fractional digits.

For positive number it behaves exactly the same as Math.floor():

console.log(Math.trunc(89.13349)); // output is 89

For negative numbers it behaves same as Math.ceil():

console.log(Math.trunc(-89.13349)); //output is -89

Hashset vs Treeset

1.HashSet allows null object.

2.TreeSet will not allow null object. If you try to add null value it will throw a NullPointerException.

3.HashSet is much faster than TreeSet.

e.g.

 TreeSet<String> ts = new TreeSet<String>();
 ts.add(null); // throws NullPointerException

 HashSet<String> hs = new HashSet<String>();
 hs.add(null); // runs fine

How to create a printable Twitter-Bootstrap page

Bootstrap 3.2 update: (current release)

Current stable Bootstrap version is 3.2.0.
With version 3.2 visible-print deprecated, so you should use like this:

Class                        Browser    Print
 -------------------------------------------------
.visible-print-block         Hidden        Visible (as block)
.visible-print-inline        Hidden        Visible (as inline)
.visible-print-inline-block  Hidden        Visible (as inline-block)
.hidden-print                Visible       Hidden

Bootstrap 3 update:

Print classes are now in documents: http://getbootstrap.com/css/#responsive-utilities-print

Similar to the regular responsive classes,
       use these for toggling content for print.

Class            Browser    Print
 ----------------------------------------
.visible-print   Hidden     Visible
.hidden-print    Visible    Hidden

Bootstrap 2.3.1 version:

After adding bootstrap.css file into your HTML,
Find the parts that you don't want to print and add hidden-print class into tags. Because css file includes this:

@media print {
  .visible-print  { display: inherit !important; }
  .hidden-print   { display: none !important; }
}

Substitute multiple whitespace with single whitespace in Python

For completeness, you can also use:

mystring = mystring.strip()  # the while loop will leave a trailing space, 
                  # so the trailing whitespace must be dealt with
                  # before or after the while loop
while '  ' in mystring:
    mystring = mystring.replace('  ', ' ')

which will work quickly on strings with relatively few spaces (faster than re in these situations).

In any scenario, Alex Martelli's split/join solution performs at least as quickly (usually significantly more so).

In your example, using the default values of timeit.Timer.repeat(), I get the following times:

str.replace: [1.4317800167340238, 1.4174888149192384, 1.4163512401715934]
re.sub:      [3.741931446594549,  3.8389395858970374, 3.973777672860706]
split/join:  [0.6530919432498195, 0.6252146571700905, 0.6346594329726258]


EDIT:

Just came across this post which provides a rather long comparison of the speeds of these methods.

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

While the official docs are happy not to provide switch, I have seen a solution using dictionaries.

For example:

# define the function blocks
def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

# map the inputs to the function blocks
options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}

Then the equivalent switch block is invoked:

options[num]()

This begins to fall apart if you heavily depend on fall through.

Insert image after each list item

The easier way to do it is just:

ul li:after {
    content: url('../images/small_triangle.png');
}

What is the difference between signed and unsigned int

As you are probably aware, ints are stored internally in binary. Typically an int contains 32 bits, but in some environments might contain 16 or 64 bits (or even a different number, usually but not necessarily a power of two).

But for this example, let's look at 4-bit integers. Tiny, but useful for illustration purposes.

Since there are four bits in such an integer, it can assume one of 16 values; 16 is two to the fourth power, or 2 times 2 times 2 times 2. What are those values? The answer depends on whether this integer is a signed int or an unsigned int. With an unsigned int, the value is never negative; there is no sign associated with the value. Here are the 16 possible values of a four-bit unsigned int:

bits  value
0000    0
0001    1
0010    2
0011    3
0100    4
0101    5
0110    6
0111    7
1000    8
1001    9
1010   10
1011   11
1100   12
1101   13
1110   14
1111   15

... and Here are the 16 possible values of a four-bit signed int:

bits  value
0000    0
0001    1
0010    2
0011    3
0100    4
0101    5
0110    6
0111    7
1000   -8
1001   -7
1010   -6
1011   -5
1100   -4
1101   -3
1110   -2
1111   -1

As you can see, for signed ints the most significant bit is 1 if and only if the number is negative. That is why, for signed ints, this bit is known as the "sign bit".

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Paths specified with a . are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js but not if you run node folder/app.js. The only exception to this is require('./file') and that is only possible because require exists per-module and thus knows what module it is being called from.

To make a path relative to the script, you must use the __dirname variable.

var path = require('path');

path.join(__dirname, 'path/to/file')

or potentially

path.join(__dirname, 'path', 'to', 'file')

Shell - Write variable contents to a file

echo has the problem that if var contains something like -e, it will be interpreted as a flag. Another option is printf, but printf "$var" > "$destdir" will expand any escaped characters in the variable, so if the variable contains backslashes the file contents won't match. However, because printf only interprets backslashes as escapes in the format string, you can use the %s format specifier to store the exact variable contents to the destination file:

printf "%s" "$var" > "$destdir"

CentOS: Copy directory to another directory

cp -r /home/server/folder/test /home/server/

Getting the Facebook like/share count for a given URL

Use the open graph API. Here is a live example querying how many likes "Coca Cola" has.

https://developers.facebook.com/tools/explorer/?method=GET&path=cocacola%3Ffields%3Dlikes

Which boils down to:

https://graph.facebook.com/cocacola?fields=likes

Which you could do in an AJAX GET

The result is:

{
  "likes": 71717854, 
  "id": "40796308305"
}

Add centered text to the middle of a <hr/>-like line

There's always the good old FIELDSET

 fieldset
 {
border-left: none;
border-right: none;
border-bottom: none;
 }
 fieldset legend
 {
text-align: center;
padding-left: 10px;
padding-right: 10px;
 }

Python handling socket.error: [Errno 104] Connection reset by peer

You can try to add some time.sleep calls to your code.

It seems like the server side limits the amount of requests per timeunit (hour, day, second) as a security issue. You need to guess how many (maybe using another script with a counter?) and adjust your script to not surpass this limit.

In order to avoid your code from crashing, try to catch this error with try .. except around the urllib2 calls.

Declare variable in SQLite and use it

I appreciate that the other solutions do not depend on any other software tool, but why not just use another programming language that can interface to SQLite such as C#, C++, Go, Haskell, Java, Lua, Python, or Rust?

How to read and write xml files?

The above answer only deal with DOM parser (that normally reads the entire file in memory and parse it, what for a big file is a problem), you could use a SAX parser that uses less memory and is faster (anyway that depends on your code).

SAX parser callback some functions when it find a start of element, end of element, attribute, text between elements, etc, so it can parse the document and at the same time you get what you need.

Some example code:

http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

    JavascriptExecutor js = (JavascriptExecutor) driver;        
    js.executeScript("document.getElementsByClassName('featured-heading')[0].setAttribute('style', 'background-color: green')");

I could add an attribute using the above code in java

Modifying location.hash without page scrolling

I think you need to reset scroll to its position before hashchange.

$(function(){
    //This emulates a click on the correct button on page load
    if(document.location.hash) {
        $("#buttons li a").removeClass('selected');
        s=$(document.location.hash).addClass('selected').attr("href").replace("javascript:","");
        eval(s);
    }

    //Click a button to change the hash
    $("#buttons li a").click(function() {
            var scrollLocation = $(window).scrollTop();
            $("#buttons li a").removeClass('selected');
            $(this).addClass('selected');
            document.location.hash = $(this).attr("id");
            $(window).scrollTop( scrollLocation );
    });
});

Pausing a batch file for amount of time

ping -n 11 -w 1000 127.0.0.1 > nul

Update

Beginner's mistake. Ping doesn't wait 1000 ms before or after an request, but inbetween requests. So to wait 10 seconds, you'll have to do 11 pings to have 10 'gaps' of a second inbetween.

Apache shutdown unexpectedly

This problem may occur because of skype installation in the system. Skype and apache service always conflict. Make sure your skype is not started before starting xampp.

Laravel: Get Object From Collection By Attribute

You can use filter, like so:

$desired_object = $food->filter(function($item) {
    return $item->id == 24;
})->first();

filter will also return a Collection, but since you know there will be only one, you can call first on that Collection.

You don't need the filter anymore (or maybe ever, I don't know this is almost 4 years old). You can just use first:

$desired_object = $food->first(function($item) {
    return $item->id == 24;
});

nginx: send all requests to a single html page

This worked for me:

location / {
    try_files $uri $uri/ /base.html;
}

Whats the CSS to make something go to the next line in the page?

There are two options that I can think of, but without more details, I can't be sure which is the better:

#elementId {
    display: block;
}

This will force the element to a 'new line' if it's not on the same line as a floated element.

#elementId {
     clear: both;
}

This will force the element to clear the floats, and move to a 'new line.'

In the case of the element being on the same line as another that has position of fixed or absolute nothing will, so far as I know, force a 'new line,' as those elements are removed from the document's normal flow.

How can I view the source code for a function?

In RStudio, there are (at least) 3 ways:

  1. Press the F2 key while cursor is on any function.
  2. Click on the function name while holding Ctrl or Command
  3. View(function_name) (as stated above)

A new pane will open with the source code. If you reach .Primitive or .C you'll need another method, sorry.

How can I convert an image into Base64 string using JavaScript?

I found that the safest and reliable way to do it is to use FileReader().

Demo: Image to Base64

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <input id="myinput" type="file" onchange="encode();" />
    <div id="dummy">
    </div>
    <div>
      <textarea style="width:100%;height:500px;" id="txt">
      </textarea>
    </div>
    <script>
      function encode() {
        var selectedfile = document.getElementById("myinput").files;
        if (selectedfile.length > 0) {
          var imageFile = selectedfile[0];
          var fileReader = new FileReader();
          fileReader.onload = function(fileLoadedEvent) {
            var srcData = fileLoadedEvent.target.result;
            var newImage = document.createElement('img');
            newImage.src = srcData;
            document.getElementById("dummy").innerHTML = newImage.outerHTML;
            document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
          }
          fileReader.readAsDataURL(imageFile);
        }
      }
    </script>
  </body>
</html>

UPDATE - THE SAME CODE WITH COMMENTS FOR @AnniekJ REQUEST:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <input id="myinput" type="file" onchange="encode();" />
    <div id="dummy">
    </div>
    <div>
      <textarea style="width:100%;height:500px;" id="txt">
      </textarea>
    </div>
    <script>
      function encode() {
        // Get the file objects that was selected by the user from myinput - a file picker control
        var selectedfile = document.getElementById("myinput").files;
        // Check that the user actually selected file/s from the "file picker" control
        // Note - selectedfile is an array, hence we check it`s length, when length of the array
        // is bigger than 0 than it means the array containes file objects
        if (selectedfile.length > 0) {
          // Set the first file object inside the array to this variable
          // Note: if multiple files are selected we can itterate on all of the selectedfile array  using a for loop - BUT in order to not make this example complicated we only take the first file object that was selected
          var imageFile = selectedfile[0];
          // Set a filereader object to asynchronously read the contents of files (or raw data buffers) stored on the            user's computer, using File or Blob objects to specify the file or data to read. 
          var fileReader = new FileReader();
          // We declare an event of the fileReader class (onload event) and we register an anonimous function that will be executed when the event is raised. it is "trick" we preapare in order for the onload event to be raised after the last line of this code will be executed (fileReader.readAsDataURL(imageFile);) - please read about events in javascript if you are not familiar with "Events" 
          fileReader.onload = function(fileLoadedEvent) {
            // AT THIS STAGE THE EVENT WAS RAISED
            // Here we are getting the file contents - basiccaly the base64 mapping
            var srcData = fileLoadedEvent.target.result;
            // We create an image html element dinamically in order to display the image
            var newImage = document.createElement('img');
            // We set the source of the image we created
            newImage.src = srcData;
            // ANOTHER TRICK TO EXTRACT THE BASE64 STRING
            // We set the outer html of the new image to the div element
            document.getElementById("dummy").innerHTML = newImage.outerHTML;
            // Then we take the inner html of the div and we have the base64 string
            document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
          }
          // This line will raise the fileReader.onload event - note we are passing the file object here as an argument to the function of the event  
          fileReader.readAsDataURL(imageFile);
        }
      }
    </script>
  </body>
</html>

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

Looks like Users that are added in your Country object, are not already present in the DB. You need to use cascade to make sure that when Country is persisted, all User which are not there in data but are associated with Country also get persisted.

Below code should help:

@ManyToOne (cascade = CascadeType.ALL)
   @JoinColumn (name = "countryId")
   private Country country;

How can I split and parse a string in Python?

Python string parsing walkthrough

Split a string on space, get a list, show its type, print it out:

el@apollo:~/foo$ python
>>> mystring = "What does the fox say?"

>>> mylist = mystring.split(" ")

>>> print type(mylist)
<type 'list'>

>>> print mylist
['What', 'does', 'the', 'fox', 'say?']

If you have two delimiters next to each other, empty string is assumed:

el@apollo:~/foo$ python
>>> mystring = "its  so   fluffy   im gonna    DIE!!!"

>>> print mystring.split(" ")
['its', '', 'so', '', '', 'fluffy', '', '', 'im', 'gonna', '', '', '', 'DIE!!!']

Split a string on underscore and grab the 5th item in the list:

el@apollo:~/foo$ python
>>> mystring = "Time_to_fire_up_Kowalski's_Nuclear_reactor."

>>> mystring.split("_")[4]
"Kowalski's"

Collapse multiple spaces into one

el@apollo:~/foo$ python
>>> mystring = 'collapse    these       spaces'

>>> mycollapsedstring = ' '.join(mystring.split())

>>> print mycollapsedstring.split(' ')
['collapse', 'these', 'spaces']

When you pass no parameter to Python's split method, the documentation states: "runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace".

Hold onto your hats boys, parse on a regular expression:

el@apollo:~/foo$ python
>>> mystring = 'zzzzzzabczzzzzzdefzzzzzzzzzghizzzzzzzzzzzz'
>>> import re
>>> mylist = re.split("[a-m]+", mystring)
>>> print mylist
['zzzzzz', 'zzzzzz', 'zzzzzzzzz', 'zzzzzzzzzzzz']

The regular expression "[a-m]+" means the lowercase letters a through m that occur one or more times are matched as a delimiter. re is a library to be imported.

Or if you want to chomp the items one at a time:

el@apollo:~/foo$ python
>>> mystring = "theres coffee in that nebula"

>>> mytuple = mystring.partition(" ")

>>> print type(mytuple)
<type 'tuple'>

>>> print mytuple
('theres', ' ', 'coffee in that nebula')

>>> print mytuple[0]
theres

>>> print mytuple[2]
coffee in that nebula

Golang append an item to a slice

Try this, which I think makes it clear. the underlying array is changed but our slice is not, print just prints len() chars, by another slice to the cap(), you can see the changed array:

func main() {

  for i := 0; i < 7; i++ {
      a[i] = i
  }

  Test(a)

  fmt.Println(a) // prints [0..6]
  fmt.Println(a[:cap(a)] // prints [0..6,100]
}

using if else with eval in aspx page

If you are trying to bind is a Model class, you can add a new readonly property to it like:

public string FormattedPercentage
{
    get
    {
        If(this.Percentage < 50)
            return "0 %";
        else 
            return string.Format("{0} %", this.Percentage)        
     }
}

Otherwise you can use Andrei's or kostas ch. suggestions if you cannot modify the class itself

How to clear memory to prevent "out of memory error" in excel vba?

Found this thread looking for a solution to my problem. Mine required a different solution that I figured out that might be of use to others. My macro was deleting rows, shifting up, and copying rows to another worksheet. Memory usage was exploding to several gigs and causing "out of memory" after processing around only 4000 records. What solved it for me?

application.screenupdating = false

Added that at the beginning of my code (be sure to make it true again, at the end) I knew that would make it run faster, which it did.. but had no idea about the memory thing.

After making this small change the memory usage didn't exceed 135 mb. Why did that work? No idea really. But it's worth a shot and might apply to you.

T-SQL How to select only Second row from a table?

with T1 as
(
  select row_number() over(order by ID) rownum, T2.ID
  from Table2 T2
)
select ID
from T1
where rownum=2

Parenthesis/Brackets Matching using Stack algorithm

Was asked to implement this algorithm at live coding interview, here's my refactored solution in C#:

Git Tests

How to pass data from Javascript to PHP and vice versa?

the other way to exchange data from php to javascript or vice versa is by using cookies, you can save cookies in php and read by your javascript, for this you don't have to use forms or ajax

How to use glOrtho() in OpenGL?

Have a look at this picture: Graphical Projections enter image description here

The glOrtho command produces an "Oblique" projection that you see in the bottom row. No matter how far away vertexes are in the z direction, they will not recede into the distance.

I use glOrtho every time I need to do 2D graphics in OpenGL (such as health bars, menus etc) using the following code every time the window is resized:

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, windowWidth, windowHeight, 0.0f, 0.0f, 1.0f);

This will remap the OpenGL coordinates into the equivalent pixel values (X going from 0 to windowWidth and Y going from 0 to windowHeight). Note that I've flipped the Y values because OpenGL coordinates start from the bottom left corner of the window. So by flipping, I get a more conventional (0,0) starting at the top left corner of the window rather.

Note that the Z values are clipped from 0 to 1. So be careful when you specify a Z value for your vertex's position, it will be clipped if it falls outside that range. Otherwise if it's inside that range, it will appear to have no effect on the position except for Z tests.

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

These are really two questions.

The first one is answered here: Calling a Sub in VBA

To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.

create table in postgreSQL

First the bigint(20) not null auto_increment will not work, simply use bigserial primary key. Then datetime is timestamp in PostgreSQL. All in all:

CREATE TABLE article (
    article_id bigserial primary key,
    article_name varchar(20) NOT NULL,
    article_desc text NOT NULL,
    date_added timestamp default NULL
);

Add column to SQL query results

why dont you add a "source" column to each of the queries with a static value like

select 'source 1' as Source, column1, column2...
from table1

UNION ALL

select 'source 2' as Source, column1, column2...
from table2

scp with port number specified

Hope this will help someone looking for a perfect answer

Copying a folder or file from a server with a port defined to another server or local machine

  1. Go to a directory where you have admin rights preferably your home directory on the machine where you want to copy files to
  2. Write the command below

scp -r -P port user@IP_address:/home/file/pathDirectory .

**Note:** The last . on the command directs it to copy everything in that folder to your directory of preference

Check if a class `active` exist on element with jquery

i wrote a helper method to help me go through all my selected elements and remove the active class.

    function removeClassFromElem(classSelect, classToRemove){
      $(classSelect).each(function(){
        var currElem=$(this);
        if(currElem.hasClass(classToRemove)){
          currElem.removeClass(classToRemove);
        }
      });
    }

    //usage
    removeClassFromElem('.someclass', 'active');

List of macOS text editors and code editors

Coda's great for PHP/ASP/HTML style development. Great interface, multiple-file search and replace with regexp support, slick FTP/SFTP/etc integration for browsing and editing remote files, SVN integration, etc.

It now supports plugins and the plugin editor can import TextMate bundles, so there's a bright future there. There aren't a lot of must-have plugins yet because the plugin support was newly introduced with version 1.6 a few months back. It's a popular app, though, so I expect more in the future.

The "killer features" for me are: * Seamless editing of remote files * Code navigator (symbol browser; pane that lists functions etc)

Most people aren't really into using symbol browsers but as I have to maintain a lot of unfamiliar code I find them invaluable.

I'm not sure that Coda has the "raw power" of TextMate though. I plan on getting familiar with TextMate next.

Flask SQLAlchemy query, specify column names

As session.query(SomeModel.col1) returns an array of tuples like this [('value_1',),('value_2',)] if you want t cast the result to a plain array you can do it by using one of the following statements:

values = [value[0] for value in session.query(SomeModel.col1)]
values = [model.col1 for model in session.query(SomeModel).options(load_only('col1'))]

Result:

 ['value_1', 'value_2']

How to convert enum value to int?

If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.

If you want a unique number that represent the enum value, you can use ordinal().

How to concatenate multiple lines of output to one line?

In bash echo without quotes remove carriage returns, tabs and multiple spaces

echo $(cat file)

Unable to convert MySQL date/time value to System.DateTime

i added both Convert Zero Datetime=True & Allow Zero Datetime=True and it works fine

Mockito match any class argument

the solution from millhouse is not working anymore with recent version of mockito

This solution work with java 8 and mockito 2.2.9

where ArgumentMatcher is an instanceof org.mockito.ArgumentMatcher

public class ClassOrSubclassMatcher<T> implements ArgumentMatcher<Class<T>> {

   private final Class<T> targetClass;

    public ClassOrSubclassMatcher(Class<T> targetClass) {
        this.targetClass = targetClass;
    }

    @Override
    public boolean matches(Class<T> obj) {
        if (obj != null) {
            if (obj instanceof Class) {
                return targetClass.isAssignableFrom( obj);
            }
        }
        return false;
    }
}

And the use

when(a.method(ArgumentMatchers.argThat(new ClassOrSubclassMatcher<>(A.class)))).thenReturn(b);

jQuery override default validation error message display (Css) Popup/Tooltip like

I use jQuery BeautyTips to achieve the little bubble effect you are talking about. I don't use the Validation plugin so I can't really help much there, but it is very easy to style and show the BeautyTips. You should look into it. It's not as simple as just CSS rules, I'm afraid, as you need to use the canvas element and include an extra javascript file for IE to play nice with it.

variable or field declared void

This is not actually a problem with the function being "void", but a problem with the function parameters. I think it's just g++ giving an unhelpful error message.

EDIT: As in the accepted answer, the fix is to use std::string instead of just string.

What is the difference between window, screen, and document in Javascript?

the window contains everything, so you can call window.screen and window.document to get those elements. Check out this fiddle, pretty-printing the contents of each object: http://jsfiddle.net/JKirchartz/82rZu/

You can also see the contents of the object in firebug/dev tools like this:

console.dir(window);
console.dir(document);
console.dir(screen);

window is the root of everything, screen just has screen dimensions, and document is top DOM object. so you can think of it as window being like a super-document...

How to add multiple columns to pandas dataframe in one assignment?

use of list comprehension, pd.DataFrame and pd.concat

pd.concat(
    [
        df,
        pd.DataFrame(
            [[np.nan, 'dogs', 3] for _ in range(df.shape[0])],
            df.index, ['column_new_1', 'column_new_2','column_new_3']
        )
    ], axis=1)

enter image description here

Insert a line break in mailto body

I would suggest you try the html tag <br>, in case your marketing application will recognize it.

I use %0D%0A. This should work as long as the email is HTML formatted.

<a href="mailto:[email protected]?subject=Subscribe&body=Lastame%20%3A%0D%0AFirstname%20%3A"><img alt="Subscribe" class="center" height="50" src="subscribe.png" style="width: 137px; height: 50px; color: #4da6f7; font-size: 20px; display: block;" width="137"></a>

You will likely want to take out the %20 before Firstname, otherwise you will have a space as the first character on the next line.

A note, when I tested this with your code, it worked (along with some extra spacing). Are you using a mail client that doesn't allow HTML formatting?

Replace part of a string in Python?

>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'

Setting environment variables for accessing in PHP when using Apache

Unbelievable, but on httpd 2.2 on centos 6.4 this works.

Export env vars in /etc/sysconfig/httpd

export mydocroot=/var/www/html

Then simply do this...

<VirtualHost *:80>
  DocumentRoot ${mydocroot}
</VirtualHost>

Then finally....

service httpd restart;

Vue template or render function not defined yet I am using neither?

When used with storybook and typescirpt, I had to add

.storybook/webpack.config.js

const path = require('path');

module.exports = async ({ config, mode }) => {

    config.module.rules.push({
        test: /\.ts$/,
        exclude: /node_modules/,
        use: [
            {
                loader: 'ts-loader',
                options: {
                    appendTsSuffixTo: [/\.vue$/],
                    transpileOnly: true
                },
            }
        ],
    });

    return config;
};

Android fastboot waiting for devices

In my case (on windows 10), it would connect fine to adb and I could type any adb commands. But as soon as it got to the bootloader using adb reboot bootloader I wasn't able to perform any fastboot commands.

What I did notice that in the device manager that it refreshed when I connected to device. Next thing to do was to check what changed when connecting. Apparently the fastboot device was inside the Kedacom USB Device. Not really sure what that was, but I updated the device to use a different driver, in my case the Fastboot interface (Google USB ID), and that fixed my waiting for device issue

Unfortunately Launcher3 has stopped working error in android studio?

May 2017; I had the same issue, could not even get to apps as it just cycled between starting and stopping. Went into avd settings, edited the multi core (unticked the box) and set graphics to software Gles. It appears to have fixed the issue

Why doesn't Dijkstra's algorithm work for negative weight edges?

Dijkstra's Algorithm assumes that all edges are positive weighted and this assumption helps the algorithm run faster ( O(V^2) ) than others which take into account the possibility of negative edges (e.g bellman ford's algorithm with complexity of O(V^3)).

This algorithm wont give the correct result in the following case where A is the source vertex:

enter image description here

Also, Dijkstra's Algorithm may sometimes give correct solution even if there are negative edges. Following is an example of such a case:

enter image description here

It will never detect a negative cycle and always produce a result which will always be incorrect if a negative weight cycle is reachable from the source, as in such a case there exists no shortest path in the graph from the source vertex.

Ways to save enums in database

If saving enums as strings in the database, you can create utility methods to (de)serialize any enum:

   public static String getSerializedForm(Enum<?> enumVal) {
        String name = enumVal.name();
        // possibly quote value?
        return name;
    }

    public static <E extends Enum<E>> E deserialize(Class<E> enumType, String dbVal) {
        // possibly handle unknown values, below throws IllegalArgEx
        return Enum.valueOf(enumType, dbVal.trim());
    }

    // Sample use:
    String dbVal = getSerializedForm(Suit.SPADE);
    // save dbVal to db in larger insert/update ...
    Suit suit = deserialize(Suit.class, dbVal);

jquery drop down menu closing by clicking outside

Another multiple dropdown example that works https://jsfiddle.net/vgjddv6u/

_x000D_
_x000D_
$('.moderate .button').on('click', (event) => {_x000D_
  $(event.target).siblings('.dropdown')_x000D_
    .toggleClass('is-open');_x000D_
});_x000D_
_x000D_
$(document).click(function(e) {_x000D_
  $('.moderate')_x000D_
    .not($('.moderate').has($(e.target)))_x000D_
    .children('.dropdown')_x000D_
    .removeClass('is-open');_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" rel="stylesheet" />_x000D_
_x000D_
<script_x000D_
  src="https://code.jquery.com/jquery-3.2.1.min.js"_x000D_
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="_x000D_
  crossorigin="anonymous"></script>_x000D_
_x000D_
<style>_x000D_
.dropdown {_x000D_
  box-shadow: 0 0 2px #777;_x000D_
  display: none;_x000D_
  left: 0;_x000D_
  position: absolute;_x000D_
  padding: 2px;_x000D_
  z-index: 10;_x000D_
}_x000D_
_x000D_
.dropdown a {_x000D_
  font-size: 12px;_x000D_
  padding: 4px;_x000D_
}_x000D_
_x000D_
.dropdown.is-open {_x000D_
  display: block;_x000D_
}_x000D_
</style>_x000D_
_x000D_
_x000D_
<div class="control moderate">_x000D_
  <button class="button is-small" type="button">_x000D_
        moderate_x000D_
      </button>_x000D_
_x000D_
  <div class="box dropdown">_x000D_
    <ul>_x000D_
      <li><a class="nav-item">edit</a></li>_x000D_
      <li><a class="nav-item">delete</a></li>_x000D_
      <li><a class="nav-item">block user</a>   </li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
_x000D_
<div class="control moderate">_x000D_
  <button class="button is-small" type="button">_x000D_
        moderate_x000D_
      </button>_x000D_
_x000D_
  <div class="box dropdown">_x000D_
    <ul>_x000D_
      <li><a class="nav-item">edit</a></li>_x000D_
      <li><a class="nav-item">delete</a></li>_x000D_
      <li><a class="nav-item">block user</a></li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to split a string in shell and get the last field

You could try something like this if you want to use cut:

echo "1:2:3:4:5" | cut -d ":" -f5

You can also use grep try like this :

echo " 1:2:3:4:5" | grep -o '[^:]*$'