Programs & Examples On #Android datepicker

Android DatePicker is a widget for selecting a date. The date can be selected by a year, month, and day spinners or a CalendarView. The set of spinners and the calendar view are automatically synchronized.

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

Because you set visibility either true or false. try that setVisible(0) to visible true . and setVisible(4) to visible false.

How set maximum date in datepicker dialog in android?

You can create Custom date picker, that is work for all api levels.

public class CustomDatePickerDialog extends DatePickerDialog {

    int maxYear;
    int maxMonth;
    int maxDay;

    public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
        super(context, callBack, year, monthOfYear, dayOfMonth);
    }

    public void setMaxDate(long maxDate) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getDatePicker().setMaxDate(System.currentTimeMillis());
        } else {
            final Calendar c = Calendar.getInstance();
            c.setTimeInMillis(maxDate);
            maxYear = c.get(Calendar.YEAR);
            maxMonth = c.get(Calendar.MONTH);
            maxDay = c.get(Calendar.DAY_OF_MONTH);
        }
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            super.onDateChanged(view, year, monthOfYear, dayOfMonth);
        } else {
            if (year > maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

            if (monthOfYear > maxMonth && year == maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

            if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
                view.updateDate(maxYear, maxMonth, maxDay);
        }
    }

set max date

final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(getActivity(),
        myDateListener, year, month, day);
pickerDialog.setMaxDate(System.currentTimeMillis());
pickerDialog.show();

How to show DatePickerDialog on Button click?

enter image description here

I. In your build.gradle add latest appcompat library, at the time 24.2.1

dependencies {  
    compile 'com.android.support:appcompat-v7:X.X.X' 
    // where X.X.X version
}

II. Make your activity extend android.support.v7.app.AppCompatActivity and implement the DatePickerDialog.OnDateSetListener interface.

public class MainActivity extends AppCompatActivity  
    implements DatePickerDialog.OnDateSetListener {

III. Create your DatePickerDialog setting a context, the implementation of the listener and the start year, month and day of the date picker.

DatePickerDialog datePickerDialog = new DatePickerDialog(  
    context, MainActivity.this, startYear, starthMonth, startDay);

IV. Show your dialog on the click event listener of your button

((Button) findViewById(R.id.myButton))
    .setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        datePickerDialog.show();
    }
});

Datepicker: How to popup datepicker when click on edittext

There is another better reusable way as well:

Create a class:

class setDate implements OnFocusChangeListener, OnDateSetListener {   

       private EditText editText;
       private Calendar myCalendar;

       public setDate(EditText editText, Context ctx){
           this.editText = editText;
           this.editText.setOnFocusChangeListener(this);
           myCalendar = Calendar.getInstance();
       }

       @Override
       public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)     {
           // this.editText.setText();

            String myFormat = "MMM dd, yyyy"; //In which you need put here
            SimpleDateFormat sdformat = new SimpleDateFormat(myFormat, Locale.US);
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            editText.setText(sdformat.format(myCalendar.getTime()));

       }

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
             new DatePickerDialog(ctx, this, myCalendar
                       .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                       myCalendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        }

    }

Then call this class under onCreate function:

    EditText editTextFromDate = (EditText) findViewById(R.id.editTextFromDate);
    setDate fromDate = new setDate(editTextFromDate, this);

How to change the style of a DatePicker in android?

Create custom DatePickerDialog style:

<style name="AppTheme.DatePickerDialog" parent="Theme.MaterialComponents.Light.Dialog">
    <item name="android:colorAccent">@color/colorPrimary</item>
    <item name="android:colorControlActivated">@color/colorPrimaryDark</item>
    <item name="android:buttonBarPositiveButtonStyle">@style/AppTheme.Alert.Button.Positive</item>
    <item name="android:buttonBarNegativeButtonStyle">@style/AppTheme.Alert.Button.Negative</item>
    <item name="android:buttonBarNeutralButtonStyle">@style/AppTheme.Alert.Button.Neutral</item>
</style>

<style name="AppTheme.Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="android:textColor">@color/buttonPositive</item>
</style>

<style name="AppTheme.Alert.Button.Negative" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="android:textColor">@color/buttonNegative</item>
</style>

<style name="AppTheme.Alert.Button.Neutral" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="android:textColor">@color/buttonNeutral</item>
</style>

Set custom datePickerDialogTheme style in app theme:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:datePickerDialogTheme">@style/AppTheme.DatePickerDialog</item>
</style>

Set theme programmatically on initialization like this:

val datetime = DatePickerDialog(this, R.style.AppTheme_DatePickerDialog)

With CSS, use "..." for overflowed block of multi-lines

display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical; 

see more click here

How to open, read, and write from serial port in C?

For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.

This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.

To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.

 cc -DDISPLAY_STRING demo.c

If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.


#define TERMINAL    "/dev/ttyUSB0"

#include <errno.h>
#include <fcntl.h> 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 1;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        printf("Error from tcsetattr: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

void set_mincount(int fd, int mcount)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error tcgetattr: %s\n", strerror(errno));
        return;
    }

    tty.c_cc[VMIN] = mcount ? 1 : 0;
    tty.c_cc[VTIME] = 5;        /* half second timer */

    if (tcsetattr(fd, TCSANOW, &tty) < 0)
        printf("Error tcsetattr: %s\n", strerror(errno));
}


int main()
{
    char *portname = TERMINAL;
    int fd;
    int wlen;
    char *xstr = "Hello!\n";
    int xlen = strlen(xstr);

    fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening %s: %s\n", portname, strerror(errno));
        return -1;
    }
    /*baudrate 115200, 8 bits, no parity, 1 stop bit */
    set_interface_attribs(fd, B115200);
    //set_mincount(fd, 0);                /* set to pure timed read */

    /* simple output */
    wlen = write(fd, xstr, xlen);
    if (wlen != xlen) {
        printf("Error from write: %d, %d\n", wlen, errno);
    }
    tcdrain(fd);    /* delay for output */


    /* simple noncanonical input */
    do {
        unsigned char buf[80];
        int rdlen;

        rdlen = read(fd, buf, sizeof(buf) - 1);
        if (rdlen > 0) {
#ifdef DISPLAY_STRING
            buf[rdlen] = 0;
            printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
            unsigned char   *p;
            printf("Read %d:", rdlen);
            for (p = buf; rdlen-- > 0; p++)
                printf(" 0x%x", *p);
            printf("\n");
#endif
        } else if (rdlen < 0) {
            printf("Error from read: %d: %s\n", rdlen, strerror(errno));
        } else {  /* rdlen == 0 */
            printf("Timeout from read\n");
        }               
        /* repeat read to get full message */
    } while (1);
}

For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.


Style input element to fill remaining width of its container

you can try this :

_x000D_
_x000D_
div#panel {_x000D_
    border:solid;_x000D_
    width:500px;_x000D_
    height:300px;_x000D_
}_x000D_
div#content {_x000D_
 height:90%;_x000D_
 background-color:#1ea8d1; /*light blue*/_x000D_
}_x000D_
div#panel input {_x000D_
 width:100%;_x000D_
 height:10%;_x000D_
 /*make input doesnt overflow inside div*/_x000D_
 -webkit-box-sizing: border-box;_x000D_
       -moz-box-sizing: border-box;_x000D_
            box-sizing: border-box;_x000D_
 /*make input doesnt overflow inside div*/_x000D_
}
_x000D_
<div id="panel">_x000D_
  <div id="content"></div>_x000D_
  <input type="text" placeholder="write here..."/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Correct way of using log4net (logger naming)

Instead of naming my invoking class, I started using the following:

private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

In this way, I can use the same line of code in every class that uses log4net without having to remember to change code when I copy and paste. Alternatively, i could create a logging class, and have every other class inherit from my logging class.

Multi-line string with extra space (preserved indentation)

I came hear looking for this answer but also wanted to pipe it to another command. The given answer is correct but if anyone wants to pipe it, you need to pipe it before the multi-line string like this

echo | tee /tmp/pipetest << EndOfMessage
This is line 1.
This is line 2.
Line 3.
EndOfMessage

This will allow you to have a multi line string but also put it in the stdin of a subsequent command.

iOS 8 UITableView separator inset 0 not working

After much investigation...

Here's the only way to fully control this stuff (that I could find)

To fully control both separator insets and layout margins on each cell. Do this in the willDisplayCell method on your UITableviewDelegate.

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.layoutMargins = UIEdgeInsetsZero
    cell.contentView.layoutMargins = UIEdgeInsetsMake(0, 10, 0, 10)
    cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
}

The cell object controls the separator, and the contentView controls everything else. If your separator inset spaces are showing up in an unexpected color this should solve it:

cell.backgroundColor = cell.contentView.backgroundColor

How do I create a Python function with optional arguments?

Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.

How to print bytes in hexadecimal using System.out.println?

System.out.println(Integer.toHexString(test[0]));

OR (pretty print)

System.out.printf("0x%02X", test[0]);

OR (pretty print)

System.out.println(String.format("0x%02X", test[0]));

How to return part of string before a certain character?

And note that first argument of subString is 0 based while second is one based.

Example:

String str= "0123456";
String sbstr= str.substring(0,5);

Output will be sbstr= 01234 and not sbstr = 012345

For loop in multidimensional javascript array

JavaScript does not have such declarations. It would be:

var cubes = ...

regardless

But you can do:

for(var i = 0; i < cubes.length; i++)
{
  for(var j = 0; j < cubes[i].length; j++)
  {

  }
}

Note that JavaScript allows jagged arrays, like:

[
  [1, 2, 3],
  [1, 2, 3, 4]
]

since arrays can contain any type of object, including an array of arbitrary length.

As noted by MDC:

"for..in should not be used to iterate over an Array where index order is important"

If you use your original syntax, there is no guarantee the elements will be visited in numeric order.

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

@bku_drytt's solution didn't do it for me.

I solved it by additionally changing every occurence of 14.0 to 12.0 and v140 to v120 manually in the .vcxproj files.

Then it compiled!

not-null property references a null or transient value

Make that variable as transient.Your problem will get solved..

@Column(name="emp_name", nullable=false, length=30)
    private transient String empName;

How to use doxygen to create UML class diagrams from C++ source

Enterprise Architect will build a UML diagram from imported source code.

Defining custom attrs

The answer above covers everything in great detail, apart from a couple of things.

First, if there are no styles, then the (Context context, AttributeSet attrs) method signature will be used to instantiate the preference. In this case just use context.obtainStyledAttributes(attrs, R.styleable.MyCustomView) to get the TypedArray.

Secondly it does not cover how to deal with plaurals resources (quantity strings). These cannot be dealt with using TypedArray. Here is a code snippet from my SeekBarPreference that sets the summary of the preference formatting its value according to the value of the preference. If the xml for the preference sets android:summary to a text string or a string resouce the value of the preference is formatted into the string (it should have %d in it, to pick up the value). If android:summary is set to a plaurals resource, then that is used to format the result.

// Use your own name space if not using an android resource.
final static private String ANDROID_NS = 
    "http://schemas.android.com/apk/res/android";
private int pluralResource;
private Resources resources;
private String summary;

public SeekBarPreference(Context context, AttributeSet attrs) {
    // ...
    TypedArray attributes = context.obtainStyledAttributes(
        attrs, R.styleable.SeekBarPreference);
    pluralResource =  attrs.getAttributeResourceValue(ANDROID_NS, "summary", 0);
    if (pluralResource !=  0) {
        if (! resources.getResourceTypeName(pluralResource).equals("plurals")) {
            pluralResource = 0;
        }
    }
    if (pluralResource ==  0) {
        summary = attributes.getString(
            R.styleable.SeekBarPreference_android_summary);
    }
    attributes.recycle();
}

@Override
public CharSequence getSummary() {
    int value = getPersistedInt(defaultValue);
    if (pluralResource != 0) {
        return resources.getQuantityString(pluralResource, value, value);
    }
    return (summary == null) ? null : String.format(summary, value);
}

  • This is just given as an example, however, if you want are tempted to set the summary on the preference screen, then you need to call notifyChanged() in the preference's onDialogClosed method.

Get distance between two points in canvas

http://en.wikipedia.org/wiki/Euclidean_distance

If you have the coordinates, use the formula to calculate the distance:

var dist = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );

If your platform supports the ** operator, you can instead use that:

const dist = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);

How to detect Ctrl+V, Ctrl+C using JavaScript?

Important note

I was using e.keyCode for a while and i detected that when i press ctrl + ., This attribute returns a wrong number, 190, while the ascii code of . is 46!

So you should use e.key.toUpperCase().charCodeAt(0) instead of e.keyCode.

How can an html element fill out 100% of the remaining screen height, using css only?

Have you tried something like this?

CSS:

.content {
    height: 100%;
    display: block;
}

HTML:

<div class=".content">
<!-- Content goes here -->
</div>

Get child Node of another Node, given node name

You should read it recursively, some time ago I had the same question and solve with this code:

public void proccessMenuNodeList(NodeList nl, JMenuBar menubar) {
    for (int i = 0; i < nl.getLength(); i++) {
        proccessMenuNode(nl.item(i), menubar);
    }
}

public void proccessMenuNode(Node n, Container parent) {
    if(!n.getNodeName().equals("menu"))
        return;
    Element element = (Element) n;
    String type = element.getAttribute("type");
    String name = element.getAttribute("name");
    if (type.equals("menu")) {
        NodeList nl = element.getChildNodes();
        JMenu menu = new JMenu(name);

        for (int i = 0; i < nl.getLength(); i++)
            proccessMenuNode(nl.item(i), menu);

        parent.add(menu);
    } else if (type.equals("item")) {
        JMenuItem item = new JMenuItem(name);
        parent.add(item);
    }
}

Probably you can adapt it for your case.

Read entire file in Scala?

Just like in Java, using CommonsIO library:

FileUtils.readFileToString(file, StandardCharsets.UTF_8)

Also, many answers here forget Charset. It's better to always provide it explicitly, or it will hit one day.

How do I correctly setup and teardown for my pytest class with tests?

When you write "tests defined as class methods", do you really mean class methods (methods which receive its class as first parameter) or just regular methods (methods which receive an instance as first parameter)?

Since your example uses self for the test methods I'm assuming the latter, so you just need to use setup_method instead:

class Test:

    def setup_method(self, test_method):
        # configure self.attribute

    def teardown_method(self, test_method):
        # tear down self.attribute

    def test_buttons(self):
        # use self.attribute for test

The test method instance is passed to setup_method and teardown_method, but can be ignored if your setup/teardown code doesn't need to know the testing context. More information can be found here.

I also recommend that you familiarize yourself with py.test's fixtures, as they are a more powerful concept.

Sticky and NON-Sticky sessions

I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477

Or you can read it there ==>

When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.

  • If you're using session replication without sticky session : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send some of these requests to the first tomcat instance, and send some other of these requests to the secondth instance, and other to the third.
  • If you're using sticky session without replication : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send the first user request to one of the three tomcat instances, and all the other requests that are sent by this user during his session will be sent to the same tomcat instance. During these requests, if you shutdown or restart this tomcat instance (tomcat instance which is used) the loadbalancer sends the remaining requests to one other tomcat instance that is still running, BUT as you don't use session replication, the instance tomcat which receives the remaining requests doesn't have a copy of the user session then for this tomcat the user begin a session : the user loose his session and is disconnected from the web app although the web app is still running.
  • If you're using sticky session WITH session replication : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send the first user request to one of the three tomcat instances, and all the other requests that are sent by this user during his session will be sent to the same tomcat instance. During these requests, if you shutdown or restart this tomcat instance (tomcat instance which is used) the loadbalancer sends the remaining requests to one other tomcat instance that is still running, as you use session replication, the instance tomcat which receives the remaining requests has a copy of the user session then the user keeps on his session : the user continue to browse your web app without being disconnected, the shutdown of the tomcat instance doesn't impact the user navigation.

appending list but error 'NoneType' object has no attribute 'append'

I think what you want is this:

last_list=[]
if p.last_name != None and p.last_name != "":
    last_list.append(p.last_name)
print last_list

Your current if statement:

if p.last_name == None or p.last_name == "":
    pass

Effectively never does anything. If p.last_name is none or the empty string, it does nothing inside the loop. If p.last_name is something else, the body of the if statement is skipped.

Also, it looks like your statement pan_list.append(p.last) is a typo, because I see neither pan_list nor p.last getting used anywhere else in the code you have posted.

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

Remove specific commit

So you did some work and pushed it, lets call them commits A and B. Your coworker did some work as well, commits C And D. You merged your coworkers work into yours (merge commit E), then continued working, committed that, too (commit F), and discovered that your coworker changed some things he shouldn't have.

So your commit history looks like this:

A -- B -- C -- D -- D' -- E -- F

You really want to get rid of C, D, and D'. Since you say you merged your coworkers work into yours, these commits already "out there", so removing the commits using e.g. git rebase is a no-no. Believe me, I've tried.

Now, I see two ways out:

  • if you haven't pushed E and F to your coworker or anyone else (typically your "origin" server) yet, you could still remove those from the history for the time being. This is your work that you want to save. This can be done with a

    git reset D'
    

    (replace D' with the actual commit hash that you can obtain from a git log

    At this point, commits E and F are gone and the changes are uncommitted changes in your local workspace again. At this point I would move them to a branch or turn them into a patch and save it for later. Now, revert your coworker's work, either automatically with a git revert or manually. When you've done that, replay your work on top of that. You may have merge conflicts, but at least they'll be in the code you wrote, instead of your coworker's code.

  • If you've already pushed the work you did after your coworker's commits, you can still try and get a "reverse patch" either manually or using git revert, but since your work is "in the way", so to speak you'll probably get more merge conflicts and more confusing ones. Looks like that's what you ended up in...

Match two strings in one line with grep

To search for files containing all the words in any order anywhere:

grep -ril \'action\' | xargs grep -il \'model\' | xargs grep -il \'view_type\'

The first grep kicks off a recursive search (r), ignoring case (i) and listing (printing out) the name of the files that are matching (l) for one term ('action' with the single quotes) occurring anywhere in the file.

The subsequent greps search for the other terms, retaining case insensitivity and listing out the matching files.

The final list of files that you will get will the ones that contain these terms, in any order anywhere in the file.

How to enable PHP's openssl extension to install Composer?

For those who're having the same problem as I was. After doing all the solutions above, still didn't work for me. I found out that, uWamp was creating the PHP.INI file in bin/apache directory. So I had to copy the PHP.INI file into php installation directory, that is, bin/php/phpXXXX directory. This should also be where the php.exe is that you selected from the composer setup.

Hope this helps.

How to change pivot table data source in Excel?

right click on the pivot table in excel choose wizard click 'back' click 'get data...' in the query window File - Table Definition

then you can create a new or choose a different connection

How to cast an object in Objective-C

Typecasting in Objective-C is easy as:

NSArray *threeViews = @[[UIView new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];

However, what happens if first object is not UIView and you try to use it:

NSArray *threeViews = @[[NSNumber new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
CGRect firstViewFrame = firstView.frame; // CRASH!

It will crash. And it's easy to find such crash for this case, but what if those lines are in different classes and the third line is executed only once in 100 cases. I bet your customers find this crash, not you! A plausible solution is to crash early, like this:

UIView *firstView = (UIView *)threeViews[0];
NSAssert([firstView isKindOfClass:[UIView class]], @"firstView is not UIView");

Those assertions doesn't look very nice, so we could improve them with this handy category:

@interface NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object;
@end


@implementation NSObject (TypecastWithAssertion)

+ (instancetype)typecastWithAssertion:(id)object {
    if (object != nil)
        NSAssert([object isKindOfClass:[self class]], @"Object %@ is not kind of class %@", object, NSStringFromClass([self class]));
    return object;
}

@end

This is much better:

UIView *firstView = [UIView typecastWithAssertion:[threeViews[0]];

P.S. For collections type safety Xcode 7 have a much better than typecasting - generics

Angular - res.json() is not a function

Don't need to use this method:

 .map((res: Response) => res.json() );

Just use this simple method instead of the previous method. hopefully you'll get your result:

.map(res => res );

Adding a month to a date in T SQL

DateAdd(m,1,reference_dt)

will add a month to the column value

Delete a row in DataGridView Control in VB.NET

Assuming you are using Windows forms, you could allow the user to select a row and in the delete key click event. It is recommended that you allow the user to select 1 row only and not a group of rows (myDataGridView.MultiSelect = false)

Private Sub pbtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If myDataGridView.SelectedRows.Count > 0 Then
            'you may want to add a confirmation message, and if the user confirms delete
            myDataGridView.Rows.Remove(myDataGridView.SelectedRows(0))
        Else
            MessageBox.Show("Select 1 row before you hit Delete")
        End If

    End Sub

Note that this will not delete the row form the database until you perform the delete in the database.

Binding multiple events to a listener (without JQuery)?

ES2015:

let el = document.getElementById("el");
let handler =()=> console.log("changed");
['change', 'keyup', 'cut'].forEach(event => el.addEventListener(event, handler));

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

How do I force Postgres to use a particular index?

Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.

As a very blunt hammer, useful for testing, you can use the enable_seqscan and enable_indexscan parameters. See:

These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_ params and walk away.

Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?

  • For small tables, it's faster to do sequential scans.
  • Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
  • Your planner settings might be causing problems.

See also this old newsgroup post.

Hibernate: flush() and commit()

By default flush mode is AUTO which means that: "The Session is sometimes flushed before query execution in order to ensure that queries never return stale state", but most of the time session is flushed when you commit your changes. Manual calling of the flush method is usefull when you use FlushMode=MANUAL or you want to do some kind of optimization. But I have never done this so I can't give you practical advice.

How to include view/partial specific styling in AngularJS

Awesome, thank you!! Just had to make a few adjustments to get it working with ui-router:

    var app = app || angular.module('app', []);

    app.directive('head', ['$rootScope', '$compile', '$state', function ($rootScope, $compile, $state) {

    return {
        restrict: 'E',
        link: function ($scope, elem, attrs, ctrls) {

            var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
            var el = $compile(html)($scope)
            elem.append(el);
            $scope.routeStyles = {};

            function applyStyles(state, action) {
                var sheets = state ? state.css : null;
                if (state.parent) {
                    var parentState = $state.get(state.parent)
                    applyStyles(parentState, action);
                }
                if (sheets) {
                    if (!Array.isArray(sheets)) {
                        sheets = [sheets];
                    }
                    angular.forEach(sheets, function (sheet) {
                        action(sheet);
                    });
                }
            }

            $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {

                applyStyles(fromState, function(sheet) {
                    delete $scope.routeStyles[sheet];
                    console.log('>> remove >> ', sheet);
                });

                applyStyles(toState, function(sheet) {
                    $scope.routeStyles[sheet] = sheet;
                    console.log('>> add >> ', sheet);
                });
            });
        }
    }
}]);

Random string generation with upper case letters and digits

I'd do it this way:

import random
from string import digits, ascii_uppercase

legals = digits + ascii_uppercase

def rand_string(length, char_set=legals):

    output = ''
    for _ in range(length): output += random.choice(char_set)
    return output

Or just:

def rand_string(length, char_set=legals):

    return ''.join( random.choice(char_set) for _ in range(length) )

How can I add items to an empty set in python

D = {} is a dictionary not set.

>>> d = {}
>>> type(d)
<type 'dict'>

Use D = set():

>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])

Why does the C++ STL not provide any "tree" containers?

All STL container are externally represented as "sequences" with one iteration mechanism. Trees don't follow this idiom.

PHP mkdir: Permission denied problem

Fix the permissions of the directory you try to create a directory in.

What does it mean to "call" a function in Python?

When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:

def add(a,b):
    return a + b

you would call the function like this:

add(3,5)

which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:

answer = add(4,7)

Which would set the variable answer equal to 11 in this case.

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

I've solved using only @JsonIgnore like @kryger has suggested. So your getter will become:

@JsonIgnore
public String getEncryptedPwd() {
    return this.encryptedPwd;
}

You can set @JsonIgnore of course on field, setter or getter like described here.

And, if you want to protect encrypted password only on serialization side (e.g. when you need to login your users), add this @JsonProperty annotation to your field:

@JsonProperty(access = Access.WRITE_ONLY)
private String encryptedPwd;

More info here.

Select values of checkbox group with jQuery

I'm not sure about the "@" used in the selector. At least with the latest jQuery, I had to remove the @ to get this to function with two different checkbox arrays, otherwise all checked items were selected for each array:

var items = [];
$("input[name='items[]']:checked").each(function(){items.push($(this).val());});

var about = [];
$("input[name='about[]']:checked").each(function(){about.push($(this).val());});

Now both, items and about work.

What's a standard way to do a no-op in python?

Use pass for no-op:

if x == 0:
  pass
else:
  print "x not equal 0"

And here's another example:

def f():
  pass

Or:

class c:
  pass

Get the first N elements of an array?

Use array_slice()

This is an example from the PHP manual: array_slice

$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

There is only a small issue

If the array indices are meaningful to you, remember that array_slice will reset and reorder the numeric array indices. You need the preserve_keys flag set to trueto avoid this. (4th parameter, available since 5.0.2).

Example:

$output = array_slice($input, 2, 3, true);

Output:

array([3]=>'c', [4]=>'d', [5]=>'e');

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Along with the embed, I also had to install the Google Cast extension in my browser.

<iframe width="1280" height="720" src="https://www.youtube.com/embed/4u856utdR94" frameborder="0" allowfullscreen></iframe>

How do I convert an NSString value to NSData?

NSString *str = @"helowrld";
// This converts the string to an NSData object
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

you can take reference from this link

Git:nothing added to commit but untracked files present

In case someone cares just about the error nothing added to commit but untracked files present (use "git add" to track) and not about Please move or remove them before you can merge.. You might have a look at the answers on Git - Won't add files?

There you find at least 2 good candidates for the issue in question here: that you either are in a subfolder or in a parent folder, but not in the actual repo folder. If you are in the directory one level too high, this will definitely raise that message "nothing added to commit…", see my answer in the link for details. I do not know if the same message occurs when you are in a subfolder, but it is likely. That could fit to your explanations.

How to execute a remote command over ssh with arguments?

This is an example that works on the AWS Cloud. The scenario is that some machine that booted from autoscaling needs to perform some action on another server, passing the newly spawned instance DNS via SSH

# Get the public DNS of the current machine (AWS specific)
MY_DNS=`curl -s http://169.254.169.254/latest/meta-data/public-hostname`


ssh \
    -o StrictHostKeyChecking=no \
    -i ~/.ssh/id_rsa \
    [email protected] \
<< EOF
cd ~/
echo "Hey I was just SSHed by ${MY_DNS}"
run_other_commands
# Newline is important before final EOF!

EOF

How to clear a chart from a canvas so that hover events cannot be triggered?

This is the only thing that worked for me:

document.getElementById("chartContainer").innerHTML = '&nbsp;';
document.getElementById("chartContainer").innerHTML = '<canvas id="myCanvas"></canvas>';
var ctx = document.getElementById("myCanvas").getContext("2d");

Calling a class function inside of __init__

I think that your problem is actually with not correctly indenting init function.It should be like this

class MyClass():
     def __init__(self, filename):
          pass

     def parse_file():
          pass

PHP page redirect

The header() function in PHP does this, but make sure that you call it before any other file contents are sent to the browser or else you will receive an error.

JavaScript is an alternative if you have already sent the file contents.

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

Getting current directory in .NET web application

Use this code:

 HttpContext.Current.Server.MapPath("~")

Detailed Reference:

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot

and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop

For example, if you call Server.MapPath in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342

then:

Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward (/) or backward slash (), the MapPath method returns a path as if Path were a full, virtual path.

If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Footnotes

Server.MapPath(null) and Server.MapPath("") will produce this effect too.

How do I discard unstaged changes in Git?

My favorite is

git checkout -p

That lets you selectively revert chunks.

See also:

git add -p

What is the difference between `Enum.name()` and `Enum.toString()`?

Use toString() when you want to present information to a user (including a developer looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overridden.

How to make shadow on border-bottom?

The issue is shadow coming out the side of the containing div. In order to avoid this, the blur value must equal the absolute value of the spread value.

_x000D_
_x000D_
div {_x000D_
  -webkit-box-shadow: 0 4px 6px -6px #222;_x000D_
  -moz-box-shadow: 0 4px 6px -6px #222;_x000D_
  box-shadow: 0 4px 6px -6px #222;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
_x000D_
_x000D_

covered in depth here

Java Pass Method as Parameter

I'm not a java expert but I solve your problem like this:

@FunctionalInterface
public interface AutoCompleteCallable<T> {
  String call(T model) throws Exception;
}

I define the parameter in my special Interface

public <T> void initialize(List<T> entries, AutoCompleteCallable getSearchText) {.......
//call here
String value = getSearchText.call(item);
...
}

Finally, I implement getSearchText method while calling initialize method.

initialize(getMessageContactModelList(), new AutoCompleteCallable() {
          @Override
          public String call(Object model) throws Exception {
            return "custom string" + ((xxxModel)model.getTitle());
          }
        })

How do I simulate placeholder functionality on input date field?

CSS

_x000D_
_x000D_
input[type="date"] {position: relative;}_x000D_
input[type="date"]:before {_x000D_
 position: absolute;left: 0px;top: 0px;_x000D_
 content: "Enter DOB";_x000D_
 color: #999;_x000D_
 width: 100%;line-height: 32px;_x000D_
}_x000D_
input[type="date"]:valid:before {display: none;}
_x000D_
<input type="date" required />
_x000D_
_x000D_
_x000D_

Java Best Practices to Prevent Cross Site Scripting

The normal practice is to HTML-escape any user-controlled data during redisplaying in JSP, not during processing the submitted data in servlet nor during storing in DB. In JSP you can use the JSTL (to install it, just drop jstl-1.2.jar in /WEB-INF/lib) <c:out> tag or fn:escapeXml function for this. E.g.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<p>Welcome <c:out value="${user.name}" /></p>

and

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="username" value="${fn:escapeXml(param.username)}">

That's it. No need for a blacklist. Note that user-controlled data covers everything which comes in by a HTTP request: the request parameters, body and headers(!!).

If you HTML-escape it during processing the submitted data and/or storing in DB as well, then it's all spread over the business code and/or in the database. That's only maintenance trouble and you will risk double-escapes or more when you do it at different places (e.g. & would become &amp;amp; instead of &amp; so that the enduser would literally see &amp; instead of & in view. The business code and DB are in turn not sensitive for XSS. Only the view is. You should then escape it only right there in view.

See also:

HTML - Alert Box when loading page

you need a tiny bit of Javascript.

<script type="text/javascript">
window.onload = function(){ 
                alert("Hi there");
                }
</script>

This is only slightly different from Adam's answer. The effective difference is that this one alerts when the browser considers the page fully loaded, while Adam's alerts when the browser scans part the <script> tag in the text. The difference is with, for example, images, which may continue loading in parallel for a while.

javascript return true or return false when and how to use it?

I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.

Basically, when you have something like:

<form onsubmit="return callSomeFunction();"></form>

or

<a href="#" onclick="return callSomeFunction();"></a>`

and callSomeFunction() returns true, then the form or a will submit, otherwise it won't.

Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.

How to Get a Sublist in C#

Reverse the items in a sub-list

int[] l = {0, 1, 2, 3, 4, 5, 6};
var res = new List<int>();
res.AddRange(l.Where((n, i) => i < 2));
res.AddRange(l.Where((n, i) => i >= 2 && i <= 4).Reverse());
res.AddRange(l.Where((n, i) => i > 4));

Gives 0,1,4,3,2,5,6

How can I simulate mobile devices and debug in Firefox Browser?

You could use the Firefox add-on User Agent Overrider. With this add-on you can use whatever user agent you want, for examlpe:

Firefox 28/Android: Mozilla/5.0 (Android; Mobile; rv:28.0) Gecko/24.0 Firefox/28.0

If your website detects mobile devices through the user agent then you can test your layout this way.


Update Nov '17:

Due to the release of Firefox 57 and the introduction of web extension this add-on sadly is no longer available. Alternatively you can edit the Firefox preference general.useragent.override in your configuration:

  1. In the address bar type about:config
  2. Search for general.useragent.override
  3. If the preference doesn't exist, right-click on the about:config page, click New, then select String
  4. Name the new preference general.useragent.override
  5. Set the value to the user agent you want

Google API for location, based on user IP address

Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country, X-AppEngine-Region, X-AppEngine-City and X-AppEngine-CityLatLong headers.

An example looks like this:

X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733

Non greedy (reluctant) regex matching in sed?

sed certainly has its place but this not not one of them !

As Dee has pointed out: Just use cut. It is far simpler and much more safe in this case. Here's an example where we extract various components from the URL using Bash syntax:

url="http://www.suepearson.co.uk/product/174/71/3816/"

protocol=$(echo "$url" | cut -d':' -f1)
host=$(echo "$url" | cut -d'/' -f3)
urlhost=$(echo "$url" | cut -d'/' -f1-3)
urlpath=$(echo "$url" | cut -d'/' -f4-)

gives you:

protocol = "http"
host = "www.suepearson.co.uk"
urlhost = "http://www.suepearson.co.uk"
urlpath = "product/174/71/3816/"

As you can see this is a lot more flexible approach.

(all credit to Dee)

Can I use a min-height for table, tr or td?

It's not a nice solution but try it like this:

<table>
    <tr>
        <td>
            <div>Lorem</div>
        </td>
    </tr>
    <tr>
        <td>
            <div>Ipsum</div>
        </td>
    </tr>
</table>

and set the divs to the min-height:

div {
    min-height: 300px;
}

Hope this is what you want ...

How to kill a running SELECT statement

To kill a session in Oracle, you use the ALTER SYSTEM KILL SESSION command.

Details here: http://www.oracle-base.com/articles/misc/KillingOracleSessions.php

How to receive serial data using android bluetooth

Take a look at incredible Bluetooth Serial class that has onResume() ability that helped me so much. I hope this helps ;)

SharePoint : How can I programmatically add items to a custom list instance

This is how it was on the Microsoft site, with me just tweaking the SPSite and SPWeb since these might vary from environment to environment and it helps not to have to hard-code these:

using (SPSite oSiteCollection = new SPSite(SPContext.Current.Site.Url))
{
    using (SPWeb oWeb = oSiteCollection.OpenWeb(SPContext.Current.Web))
    {
        SPList oList = oWeb.Lists["Announcements"];
        // You may also use 
        // SPList oList = oWeb.GetList("/Lists/Announcements");
        // to avoid querying all of the sites' lists
        SPListItem oListItem = oList.Items.Add();
        oListItem["Title"] = "My Item";
        oListItem["Created"] = new DateTime(2004, 1, 23);
        oListItem["Modified"] = new DateTime(2005, 10, 1);
        oListItem["Author"] = 3;
        oListItem["Editor"] = 3;
        oListItem.Update();
    }
}

Source: SPListItemClass (Microsoft.SharePoint). (2012). Retrieved February 22, 2012, from http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.aspx.

How to picture "for" loop in block representation of algorithm

What's a "block scheme"?

If I were drawing it, I might draw a box with "for each x in y" written in it.

If you're drawing a flowchart, there's always a loop with a decision box.

Nassi-Schneiderman diagrams have a loop construct you could use.

Better way to sum a property value in an array

You can do the following:

$scope.traveler.map(o=>o.Amount).reduce((a,c)=>a+c);

Take n rows from a spark dataframe and pass to toPandas()

You could get first rows of Spark DataFrame with head and then create Pandas DataFrame:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])

df_pandas = pd.DataFrame(df.head(3), columns=df.columns)

In [4]: df_pandas
Out[4]: 
     name  age
0   Alice    1
1     Jim    2
2  Sandra    3

HTML - Display image after selecting filename

Here You Go:

HTML

<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <input type='file' onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
</body>
</html>

Script:

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

Live Demo

What do \t and \b do?

\t is the tab character, and is doing exactly what you're anticipating based on the action of \b - it goes to the next tab stop, then gets decremented, and then goes to the next tab stop (which is in this case the same tab stop, because of the \b.

Preserve Line Breaks From TextArea When Writing To MySQL

Two solutions for this:

  1. PHP function nl2br():

    e.g.,

    echo nl2br("This\r\nis\n\ra\nstring\r");
    
    // will output
    This<br />
    is<br />
    a<br />
    string<br />
    
  2. Wrap the input in <pre></pre> tags.

    See: W3C Wiki - HTML/Elements/pre

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

 Use the below code to solve the CertPathValidatorException issue.


 Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(YOUR_BASE_URL)
        .client(getUnsafeOkHttpClient().build())
        .build();


  public static OkHttpClient.Builder getUnsafeOkHttpClient() {

    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[]{};
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

For more details visit https://mobikul.com/android-retrofit-handling-sslhandshakeexception/

JSHint and jQuery: '$' is not defined

If you're using an IntelliJ editor, under

  • Preferences/Settings
    • Javascript
      • Code Quality Tools
        • JSHint
          • Predefined (at bottom), click Set

You can type in anything, for instance console:false, and it will add that to the list (.jshintrc) as well - as a global.

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

Clear() set the Text property to nothing. So txtbox1.Text = Nothing does the same thing as clear. An empty string (also available through String.Empty) is not a null reference, but has no value of course.

Set specific precision of a BigDecimal

 BigDecimal decPrec = (BigDecimal)yo.get("Avg");
 decPrec = decPrec.setScale(5, RoundingMode.CEILING);
 String value= String.valueOf(decPrec);

This way you can set specific precision of a BigDecimal.

The value of decPrec was 1.5726903423607562595809913132345426 which is rounded off to 1.57267.

div hover background-color change?

div hover background color change

Try like this:

.class_name:hover{
    background-color:#FF0000;
}

LF will be replaced by CRLF in git - What is that and is it important?

In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.

If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line

git config core.autocrlf true

If you want to make an intelligent decision how git should handle this, read the documentation

Here is a snippet

Formatting and Whitespace

Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.

core.autocrlf

If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.

Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:

$ git config --global core.autocrlf true

If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:

$ git config --global core.autocrlf input

This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.

If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:

$ git config --global core.autocrlf false

how to check if the input is a number or not in C?

A self-made solution:

bool isNumeric(const char *str) 
{
    while(*str != '\0')
    {
        if(*str < '0' || *str > '9')
            return false;
        str++;
    }
    return true;
}

Note that this solution should not be used in production-code, because it has severe limitations. But I like it for understanding C-Strings and ASCII.

Validate Dynamically Added Input fields

In case you have a form you can add a class name as such:

<form id="my-form">
  <input class="js-input" type="text" name="samplename" />
  <input class="js-input" type="text" name="samplename" />
  <input class="submit" type="submit" value="Submit" />
</form>

you can then use the addClassRules method of validator to add your rules like this and this will apply to all the dynamically added inputs:

$(document).ready(function() {
  $.validator.addClassRules('js-input', {
    required: true,
  });
  //validate the form
  $('#my-form').validate();
});

design a stack such that getMinimum( ) should be O(1)

I found this solution here

struct StackGetMin {
  void push(int x) {
    elements.push(x);
    if (minStack.empty() || x <= minStack.top())
      minStack.push(x);
  }
  bool pop() {
    if (elements.empty()) return false;
    if (elements.top() == minStack.top())
      minStack.pop();
    elements.pop();
    return true;
  }
  bool getMin(int &min) {
    if (minStack.empty()) {
      return false;
    } else {
      min = minStack.top();
      return true;
    }
  }
  stack<int> elements;
  stack<int> minStack;
};

MySQL error 1241: Operand should contain 1 column(s)

Syntax error, remove the ( ) from select.

insert into table2 (name, subject, student_id, result)
select name, subject, student_id, result
from table1;

Safely remove migration In Laravel

This works for me:

  1. I deleted all tables in my database, mainly the migrations table.
  2. php artisan migrate:refresh

in laravel 5.5.43

PowerShell try/catch/finally

That is very odd.

I went through ItemNotFoundException's base classes and tested the following multiple catches to see what would catch it:

try {
  remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
  write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
  write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
  write-host 'RuntimeException'
}
catch [System.SystemException] {
  write-host 'SystemException'
}
catch [System.Exception] {
  write-host 'Exception'
}
catch {
  write-host 'well, darn'
}

As it turns out, the output was 'RuntimeException'. I also tried it with a different exception CommandNotFoundException:

try {
  do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
  write-host 'CommandNotFoundException'
}
catch {
  write-host 'well, darn'
}

That output 'CommandNotFoundException' correctly.

I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type they could and then use a switch. The following just catches Exception instead of RuntimeException, but is the switch equivalent of my first example that checks all base types of ItemNotFoundException:

try {
  Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
  switch($_.Exception.GetType().FullName) {
    'System.Management.Automation.ItemNotFoundException' {
      write-host 'ItemNotFound'
    }
    'System.Management.Automation.SessionStateException' {
      write-host 'SessionState'
    }
    'System.Management.Automation.RuntimeException' {
      write-host 'RuntimeException'
    }
    'System.SystemException' {
      write-host 'SystemException'
    }
    'System.Exception' {
      write-host 'Exception'
    }
    default {'well, darn'}
  }
}

This writes 'ItemNotFound', as it should.

Using jQuery to test if an input has focus

What I wound up doing is creating an arbitrary class called .elementhasfocus which is added and removed within the jQuery focus() function. When the hover() function runs on mouse out, it checks for .elementhasfocus:

if(!$("#quotebox").is(".boxhasfocus")) $(this).removeClass("box_border");

So if it doesn't have that class (read: no elements within the div have focus) the border is removed. Otherwise, nothing happens.

Best way to run scheduled tasks

One option would be to set up a windows service and get that to call your scheduled task.

In winforms I've used Timers put don't think this would work well in ASP.NET

Undo scaffolding in Rails

rails d scaffold <scaffoldname>

Also, make sure you undo the migration you made either by rollback or to a particular version.

MySQL SELECT DISTINCT multiple columns

Another simple way to do it is with concat()

SELECT DISTINCT(CONCAT(a,b)) AS cc FROM my_table GROUP BY (cc);

require(vendor/autoload.php): failed to open stream

If you get the error also when you run

composer install

Just run this command first

composer dump-autoload

This command will clean up all compiled files and their paths.

Accessing JSON object keys having spaces

The way to do this is via the bracket notation.

_x000D_
_x000D_
var test = {_x000D_
    "id": "109",_x000D_
    "No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
_x000D_
_x000D_

For more info read out here:

Forward request headers from nginx proxy server

The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:

underscores_in_headers on;

This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997

I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.

What does the Visual Studio "Any CPU" target mean?

Here's a quick overview that explains the different build targets.

From my own experience, if you're looking to build a project that will run on both x86 and x64 platforms, and you don't have any specific x64 optimizations, I'd change the build to specifically say "x86."

The reason for this is sometimes you can get some DLL files that collide or some code that winds up crashing WoW in the x64 environment. By specifically specifying x86, the x64 OS will treat the application as a pure x86 application and make sure everything runs smoothly.

Multiple cases in switch statement

You can also have conditions that are completely different

            bool isTrue = true;

            switch (isTrue)
            {
                case bool ifTrue when (ex.Message.Contains("not found")):
                case bool ifTrue when (thing.number = 123):
                case bool ifTrue when (thing.othernumber != 456):
                    response.respCode = 5010;
                    break;
                case bool ifTrue when (otherthing.text = "something else"):
                    response.respCode = 5020;
                    break;
                default:
                    response.respCode = 5000;
                    break;
            }

URL encode sees “&” (ampersand) as “&amp;” HTML entity

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&amp;/g, "&"));

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

Loop through a date range with JavaScript

Let us assume you got the start date and end date from the UI and stored it in the scope variable in the controller.

Then declare an array which will get reset on every function call so that on the next call for the function the new data can be stored.

var dayLabel = [];

Remember to use new Date(your starting variable) because if you dont use the new date and directly assign it to variable the setDate function will change the origional variable value in each iteration`

for (var d = new Date($scope.startDate); d <= $scope.endDate; d.setDate(d.getDate() + 1)) {
                dayLabel.push(new Date(d));
            }

What is w3wp.exe?

An Internet Information Services (IIS) worker process is a windows process (w3wp.exe) which runs Web applications, and is responsible for handling requests sent to a Web Server for a specific application pool.

It is the worker process for IIS. Each application pool creates at least one instance of w3wp.exe and that is what actually processes requests in your application. It is not dangerous to attach to this, that is just a standard windows message.

<div style display="none" > inside a table not working

simply change <div> to <tbody>

<table id="authenticationSetting" style="display: none">
  <tbody id="authenticationOuterIdentityBlock" style="display: none;">
    <tr>
      <td class="orionSummaryHeader">
        <orion:message key="policy.wifi.enterprise.authentication.outeridentitity" />:</td>
      <td class="orionSummaryColumn">
        <orion:textbox id="authenticationOuterIdentity" size="30" />
      </td>
    </tr>
  </tbody>
</table>

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

You can increase the memory allowed to php script by executing the following line above all the codes in the script:

ini_set('memory_limit','-1'); // enabled the full memory available.

And also de allocate the unwanted variables in the script.

Check this php library : Freeing memory with PHP

Mercurial: how to amend the last commit?

GUI equivalent for hg commit --amend:

This also works from TortoiseHG's GUI (I'm using v2.5):

Swich to the 'Commit' view or, in the workbench view, select the 'working directory' entry. The 'Commit' button has an option named 'Amend current revision' (click the button's drop-down arrow to find it).

enter image description here

          ||
          ||
          \/

enter image description here

Caveat emptor:

This extra option will only be enabled if the mercurial version is at least 2.2.0, and if the current revision is not public, is not a patch and has no children. [...]

Clicking the button will call 'commit --amend' to 'amend' the revision.

More info about this on the THG dev channel

How do I debug jquery AJAX calls?

You can use the "Network" tab in the browser (shift+ctrl+i) or Firebug.
But an even better solution - in my opinion - is in addition to use an external program such as Fiddler to monitor/catch the traffic between browser and server.

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

Resolution fix: For me, the problem was related to active chrome sessions. I closed all of my chrome browser sessions and then tried building to chrome again. I am using Visual Studio Professional 2017 version 15.3.2. The VS application I was running into build errors with was a WebAPI project. When trying to click the green play button, I was getting dialog error stating "Unable to start the program 'http://localhost:18980/'. An operation is not legal in the current state. Hopefully this post helps someone.

Installing tensorflow with anaconda in windows

The following command from inside your command window (and preferably, conda environment) will work provided you have an Nvidia graphics card.

conda install tensorflow-gpu 

Getting error "No such module" using Xcode, but the framework is there

For what it's worth (I'm new to this using Xcode 7.2/Swift 2), but I noticed that just having the .swift file from the library in the project directory automatically gives you access to it and does not need the using statement.

Example: I'm using SwiftyJSON and just having the SwiftyJSON.swift file in the project was all I needed. The using statement was actually giving me the 'no such module' error and taking it out resolved it, and it works fine.

php - insert a variable in an echo string

Variable interpolation does not happen in single quotes. You need to use double quotes as:

$i = 1
echo "<p class=\"paragraph$i\"></p>";
++i;

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

While most of the answers here are valid, for me the issue was that I was running long processes as part of npm run start which caused the timeout.

I found the solution here and to summarize it, I just had to move npm run build to a postinstall task.

In other words, I changed this:

"start": "npm run build && node server.js"

to this:

"postinstall": "npm run build",
"start": "node server.js"

Come to think of this, it totally makes sense because this error (which used to appear occasionally) was becoming more and more common as my app kept growing.

SQL UPDATE with sub-query that references the same table in MySQL

I needed this for SQL Server. Here it is:

UPDATE user_account 
SET student_education_facility_id = cnt.education_facility_id
from  (
   SELECT user_account_id,education_facility_id
   FROM user_account 
   WHERE user_type = 'ROLE_TEACHER'
) as cnt
WHERE user_account.user_type = 'ROLE_STUDENT' and cnt.user_account_id = user_account.teacher_id

I think it works with other RDBMSes (please confirm). I like the syntax because it's extensible.

The format I needed was this actually:

UPDATE table1 
SET f1 = cnt.computed_column
from  (
   SELECT id,computed_column --can be any complex subquery
   FROM table1
) as cnt
WHERE cnt.id = table1.id

Commit only part of a file in Git

If it's on Windows platform, in my opinion git gui is very good tool to stage/commit few lines from unstaged file

1. Hunk wise:

  • Select the file from unstagged Changes section
  • Right click chunk of code which needs to be staged
  • Select Stage Hunk for commit

2. Line wise:

  • Select the file from unstagged Changes section
  • Select the line/lines to be staged
  • Right click and select Stage Lines for commit

3. If you want to stage the complete file except couple of lines:

  • Select the file from unstagged Changes section
  • Press Ctrl+T (Stage file to commit)
  • Selected file now moves to Staged Changes Section
  • Select the line/lines be staged
  • Right click and select UnStage Lines for commit

vertical divider between two columns in bootstrap

If you want a vertical divider between 2 columns, all you need is add

class="col-6 border-left" 

to one of your column div-s

BUT

In the world of responsive design, you may need to make it disappear sometimes.

The solution is disappearing <hr> + disappearing <div> + margin-left: -1px;

<div class="container">
  <div class="row">
    <div class="col-md-7">
      1 of 2
    </div>
    <div class="border-left d-sm-none d-md-block" style="width: 0px;"></div>
    <div class="col-md-5" style="margin-left: -1px;">
    <hr class="d-sm-block d-md-none">
      2 of 2
    </div>
  </div>
</div>

https://jsfiddle.net/8z1pag7s/

tested on Bootstrap 4.1

Spring JPA @Query with LIKE

Easy to use following (no need use CONCAT or ||):

@Query("from Service s where s.category.typeAsString like :parent%")
List<Service> findAll(@Param("parent") String parent);

Documented in: http://docs.spring.io/spring-data/jpa/docs/current/reference/html.

Error: Jump to case label

Declaration of new variables in case statements is what causing problems. Enclosing all case statements in {} will limit the scope of newly declared variables to the currently executing case which solves the problem.

switch(choice)
{
    case 1: {
       // .......
    }break;
    case 2: {
       // .......
    }break;
    case 3: {
       // .......
    }break;
}    

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

How to export data from Spark SQL to CSV

The simplest way is to map over the DataFrame's RDD and use mkString:

  df.rdd.map(x=>x.mkString(","))

As of Spark 1.5 (or even before that) df.map(r=>r.mkString(",")) would do the same if you want CSV escaping you can use apache commons lang for that. e.g. here's the code we're using

 def DfToTextFile(path: String,
                   df: DataFrame,
                   delimiter: String = ",",
                   csvEscape: Boolean = true,
                   partitions: Int = 1,
                   compress: Boolean = true,
                   header: Option[String] = None,
                   maxColumnLength: Option[Int] = None) = {

    def trimColumnLength(c: String) = {
      val col = maxColumnLength match {
        case None => c
        case Some(len: Int) => c.take(len)
      }
      if (csvEscape) StringEscapeUtils.escapeCsv(col) else col
    }
    def rowToString(r: Row) = {
      val st = r.mkString("~-~").replaceAll("[\\p{C}|\\uFFFD]", "") //remove control characters
      st.split("~-~").map(trimColumnLength).mkString(delimiter)
    }

    def addHeader(r: RDD[String]) = {
      val rdd = for (h <- header;
                     if partitions == 1; //headers only supported for single partitions
                     tmpRdd = sc.parallelize(Array(h))) yield tmpRdd.union(r).coalesce(1)
      rdd.getOrElse(r)
    }

    val rdd = df.map(rowToString).repartition(partitions)
    val headerRdd = addHeader(rdd)

    if (compress)
      headerRdd.saveAsTextFile(path, classOf[GzipCodec])
    else
      headerRdd.saveAsTextFile(path)
  }

Visual Studio Code Search and Replace with Regular Expressions

So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ??F on Mac to enable search and replace tool:

Visual studio code's search & replace tab If you mean to disable the code, you just have to put <h1> in search, and replace to ####.

But if you want to use this regex instead, you may enable it in the icon: .* and use the regex: <h1>(.+?)<\/h1> and replace to: #### $1.

And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:

How do I compare strings in GoLang?

== is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString do not contain "a", but "a\n" (if you look closely, you'll see the extra line break in your example output).

You can use the strings.TrimRight function to remove trailing whitespaces from your input:

if strings.TrimRight(input, "\n") == "a" {
    // ...
}

How to automatically allow blocked content in IE?

Alternatively, as long as permissions are not given, the good old <noscript> tags works. You can cover the page in css and tell them what's wrong, ... without using javascript ofcourse.

sql try/catch rollback/commit - preventing erroneous commit after rollback

In your first example, you are correct. The batch will hit the commit transaction, regardless of whether the try block fires.

In your second example, I agree with other commenters. Using the success flag is unnecessary.

I consider the following approach to be, essentially, a light weight best practice approach.

If you want to see how it handles an exception, change the value on the second insert from 255 to 256.

CREATE TABLE #TEMP ( ID TINYINT NOT NULL );
INSERT  INTO #TEMP( ID ) VALUES  ( 1 )

BEGIN TRY
    BEGIN TRANSACTION

    INSERT  INTO #TEMP( ID ) VALUES  ( 2 )
    INSERT  INTO #TEMP( ID ) VALUES  ( 255 )

    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    DECLARE 
        @ErrorMessage NVARCHAR(4000),
        @ErrorSeverity INT,
        @ErrorState INT;
    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();
    RAISERROR (
        @ErrorMessage,
        @ErrorSeverity,
        @ErrorState    
        );
    ROLLBACK TRANSACTION
END CATCH

SET NOCOUNT ON

SELECT ID
FROM #TEMP

DROP TABLE #TEMP

How do I "Add Existing Item" an entire directory structure in Visual Studio?

I just want to point out that two of the solutions offered previously,

  • Drag and drop from Windows Explorer
  • Show All Files and then include in project.

do not do what the question asked for:

Include in project while preserving the directory structure.

At least not in my case (C++/CLI project Visual Studio 2013 on Windows 7).

In Visual Studio, once you are back in the normal view (not Show All Files), the files you added are all listed at the top level of the project.

Yes, on disk they still reside where they were, but in Solution Explorer they are loose.

I did not find a way around it except recreating the directory structure in Solution Explorer and then doing Add Existing Items at the right location.

C# find biggest number

If your numbers are a, b and c then:

    int a = 1;
    int b = 2;
    int c = 3;

    int d =  a > b ? a : b;
    return c > d ? c : d;

This could turn into one of those "how many different ways can we do this" type questions!

Could not create the Java virtual machine

Just be careful. You will get this message if you try to enter a command that doesn't exist like this

/usr/bin/java -v

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

Since your server already includes the sites-enabled folder ( notice the include /etc/nginx/sites-enabled/* line ), then you better use that.

  1. Create a file inside /etc/nginx/sites-available and call it whatever you want, I'll call it django since it's a djanog server

    sudo touch /etc/nginx/sites-available/django
    
  2. Then create a symlink that points to it

    sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
    
  3. Then edit that file with whatever file editor you use, vim or nano or whatever and create the server inside it

    server {
        # hostname or ip or multiple separated by spaces
        server_name localhost example.com 192.168.1.1; #change to your setting
        location / {
            root /home/techcee/scrapbook/local/lib/python2.7/site-packages/django/__init__.pyc/;
        }
    }
    
  4. Restart or reload nginx settings

    sudo service nginx reload
    

Note I believe that your configuration like this probably won't work yet because you need to pass it to a fastcgi server or something, but at least this is how you could create a valid server

annotation to make a private method public only for test classes

Okay, so here we have two things that are being mixed. First thing, is when you need to mark something to be used only on test, which I agree with @JB Nizet, using the guava annotation would be good.

A different thing, is to test private methods. Why should you test private methods from the outside? I mean.. You should be able to test the object by their public methods, and at the end that its behavior. At least, that we are doing and trying to teach to junior developers, that always try to test private methods (as a good practice).

Hiding a button in Javascript

<script>
    $('#btn_hide').click( function () {
      $('#btn_hide').hide();
    });
</script>
<input type="button" id="btn_hide"/>

this will be enough

How to handle errors with boto3?

As a few others already mentioned, you can catch certain errors using the service client (service_client.exceptions.<ExceptionClass>) or resource (service_resource.meta.client.exceptions.<ExceptionClass>), however it is not well documented (also which exceptions belong to which clients). So here is how to get the complete mapping at time of writing (January 2020) in region EU (Ireland) (eu-west-1):

import boto3, pprint

region_name = 'eu-west-1'
session = boto3.Session(region_name=region_name)
exceptions = {
  service: list(boto3.client('sts').exceptions._code_to_exception)
  for service in session.get_available_services()
}
pprint.pprint(exceptions, width=20000)

Here is a subset of the pretty large document:

{'acm': ['InvalidArnException', 'InvalidDomainValidationOptionsException', 'InvalidStateException', 'InvalidTagException', 'LimitExceededException', 'RequestInProgressException', 'ResourceInUseException', 'ResourceNotFoundException', 'TooManyTagsException'],
 'apigateway': ['BadRequestException', 'ConflictException', 'LimitExceededException', 'NotFoundException', 'ServiceUnavailableException', 'TooManyRequestsException', 'UnauthorizedException'],
 'athena': ['InternalServerException', 'InvalidRequestException', 'TooManyRequestsException'],
 'autoscaling': ['AlreadyExists', 'InvalidNextToken', 'LimitExceeded', 'ResourceContention', 'ResourceInUse', 'ScalingActivityInProgress', 'ServiceLinkedRoleFailure'],
 'cloudformation': ['AlreadyExistsException', 'ChangeSetNotFound', 'CreatedButModifiedException', 'InsufficientCapabilitiesException', 'InvalidChangeSetStatus', 'InvalidOperationException', 'LimitExceededException', 'NameAlreadyExistsException', 'OperationIdAlreadyExistsException', 'OperationInProgressException', 'OperationNotFoundException', 'StackInstanceNotFoundException', 'StackSetNotEmptyException', 'StackSetNotFoundException', 'StaleRequestException', 'TokenAlreadyExistsException'],
 'cloudfront': ['AccessDenied', 'BatchTooLarge', 'CNAMEAlreadyExists', 'CannotChangeImmutablePublicKeyFields', 'CloudFrontOriginAccessIdentityAlreadyExists', 'CloudFrontOriginAccessIdentityInUse', 'DistributionAlreadyExists', 'DistributionNotDisabled', 'FieldLevelEncryptionConfigAlreadyExists', 'FieldLevelEncryptionConfigInUse', 'FieldLevelEncryptionProfileAlreadyExists', 'FieldLevelEncryptionProfileInUse', 'FieldLevelEncryptionProfileSizeExceeded', 'IllegalFieldLevelEncryptionConfigAssociationWithCacheBehavior', 'IllegalUpdate', 'InconsistentQuantities', 'InvalidArgument', 'InvalidDefaultRootObject', 'InvalidErrorCode', 'InvalidForwardCookies', 'InvalidGeoRestrictionParameter', 'InvalidHeadersForS3Origin', 'InvalidIfMatchVersion', 'InvalidLambdaFunctionAssociation', 'InvalidLocationCode', 'InvalidMinimumProtocolVersion', 'InvalidOrigin', 'InvalidOriginAccessIdentity', 'InvalidOriginKeepaliveTimeout', 'InvalidOriginReadTimeout', 'InvalidProtocolSettings', 'InvalidQueryStringParameters', 'InvalidRelativePath', 'InvalidRequiredProtocol', 'InvalidResponseCode', 'InvalidTTLOrder', 'InvalidTagging', 'InvalidViewerCertificate', 'InvalidWebACLId', 'MissingBody', 'NoSuchCloudFrontOriginAccessIdentity', 'NoSuchDistribution', 'NoSuchFieldLevelEncryptionConfig', 'NoSuchFieldLevelEncryptionProfile', 'NoSuchInvalidation', 'NoSuchOrigin', 'NoSuchPublicKey', 'NoSuchResource', 'NoSuchStreamingDistribution', 'PreconditionFailed', 'PublicKeyAlreadyExists', 'PublicKeyInUse', 'QueryArgProfileEmpty', 'StreamingDistributionAlreadyExists', 'StreamingDistributionNotDisabled', 'TooManyCacheBehaviors', 'TooManyCertificates', 'TooManyCloudFrontOriginAccessIdentities', 'TooManyCookieNamesInWhiteList', 'TooManyDistributionCNAMEs', 'TooManyDistributions', 'TooManyDistributionsAssociatedToFieldLevelEncryptionConfig', 'TooManyDistributionsWithLambdaAssociations', 'TooManyFieldLevelEncryptionConfigs', 'TooManyFieldLevelEncryptionContentTypeProfiles', 'TooManyFieldLevelEncryptionEncryptionEntities', 'TooManyFieldLevelEncryptionFieldPatterns', 'TooManyFieldLevelEncryptionProfiles', 'TooManyFieldLevelEncryptionQueryArgProfiles', 'TooManyHeadersInForwardedValues', 'TooManyInvalidationsInProgress', 'TooManyLambdaFunctionAssociations', 'TooManyOriginCustomHeaders', 'TooManyOriginGroupsPerDistribution', 'TooManyOrigins', 'TooManyPublicKeys', 'TooManyQueryStringParameters', 'TooManyStreamingDistributionCNAMEs', 'TooManyStreamingDistributions', 'TooManyTrustedSigners', 'TrustedSignerDoesNotExist'],
 'cloudtrail': ['CloudTrailARNInvalidException', 'CloudTrailAccessNotEnabledException', 'CloudWatchLogsDeliveryUnavailableException', 'InsufficientDependencyServiceAccessPermissionException', 'InsufficientEncryptionPolicyException', 'InsufficientS3BucketPolicyException', 'InsufficientSnsTopicPolicyException', 'InvalidCloudWatchLogsLogGroupArnException', 'InvalidCloudWatchLogsRoleArnException', 'InvalidEventSelectorsException', 'InvalidHomeRegionException', 'InvalidKmsKeyIdException', 'InvalidLookupAttributesException', 'InvalidMaxResultsException', 'InvalidNextTokenException', 'InvalidParameterCombinationException', 'InvalidS3BucketNameException', 'InvalidS3PrefixException', 'InvalidSnsTopicNameException', 'InvalidTagParameterException', 'InvalidTimeRangeException', 'InvalidTokenException', 'InvalidTrailNameException', 'KmsException', 'KmsKeyDisabledException', 'KmsKeyNotFoundException', 'MaximumNumberOfTrailsExceededException', 'NotOrganizationMasterAccountException', 'OperationNotPermittedException', 'OrganizationNotInAllFeaturesModeException', 'OrganizationsNotInUseException', 'ResourceNotFoundException', 'ResourceTypeNotSupportedException', 'S3BucketDoesNotExistException', 'TagsLimitExceededException', 'TrailAlreadyExistsException', 'TrailNotFoundException', 'TrailNotProvidedException', 'UnsupportedOperationException'],
 'cloudwatch': ['InvalidParameterInput', 'ResourceNotFound', 'InternalServiceError', 'InvalidFormat', 'InvalidNextToken', 'InvalidParameterCombination', 'InvalidParameterValue', 'LimitExceeded', 'MissingParameter'],
 'codebuild': ['AccountLimitExceededException', 'InvalidInputException', 'OAuthProviderException', 'ResourceAlreadyExistsException', 'ResourceNotFoundException'],
 'config': ['InsufficientDeliveryPolicyException', 'InsufficientPermissionsException', 'InvalidConfigurationRecorderNameException', 'InvalidDeliveryChannelNameException', 'InvalidLimitException', 'InvalidNextTokenException', 'InvalidParameterValueException', 'InvalidRecordingGroupException', 'InvalidResultTokenException', 'InvalidRoleException', 'InvalidS3KeyPrefixException', 'InvalidSNSTopicARNException', 'InvalidTimeRangeException', 'LastDeliveryChannelDeleteFailedException', 'LimitExceededException', 'MaxNumberOfConfigRulesExceededException', 'MaxNumberOfConfigurationRecordersExceededException', 'MaxNumberOfDeliveryChannelsExceededException', 'MaxNumberOfRetentionConfigurationsExceededException', 'NoAvailableConfigurationRecorderException', 'NoAvailableDeliveryChannelException', 'NoAvailableOrganizationException', 'NoRunningConfigurationRecorderException', 'NoSuchBucketException', 'NoSuchConfigRuleException', 'NoSuchConfigurationAggregatorException', 'NoSuchConfigurationRecorderException', 'NoSuchDeliveryChannelException', 'NoSuchRetentionConfigurationException', 'OrganizationAccessDeniedException', 'OrganizationAllFeaturesNotEnabledException', 'OversizedConfigurationItemException', 'ResourceInUseException', 'ResourceNotDiscoveredException', 'ValidationException'],
 'dynamodb': ['BackupInUseException', 'BackupNotFoundException', 'ConditionalCheckFailedException', 'ContinuousBackupsUnavailableException', 'GlobalTableAlreadyExistsException', 'GlobalTableNotFoundException', 'IdempotentParameterMismatchException', 'IndexNotFoundException', 'InternalServerError', 'InvalidRestoreTimeException', 'ItemCollectionSizeLimitExceededException', 'LimitExceededException', 'PointInTimeRecoveryUnavailableException', 'ProvisionedThroughputExceededException', 'ReplicaAlreadyExistsException', 'ReplicaNotFoundException', 'RequestLimitExceeded', 'ResourceInUseException', 'ResourceNotFoundException', 'TableAlreadyExistsException', 'TableInUseException', 'TableNotFoundException', 'TransactionCanceledException', 'TransactionConflictException', 'TransactionInProgressException'],
 'ec2': [],
 'ecr': ['EmptyUploadException', 'ImageAlreadyExistsException', 'ImageNotFoundException', 'InvalidLayerException', 'InvalidLayerPartException', 'InvalidParameterException', 'InvalidTagParameterException', 'LayerAlreadyExistsException', 'LayerInaccessibleException', 'LayerPartTooSmallException', 'LayersNotFoundException', 'LifecyclePolicyNotFoundException', 'LifecyclePolicyPreviewInProgressException', 'LifecyclePolicyPreviewNotFoundException', 'LimitExceededException', 'RepositoryAlreadyExistsException', 'RepositoryNotEmptyException', 'RepositoryNotFoundException', 'RepositoryPolicyNotFoundException', 'ServerException', 'TooManyTagsException', 'UploadNotFoundException'],
 'ecs': ['AccessDeniedException', 'AttributeLimitExceededException', 'BlockedException', 'ClientException', 'ClusterContainsContainerInstancesException', 'ClusterContainsServicesException', 'ClusterContainsTasksException', 'ClusterNotFoundException', 'InvalidParameterException', 'MissingVersionException', 'NoUpdateAvailableException', 'PlatformTaskDefinitionIncompatibilityException', 'PlatformUnknownException', 'ResourceNotFoundException', 'ServerException', 'ServiceNotActiveException', 'ServiceNotFoundException', 'TargetNotFoundException', 'UnsupportedFeatureException', 'UpdateInProgressException'],
 'efs': ['BadRequest', 'DependencyTimeout', 'FileSystemAlreadyExists', 'FileSystemInUse', 'FileSystemLimitExceeded', 'FileSystemNotFound', 'IncorrectFileSystemLifeCycleState', 'IncorrectMountTargetState', 'InsufficientThroughputCapacity', 'InternalServerError', 'IpAddressInUse', 'MountTargetConflict', 'MountTargetNotFound', 'NetworkInterfaceLimitExceeded', 'NoFreeAddressesInSubnet', 'SecurityGroupLimitExceeded', 'SecurityGroupNotFound', 'SubnetNotFound', 'ThroughputLimitExceeded', 'TooManyRequests', 'UnsupportedAvailabilityZone'],
 'eks': ['ClientException', 'InvalidParameterException', 'InvalidRequestException', 'ResourceInUseException', 'ResourceLimitExceededException', 'ResourceNotFoundException', 'ServerException', 'ServiceUnavailableException', 'UnsupportedAvailabilityZoneException'],
 'elasticache': ['APICallRateForCustomerExceeded', 'AuthorizationAlreadyExists', 'AuthorizationNotFound', 'CacheClusterAlreadyExists', 'CacheClusterNotFound', 'CacheParameterGroupAlreadyExists', 'CacheParameterGroupNotFound', 'CacheParameterGroupQuotaExceeded', 'CacheSecurityGroupAlreadyExists', 'CacheSecurityGroupNotFound', 'QuotaExceeded.CacheSecurityGroup', 'CacheSubnetGroupAlreadyExists', 'CacheSubnetGroupInUse', 'CacheSubnetGroupNotFoundFault', 'CacheSubnetGroupQuotaExceeded', 'CacheSubnetQuotaExceededFault', 'ClusterQuotaForCustomerExceeded', 'InsufficientCacheClusterCapacity', 'InvalidARN', 'InvalidCacheClusterState', 'InvalidCacheParameterGroupState', 'InvalidCacheSecurityGroupState', 'InvalidParameterCombination', 'InvalidParameterValue', 'InvalidReplicationGroupState', 'InvalidSnapshotState', 'InvalidSubnet', 'InvalidVPCNetworkStateFault', 'NoOperationFault', 'NodeGroupNotFoundFault', 'NodeGroupsPerReplicationGroupQuotaExceeded', 'NodeQuotaForClusterExceeded', 'NodeQuotaForCustomerExceeded', 'ReplicationGroupAlreadyExists', 'ReplicationGroupNotFoundFault', 'ReservedCacheNodeAlreadyExists', 'ReservedCacheNodeNotFound', 'ReservedCacheNodeQuotaExceeded', 'ReservedCacheNodesOfferingNotFound', 'ServiceLinkedRoleNotFoundFault', 'SnapshotAlreadyExistsFault', 'SnapshotFeatureNotSupportedFault', 'SnapshotNotFoundFault', 'SnapshotQuotaExceededFault', 'SubnetInUse', 'TagNotFound', 'TagQuotaPerResourceExceeded', 'TestFailoverNotAvailableFault'],
 'elasticbeanstalk': ['CodeBuildNotInServiceRegionException', 'ElasticBeanstalkServiceException', 'InsufficientPrivilegesException', 'InvalidRequestException', 'ManagedActionInvalidStateException', 'OperationInProgressFailure', 'PlatformVersionStillReferencedException', 'ResourceNotFoundException', 'ResourceTypeNotSupportedException', 'S3LocationNotInServiceRegionException', 'S3SubscriptionRequiredException', 'SourceBundleDeletionFailure', 'TooManyApplicationVersionsException', 'TooManyApplicationsException', 'TooManyBucketsException', 'TooManyConfigurationTemplatesException', 'TooManyEnvironmentsException', 'TooManyPlatformsException', 'TooManyTagsException'],
 'elb': ['LoadBalancerNotFound', 'CertificateNotFound', 'DependencyThrottle', 'DuplicateLoadBalancerName', 'DuplicateListener', 'DuplicatePolicyName', 'DuplicateTagKeys', 'InvalidConfigurationRequest', 'InvalidInstance', 'InvalidScheme', 'InvalidSecurityGroup', 'InvalidSubnet', 'ListenerNotFound', 'LoadBalancerAttributeNotFound', 'OperationNotPermitted', 'PolicyNotFound', 'PolicyTypeNotFound', 'SubnetNotFound', 'TooManyLoadBalancers', 'TooManyPolicies', 'TooManyTags', 'UnsupportedProtocol'],
 'emr': ['InternalServerError', 'InternalServerException', 'InvalidRequestException'],
 'es': ['BaseException', 'DisabledOperationException', 'InternalException', 'InvalidTypeException', 'LimitExceededException', 'ResourceAlreadyExistsException', 'ResourceNotFoundException', 'ValidationException'],
 'events': ['ConcurrentModificationException', 'InternalException', 'InvalidEventPatternException', 'LimitExceededException', 'ManagedRuleException', 'PolicyLengthExceededException', 'ResourceNotFoundException'],
 'firehose': ['ConcurrentModificationException', 'InvalidArgumentException', 'LimitExceededException', 'ResourceInUseException', 'ResourceNotFoundException', 'ServiceUnavailableException'],
 'glacier': ['InsufficientCapacityException', 'InvalidParameterValueException', 'LimitExceededException', 'MissingParameterValueException', 'PolicyEnforcedException', 'RequestTimeoutException', 'ResourceNotFoundException', 'ServiceUnavailableException'],
 'glue': ['AccessDeniedException', 'AlreadyExistsException', 'ConcurrentModificationException', 'ConcurrentRunsExceededException', 'ConditionCheckFailureException', 'CrawlerNotRunningException', 'CrawlerRunningException', 'CrawlerStoppingException', 'EntityNotFoundException', 'GlueEncryptionException', 'IdempotentParameterMismatchException', 'InternalServiceException', 'InvalidInputException', 'NoScheduleException', 'OperationTimeoutException', 'ResourceNumberLimitExceededException', 'SchedulerNotRunningException', 'SchedulerRunningException', 'SchedulerTransitioningException', 'ValidationException', 'VersionMismatchException'],
 'iam': ['ConcurrentModification', 'ReportExpired', 'ReportNotPresent', 'ReportInProgress', 'DeleteConflict', 'DuplicateCertificate', 'DuplicateSSHPublicKey', 'EntityAlreadyExists', 'EntityTemporarilyUnmodifiable', 'InvalidAuthenticationCode', 'InvalidCertificate', 'InvalidInput', 'InvalidPublicKey', 'InvalidUserType', 'KeyPairMismatch', 'LimitExceeded', 'MalformedCertificate', 'MalformedPolicyDocument', 'NoSuchEntity', 'PasswordPolicyViolation', 'PolicyEvaluation', 'PolicyNotAttachable', 'ServiceFailure', 'NotSupportedService', 'UnmodifiableEntity', 'UnrecognizedPublicKeyEncoding'],
 'kinesis': ['ExpiredIteratorException', 'ExpiredNextTokenException', 'InternalFailureException', 'InvalidArgumentException', 'KMSAccessDeniedException', 'KMSDisabledException', 'KMSInvalidStateException', 'KMSNotFoundException', 'KMSOptInRequired', 'KMSThrottlingException', 'LimitExceededException', 'ProvisionedThroughputExceededException', 'ResourceInUseException', 'ResourceNotFoundException'],
 'kms': ['AlreadyExistsException', 'CloudHsmClusterInUseException', 'CloudHsmClusterInvalidConfigurationException', 'CloudHsmClusterNotActiveException', 'CloudHsmClusterNotFoundException', 'CloudHsmClusterNotRelatedException', 'CustomKeyStoreHasCMKsException', 'CustomKeyStoreInvalidStateException', 'CustomKeyStoreNameInUseException', 'CustomKeyStoreNotFoundException', 'DependencyTimeoutException', 'DisabledException', 'ExpiredImportTokenException', 'IncorrectKeyMaterialException', 'IncorrectTrustAnchorException', 'InvalidAliasNameException', 'InvalidArnException', 'InvalidCiphertextException', 'InvalidGrantIdException', 'InvalidGrantTokenException', 'InvalidImportTokenException', 'InvalidKeyUsageException', 'InvalidMarkerException', 'KMSInternalException', 'KMSInvalidStateException', 'KeyUnavailableException', 'LimitExceededException', 'MalformedPolicyDocumentException', 'NotFoundException', 'TagException', 'UnsupportedOperationException'],
 'lambda': ['CodeStorageExceededException', 'EC2AccessDeniedException', 'EC2ThrottledException', 'EC2UnexpectedException', 'ENILimitReachedException', 'InvalidParameterValueException', 'InvalidRequestContentException', 'InvalidRuntimeException', 'InvalidSecurityGroupIDException', 'InvalidSubnetIDException', 'InvalidZipFileException', 'KMSAccessDeniedException', 'KMSDisabledException', 'KMSInvalidStateException', 'KMSNotFoundException', 'PolicyLengthExceededException', 'PreconditionFailedException', 'RequestTooLargeException', 'ResourceConflictException', 'ResourceInUseException', 'ResourceNotFoundException', 'ServiceException', 'SubnetIPAddressLimitReachedException', 'TooManyRequestsException', 'UnsupportedMediaTypeException'],
 'logs': ['DataAlreadyAcceptedException', 'InvalidOperationException', 'InvalidParameterException', 'InvalidSequenceTokenException', 'LimitExceededException', 'MalformedQueryException', 'OperationAbortedException', 'ResourceAlreadyExistsException', 'ResourceNotFoundException', 'ServiceUnavailableException', 'UnrecognizedClientException'],
 'neptune': ['AuthorizationNotFound', 'CertificateNotFound', 'DBClusterAlreadyExistsFault', 'DBClusterNotFoundFault', 'DBClusterParameterGroupNotFound', 'DBClusterQuotaExceededFault', 'DBClusterRoleAlreadyExists', 'DBClusterRoleNotFound', 'DBClusterRoleQuotaExceeded', 'DBClusterSnapshotAlreadyExistsFault', 'DBClusterSnapshotNotFoundFault', 'DBInstanceAlreadyExists', 'DBInstanceNotFound', 'DBParameterGroupAlreadyExists', 'DBParameterGroupNotFound', 'DBParameterGroupQuotaExceeded', 'DBSecurityGroupNotFound', 'DBSnapshotAlreadyExists', 'DBSnapshotNotFound', 'DBSubnetGroupAlreadyExists', 'DBSubnetGroupDoesNotCoverEnoughAZs', 'DBSubnetGroupNotFoundFault', 'DBSubnetGroupQuotaExceeded', 'DBSubnetQuotaExceededFault', 'DBUpgradeDependencyFailure', 'DomainNotFoundFault', 'EventSubscriptionQuotaExceeded', 'InstanceQuotaExceeded', 'InsufficientDBClusterCapacityFault', 'InsufficientDBInstanceCapacity', 'InsufficientStorageClusterCapacity', 'InvalidDBClusterSnapshotStateFault', 'InvalidDBClusterStateFault', 'InvalidDBInstanceState', 'InvalidDBParameterGroupState', 'InvalidDBSecurityGroupState', 'InvalidDBSnapshotState', 'InvalidDBSubnetGroupStateFault', 'InvalidDBSubnetStateFault', 'InvalidEventSubscriptionState', 'InvalidRestoreFault', 'InvalidSubnet', 'InvalidVPCNetworkStateFault', 'KMSKeyNotAccessibleFault', 'OptionGroupNotFoundFault', 'ProvisionedIopsNotAvailableInAZFault', 'ResourceNotFoundFault', 'SNSInvalidTopic', 'SNSNoAuthorization', 'SNSTopicArnNotFound', 'SharedSnapshotQuotaExceeded', 'SnapshotQuotaExceeded', 'SourceNotFound', 'StorageQuotaExceeded', 'StorageTypeNotSupported', 'SubnetAlreadyInUse', 'SubscriptionAlreadyExist', 'SubscriptionCategoryNotFound', 'SubscriptionNotFound'],
 'rds': ['AuthorizationAlreadyExists', 'AuthorizationNotFound', 'AuthorizationQuotaExceeded', 'BackupPolicyNotFoundFault', 'CertificateNotFound', 'DBClusterAlreadyExistsFault', 'DBClusterBacktrackNotFoundFault', 'DBClusterEndpointAlreadyExistsFault', 'DBClusterEndpointNotFoundFault', 'DBClusterEndpointQuotaExceededFault', 'DBClusterNotFoundFault', 'DBClusterParameterGroupNotFound', 'DBClusterQuotaExceededFault', 'DBClusterRoleAlreadyExists', 'DBClusterRoleNotFound', 'DBClusterRoleQuotaExceeded', 'DBClusterSnapshotAlreadyExistsFault', 'DBClusterSnapshotNotFoundFault', 'DBInstanceAlreadyExists', 'DBInstanceAutomatedBackupNotFound', 'DBInstanceAutomatedBackupQuotaExceeded', 'DBInstanceNotFound', 'DBInstanceRoleAlreadyExists', 'DBInstanceRoleNotFound', 'DBInstanceRoleQuotaExceeded', 'DBLogFileNotFoundFault', 'DBParameterGroupAlreadyExists', 'DBParameterGroupNotFound', 'DBParameterGroupQuotaExceeded', 'DBSecurityGroupAlreadyExists', 'DBSecurityGroupNotFound', 'DBSecurityGroupNotSupported', 'QuotaExceeded.DBSecurityGroup', 'DBSnapshotAlreadyExists', 'DBSnapshotNotFound', 'DBSubnetGroupAlreadyExists', 'DBSubnetGroupDoesNotCoverEnoughAZs', 'DBSubnetGroupNotAllowedFault', 'DBSubnetGroupNotFoundFault', 'DBSubnetGroupQuotaExceeded', 'DBSubnetQuotaExceededFault', 'DBUpgradeDependencyFailure', 'DomainNotFoundFault', 'EventSubscriptionQuotaExceeded', 'GlobalClusterAlreadyExistsFault', 'GlobalClusterNotFoundFault', 'GlobalClusterQuotaExceededFault', 'InstanceQuotaExceeded', 'InsufficientDBClusterCapacityFault', 'InsufficientDBInstanceCapacity', 'InsufficientStorageClusterCapacity', 'InvalidDBClusterCapacityFault', 'InvalidDBClusterEndpointStateFault', 'InvalidDBClusterSnapshotStateFault', 'InvalidDBClusterStateFault', 'InvalidDBInstanceAutomatedBackupState', 'InvalidDBInstanceState', 'InvalidDBParameterGroupState', 'InvalidDBSecurityGroupState', 'InvalidDBSnapshotState', 'InvalidDBSubnetGroupFault', 'InvalidDBSubnetGroupStateFault', 'InvalidDBSubnetStateFault', 'InvalidEventSubscriptionState', 'InvalidGlobalClusterStateFault', 'InvalidOptionGroupStateFault', 'InvalidRestoreFault', 'InvalidS3BucketFault', 'InvalidSubnet', 'InvalidVPCNetworkStateFault', 'KMSKeyNotAccessibleFault', 'OptionGroupAlreadyExistsFault', 'OptionGroupNotFoundFault', 'OptionGroupQuotaExceededFault', 'PointInTimeRestoreNotEnabled', 'ProvisionedIopsNotAvailableInAZFault', 'ReservedDBInstanceAlreadyExists', 'ReservedDBInstanceNotFound', 'ReservedDBInstanceQuotaExceeded', 'ReservedDBInstancesOfferingNotFound', 'ResourceNotFoundFault', 'SNSInvalidTopic', 'SNSNoAuthorization', 'SNSTopicArnNotFound', 'SharedSnapshotQuotaExceeded', 'SnapshotQuotaExceeded', 'SourceNotFound', 'StorageQuotaExceeded', 'StorageTypeNotSupported', 'SubnetAlreadyInUse', 'SubscriptionAlreadyExist', 'SubscriptionCategoryNotFound', 'SubscriptionNotFound'],
 'route53': ['ConcurrentModification', 'ConflictingDomainExists', 'ConflictingTypes', 'DelegationSetAlreadyCreated', 'DelegationSetAlreadyReusable', 'DelegationSetInUse', 'DelegationSetNotAvailable', 'DelegationSetNotReusable', 'HealthCheckAlreadyExists', 'HealthCheckInUse', 'HealthCheckVersionMismatch', 'HostedZoneAlreadyExists', 'HostedZoneNotEmpty', 'HostedZoneNotFound', 'HostedZoneNotPrivate', 'IncompatibleVersion', 'InsufficientCloudWatchLogsResourcePolicy', 'InvalidArgument', 'InvalidChangeBatch', 'InvalidDomainName', 'InvalidInput', 'InvalidPaginationToken', 'InvalidTrafficPolicyDocument', 'InvalidVPCId', 'LastVPCAssociation', 'LimitsExceeded', 'NoSuchChange', 'NoSuchCloudWatchLogsLogGroup', 'NoSuchDelegationSet', 'NoSuchGeoLocation', 'NoSuchHealthCheck', 'NoSuchHostedZone', 'NoSuchQueryLoggingConfig', 'NoSuchTrafficPolicy', 'NoSuchTrafficPolicyInstance', 'NotAuthorizedException', 'PriorRequestNotComplete', 'PublicZoneVPCAssociation', 'QueryLoggingConfigAlreadyExists', 'ThrottlingException', 'TooManyHealthChecks', 'TooManyHostedZones', 'TooManyTrafficPolicies', 'TooManyTrafficPolicyInstances', 'TooManyTrafficPolicyVersionsForCurrentPolicy', 'TooManyVPCAssociationAuthorizations', 'TrafficPolicyAlreadyExists', 'TrafficPolicyInUse', 'TrafficPolicyInstanceAlreadyExists', 'VPCAssociationAuthorizationNotFound', 'VPCAssociationNotFound'],
 's3': ['BucketAlreadyExists', 'BucketAlreadyOwnedByYou', 'NoSuchBucket', 'NoSuchKey', 'NoSuchUpload', 'ObjectAlreadyInActiveTierError', 'ObjectNotInActiveTierError'],
 'sagemaker': ['ResourceInUse', 'ResourceLimitExceeded', 'ResourceNotFound'],
 'secretsmanager': ['DecryptionFailure', 'EncryptionFailure', 'InternalServiceError', 'InvalidNextTokenException', 'InvalidParameterException', 'InvalidRequestException', 'LimitExceededException', 'MalformedPolicyDocumentException', 'PreconditionNotMetException', 'ResourceExistsException', 'ResourceNotFoundException'],
 'ses': ['AccountSendingPausedException', 'AlreadyExists', 'CannotDelete', 'ConfigurationSetAlreadyExists', 'ConfigurationSetDoesNotExist', 'ConfigurationSetSendingPausedException', 'CustomVerificationEmailInvalidContent', 'CustomVerificationEmailTemplateAlreadyExists', 'CustomVerificationEmailTemplateDoesNotExist', 'EventDestinationAlreadyExists', 'EventDestinationDoesNotExist', 'FromEmailAddressNotVerified', 'InvalidCloudWatchDestination', 'InvalidConfigurationSet', 'InvalidFirehoseDestination', 'InvalidLambdaFunction', 'InvalidPolicy', 'InvalidRenderingParameter', 'InvalidS3Configuration', 'InvalidSNSDestination', 'InvalidSnsTopic', 'InvalidTemplate', 'InvalidTrackingOptions', 'LimitExceeded', 'MailFromDomainNotVerifiedException', 'MessageRejected', 'MissingRenderingAttribute', 'ProductionAccessNotGranted', 'RuleDoesNotExist', 'RuleSetDoesNotExist', 'TemplateDoesNotExist', 'TrackingOptionsAlreadyExistsException', 'TrackingOptionsDoesNotExistException'],
 'sns': ['AuthorizationError', 'EndpointDisabled', 'FilterPolicyLimitExceeded', 'InternalError', 'InvalidParameter', 'ParameterValueInvalid', 'InvalidSecurity', 'KMSAccessDenied', 'KMSDisabled', 'KMSInvalidState', 'KMSNotFound', 'KMSOptInRequired', 'KMSThrottling', 'NotFound', 'PlatformApplicationDisabled', 'SubscriptionLimitExceeded', 'Throttled', 'TopicLimitExceeded'],
 'sqs': ['AWS.SimpleQueueService.BatchEntryIdsNotDistinct', 'AWS.SimpleQueueService.BatchRequestTooLong', 'AWS.SimpleQueueService.EmptyBatchRequest', 'InvalidAttributeName', 'AWS.SimpleQueueService.InvalidBatchEntryId', 'InvalidIdFormat', 'InvalidMessageContents', 'AWS.SimpleQueueService.MessageNotInflight', 'OverLimit', 'AWS.SimpleQueueService.PurgeQueueInProgress', 'AWS.SimpleQueueService.QueueDeletedRecently', 'AWS.SimpleQueueService.NonExistentQueue', 'QueueAlreadyExists', 'ReceiptHandleIsInvalid', 'AWS.SimpleQueueService.TooManyEntriesInBatchRequest', 'AWS.SimpleQueueService.UnsupportedOperation'],
 'ssm': ['AlreadyExistsException', 'AssociatedInstances', 'AssociationAlreadyExists', 'AssociationDoesNotExist', 'AssociationExecutionDoesNotExist', 'AssociationLimitExceeded', 'AssociationVersionLimitExceeded', 'AutomationDefinitionNotFoundException', 'AutomationDefinitionVersionNotFoundException', 'AutomationExecutionLimitExceededException', 'AutomationExecutionNotFoundException', 'AutomationStepNotFoundException', 'ComplianceTypeCountLimitExceededException', 'CustomSchemaCountLimitExceededException', 'DocumentAlreadyExists', 'DocumentLimitExceeded', 'DocumentPermissionLimit', 'DocumentVersionLimitExceeded', 'DoesNotExistException', 'DuplicateDocumentContent', 'DuplicateDocumentVersionName', 'DuplicateInstanceId', 'FeatureNotAvailableException', 'HierarchyLevelLimitExceededException', 'HierarchyTypeMismatchException', 'IdempotentParameterMismatch', 'InternalServerError', 'InvalidActivation', 'InvalidActivationId', 'InvalidAggregatorException', 'InvalidAllowedPatternException', 'InvalidAssociation', 'InvalidAssociationVersion', 'InvalidAutomationExecutionParametersException', 'InvalidAutomationSignalException', 'InvalidAutomationStatusUpdateException', 'InvalidCommandId', 'InvalidDeleteInventoryParametersException', 'InvalidDeletionIdException', 'InvalidDocument', 'InvalidDocumentContent', 'InvalidDocumentOperation', 'InvalidDocumentSchemaVersion', 'InvalidDocumentVersion', 'InvalidFilter', 'InvalidFilterKey', 'InvalidFilterOption', 'InvalidFilterValue', 'InvalidInstanceId', 'InvalidInstanceInformationFilterValue', 'InvalidInventoryGroupException', 'InvalidInventoryItemContextException', 'InvalidInventoryRequestException', 'InvalidItemContentException', 'InvalidKeyId', 'InvalidNextToken', 'InvalidNotificationConfig', 'InvalidOptionException', 'InvalidOutputFolder', 'InvalidOutputLocation', 'InvalidParameters', 'InvalidPermissionType', 'InvalidPluginName', 'InvalidResourceId', 'InvalidResourceType', 'InvalidResultAttributeException', 'InvalidRole', 'InvalidSchedule', 'InvalidTarget', 'InvalidTypeNameException', 'InvalidUpdate', 'InvocationDoesNotExist', 'ItemContentMismatchException', 'ItemSizeLimitExceededException', 'MaxDocumentSizeExceeded', 'ParameterAlreadyExists', 'ParameterLimitExceeded', 'ParameterMaxVersionLimitExceeded', 'ParameterNotFound', 'ParameterPatternMismatchException', 'ParameterVersionLabelLimitExceeded', 'ParameterVersionNotFound', 'ResourceDataSyncAlreadyExistsException', 'ResourceDataSyncCountExceededException', 'ResourceDataSyncInvalidConfigurationException', 'ResourceDataSyncNotFoundException', 'ResourceInUseException', 'ResourceLimitExceededException', 'StatusUnchanged', 'SubTypeCountLimitExceededException', 'TargetInUseException', 'TargetNotConnected', 'TooManyTagsError', 'TooManyUpdates', 'TotalSizeLimitExceededException', 'UnsupportedInventoryItemContextException', 'UnsupportedInventorySchemaVersionException', 'UnsupportedOperatingSystem', 'UnsupportedParameterType', 'UnsupportedPlatformType'],
 'stepfunctions': ['ActivityDoesNotExist', 'ActivityLimitExceeded', 'ActivityWorkerLimitExceeded', 'ExecutionAlreadyExists', 'ExecutionDoesNotExist', 'ExecutionLimitExceeded', 'InvalidArn', 'InvalidDefinition', 'InvalidExecutionInput', 'InvalidName', 'InvalidOutput', 'InvalidToken', 'MissingRequiredParameter', 'ResourceNotFound', 'StateMachineAlreadyExists', 'StateMachineDeleting', 'StateMachineDoesNotExist', 'StateMachineLimitExceeded', 'TaskDoesNotExist', 'TaskTimedOut', 'TooManyTags'],
 'sts': ['ExpiredTokenException', 'IDPCommunicationError', 'IDPRejectedClaim', 'InvalidAuthorizationMessageException', 'InvalidIdentityToken', 'MalformedPolicyDocument', 'PackedPolicyTooLarge', 'RegionDisabledException'],
 'xray': ['InvalidRequestException', 'RuleLimitExceededException', 'ThrottledException']}

What is the purpose of a self executing function in javascript?

One difference is that the variables that you declare in the function are local, so they go away when you exit the function and they don't conflict with other variables in other or same code.

How can I convert a long to int in Java?

If direct casting shows error you can do it like this:

Long id = 100;
int int_id = (int) (id % 100000);

Call of overloaded function is ambiguous

That is ambiguous because a pointer is just an address, so an int can also be treated as a pointer – 0 (an int) can be converted to unsigned int or char * equally easily.

The short answer is to call p.setval() with something that's unambiguously one of the types it's implemented for: unsigned int or char *. p.setval(0U), p.setval((unsigned int)0), and p.setval((char *)0) will all compile.

It's generally a good idea to stay out of this situation in the first place, though, by not defining overloaded functions with such similar types.

how to pass parameter from @Url.Action to controller function

public ActionResult CreatePerson (string id)

window.location.href = '@Url.Action("CreatePerson", "Person" , new {id = "ID"})'.replace("ID",id);

public ActionResult CreatePerson (int id)

window.location.href = '@Url.Action("CreatePerson", "Person" , new {id = "ID"})'.replace("ID", parseInt(id));

What is the difference between association, aggregation and composition?

Association is a relationship between two separate classes and the association can be of any type say one to one, one to may etc. It joins two entirely separate entities.

Aggregation is a special form of association which is a unidirectional one way relationship between classes (or entities), for e.g. Wallet and Money classes. Wallet has Money but money doesn’t need to have Wallet necessarily so its a one directional relationship. In this relationship both the entries can survive if other one ends. In our example if Wallet class is not present, it does not mean that the Money class cannot exist.

Composition is a restricted form of Aggregation in which two entities (or you can say classes) are highly dependent on each other. For e.g. Human and Heart. A human needs heart to live and a heart needs a Human body to survive. In other words when the classes (entities) are dependent on each other and their life span are same (if one dies then another one too) then its a composition. Heart class has no sense if Human class is not present.

Photoshop text tool adds punctuation to the beginning of text

Select all text afected by this issue:

Window -> Character, click the icon next to hide the Character Window, Middle Western Features and select Left-to-right character direction.

Eclipse Optimize Imports to Include Static Imports

I'm using Eclipse Europa, which also has the Favorite preference section:

Window > Preferences > Java > Editor > Content Assist > Favorites

In mine, I have the following entries (when adding, use "New Type" and omit the .*):

org.hamcrest.Matchers.*
org.hamcrest.CoreMatchers.*
org.junit.*
org.junit.Assert.*
org.junit.Assume.*
org.junit.matchers.JUnitMatchers.*

All but the third of those are static imports. By having those as favorites, if I type "assertT" and hit Ctrl+Space, Eclipse offers up assertThat as a suggestion, and if I pick it, it will add the proper static import to the file.

push object into array

Create an array of object like this:

var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;

First you create the object inside of the push method and then return the newly created array.

Datepicker: How to popup datepicker when click on edittext

public class DatePickerActivity extends AppCompatActivity {
    Button button;
    static TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button= (Button) findViewById(R.id.btn_click);
        textView= (TextView) findViewById(R.id.txt_date);



        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment newFragment=new DatePickerFragment();
                newFragment.show(getFragmentManager(), "datepicker");
            }
        });

    }

    public class DatePickerFragment extends DialogFragment implements    DatePickerDialog.OnDateSetListener{
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int  day) {
            String years=""+year;
            String months=""+(monthOfYear+1);
            String days=""+day;
            if(monthOfYear>=0 && monthOfYear<9){
                months="0"+(monthOfYear+1);
            }
            if(day>0 && day<10){
                days="0"+day;

            }
            textView.setText(days+"/"+months+"/"+years);


        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            //use the current date as the default date in the picker
            final Calendar c=Calendar.getInstance();
            int year=c.get(Calendar.YEAR);
            int month=c.get(Calendar.MONTH);
            int day=c.get(Calendar.DAY_OF_MONTH);
            DatePickerDialog datePickerDialog=null;
            datePickerDialog=new DatePickerDialog(getActivity(), this, year,  month, day);

            return datePickerDialog;
        }

    }

}

How to handle login pop up window using Selenium WebDriver?

Solution: Windows active directory authentication using Thread and Robot

I used Java Thread and Robot with Selenium webdriver to automate windows active directory authentication process of our website. This logic worked fine in Firefox and Chrome but it didn't work in IE. For some reason IE kills the webdriver when authentication window pops up whereas Chrome and Firefox prevents the web driver from getting killed. I didn't try in other web browser such as Safari.

//...
//Note: this logic works in Chrome and Firefox. It did not work in IE and I did not try Safari.
//...

//import relevant packages here

public class TestDemo {

    static WebDriver driver;

    public static void main(String[] args) {

        //setup web driver
        System.setProperty("webdriver.chrome.driver", "path to your chromedriver.exe");
        driver = new ChromeDriver();

        //create new thread for interaction with windows authentication window
        (new Thread(new LoginWindow())).start();                

        //open your url. this will prompt you for windows authentication
        driver.get("your url");

        //add test scripts below ...
        driver.findElement(By.linkText("Home")).click();    
        //.....
        //.....
    }

    //inner class for Login thread    
    public class LoginWindow implements Runnable {

        @Override
        public void run() {
            try {
                login();
            } catch (Exception ex) {
                System.out.println("Error in Login Thread: " + ex.getMessage());
            }
        }

        public void login() throws Exception {

            //wait - increase this wait period if required
            Thread.sleep(5000);

            //create robot for keyboard operations
            Robot rb = new Robot();

            //Enter user name by ctrl-v
            StringSelection username = new StringSelection("username");
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(username, null);            
            rb.keyPress(KeyEvent.VK_CONTROL);
            rb.keyPress(KeyEvent.VK_V);
            rb.keyRelease(KeyEvent.VK_V);
            rb.keyRelease(KeyEvent.VK_CONTROL);

            //tab to password entry field
            rb.keyPress(KeyEvent.VK_TAB);
            rb.keyRelease(KeyEvent.VK_TAB);
            Thread.sleep(2000);

            //Enter password by ctrl-v
            StringSelection pwd = new StringSelection("password");
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(pwd, null);
            rb.keyPress(KeyEvent.VK_CONTROL);
            rb.keyPress(KeyEvent.VK_V);
            rb.keyRelease(KeyEvent.VK_V);
            rb.keyRelease(KeyEvent.VK_CONTROL);

            //press enter
            rb.keyPress(KeyEvent.VK_ENTER);
            rb.keyRelease(KeyEvent.VK_ENTER);

            //wait
            Thread.sleep(5000);
        }                        
    }      
}

Differences between Octave and MATLAB?

The thing makes Matlab so popular and special is its excellent toolboxes in different disciplines. Since your main goal is to learn Matlab, so there is not different at all if you work with Octave or Matlab!

Just going and buying Matlab without any cool toolbox (which basically depends on your major) is not really a reasonable expense!

You can definitely have a good start with Octave, and follow tons of tutorials on Matlab on the internet.

How to print values separated by spaces instead of new lines in Python 2.7

First of all print isn't a function in Python 2, it is a statement.

To suppress the automatic newline add a trailing ,(comma). Now a space will be used instead of a newline.

Demo:

print 1,
print 2

output:

1 2

Or use Python 3's print() function:

from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'
print(2)

As you can clearly see print() function is much more powerful as we can specify any string to be used as end rather a fixed space.

Stretch background image css?

This works flawlessly @ 2019

.marketing-panel  {
    background-image: url("../images/background.jpg");
    background-repeat: no-repeat;
    background-size: auto;
    background-position: center;
}

Neither BindingResult nor plain target object for bean name available as request attr

I worked on this same issue and I am sure I have found out the exact reason for it.

Neither BindingResult nor plain target object for bean name 'command' available as request attribute

If your successView property value (name of jsp page) is the same as your input page name, then second value of ModelAndView constructor must be match with the commandName of the input page.

E.g.

index.jsp

<html>
<body>
    <table>
        <tr><td><a href="Login.html">Login</a></td></tr>
    </table>
</body>
</html>

dispatcher-servlet.xml

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix">
        <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>
<bean id="urlMapping"
    class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="urlMap">
        <map>              
            <entry key="/Login.html">
                <ref bean="userController"/>
            </entry>
        </map>          
    </property>             
</bean>     
 <bean id="userController" class="controller.AddCountryFormController">     
       <property name="commandName"><value>country</value></property>
       <property name="commandClass"><value>controller.Country</value></property>        
       <property name="formView"><value>countryForm</value></property>
       <property name="successView"><value>countryForm</value></property>
   </bean>      

AddCountryFormController.java

package controller;

import javax.servlet.http.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.SimpleFormController;


public class AddCountryFormController extends SimpleFormController
{

    public AddCountryFormController(){
        setCommandName("Country.class");
    }

    protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException errors){

            Country country=(Country)command;

            System.out.println("calling onsubmit method !!!!!");

        return new ModelAndView(getSuccessView(),"country",country);

    }

}

Country.java

package controller;

public class Country
{
    private String countryName;

    public void setCountryName(String value){
        countryName=value;
    }

    public String getCountryName(){
        return countryName;
    }

}

countryForm.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
    <form:form commandName="country" method="POST" >
            <table>
                    <tr><td><form:input path="countryName"/></td></tr>
                    <tr><td><input type="submit" value="Save"/></td></tr>
            </table>
    </form:form>
</body>
<html>

Input page commandName="country" ModelAndView Constructor as return new ModelAndView(getSuccessView(),"country",country); Means inputpage commandName==ModeAndView(,"commandName",)

Getting the difference between two repositories

You can add other repo first as a remote to your current repo:

git remote add other_name PATH_TO_OTHER_REPO

then fetch brach from that remote:

git fetch other_name branch_name:branch_name

this creates that branch as a new branch in your current repo, then you can diff that branch with any of your branches, for example, to compare current branch against new branch(branch_name):

git diff branch_name

Permission to write to the SD card

You're right that the SD Card directory is /sdcard but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory() to get the directory:

File sdDir = Environment.getExternalStorageDirectory();

If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:

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

How to fix: "HAX is not working and emulator runs in emulation mode"

The way I solved it is by setting the AVD memory limit and HAXM memory to be equal in size which is 1 GB = 1024 MB. The AVD cannot have higher memory limit than the HAXM.

1. Setting the HAXM memory to be 1024 M

The only way to change the HAXM memory is by installing it again. I did it using the terminal. Locate Hardware_Accelerated_Execution_Manager in your machine. Then change directory that folder to run the installation script.

cd ~/Library/Android/sdk/extras/intel/Hardware_Accelerated_Execution_Manager

-OR-

cd ~/Library/Developer/Xamarin/android-sdk-macosx/extras/intel/Hardware_Accelerated_Execution_Manager

May need to change permissions:

sudo chmod 755 "HAXM installation"

Then:

./HAXM\ installation -m 1024

-OR-

sudo ./"HAXM installation" -m 1024

2. Setting the virtual device the same size with HAXM memory limit

enter image description here

This works for me. Good luck!

Use child_process.execSync but keep output in console

Unless you redirect stdout and stderr as the accepted answer suggests, this is not possible with execSync or spawnSync. Without redirecting stdout and stderr those commands only return stdout and stderr when the command is completed.

To do this without redirecting stdout and stderr, you are going to need to use spawn to do this but it's pretty straight forward:

var spawn = require('child_process').spawn;

//kick off process of listing files
var child = spawn('ls', ['-l', '/']);

//spit stdout to screen
child.stdout.on('data', function (data) {   process.stdout.write(data.toString());  });

//spit stderr to screen
child.stderr.on('data', function (data) {   process.stdout.write(data.toString());  });

child.on('close', function (code) { 
    console.log("Finished with code " + code);
});

I used an ls command that recursively lists files so that you can test it quickly. Spawn takes as first argument the executable name you are trying to run and as it's second argument it takes an array of strings representing each parameter you want to pass to that executable.

However, if you are set on using execSync and can't redirect stdout or stderr for some reason, you can open up another terminal like xterm and pass it a command like so:

var execSync = require('child_process').execSync;

execSync("xterm -title RecursiveFileListing -e ls -latkR /");

This will allow you to see what your command is doing in the new terminal but still have the synchronous call.

Querying Datatable with where condition

You can do it with Linq, as mamoo showed, but the oldies are good too:

var filteredDataTable = dt.Select(@"EmpId > 2
    AND (EmpName <> 'abc' OR EmpName <> 'xyz')
    AND EmpName like '%il%'" );

Saving an Excel sheet in a current directory with VBA

Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:\property\california\sacramento\workbook.xlsx, use this to move the property to berkley:

workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "\" & "newFileName.xlsx"

Only works if your file structure contains one instance of the text used to replace. YMMV.

How to get HQ youtube thumbnails?

You need to get id from:

youtube.com/watch?v=VIDEO_ID

And put this in:

i.ytimg.com/vi/VIDEO_ID/maxresdefault.jpg

I hope that I helped :D

Get Filename Without Extension in Python

You can use stem method to get file name.

Here is an example:

from pathlib import Path

p = Path(r"\\some_directory\subdirectory\my_file.txt")
print(p.stem)
# my_file

How to find what code is run by a button or element in Chrome using Developer Tools

Solution 1: Framework blackboxing

Works great, minimal setup and no third parties.

According to Chrome's documentation:

What happens when you blackbox a script?

Exceptions thrown from library code will not pause (if Pause on exceptions is enabled), Stepping into/out/over bypasses the library code, Event listener breakpoints don't break in library code, The debugger will not pause on any breakpoints set in library code. The end result is you are debugging your application code instead of third party resources.

Here's the updated workflow:
  1. Pop open Chrome Developer Tools (F12 or ?+?+i), go to settings (upper right, or F1). Find a tab on the left called "Blackboxing"

enter image description here

  1. This is where you put the RegEx pattern of the files you want Chrome to ignore while debugging. For example: jquery\..*\.js (glob pattern/human translation: jquery.*.js)
  2. If you want to skip files with multiple patterns you can add them using the pipe character, |, like so: jquery\..*\.js|include\.postload\.js (which acts like an "or this pattern", so to speak. Or keep adding them with the "Add" button.
  3. Now continue to Solution 3 described down below.

Bonus tip! I use Regex101 regularly (but there are many others: ) to quickly test my rusty regex patterns and find out where I'm wrong with the step-by-step regex debugger. If you are not yet "fluent" in Regular Expressions I recommend you start using sites that help you write and visualize them such as http://buildregex.com/ and https://www.debuggex.com/

You can also use the context menu when working in the Sources panel. When viewing a file, you can right-click in the editor and choose Blackbox Script. This will add the file to the list in the Settings panel:

enter image description here


Solution 2: Visual Event

enter image description here

It's an excellent tool to have:

Visual Event is an open-source Javascript bookmarklet which provides debugging information about events that have been attached to DOM elements. Visual Event shows:

  • Which elements have events attached to them
  • The type of events attached to an element
  • The code that will be run with the event is triggered
  • The source file and line number for where the attached function was defined (Webkit browsers and Opera only)


Solution 3: Debugging

You can pause the code when you click somewhere in the page, or when the DOM is modified... and other kinds of JS breakpoints that will be useful to know. You should apply blackboxing here to avoid a nightmare.

In this instance, I want to know what exactly goes on when I click the button.

  1. Open Dev Tools -> Sources tab, and on the right find Event Listener Breakpoints:

    enter image description here

  2. Expand Mouse and select click

  3. Now click the element (execution should pause), and you are now debugging the code. You can go through all code pressing F11 (which is Step in). Or go back a few jumps in the stack. There can be a ton of jumps


Solution 4: Fishing keywords

With Dev Tools activated, you can search the whole codebase (all code in all files) with ?+?+F or:

enter image description here

and searching #envio or whatever the tag/class/id you think starts the party and you may get somewhere faster than anticipated.

Be aware sometimes there's not only an img but lots of elements stacked, and you may not know which one triggers the code.


If this is a bit out of your knowledge, take a look at Chrome's tutorial on debugging.

Using Enum values as String literals

As far as I know, the only way to get the name would be

Mode.mode1.name();

If you really need it this way, however, you could do:

public enum Modes {
    mode1 ("Mode1"),
    mode2 ("Mode2"),
    mode3 ("Mode3");

    private String name;       

    private Modes(String s) {
        name = s;
    }
}

MySQL INSERT INTO ... VALUES and SELECT

All other answers solves the problem and my answer works the same way as the others, but just on a more didactically way (this works on MySQL... don't know other SQL servers):

INSERT INTO table1 SET 
  stringColumn  = 'A String', 
  numericColumn = 5, 
  selectColumn  = (SELECT idTable2 FROM table2 WHERE ...);

You can refer the MySQL documentation: INSERT Syntax

Description Box using "onmouseover"

The CSS Tooltip allows you to format the popup as you like as any div section! And no Javascript needed.

How to fit a smooth curve to my data in R?

In order to get it REALLY smoooth...

x <- 1:10
y <- c(2,4,6,8,7,8,14,16,18,20)
lo <- loess(y~x)
plot(x,y)
xl <- seq(min(x),max(x), (max(x) - min(x))/1000)
lines(xl, predict(lo,xl), col='red', lwd=2)

This style interpolates lots of extra points and gets you a curve that is very smooth. It also appears to be the the approach that ggplot takes. If the standard level of smoothness is fine you can just use.

scatter.smooth(x, y)

How do I disable right click on my web page?

Put this code into your <head> tag of your page.

<script type="text/javascript"> 
function disableselect(e){  
return false  
}  

function reEnable(){  
return true  
}  

//if IE4+  
document.onselectstart=new Function ("return false")  
document.oncontextmenu=new Function ("return false")  
//if NS6  
if (window.sidebar){  
document.onmousedown=disableselect  
document.onclick=reEnable  
}
</script>

This will disable right click on your whole web page, but only when JavaScript is enabled.

Is there a difference between x++ and ++x in java?

The Question is already answered, but allow me to add from my side too.

First of all ++ means increment by one and -- means decrement by one.

Now x++ means Increment x after this line and ++x means Increment x before this line.

Check this Example

class Example {
public static void main (String args[]) {
      int x=17,a,b;
      a=x++;
      b=++x;
      System.out.println(“x=” + x +“a=” +a);
      System.out.println(“x=” + x + “b=” +b);
      a = x--;
      b = --x;
      System.out.println(“x=” + x + “a=” +a);
      System.out.println(“x=” + x + “b=” +b);
      }
}

It will give the following output:

x=19 a=17
x=19 b=19
x=18 a=19
x=17 b=17

How can I perform a short delay in C# without using sleep?

By adding using System.Timers; to your program you can use this function:

private static void delay(int Time_delay)
{
   int i=0;
  //  ameTir = new System.Timers.Timer();
    _delayTimer = new System.Timers.Timer();
    _delayTimer.Interval = Time_delay;
    _delayTimer.AutoReset = false; //so that it only calls the method once
    _delayTimer.Elapsed += (s, args) => i = 1;
    _delayTimer.Start();
    while (i == 0) { };
}

Delay is a function and can be used like:

delay(5000);

ScriptManager.RegisterStartupScript code not working - why?

You must put the updatepanel id in the first argument if the control causing the script is inside the updatepanel else use the keyword 'this' instead of update panel here is the code

ScriptManager.RegisterStartupScript(UpdatePanel3, this.GetType(), UpdatePanel3.UniqueID, "showError();", true);

PHP script to loop through all of the files in a directory?

glob() has provisions for sorting and pattern matching. Since the return value is an array, you can do most of everything else you need.

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

You have to know if the problem come from the listener or from the database.

  • So first, restart the listener, it could solve the problem.

  • Second, it could come from the db if it's not in open mode (nomount, mount, restrict). To check it, connect locally and do the following query:

    sqlplus /nolog

    connect / as sysdba

    SQL> select instance_name, status, database_status from v$instance;

How do you reindex an array in PHP but with indexes starting from 1?

Here is the best way:

# Array
$array = array('tomato', '', 'apple', 'melon', 'cherry', '', '', 'banana');

that returns

Array
(
    [0] => tomato
    [1] => 
    [2] => apple
    [3] => melon
    [4] => cherry
    [5] => 
    [6] => 
    [7] => banana
)

by doing this

$array = array_values(array_filter($array));

you get this

Array
(
    [0] => tomato
    [1] => apple
    [2] => melon
    [3] => cherry
    [4] => banana
)

Explanation

array_values() : Returns the values of the input array and indexes numerically.

array_filter() : Filters the elements of an array with a user-defined function (UDF If none is provided, all entries in the input table valued FALSE will be deleted.)

How to split csv whose columns may contain ,

Use the Microsoft.VisualBasic.FileIO.TextFieldParser class. This will handle parsing a delimited file, TextReader or Stream where some fields are enclosed in quotes and some are not.

For example:

using Microsoft.VisualBasic.FileIO;

string csv = "2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,\"Corvallis, OR\",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";

TextFieldParser parser = new TextFieldParser(new StringReader(csv));

// You can also read from a file
// TextFieldParser parser = new TextFieldParser("mycsvfile.csv");

parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");

string[] fields;

while (!parser.EndOfData)
{
    fields = parser.ReadFields();
    foreach (string field in fields)
    {
        Console.WriteLine(field);
    }
} 

parser.Close();

This should result in the following output:

2
1016
7/31/2008 14:22
Geoff Dalgas
6/5/2011 22:21
http://stackoverflow.com
Corvallis, OR
7679
351
81
b437f461b3fd27387c5d8ab47a293d35
34

See Microsoft.VisualBasic.FileIO.TextFieldParser for more information.

You need to add a reference to Microsoft.VisualBasic in the Add References .NET tab.

Adding a user on .htpasswd

Exact same thing, just omit the -c option. Apache's docs on it here.

htpasswd /etc/apache2/.htpasswd newuser

Also, htpasswd typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).

Convert a Python int into a big-endian string of bytes

def tost(i):
  result = []
  while i:
    result.append(chr(i&0xFF))
    i >>= 8
  result.reverse()
  return ''.join(result)

Disable future dates after today in Jquery Ui Datepicker

maxDate: new Date() 

its working fine for me disable with current date in date range picker

Finding the average of an array using JS

For the second part of your question you can use reduce to good effect here:

_x000D_
_x000D_
const grades = [80, 77, 88, 95, 68];_x000D_
_x000D_
function getAvg(grades) {_x000D_
  const total = grades.reduce((acc, c) => acc + c, 0);_x000D_
  return total / grades.length;_x000D_
}_x000D_
_x000D_
const average = getAvg(grades);_x000D_
console.log(average);
_x000D_
_x000D_
_x000D_

The other answers have given good insight into why you got 68, so I won't repeat it here.

How to collapse blocks of code in Eclipse?

Preferences -> C++ -> Editor -> Folding ?

Make a right click in the editor window and go to preferences there, then only the editor-relevant section of the preferences dialog will appear. This works for JDT, CDT etc...

React Native absolute positioning horizontal centre

If you want to center one element itself you could use alignSelf:

logoImg: {
    position: 'absolute',
    alignSelf: 'center',
    bottom: '-5%'
}

This is an example (Note the logo parent is a view with position: relative)

enter image description here

How do I check if a given string is a legal/valid file name under Windows?

I got this idea from someone. - don't know who. Let the OS do the heavy lifting.

public bool IsPathFileNameGood(string fname)
{
    bool rc = Constants.Fail;
    try
    {
        this._stream = new StreamWriter(fname, true);
        rc = Constants.Pass;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Problem opening file");
        rc = Constants.Fail;
    }
    return rc;
}

Convert Numeric value to Varchar

First convert the numeric value then add the 'S':

 select convert(varchar(10),StandardCost) +'S'
 from DimProduct where ProductKey = 212

Basic Apache commands for a local Windows machine

Going back to absolute basics here. The answers on this page and a little googling have brought me to the following resolution to my issue. Steps to restart the apache service with Xampp installed:-

  1. Click the start button and type CMD (if on Windows Vista or later and Apache is installed as a service make sure this is an elevated command prompt)
  2. In the command window that appears type cd C:\xampp\apache\bin (the default installation path for Xampp)
  3. Then type httpd -k restart

I hope that this is of use to others just starting out with running a local Apache server.

Failed linking file resources

I had the same problem but it occured in all my projects, I tried Invalidate Cache / Restart but even it doesn´t solved the problem.

At the end I realized that in my Gradle Settings, Offline Work was enabled.

Go to Build, Execution, Deployment > Gradle in Gradle Settings unchecked Offline Work.

enter image description here

It solved the the problem downloading some configuration files for my Android Studio.

ASP.NET Core Identity - get current user

In .NET Core 2.0 the user already exists as part of the underlying inherited controller. Just use the User as you would normally or pass across to any repository code.

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "TENANT")]
[HttpGet("issue-type-selection"), Produces("application/json")]
public async Task<IActionResult> IssueTypeSelection()
{
    try
    {
        return new ObjectResult(await _item.IssueTypeSelection(User));
    }
    catch (ExceptionNotFound)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json(new
        {
            error = "invalid_grant",
            error_description = "Item Not Found"
        });
    }
}

This is where it inherits it from

#region Assembly Microsoft.AspNetCore.Mvc.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// C:\Users\BhailDa\.nuget\packages\microsoft.aspnetcore.mvc.core\2.0.0\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Core.dll
#endregion

using System;
using System.IO;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Routing;
using Microsoft.Net.Http.Headers;

namespace Microsoft.AspNetCore.Mvc
{
    //
    // Summary:
    //     A base class for an MVC controller without view support.
    [Controller]
    public abstract class ControllerBase
    {
        protected ControllerBase();

        //
        // Summary:
        //     Gets the System.Security.Claims.ClaimsPrincipal for user associated with the
        //     executing action.
        public ClaimsPrincipal User { get; }

Delete rows with blank values in one particular column

An elegant solution with dplyr would be:

df %>%
  # recode empty strings "" by NAs
  na_if("") %>%
  # remove NAs
  na.omit

T-SQL: Selecting rows to delete via joins

It's almost the same in MySQL, but you have to use the table alias right after the word "DELETE":

DELETE a
FROM TableA AS a
INNER JOIN TableB AS b
ON a.BId = b.BId
WHERE [filter condition]

Graphviz's executables are not found (Python 3.4)

This is the fresh solution I've used :)

I got the same problem, I'm using Anaconda and Jupyter Notebook.

What I did to solve this problem is NOT to install Graphiz.zip from the intenet!

I just did these steps:

  1. Create a new environment using >>conda create -n [env_name]
  2. install graphviz lib inside this new env: >> conda install graphviz
  3. I wrote this lines in the notebook cell and run it import os os.environ['PATH'] = os.environ['PATH']+';'+os.environ['CONDA_PREFIX']+r"\Library\bin\graphviz"

Finally, The image is appeared, I made a small party for this because it took 3 days from me :(

General error: 1364 Field 'user_id' doesn't have a default value

I've had a similar issue with User registration today and I was getting a

SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value (SQL: insert into users

I fixed it by adding password to my protected $fillable array and it worked

protected $fillable = [
  'name',
  'email',
  'password',
];

I hope this helps.

how do I query sql for a latest record date for each user

SELECT Username, date, value
 from MyTable mt
 inner join (select username, max(date) date
              from MyTable
              group by username) sub
  on sub.username = mt.username
   and sub.date = mt.date

Would address the updated problem. It might not work so well on large tables, even with good indexing.

How do I output an ISO 8601 formatted string in JavaScript?

There is a '+' missing after the 'T'

isoDate: function(msSinceEpoch) {
  var d = new Date(msSinceEpoch);
  return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T'
         + d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}

should do it.

For the leading zeros you could use this from here:

function PadDigits(n, totalDigits) 
{ 
    n = n.toString(); 
    var pd = ''; 
    if (totalDigits > n.length) 
    { 
        for (i=0; i < (totalDigits-n.length); i++) 
        { 
            pd += '0'; 
        } 
    } 
    return pd + n.toString(); 
} 

Using it like this:

PadDigits(d.getUTCHours(),2)

How to print colored text to the terminal?

Yet another PyPI module that wraps the Python 3 print function:

https://pypi.python.org/pypi/colorprint

It's usable in Python 2.x if you also from __future__ import print. Here is a Python 2 example from the modules PyPI page:

from __future__ import print_function
from colorprint import *

print('Hello', 'world', color='blue', end='', sep=', ')
print('!', color='red', format=['bold', 'blink'])

It outputs "Hello, world!" with the words in blue and the exclamation mark bold red and blinking.

Android SharedPreferences in Fragment

You can make the SharedPrefences in onAttach method of fragment like this:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    SharedPreferences preferences = context.getSharedPreferences("pref", 0);
}

Reverse colormap in matplotlib

There are two types of LinearSegmentedColormaps. In some, the _segmentdata is given explicitly, e.g., for jet:

>>> cm.jet._segmentdata
{'blue': ((0.0, 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65, 0, 0), (1, 0, 0)), 'red': ((0.0, 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89, 1, 1), (1, 0.5, 0.5)), 'green': ((0.0, 0, 0), (0.125, 0, 0), (0.375, 1, 1), (0.64, 1, 1), (0.91, 0, 0), (1, 0, 0))}

For rainbow, _segmentdata is given as follows:

>>> cm.rainbow._segmentdata
{'blue': <function <lambda> at 0x7fac32ac2b70>, 'red': <function <lambda> at 0x7fac32ac7840>, 'green': <function <lambda> at 0x7fac32ac2d08>}

We can find the functions in the source of matplotlib, where they are given as

_rainbow_data = {
        'red': gfunc[33],   # 33: lambda x: np.abs(2 * x - 0.5),
        'green': gfunc[13], # 13: lambda x: np.sin(x * np.pi),
        'blue': gfunc[10],  # 10: lambda x: np.cos(x * np.pi / 2)
}

Everything you want is already done in matplotlib, just call cm.revcmap, which reverses both types of segmentdata, so

cm.revcmap(cm.rainbow._segmentdata)

should do the job - you can simply create a new LinearSegmentData from that. In revcmap, the reversal of function based SegmentData is done with

def _reverser(f):
    def freversed(x):
        return f(1 - x)
    return freversed

while the other lists are reversed as usual

valnew = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(val)] 

So actually the whole thing you want, is

def reverse_colourmap(cmap, name = 'my_cmap_r'):
     return mpl.colors.LinearSegmentedColormap(name, cm.revcmap(cmap._segmentdata)) 

Why do I need an IoC container as opposed to straightforward DI code?

you do not need a framework to achieve dependency injection. You can do this by core java concepts as well. http://en.wikipedia.org/wiki/Dependency_injection#Code_illustration_using_Java

Difference between two numpy arrays in python

You can also use numpy.subtract

It has the advantage over the difference operator, -, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:

array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])

Example: (Python 3.5)

import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)

which gives you

the difference = [ 0.1  0.2  0.3]

Remember, however, that if you try to subtract sequences (lists or tuples) with the - operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays

Wrong Code:

print([1.1, 2.2, 3.3] - [1, 2, 3])

How can we run a test method with multiple parameters in MSTest?

MSTest does not support that feature, but you can implement your own attribute to achieve that.

Have a look at Enabling parameterized tests in MSTest using PostSharp.

call a function in success of datatable ajax call

Maybe it's not exactly what you want to do, but using the ajax complete solved my problem of hiding a spinner when the ajax call returned.

So it would look something like this

var table = $('#example').DataTable( {
    "ajax": {
            "type" : "GET",
            "url" : "ajax.php",
            "dataSrc": "",
            "success": function () {
                alert("Done!");
            }       
    },
    "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }            
        ]
    } );

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

If you are running your code on 8.0 then application will crash. So start the service in the foreground. If below 8.0 use this :

Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
context.startService(serviceIntent);

If above or 8.0 then use this :

Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
ContextCompat.startForegroundService(context, serviceIntent );

How to create a shortcut using PowerShell

Beginning PowerShell 5.0 New-Item, Remove-Item, and Get-ChildItem have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.

New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"

Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.

Anyway if you want to create a Run As Administrator shortcut using Powershell you can use

$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)

If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.

How to disable text selection highlighting

NOTE:

The correct answer is correct in that it prevents you from being able to select the text. However, it does not prevent you from being able to copy the text, as I'll show with the next couple of screenshots (as of 7th Nov 2014).

Before we have selected anything

After we have selected

The numbers have been copied

As you can see, we were unable to select the numbers, but we were able to copy them.

Tested on: Ubuntu, Google Chrome 38.0.2125.111.

How to give a pattern for new line in grep?

Thanks to @jarno I know about the -z option and I found out that when using GNU grep with the -P option, matching against \n is possible. :)

Example:

grep -zoP 'foo\n\K.*'<<<$'foo\nbar'

Prints bar

The correct way to read a data file into an array

Tie::File is what you need:

Synopsis

# This file documents Tie::File version 0.98
use Tie::File;

tie @array, 'Tie::File', 'filename' or die ...;

$array[13] = 'blah';     # line 13 of the file is now 'blah'
print $array[42];        # display line 42 of the file

$n_recs = @array;        # how many records are in the file?
$#array -= 2;            # chop two records off the end


for (@array) {
  s/PERL/Perl/g;         # Replace PERL with Perl everywhere in the file
}

# These are just like regular push, pop, unshift, shift, and splice
# Except that they modify the file in the way you would expect

push @array, new recs...;
my $r1 = pop @array;
unshift @array, new recs...;
my $r2 = shift @array;
@old_recs = splice @array, 3, 7, new recs...;

untie @array;            # all finished

Mean filter for smoothing images in Matlab

I = imread('peppers.png');
H = fspecial('average', [5 5]);
I = imfilter(I, H);
imshow(I)

Note that filters can be applied to intensity images (2D matrices) using filter2, while on multi-dimensional images (RGB images or 3D matrices) imfilter is used.

Also on Intel processors, imfilter can use the Intel Integrated Performance Primitives (IPP) library to accelerate execution.

openssl s_client -cert: Proving a client certificate was sent to the server

I know this is an old question but it does not yet appear to have an answer. I've duplicated this situation, but I'm writing the server app, so I've been able to establish what happens on the server side as well. The client sends the certificate when the server asks for it and if it has a reference to a real certificate in the s_client command line. My server application is set up to ask for a client certificate and to fail if one is not presented. Here is the command line I issue:

Yourhostname here -vvvvvvvvvv s_client -connect <hostname>:443 -cert client.pem -key cckey.pem -CAfile rootcert.pem -cipher ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH -tls1 -state

When I leave out the "-cert client.pem" part of the command the handshake fails on the server side and the s_client command fails with an error reported. I still get the report "No client certificate CA names sent" but I think that has been answered here above.

The short answer then is that the server determines whether a certificate will be sent by the client under normal operating conditions (s_client is not normal) and the failure is due to the server not recognizing the CA in the certificate presented. I'm not familiar with many situations in which two-way authentication is done although it is required for my project.

You are clearly sending a certificate. The server is clearly rejecting it.

The missing information here is the exact manner in which the certs were created and the way in which the provider loaded the cert, but that is probably all wrapped up by now.

See what's in a stash without applying it

From the man git-stash page:

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show

show [<stash>]
       Show the changes recorded in the stash as a diff between the stashed state and
       its original parent. When no <stash> is given, shows the latest one. By default,
       the command shows the diffstat, but it will accept any format known to git diff
       (e.g., git stash show -p stash@{1} to view the second most recent stash in patch
       form).

To list the stashed modifications

git stash list

To show files changed in the last stash

git stash show

So, to view the content of the most recent stash, run

git stash show -p

To view the content of an arbitrary stash, run something like

git stash show -p stash@{1}

Getting All Variables In Scope

The Simplest Way to Get Access to Vars in a Particular Scope

  1. Open Developer Tools > Resources (in Chrome)
  2. Open file with a function that has access to that scope (tip cmd/ctrl+p to find file)
  3. Set breakpoint inside that function and run your code
  4. When it stops at your breakpoint, you can access the scope var through console (or scope var window)

Note: You want to do this against un-minified js.

The Simplest Way to Show All Non-Private Vars

  1. Open Console (in Chrome)
  2. Type: this.window
  3. Hit Enter

Now you will see an object tree you can expand with all declared objects.

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

Based on your application type/size/load/no. of users ..etc - u can keep following as your production properties

spring.datasource.tomcat.initial-size=50
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=300
spring.datasource.tomcat.max-idle=150
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.default-auto-commit=true