Programs & Examples On #Accessor

An Accessor is (usually) a function that is responsible for reading or writing a property.

Java - Using Accessor and Mutator methods

You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables

public class IDCard {
    public String name, fileName;
    public int id;

    public IDCard(final String name, final String fileName, final int id) {
        this.name = name;
        this.fileName = fileName
        this.id = id;
    }

    public String getName() {
        return name;
    }
}

You can the create an IDCard and use the accessor like this:

final IDCard card = new IDCard();
card.getName();

Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.

If you use the static keyword then those variables are common across every instance of IDCard.

A couple of things to bear in mind:

  1. don't add useless comments - they add code clutter and nothing else.
  2. conform to naming conventions, use lower case of variable names - name not Name.

What are 'get' and 'set' in Swift?

You should look at Computed Properties

In your code sample, perimeter is a property not backed up by a class variable, instead its value is computed using the get method and stored via the set method - usually referred to as getter and setter.

When you use that property like this:

var cp = myClass.perimeter

you are invoking the code contained in the get code block, and when you use it like this:

myClass.perimeter = 5.0

you are invoking the code contained in the set code block, where newValue is automatically filled with the value provided at the right of the assignment operator.

Computed properties can be readwrite if both a getter and a setter are specified, or readonly if the getter only is specified.

How do you detect Credit card type based on number?

Here is an example of some boolean functions written in Python that return True if the card is detected as per the function name.

def is_american_express(cc_number):
    """Checks if the card is an american express. If us billing address country code, & is_amex, use vpos
    https://en.wikipedia.org/wiki/Bank_card_number#cite_note-GenCardFeatures-3
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^3[47][0-9]{13}$', cc_number))


def is_visa(cc_number):
    """Checks if the card is a visa, begins with 4 and 12 or 15 additional digits.
    :param cc_number: unicode card number
    """

    # Standard Visa is 13 or 16, debit can be 19
    if bool(re.match(r'^4', cc_number)) and len(cc_number) in [13, 16, 19]:
        return True

    return False


def is_mastercard(cc_number):
    """Checks if the card is a mastercard. Begins with 51-55 or 2221-2720 and 16 in length.
    :param cc_number: unicode card number
    """
    if len(cc_number) == 16 and cc_number.isdigit():  # Check digit, before cast to int
        return bool(re.match(r'^5[1-5]', cc_number)) or int(cc_number[:4]) in range(2221, 2721)
    return False


def is_discover(cc_number):
    """Checks if the card is discover, re would be too hard to maintain. Not a supported card.
    :param cc_number: unicode card number
    """
    if len(cc_number) == 16:
        try:
            # return bool(cc_number[:4] == '6011' or cc_number[:2] == '65' or cc_number[:6] in range(622126, 622926))
            return bool(cc_number[:4] == '6011' or cc_number[:2] == '65' or 622126 <= int(cc_number[:6]) <= 622925)
        except ValueError:
            return False
    return False


def is_jcb(cc_number):
    """Checks if the card is a jcb. Not a supported card.
    :param cc_number: unicode card number
    """
    # return bool(re.match(r'^(?:2131|1800|35\d{3})\d{11}$', cc_number))  # wikipedia
    return bool(re.match(r'^35(2[89]|[3-8][0-9])[0-9]{12}$', cc_number))  # PawelDecowski


def is_diners_club(cc_number):
    """Checks if the card is a diners club. Not a supported card.
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^3(?:0[0-6]|[68][0-9])[0-9]{11}$', cc_number))  # 0-5 = carte blance, 6 = international


def is_laser(cc_number):
    """Checks if the card is laser. Not a supported card.
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^(6304|670[69]|6771)', cc_number))


def is_maestro(cc_number):
    """Checks if the card is maestro. Not a supported card.
    :param cc_number: unicode card number
    """
    possible_lengths = [12, 13, 14, 15, 16, 17, 18, 19]
    return bool(re.match(r'^(50|5[6-9]|6[0-9])', cc_number)) and len(cc_number) in possible_lengths


# Child cards

def is_visa_electron(cc_number):
    """Child of visa. Checks if the card is a visa electron. Not a supported card.
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^(4026|417500|4508|4844|491(3|7))', cc_number)) and len(cc_number) == 16


def is_total_rewards_visa(cc_number):
    """Child of visa. Checks if the card is a Total Rewards Visa. Not a supported card.
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^41277777[0-9]{8}$', cc_number))


def is_diners_club_carte_blanche(cc_number):
    """Child card of diners. Checks if the card is a diners club carte blance. Not a supported card.
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^30[0-5][0-9]{11}$', cc_number))  # github PawelDecowski, jquery-creditcardvalidator


def is_diners_club_carte_international(cc_number):
    """Child card of diners. Checks if the card is a diners club international. Not a supported card.
    :param cc_number: unicode card number
    """
    return bool(re.match(r'^36[0-9]{12}$', cc_number))  # jquery-creditcardvalidator

How can I hide/show a div when a button is clicked?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show and hide div with JavaScript</title>
<script>

    var button_beg = '<button id="button" onclick="showhide()">', button_end = '</button>';
    var show_button = 'Show', hide_button = 'Hide';
    function showhide() {
        var div = document.getElementById( "hide_show" );
        var showhide = document.getElementById( "showhide" );
        if ( div.style.display !== "none" ) {
            div.style.display = "none";
            button = show_button;
            showhide.innerHTML = button_beg + button + button_end;
        } else {
            div.style.display = "block";
            button = hide_button;
            showhide.innerHTML = button_beg + button + button_end;
        }
    }
    function setup_button( status ) {
        if ( status == 'show' ) {
            button = hide_button;
        } else {
            button = show_button;
        }
        var showhide = document.getElementById( "showhide" );
        showhide.innerHTML = button_beg + button + button_end;
    }
    window.onload = function () {
        setup_button( 'hide' );
        showhide(); // if setup_button is set to 'show' comment this line
    }
</script>
</head>
<body>
    <div id="showhide"></div>
    <div id="hide_show">
        <p>This div will be show and hide on button click</p>
    </div>
</body>
</html>

Select All distinct values in a column using LINQ

To have unique Categories:

var uniqueCategories =  repository.GetAllProducts()
                                  .Select(p=>p.Category)
                                  .Distinct();

What's the best/easiest GUI Library for Ruby?

There are Ruby bindings for QT and GTK so you can't go wrong with those ones (they're portable too).

The Pragmatic Programmers published a mini book on Ruby with QT and a full book on FXRuby, so I think the latter's another good choice.

Shoes, although easy to learn and cute, is pretty situational and doesn't provide as many options for controls as any of the other ones do, so if you want to build anything beyond a simple UI (not to hate Shoes but it's not mature enough yet), I'd recommend you to use one of the more mature and tested toolkits.

SQL query to select distinct row with minimum value

SELECT DISTINCT 
FIRST_VALUE(ID) OVER (Partition by Game ORDER BY Point) AS ID,
Game,
FIRST_VALUE(Point) OVER (Partition by Game ORDER BY Point) AS Point
FROM #T

How to check whether an object has certain method/property?

It is an old question, but I just ran into it. Type.GetMethod(string name) will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case

public static bool HasMethod(this object objectToCheck, string methodName)
{
    try
    {
        var type = objectToCheck.GetType();
        return type.GetMethod(methodName) != null;
    }
    catch(AmbiguousMatchException)
    {
        // ambiguous means there is more than one result,
        // which means: a method with that name does exist
        return true;
    }
} 

Optimal number of threads per core

You will find how many threads you can run on your machine by running htop or ps command that returns number of process on your machine.

You can use man page about 'ps' command.

man ps

If you want to calculate number of all users process, you can use one of these commands:

  1. ps -aux| wc -l
  2. ps -eLf | wc -l

Calculating number of an user process:

  1. ps --User root | wc -l

Also, you can use "htop" [Reference]:

Installing on Ubuntu or Debian:

sudo apt-get install htop

Installing on Redhat or CentOS:

yum install htop
dnf install htop      [On Fedora 22+ releases]

If you want to compile htop from source code, you will find it here.

How to sort a list of lists by a specific index of the inner list?

Sorting a Multidimensional Array execute here

arr=[[2,1],[1,2],[3,5],[4,5],[3,1],[5,2],[3,8],[1,9],[1,3]]



arr.sort(key=lambda x:x[0])
la=set([i[0] for i in Points])

for i in la:
    tempres=list()
    for j in arr:
        if j[0]==i:
            tempres.append(j[1])

    for j in sorted(tempres,reverse=True):
        print(i,j)

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

It is as simple as to Add one dimension, so I was going through the tutorial taught by Siraj Rawal on CNN Code Deployment tutorial, it was working on his terminal, but the same code was not working on my terminal, so I did some research about it and solved, I don't know if that works for you all. Here I have come up with solution;

Unsolved code lines which gives you problem:

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    print(x_train.shape)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols)
    input_shape = (img_rows, img_cols, 1)

Solved Code:

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    print(x_train.shape)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

Please share the feedback here if that worked for you.

SVN undo delete before commit

The simplest solution I could find was to delete the parent directory from the working copy (with rm -rf, not svn delete), and then run svn update in the grandparent. Eg, if you deleted a/b/c, rm -rf a/b, cd a, svn up. That brings everything back. Of course, this is only a good solution if you have no other uncommitted changes in the parent directory that you want to keep.

Hopefully this page will be at the top of the results next time I google this question. It would be even better if someone suggested a cleaner method, of course.

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

There seem to be a lot of solutions for Windows here but this is the simplest:

Tools -> Build System -> New Build System, type in the above, save as Browser.sublime-build:

{
    "cmd": "explorer $file"
}

Then go back to your HTML file. Tools -> Build System -> Browser. Then press CTRL-B and the file will be opened in whatever browser is your system default browser.

QtCreator: No valid kits found

Though OP is asking about Windows, this error also occurs on Ubuntu Linux and Google lists this result first when you search for the error"QtCreator: No valid kits found".

On Ubuntu this is solved by running:

For Qt5:

sudo apt-get install qt5-default

For Qt4:

sudo apt-get install qt4-dev-tools libqt4-dev libqt4-core libqt4-gui

This question is answered here and here, though those entries are less SEO-friendly...

How to restart remote MySQL server running on Ubuntu linux?

Another way is:

systemctl restart mysql

TypeScript hashmap/dictionary interface

Just as a normal js object:

let myhash: IHash = {};   

myhash["somestring"] = "value"; //set

let value = myhash["somestring"]; //get

There are two things you're doing with [indexer: string] : string

  • tell TypeScript that the object can have any string-based key
  • that for all key entries the value MUST be a string type.

enter image description here

You can make a general dictionary with explicitly typed fields by using [key: string]: any;

enter image description here

e.g. age must be number, while name must be a string - both are required. Any implicit field can be any type of value.

As an alternative, there is a Map class:

let map = new Map<object, string>(); 

let key = new Object();

map.set(key, "value");
map.get(key); // return "value"

This allows you have any Object instance (not just number/string) as the key.

Although its relatively new so you may have to polyfill it if you target old systems.

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Qt Creator, apart from other goodies, also has a good debugger integration, for CDB, GDB and the Symnbian debugger, on all supported platforms. You don't need to use Qt to use the Qt Creator IDE, nor do you need to use QMake - it also has CMake integration, although QMake is very easy to use.

You may want to use Qt Creator as the IDE to teach programming with, consider it has some good features:

  • Very smart and advanced C++ editor
  • Project and build management tools
  • QMake and CMake integration
  • Integrated, context-sensitive help system
  • Excellent visual debugger (CDB, GDB and Symbian)
  • Supports GCC and VC++
  • Rapid code navigation tools
  • Supports Windows, Linux and Mac OS X

Recursively find all files newer than a given time

Assuming a modern release, find -newermt is powerful:

find -newermt '10 minutes ago' ## other units work too, see `Date input formats`

or, if you want to specify a time_t (seconds since epoch):

find -newermt @1568670245

For reference, -newermt is not directly listed in the man page for find. Instead, it is shown as -newerXY, where XY are placeholders for mt. Other replacements are legal, but not applicable for this solution.

From man find -newerXY:

Time specifications are interpreted as for the argument to the -d option of GNU date.

So the following are equivalent to the initial example:

find -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d '10 minutes ago')" ## long form using 'date'
find -newermt "@$(date +%s -d '10 minutes ago')" ## short form using 'date' -- notice '@'

The date -d (and find -newermt) arguments are quite flexible, but the documentation is obscure. Here's one source that seems to be on point: Date input formats

Sort a Map<Key, Value> by values

From http://www.programmersheaven.com/download/49349/download.aspx

private static <K, V> Map<K, V> sortByValue(Map<K, V> map) {
    List<Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort(list, new Comparator<Object>() {
        @SuppressWarnings("unchecked")
        public int compare(Object o1, Object o2) {
            return ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue()).compareTo(((Map.Entry<K, V>) (o2)).getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<>();
    for (Iterator<Entry<K, V>> it = list.iterator(); it.hasNext();) {
        Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();
        result.put(entry.getKey(), entry.getValue());
    }

    return result;
}

Removing the first 3 characters from a string

Just use substring: "apple".substring(3); will return le

How to set space between listView Items in Android

<ListView
    android:clipToPadding="false"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:dividerHeight="10dp"
    android:divider="@null"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</ListView>

and set paddingTop, paddingBottom and dividerHeight to the same value to get equal spacing between all elements and space at the top and bottom of the list.

I set clipToPadding to false to let the views be drawn in this padded area.

I set divider to @null to remove the lines between list elements.

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

Check Java versions That was a problem for me. IDE (Intellij in my case) could launch without the problem, but when I tried to run war inside tomcat docker image app didn't work. The reason was docker image had a different (lower) version compare to the development environment. There were no errors messages indicating any of this.

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

There are similar questions:

Usually, the solution is:

sudo apt-get install ruby-dev

Or, if that doesn't work, depending on your ruby version, run something like:

sudo apt-get install ruby1.9.1-dev

Should fix your problem.


Still not working? Try the following after installing ruby-dev:

sudo apt-get install make

Get the position of a div/span tag

As Alex noted you can use jQuery offset() to get the position relative to the document flow. Use position() for its x,y coordinates relative to the parent.

EDIT: Switched document.ready for window.load because load waits for all of the elements so you get their size instead of simply preparing the DOM. In my experience, load results in fewer incorrectly Javascript positioned elements.

$(window).load(function(){ 
  // Log the position with jQuery
  var position = $('#myDivInQuestion').position();
  console.log('X: ' + position.left + ", Y: " + position.top );
});

How do I test for an empty JavaScript object?

That's similar way of how it gets checked in lodash source for object :

const isEmpty = value => {
  for (const key in value) {
    if (hasOwnProperty.call(value, key)) {
      return false
    }
  }
  return true;
}

But there are many other ways to do that.

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Put quotes around $username. String values, as opposed to numeric values, must be enclosed in quotes.

$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");

Also, there is no point in using the LIKE condition if you're not using wildcards: if you need an exact match use = instead of LIKE.

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

Check if a string contains a number

You can use NLTK method for it.

This will find both '1' and 'One' in the text:

import nltk 

def existence_of_numeric_data(text):
    text=nltk.word_tokenize(text)
    pos = nltk.pos_tag(text)
    count = 0
    for i in range(len(pos)):
        word , pos_tag = pos[i]
        if pos_tag == 'CD':
            return True
    return False

existence_of_numeric_data('We are going out. Just five you and me.')

How do I run Selenium in Xvfb?

You can use PyVirtualDisplay (a Python wrapper for Xvfb) to run headless WebDriver tests.

#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(800, 600))
display.start()

# now Firefox will run in a virtual display. 
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()

display.stop()

more info


You can also use xvfbwrapper, which is a similar module (but has no external dependencies):

from xvfbwrapper import Xvfb

vdisplay = Xvfb()
vdisplay.start()

# launch stuff inside virtual display here

vdisplay.stop()

or better yet, use it as a context manager:

from xvfbwrapper import Xvfb

with Xvfb() as xvfb:
    # launch stuff inside virtual display here.
    # It starts/stops in this code block.

How to open my files in data_folder with pandas using relative path?

This link here answers it. Reading file using relative path in python project

Basically using Path from pathlib you'll do the following in script.py

from pathlib import Path
path = Path(__file__).parent / "../data_folder/data.csv"
pd.read_csv(path)

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

For those who need the same feature in IE 8, this is how I solved the problem:

  var myImage = $('<img/>');

               myImage.attr('width', 300);
               myImage.attr('height', 300);
               myImage.attr('class', "groupMediaPhoto");
               myImage.attr('src', photoUrl);

I could not force IE8 to use object in constructor.

How do I extract a substring from a string until the second space is encountered?

A straightforward approach would be the following:

string[] tokens = str.Split(' ');
string retVal = tokens[0] + " " + tokens[1];

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

use this code

 public List<Blog> removeDuplicates(List<Blog> list) {
    // Set set1 = new LinkedHashSet(list);
    Set set = new TreeSet(new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            if (((Blog) o1).get().equalsIgnoreCase(((Blog) o2).getId()) /*&&
                    ((Blog)o1).getName().equalsIgnoreCase(((Blog)o2).getName())*/) {
                return 0;
            }
            return 1;
        }
    });
    set.addAll(list);

    final List newList = new ArrayList(set);
    return newList;
}

Download image with JavaScript

As @Ian explained, the problem is that jQuery's click() is not the same as the native one.

Therefore, consider using vanilla-js instead of jQuery:

var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

Demo

Export table from database to csv file

From SQL Server Management Studio

Right click the table you want to export and select "Select All Rows"

Right click the results window and select "Save Results As..."

Search for exact match of string in excel row using VBA Macro

Try this:

Sub GetColumns()

Dim lnRow As Long, lnCol As Long

lnRow = 3 'For testing

lnCol = Sheet1.Cells(lnRow, 1).EntireRow.Find(What:="sds", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column

End Sub

Probably best not to use colIndex and rowIndex as variable names as they are already mentioned in the Excel Object Library.

mappedBy reference an unknown target entity property

I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.

If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany annotation with the 'mappedBy' property, it also means that the other side holding the @ManyToOne annotation with the @JoinColumn is the 'owner' of this bi-directional relationship.

Also, mappedBy takes in the instance name (mCustomer in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).

BONUS : Also, look into the orphanRemoval property of @OneToMany annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.

error C2220: warning treated as error - no 'object' file generated

This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):

warning C4101: 'i': unreferenced local variable

After I commented this unused i, and compiled it, the other error went away.

Importing lodash into angular2 + typescript application

Here is how to do this as of Typescript 2.0: (tsd and typings are being deprecated in favor of the following):

$ npm install --save lodash

# This is the new bit here: 
$ npm install --save-dev @types/lodash

Then, in your .ts file:

Either:

import * as _ from "lodash";

Or (as suggested by @Naitik):

import _ from "lodash";

I'm not positive what the difference is. We use and prefer the first syntax. However, some report that the first syntax doesn't work for them, and someone else has commented that the latter syntax is incompatible with lazy loaded webpack modules. YMMV.

Edit on Feb 27th, 2017:

According to @Koert below, import * as _ from "lodash"; is the only working syntax as of Typescript 2.2.1, lodash 4.17.4, and @types/lodash 4.14.53. He says that the other suggested import syntax gives the error "has no default export".

Select Last Row in the Table

Don't use Model::latest()->first(); because if your collection has multiple rows created at the same timestamp (this will happen when you use database transaction DB::beginTransaction(); and DB::commit()) then the first row of the collection will be returned and obviously this will not be the last row.

Suppose row with id 11, 12, 13 are created using transaction then all of them will have the same timestamp so what you will get by Model::latest()->first(); is the row with id: 11.

View markdown files offline

Remarkable, certainly a great tool.

Features:

  • Live preview
  • It's free.
  • Extremely lightweight
  • Export to HTML, PDF

Download: https://remarkableapp.github.io/

Quicksort: Choosing the pivot

Never ever choose a fixed pivot - this can be attacked to exploit your algorithm's worst case O(n2) runtime, which is just asking for trouble. Quicksort's worst case runtime occurs when partitioning results in one array of 1 element, and one array of n-1 elements. Suppose you choose the first element as your partition. If someone feeds an array to your algorithm that is in decreasing order, your first pivot will be the biggest, so everything else in the array will move to the left of it. Then when you recurse, the first element will be the biggest again, so once more you put everything to the left of it, and so on.

A better technique is the median-of-3 method, where you pick three elements at random, and choose the middle. You know that the element that you choose won't be the the first or the last, but also, by the central limit theorem, the distribution of the middle element will be normal, which means that you will tend towards the middle (and hence, nlog(n) time).

If you absolutely want to guarantee O(nlog(n)) runtime for the algorithm, the columns-of-5 method for finding the median of an array runs in O(n) time, which means that the recurrence equation for quicksort in the worst case will be:

T(n) = O(n) (find the median) + O(n) (partition) + 2T(n/2) (recurse left and right)

By the Master Theorem, this is O(nlog(n)). However, the constant factor will be huge, and if worst case performance is your primary concern, use a merge sort instead, which is only a little bit slower than quicksort on average, and guarantees O(nlog(n)) time (and will be much faster than this lame median quicksort).

Explanation of the Median of Medians Algorithm

How can I add a custom HTTP header to ajax request with js or jQuery?

You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there:

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
    this.setRequestHeader('x-my-custom-header', 'some value');
    this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;

C++ cout hex values?

There are different kinds of flags & masks you can use as well. Please refer http://www.cplusplus.com/reference/iostream/ios_base/setf/ for more information.

#include <iostream>
using namespace std;

int main()
{
    int num = 255;
    cout.setf(ios::hex, ios::basefield);
    cout << "Hex: " << num << endl;

    cout.unsetf(ios::hex);
    cout << "Original format: " << num << endl;

    return 0;
}

What is getattr() exactly and how do I use it?

It is also clarifying from https://www.programiz.com/python-programming/methods/built-in/getattr

class Person:
    age = 23
    name = "Adam"

person = Person()
print('The age is:', getattr(person, "age"))
print('The age is:', person.age)

The age is: 23

The age is: 23

class Person:
    age = 23
    name = "Adam"

person = Person()

# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))

# when no default value is provided
print('The sex is:', getattr(person, 'sex'))

The sex is: Male

AttributeError: 'Person' object has no attribute 'sex'

How to implement a ConfigurationSection with a ConfigurationElementCollection

The previous answer is correct but I'll give you all the code as well.

Your app.config should look like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <configSections>
      <section name="ServicesSection" type="RT.Core.Config.ServiceConfigurationSection, RT.Core"/>
   </configSections>
   <ServicesSection>
      <Services>
         <add Port="6996" ReportType="File" />
         <add Port="7001" ReportType="Other" />
      </Services>
   </ServicesSection>
</configuration>

Your ServiceConfig and ServiceCollection classes remain unchanged.

You need a new class:

public class ServiceConfigurationSection : ConfigurationSection
{
   [ConfigurationProperty("Services", IsDefaultCollection = false)]
   [ConfigurationCollection(typeof(ServiceCollection),
       AddItemName = "add",
       ClearItemsName = "clear",
       RemoveItemName = "remove")]
   public ServiceCollection Services
   {
      get
      {
         return (ServiceCollection)base["Services"];
      }
   }
}

And that should do the trick. To consume it you can use:

ServiceConfigurationSection serviceConfigSection =
   ConfigurationManager.GetSection("ServicesSection") as ServiceConfigurationSection;

ServiceConfig serviceConfig = serviceConfigSection.Services[0];

How to initialize an array's length in JavaScript?

var arr=[];
arr[5]=0;
alert("length="+arr.length); // gives 6

How to clear the cache of nginx?

On my server, the nginx cache folder is at /data/nginx/cache/

So I removed it only: sudo rm -rf /data/nginx/cache/

Hope this will help anyone.

Search and get a line in Python

If you prefer a one-liner:

matched_lines = [line for line in my_string.split('\n') if "substring" in line]

newline character in c# string

A great way of handling this is with regular expressions.

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.

Get table names using SELECT statement in MySQL

Besides using the INFORMATION_SCHEMA table, to use SHOW TABLES to insert into a table you would use the following

<?php
 $sql = "SHOW TABLES FROM $dbname";
 $result = mysql_query($sql);
 $arrayCount = 0
 while ($row = mysql_fetch_row($result)) {
  $tableNames[$arrayCount] = $row[0];
  $arrayCount++; //only do this to make sure it starts at index 0
 }
 foreach ($tableNames as &$name {
  $query = "INSERT INTO metadata (table_name) VALUES ('".$name."')";
  mysql_query($query);
 }
?>

Google Maps API 3 - Custom marker color for default (dot) marker

Well the closest thing I've been able to get with the StyledMarker is this.

The bullet in the middle isn't quite a big as the default one though. The StyledMarker class simply builds this url and asks the google api to create the marker.

From the class use example use "%E2%80%A2" as your text, as in:

var styleMaker2 = new StyledMarker({styleIcon:new StyledIcon(StyledIconTypes.MARKER,{text:"%E2%80%A2"},styleIconClass),position:new google.maps.LatLng(37.263477473067, -121.880502070713),map:map});

You will need to modifiy StyledMarker.js to comment out the lines:

  if (text_) {
    text_ = text_.substr(0,2);
  }

as this will trim the text string to 2 characters.

Alternatively you could create custom marker images based on the default one with the colors you desire and override the default marker with code such as this:

marker = new google.maps.Marker({
  map:map,
  position: latlng,
  icon: new google.maps.MarkerImage(
    'http://www.gettyicons.com/free-icons/108/gis-gps/png/24/needle_left_yellow_2_24.png',
    new google.maps.Size(24, 24),
    new google.maps.Point(0, 0),
    new google.maps.Point(0, 24)
  )
});

Python - 'ascii' codec can't decode byte

If you are starting the python interpreter from a shell on Linux or similar systems (BSD, not sure about Mac), you should also check the default encoding for the shell.

Call locale charmap from the shell (not the python interpreter) and you should see

[user@host dir] $ locale charmap
UTF-8
[user@host dir] $ 

If this is not the case, and you see something else, e.g.

[user@host dir] $ locale charmap
ANSI_X3.4-1968
[user@host dir] $ 

Python will (at least in some cases such as in mine) inherit the shell's encoding and will not be able to print (some? all?) unicode characters. Python's own default encoding that you see and control via sys.getdefaultencoding() and sys.setdefaultencoding() is in this case ignored.

If you find that you have this problem, you can fix that by

[user@host dir] $ export LC_CTYPE="en_EN.UTF-8"
[user@host dir] $ locale charmap
UTF-8
[user@host dir] $ 

(Or alternatively choose whichever keymap you want instead of en_EN.) You can also edit /etc/locale.conf (or whichever file governs the locale definition in your system) to correct this.

How to correctly implement custom iterators and const_iterators?

Boost has something to help: the Boost.Iterator library.

More precisely this page: boost::iterator_adaptor.

What's very interesting is the Tutorial Example which shows a complete implementation, from scratch, for a custom type.

template <class Value>
class node_iter
  : public boost::iterator_adaptor<
        node_iter<Value>                // Derived
      , Value*                          // Base
      , boost::use_default              // Value
      , boost::forward_traversal_tag    // CategoryOrTraversal
    >
{
 private:
    struct enabler {};  // a private type avoids misuse

 public:
    node_iter()
      : node_iter::iterator_adaptor_(0) {}

    explicit node_iter(Value* p)
      : node_iter::iterator_adaptor_(p) {}

    // iterator convertible to const_iterator, not vice-versa
    template <class OtherValue>
    node_iter(
        node_iter<OtherValue> const& other
      , typename boost::enable_if<
            boost::is_convertible<OtherValue*,Value*>
          , enabler
        >::type = enabler()
    )
      : node_iter::iterator_adaptor_(other.base()) {}

 private:
    friend class boost::iterator_core_access;
    void increment() { this->base_reference() = this->base()->next(); }
};

The main point, as has been cited already, is to use a single template implementation and typedef it.

must appear in the GROUP BY clause or be used in an aggregate function

This seems to work as well

SELECT *
FROM makerar m1
WHERE m1.avg = (SELECT MAX(avg)
                FROM makerar m2
                WHERE m1.cname = m2.cname
               )

Java Thread Example?

There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.

Adding Multiple Values in ArrayList at a single index

ArrayList<ArrayList> arrObjList = new ArrayList<ArrayList>();
ArrayList<Double> arrObjInner1= new ArrayList<Double>();
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);

arrObjList.add(arrObjInner1);

You can have as many ArrayList inside the arrObjList. I hope this will help you.

How does one convert a HashMap to a List in Java?

If you only want it to iterate over your HashMap, no need for a list:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values()) {
    System.out.println(s);
}

Of course, if you want to modify your map structurally (i.e. more than only changing the value for an existing key) while iterating, then you better use the "copy to ArrayList" method, since otherwise you'll get a ConcurrentModificationException. Or export as an array:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values().toArray(new String[]{})) {
    System.out.println(s);
}

Select <a> which href ends with some string

$("a[href*='id=ABC']").addClass('active_jquery_menu');

SQL Server copy all rows from one table into another i.e duplicate table

Don't have sql server around to test but I think it's just:

insert into newtable select * from oldtable;

gnuplot plotting multiple line graphs

I think your problem is your version numbers. Try making 8.1 --> 8.01, and so forth. That should put the points in the right order.

Alternatively, you could plot using X, where X is the column number you want, instead of using 1:X. That will plot those values on the y axis and integers on the x axis. Try:

plot "ls.dat" using 2 title 'Removed' with lines, \
     "ls.dat" using 3 title 'Added' with lines, \
     "ls.dat" using 4 title 'Modified' with lines

Simple argparse example wanted: 1 argument, 3 results

A really simple way to use argparse and amend the '-h'/ '--help' switches to display your own personal code help instructions is to set the default help to False, you can also add as many additional .add_arguments as you like:

import argparse

parser = argparse.ArgumentParser(add_help=False)

parser.add_argument('-h', '--help', action='help',
                help='To run this script please provide two arguments')
parser.parse_args()

Run: python test.py -h

Output:

usage: test.py [-h]

optional arguments:
  -h, --help  To run this script please provide two arguments

How do I change Eclipse to use spaces instead of tabs?

Eclipse IDE for C/C++ Developers, Version: Helios Service Release 2

You need to create new profile by pressing New button inside "Window->Preferences->Code Style"

Go to Indentation tab and select "Tab policy = Space only"


Eclipse IDE for C/C++ Developers, Version: Kepler Service Release 1

Follow the path below to create new profile: "Window > Preferences > C/C++ > Code Style > Formatter"

Go to Indentation tab and select "Tab policy = Space only"

Convert timestamp in milliseconds to string formatted time in Java

Try this:

Date date = new Date(logEvent.timeSTamp);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateFormatted = formatter.format(date);

See SimpleDateFormat for a description of other format strings that the class accepts.

See runnable example using input of 1200 ms.

Pass Multiple Parameters to jQuery ajax call

            data: JSON.stringify({ "objectnameOFcontroller": data, "Sel": $(th).val() }),

controller object name

Detecting locked tables (locked by LOCK TABLE)

You could also get all relevant details from performance_schema:

SELECT
OBJECT_SCHEMA
,OBJECT_NAME
,GROUP_CONCAT(DISTINCT EXTERNAL_LOCK)
FROM performance_schema.table_handles 
WHERE EXTERNAL_LOCK IS NOT NULL

GROUP BY
OBJECT_SCHEMA
,OBJECT_NAME

This works similar as

show open tables WHERE In_use > 0

Read line by line in bash script

FILE=test

while read CMD; do
    echo "$CMD"
done < "$FILE"

A redirection with < "$FILE" has a few advantages over cat "$FILE" | while .... It avoids a useless use of cat, saving an unnecessary child process. It also avoids a common pitfall where the loop runs in a subshell. In bash, commands in a | pipeline run in subshells, which means variable assignments are lost after the loop ends. Redirection with < doesn't have that problem, so you could use $CMD after the loop or modify other variables inside the loop. It also, again, avoids unnecessary child processes.

There are some additional improvements that could be made:

  • Add IFS= so that read won't trim leading and trailing whitespace from each line.
  • Add -r to read to prevent from backslashes from being interpreted as escape sequences.
  • Lower case CMD and FILE. The bash convention is only environmental and internal shell variables are uppercase.
  • Use printf in place of echo which is safer if $cmd is a string like -n, which echo would interpret as a flag.
file=test

while IFS= read -r cmd; do
    printf '%s\n' "$cmd"
done < "$file"

Catch multiple exceptions in one line (except block)

One of the way to do this is..

try:
   You do your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

and another way is to create method which performs task executed by except block and call it through all of the except block that you write..

try:
   You do your operations here;
   ......................
except Exception1:
    functionname(parameterList)
except Exception2:
    functionname(parameterList)
except Exception3:
    functionname(parameterList)
else:
   If there is no exception then execute this block. 

def functionname( parameters ):
   //your task..
   return [expression]

I know that second one is not the best way to do this, but i'm just showing number of ways to do this thing.

postgresql duplicate key violates unique constraint

The primary key is already protecting you from inserting duplicate values, as you're experiencing when you get that error. Adding another unique constraint isn't necessary to do that.

The "duplicate key" error is telling you that the work was not done because it would produce a duplicate key, not that it discovered a duplicate key already commited to the table.

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

I face the same issue. I am using docker version:17.09.0-ce.

I follow below steps:

  1. Create Dockerfile and added commands for creating docker image
  2. Go to directory where we have created Dockfile
  3. execute below command $ sudo docker build -t ubuntu-test:latest .

It resolved issue and image created successsfully.

Note: build command depend on docker version as well as which build option we are using. :)

JavaScript file upload size validation

JQuery example provided in this thread was extremely outdated, and google wasn't helpful at all so here is my revision:

 <script type="text/javascript">
        $('#image-file').on('change', function() {
            console.log($(this)[0].files[0].name+' file size is: ' + $(this)[0].files[0].size/1024/1024 + 'Mb');
        });
    </script>

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

Update 2nd table data in 1st table need to Inner join before SET :

`UPDATE `table1` INNER JOIN `table2` ON `table2`.`id`=`table1`.`id` SET `table1`.`name`=`table2`.`name`, `table1`.`template`=`table2`.`template`;

Hide horizontal scrollbar on an iframe?

This answer is only applicable for websites which use Bootstrap. The responsive embed feature of the Bootstrap takes care of the scrollbars.

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="http://www.youtube.com/embed/WsFWhL4Y84Y"></iframe>
</div> 

jsfiddle: http://jsfiddle.net/00qggsjj/2/

http://getbootstrap.com/components/#responsive-embed

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

If you migrated to Laravel 8, you have to add a namespace to the seeders class:

<?php

namespace Database\Seeders;

...

Next, in your composer.json file, remove classmap block from the autoload section and add the new namespaced class directory mappings:

"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Database\\Seeders\\": "database/seeds/"
    }
},

An finally, do a composer dump-autoload.

For more information: https://laravel.com/docs/8.x/upgrade#seeder-factory-namespaces

How to change node.js's console font color?

You can also use colorworks.

Usage:

var cw = require('colorworks').create();
console.info(cw.compile('[[red|Red message with a [[yellow|yellow]] word.]]'));

To make life easier, you can also make a function with it.

function say(msg) {
  console.info(cw.compile(msg));
}

Now you can do:

say(`[[yellow|Time spent: [[green|${time}]]ms.]]`);

How to define constants in Visual C# like #define in C?

In C#, per MSDN library, we have the "const" keyword that does the work of the "#define" keyword in other languages.

"...when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces." ( https://msdn.microsoft.com/en-us/library/ms173119.aspx )

Initialize constants at time of declaration since there is no changing them.

public const int cMonths = 12;

Git Commit Messages: 50/72 Formatting

Regarding the “summary” line (the 50 in your formula), the Linux kernel documentation has this to say:

For these reasons, the "summary" must be no more than 70-75
characters, and it must describe both what the patch changes, as well
as why the patch might be necessary.  It is challenging to be both
succinct and descriptive, but that is what a well-written summary
should do.

That said, it seems like kernel maintainers do indeed try to keep things around 50. Here’s a histogram of the lengths of the summary lines in the git log for the kernel:

Lengths of Git summary lines (view full-sized)

There is a smattering of commits that have summary lines that are longer (some much longer) than this plot can hold without making the interesting part look like one single line. (There’s probably some fancy statistical technique for incorporating that data here but oh well… :-)

If you want to see the raw lengths:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{print length($0)}'

or a text-based histogram:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{lens[length($0)]++;} END {for (len in lens) print len, lens[len] }' | sort -n

Python Graph Library

I would like to plug my own graph python library: graph-tool.

It is very fast, since it is implemented in C++ with the Boost Graph Library, and it contains lots of algorithms and extensive documentation.

Android, How to create option Menu

Android UI programming is a little bit tricky. To enable the Options menu, in addition to the code you wrote, we also need to call setHasOptionsMenu(true) in your overriden method OnCreate(). Hope this will help you out.

How do I create a sequence in MySQL?

If You need sth different than AUTO_INCREMENT you can still use triggers.

How to remove item from array by value?

ES6 way.

const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);

How should I set the default proxy to use default credentials?

Is need in some systems set null the Proxy proprerty:

Net.WebRequest.DefaultWebProxy.Credentials = System.Net.CredentialCache.DefaultCredentials Dim request As WebRequest = WebRequest.Create(sRemoteFileURL) request.Proxy = Nothing

It's a bug.

How to set default value to the input[type="date"]

1 - @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    <input type="date" "myDate">
    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

    var today = new Date();
    $('#myDate').val(today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2));

2 - @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   <input type="datatime-local" id="myLocalDataTime" step="1">
    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

var today = new Date();
$('#myLocalDataTime').val(today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2)+'T'+today.getHours()+':'+today.getMinutes());

Rotating a two-dimensional array in Python

There are three parts to this:

  1. original[::-1] reverses the original array. This notation is Python list slicing. This gives you a "sublist" of the original list described by [start:end:step], start is the first element, end is the last element to be used in the sublist. step says take every step'th element from first to last. Omitted start and end means the slice will be the entire list, and the negative step means that you'll get the elements in reverse. So, for example, if original was [x,y,z], the result would be [z,y,x]
  2. The * when preceding a list/tuple in the argument list of a function call means "expand" the list/tuple so that each of its elements becomes a separate argument to the function, rather than the list/tuple itself. So that if, say, args = [1,2,3], then zip(args) is the same as zip([1,2,3]), but zip(*args) is the same as zip(1,2,3).
  3. zip is a function that takes n arguments each of which is of length m and produces a list of length m, the elements of are of length n and contain the corresponding elements of each of the original lists. E.g., zip([1,2],[a,b],[x,y]) is [[1,a,x],[2,b,y]]. See also Python documentation.

How to get status code from webclient?

This is what I use for expanding WebClient functionality. StatusCode and StatusDescription will always contain the most recent response code/description.

                /// <summary>
                /// An expanded web client that allows certificate auth and 
                /// the retrieval of status' for successful requests
                /// </summary>
                public class WebClientCert : WebClient
                {
                    private X509Certificate2 _cert;
                    public WebClientCert(X509Certificate2 cert) : base() { _cert = cert; }
                    protected override WebRequest GetWebRequest(Uri address)
                    {
                        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
                        if (_cert != null) { request.ClientCertificates.Add(_cert); }
                        return request;
                    }
                    protected override WebResponse GetWebResponse(WebRequest request)
                    {
                        WebResponse response = null;
                        response = base.GetWebResponse(request);
                        HttpWebResponse baseResponse = response as HttpWebResponse;
                        StatusCode = baseResponse.StatusCode;
                        StatusDescription = baseResponse.StatusDescription;
                        return response;
                    }
                    /// <summary>
                    /// The most recent response statusCode
                    /// </summary>
                    public HttpStatusCode StatusCode { get; set; }
                    /// <summary>
                    /// The most recent response statusDescription
                    /// </summary>
                    public string StatusDescription { get; set; }
                }

Thus you can do a post and get result via:

            byte[] response = null;
            using (WebClientCert client = new WebClientCert())
            {
                response = client.UploadValues(postUri, PostFields);
                HttpStatusCode code = client.StatusCode;
                string description = client.StatusDescription;
                //Use this information
            }

How to install pip for Python 3 on Mac OS X?

I had to go through this process myself and chose a different way that I think is better in the long run.

I installed homebrew

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

then:

brew doctor

The last step gives you some warnings and errors that you have to resolve. One of those will be to download and install the Mac OS X command-line tools.

then:

brew install python3

This gave me python3 and pip3 in my path.

pieter$ which pip3 python3
/usr/local/bin/pip3
/usr/local/bin/python3

Change status bar text color to light in iOS 9 with Objective-C

iOS Status bar has only 2 options (black and white). You can try this in AppDelegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    [[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleLightContent];
}

Run Function After Delay

You can simply use jQuery’s delay() method to set the delay time interval.

HTML code:

  <div class="box"></div>

JQuery code:

  $(document).ready(function(){ 
    $(".show-box").click(function(){
      $(this).text('loading...').delay(1000).queue(function() {
        $(this).hide();
        showBox(); 
        $(this).dequeue();
      });        
    });
  });

You can see an example here: How to Call a Function After Some Time in jQuery

How can I install the Beautiful Soup module on the Mac?

Download the package and unpack it. In Terminal, go to the package's directory and type

python setup.py install

C++ Convert string (or char*) to wstring (or wchar_t*)

This variant of it is my favourite in real life. It converts the input, if it is valid UTF-8, to the respective wstring. If the input is corrupted, the wstring is constructed out of the single bytes. This is extremely helpful if you cannot really be sure about the quality of your input data.

std::wstring convert(const std::string& input)
{
    try
    {
        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
        return converter.from_bytes(input);
    }
    catch(std::range_error& e)
    {
        size_t length = input.length();
        std::wstring result;
        result.reserve(length);
        for(size_t i = 0; i < length; i++)
        {
            result.push_back(input[i] & 0xFF);
        }
        return result;
    }
}

Vue equivalent of setTimeout?

You can use Vue.nextTick

addToBasket: function(){
                item = this.photo;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
                Vue.nextTick(() =>{
                    this.basketAddSuccess = false;
                });
            }

Can you overload controller methods in ASP.NET MVC?

You can use [ActionName("NewActionName")] to use the same method with a different name:

public class HomeController : Controller
{
    public ActionResult GetEmpName()
    {
        return Content("This is the test Message");
    }

    [ActionName("GetEmpWithCode")]
    public ActionResult GetEmpName(string EmpCode)
    {
        return Content("This is the test Messagewith Overloaded");
    }
}

Generate a Hash from string in Javascript

I went for a simple concatenation of char codes converted to hex strings. This serves a relatively narrow purpose, namely just needing a hash representation of a SHORT string (e.g. titles, tags) to be exchanged with a server side that for not relevant reasons can't easily implement the accepted hashCode Java port. Obviously no security application here.

String.prototype.hash = function() {
  var self = this, range = Array(this.length);
  for(var i = 0; i < this.length; i++) {
    range[i] = i;
  }
  return Array.prototype.map.call(range, function(i) {
    return self.charCodeAt(i).toString(16);
  }).join('');
}

This can be made more terse and browser-tolerant with Underscore. Example:

"Lorem Ipsum".hash()
"4c6f72656d20497073756d"

I suppose if you wanted to hash larger strings in similar fashion you could just reduce the char codes and hexify the resulting sum rather than concatenate the individual characters together:

String.prototype.hashLarge = function() {
  var self = this, range = Array(this.length);
  for(var i = 0; i < this.length; i++) {
    range[i] = i;
  }
  return Array.prototype.reduce.call(range, function(sum, i) {
    return sum + self.charCodeAt(i);
  }, 0).toString(16);
}

'One time, I hired a monkey to take notes for me in class. I would just sit back with my mind completely blank while the monkey scribbled on little pieces of paper. At the end of the week, the teacher said, "Class, I want you to write a paper using your notes." So I wrote a paper that said, "Hello! My name is Bingo! I like to climb on things! Can I have a banana? Eek, eek!" I got an F. When I told my mom about it, she said, "I told you, never trust a monkey!"'.hashLarge()
"9ce7"

Naturally more risk of collision with this method, though you could fiddle with the arithmetic in the reduce however you wanted to diversify and lengthen the hash.

Disable scrolling on `<input type=number>`

Prevent the default behavior of the mousewheel event on input-number elements like suggested by others (calling "blur()" would normally not be the preferred way to do it, because that wouldn't be, what the user wants).

BUT. I would avoid listening for the mousewheel event on all input-number elements all the time and only do it, when the element is in focus (that's when the problem exists). Otherwise the user cannot scroll the page when the mouse pointer is anywhere over a input-number element.

Solution for jQuery:

// disable mousewheel on a input number field when in focus
// (to prevent Cromium browsers change the value when scrolling)
$('form').on('focus', 'input[type=number]', function (e) {
  $(this).on('wheel.disableScroll', function (e) {
    e.preventDefault()
  })
})
$('form').on('blur', 'input[type=number]', function (e) {
  $(this).off('wheel.disableScroll')
})

(Delegate focus events to the surrounding form element - to avoid to many event listeners, which are bad for performance.)

Can’t delete docker image with dependent child images

What worked to me was to use the REPOSITORY:TAG combination rather than IMAGE ID.

When I tried to delete a docker image with the command docker rmi <IMAGE ID> with no containers associated with this image I had the message:

$ docker rmi 3f66bec2c6bf
Error response from daemon: conflict: unable to delete 3f66bec2c6bf (cannot be forced) - image has dependent child images

I could delete with success when I used the command docker rmi RPOSITORY:TAG

$ docker rmi ubuntu:18.04v1
Untagged: ubuntu:18.04v1

Method has the same erasure as another method in type

It could be possible that the compiler translates Set(Integer) to Set(Object) in java byte code. If this is the case, Set(Integer) would be used only at compile phase for syntax checking.

Content Type application/soap+xml; charset=utf-8 was not supported by service

In my case same error was caused by missing

[DataContract]
...
[DataMember] 

attributes in the returned data type.

Check for that and try addinging those and see if it helps.

How to set app icon for Electron / Atom Shell App

For windows use Resource Hacker

Download and Install: :D

http://www.angusj.com/resourcehacker/

  • Run It
  • Select open and select exe file
  • On your left open a folder called Icon Group
  • Right click 1: 1033
  • Click replace icon
  • Select the icon of your choice
  • Then select replace icon
  • Save then close

You should have build the app

mysql SELECT IF statement with OR

IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment

Will do the job as Buttle Butkus suggested.

long long in C/C++

The letters 100000000000 make up a literal integer constant, but the value is too large for the type int. You need to use a suffix to change the type of the literal, i.e.

long long num3 = 100000000000LL;

The suffix LL makes the literal into type long long. C is not "smart" enough to conclude this from the type on the left, the type is a property of the literal itself, not the context in which it is being used.

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

I solved this with this commands:

1- Run the container

# docker run -d <image-name>

2- List containers

   # docker ps -a

3- Use the container ID

# docker exec -it <container-id> /bin/sh

How to quickly clear a JavaScript Object?

So to recap your question: you want to avoid, as much as possible, trouble with the IE6 GC bug. That bug has two causes:

  1. Garbage Collection occurs once every so many allocations; therefore, the more allocations you make, the oftener GC will run;
  2. The more objects you've got ‘in the air’, the more time each Garbage Collection run takes (since it'll crawl through the entire list of objects to see which are marked as garbage).

The solution to cause 1 seems to be: keep the number of allocations down; assign new objects and strings as little as possible.

The solution to cause 2 seems to be: keep the number of 'live' objects down; delete your strings and objects as soon as you don't need them anymore, and create them afresh when necessary.

To a certain extent, these solutions are contradictory: to keep the number of objects in memory low will entail more allocations and de-allocations. Conversely, constantly reusing the same objects could mean keeping more objects in memory than strictly necessary.


Now for your question. Whether you'll reset an object by creating a new one, or by deleting all its properties: that will depend on what you want to do with it afterwards.

You’ll probably want to assign new properties to it:

  • If you do so immediately, then I suggest assigning the new properties straightaway, and skip deleting or clearing first. (Make sure that all properties are either overwritten or deleted, though!)
  • If the object won't be used immediately, but will be repopulated at some later stage, then I suggest deleting it or assigning it null, and create a new one later on.

There's no fast, easy to use way to clear a JScript object for reuse as if it were a new object — without creating a new one. Which means the short answer to your question is ‘No’, like jthompson says.

Fatal error: Call to a member function prepare() on null

You can try/catch PDOExceptions (your configs could differ but the important part is the try/catch):

try {
        $dbh = new PDO(
            DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_PERSISTENT            => true,
                PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE

            ]
        );
    } catch ( PDOException $e ) {
        echo 'ERROR!';
        print_r( $e );
    }

The print_r( $e ); line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'.

Contain form within a bootstrap popover?

I would put my form into the markup and not into some data tag. This is how it could work:

JS Code:

$('#popover').popover({ 
    html : true,
    title: function() {
      return $("#popover-head").html();
    },
    content: function() {
      return $("#popover-content").html();
    }
});

HTML Markup:

<a href="#" id="popover">the popover link</a>
<div id="popover-head" class="hide">
  some title
</div>
<div id="popover-content" class="hide">
  <!-- MyForm -->
</div>

Demo

Alternative Approaches:

X-Editable

You might want to take a look at X-Editable. A library that allows you to create editable elements on your page based on popovers.

X-Editable demo

Webcomponents

Mike Costello has released Bootstrap Web Components. This nifty library has a Popovers Component that lets you embed the form as markup:

<button id="popover-target" data-original-title="MyTitle" title="">Popover</button>

<bs-popover title="Popover with Title" for="popover-target">
  <!-- MyForm -->
</bs-popover>

Demo

Match groups in Python

Less efficient, but simpler-looking:

m0 = re.match("I love (\w+)", statement)
m1 = re.match("Ich liebe (\w+)", statement)
m2 = re.match("Je t'aime (\w+)", statement)
if m0:
  print "He loves",m0.group(1)
elif m1:
  print "Er liebt",m1.group(1)
elif m2:
  print "Il aime",m2.group(1)

The problem with the Perl stuff is the implicit updating of some hidden variable. That's simply hard to achieve in Python because you need to have an assignment statement to actually update any variables.

The version with less repetition (and better efficiency) is this:

pats = [
    ("I love (\w+)", "He Loves {0}" ),
    ("Ich liebe (\w+)", "Er Liebe {0}" ),
    ("Je t'aime (\w+)", "Il aime {0}")
 ]
for p1, p3 in pats:
    m= re.match( p1, statement )
    if m:
        print p3.format( m.group(1) )
        break

A minor variation that some Perl folk prefer:

pats = {
    "I love (\w+)" : "He Loves {0}",
    "Ich liebe (\w+)" : "Er Liebe {0}",
    "Je t'aime (\w+)" : "Il aime {0}",
}
for p1 in pats:
    m= re.match( p1, statement )
    if m:
        print pats[p1].format( m.group(1) )
        break

This is hardly worth mentioning except it does come up sometimes from Perl programmers.

SQL distinct for 2 fields in a database

Share my stupid thought:

Maybe I can select distinct only on c1 but not on c2, so the syntax may be select ([distinct] col)+ where distinct is a qualifier for each column.

But after thought, I find that distinct on only one column is nonsense. Take the following relationship:

   | A | B
__________
  1| 1 | 2
  2| 1 | 1

If we select (distinct A), B, then what is the proper B for A = 1?

Thus, distinct is a qualifier for a statement.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

In my case problem occurred after namespace renaming. I didn't use external tool like Re-sharper, I did renaming manually.

In that process, Views/Web.config file was left unchanged. After replacing old namespace name with the new one in this file, the error disappeared.

Object of class stdClass could not be converted to string

I use codeignator and I got the error:

Object of class stdClass could not be converted to string.

for this post I get my result

I use in my model section

$query = $this->db->get('user', 10);
        return $query->result();

and from this post I use

$query = $this->db->get('user', 10);
        return $query->row();

and I solved my problem

Remove Null Value from String array in java

A gc-friendly piece of code:

public static<X> X[] arrayOfNotNull(X[] array) {
    for (int p=0, N=array.length; p<N; ++p) {
        if (array[p] == null) {
            int m=p; for (int i=p+1; i<N; ++i) if (array[i]!=null) ++m;
            X[] res = Arrays.copyOf(array, m);
            for (int i=p+1; i<N; ++i) if (array[i]!=null) res[p++] = array[i];
            return res;
        }
    }
    return array;
}

It returns the original array if it contains no nulls. It does not modify the original array.

How to get length of a string using strlen function

If you really, really want to use strlen(), then

cout << strlen(str.c_str()) << endl;

else the use of .length() is more in keeping with C++.

What is the proper declaration of main in C++?

Details on return values and their meaning

Per 3.6.1 ([basic.start.main]):

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0;

The behavior of std::exit is detailed in section 18.5 ([support.start.term]), and describes the status code:

Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

Laravel Eloquent inner join with multiple conditions

This is not politically correct but works

   ->leftJoin("players as p","n.item_id", "=", DB::raw("p.id_player and n.type='player'"))

Change the borderColor of the TextBox

set Text box Border style to None then write this code to container form "paint" event

private void Form1_Paint(object sender, PaintEventArgs e)
{
    System.Drawing.Rectangle rect = new Rectangle(TextBox1.Location.X, 
    TextBox1.Location.Y, TextBox1.ClientSize.Width, TextBox1.ClientSize.Height);
                
                rect.Inflate(1, 1); // border thickness
                System.Windows.Forms.ControlPaint.DrawBorder(e.Graphics, rect, 
    Color.DeepSkyBlue, ButtonBorderStyle.Solid);
}

Error loading the SDK when Eclipse starts

Copy the default devices.xml file from : /home/user/android-sdk/tools/lib/devices.xml

and paste it in the below paths: /android-sdk/system-images/android-22/android-wear/armeabi-v7a/ and /android-sdk/system-images/android-22/android-wear/x86/

This is a alternative solution, however, before replacing the devices.xml, take backup of the existing devices.xml file in these folders.

How can I create numbered map markers in Google Maps V3?

EASIEST SOLUTION - USE SVG

Works in: in IE9, IE10, FF, Chrome, Safari

(if you are using other browsers please "Run code snippet" and place a comment)

No external dependencies besides Google Maps API!

enter image description here

This is quite easy provided that you have your icon in .svg format. If that is the case just add appropriate text element and change its content to fit your needs with JS.

Add something like this to your .svg code (this is text "section" which will be later changed with JS):

<text id="1" fill="#20539F" font-family="NunitoSans-ExtraBold, Nunito Sans" font-size="18" font-weight="600" letter-spacing=".104" text-anchor="middle" x="50%" y="28">1</text>

Example: (partially copied from @EstevãoLucas)

Important: Use correct <text> tag properties. Note text-anchor="middle" x="50%" y="28" which center longer numbers (more info: How to place and center text in an SVG rectangle)

Use encodeURIComponent() (this probably ensures compatibility with IE9 and 10)

_x000D_
_x000D_
// Most important part (use output as Google Maps icon)_x000D_
function getMarkerIcon(number) {_x000D_
  // inline your SVG image with number variable_x000D_
  var svg = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="40" height="40" viewBox="0 0 40 40"> <defs> <rect id="path-1" width="40" height="40"/> <mask id="mask-2" width="40" height="40" x="0" y="0" fill="white"> <use xlink:href="#path-1"/> </mask> </defs> <g id="Page-1" fill="none" fill-rule="evenodd"> <g id="Phone-Portrait---320" transform="translate(-209 -51)"> <g id="Group" transform="translate(209 51)"> <use id="Rectangle" fill="#FFEB3B" stroke="#F44336" stroke-width="4" mask="url(#mask-2)" xlink:href="#path-1"/> <text id="1" fill="#20539F" font-family="NunitoSans-ExtraBold, Nunito Sans" font-size="18" font-weight="600" letter-spacing=".104" text-anchor="middle" x="50%" y="28">' + number + '</text> </g> </g> </g> </svg>';_x000D_
  // use SVG without base64 see: https://css-tricks.com/probably-dont-base64-svg/_x000D_
  return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);_x000D_
}_x000D_
_x000D_
// Standard Maps API code_x000D_
var markers = [_x000D_
  [1, -14.2350040, -51.9252800],_x000D_
  [2, -34.028249, 151.157507],_x000D_
  [3, 39.0119020, -98.4842460],_x000D_
  [5, 48.8566140, 2.3522220],_x000D_
  [9, 38.7755940, -9.1353670],_x000D_
  [12, 12.0733335, 52.8234367],_x000D_
];_x000D_
_x000D_
function initializeMaps() {_x000D_
  var myLatLng = {_x000D_
    lat: -25.363,_x000D_
    lng: 131.044_x000D_
  };_x000D_
_x000D_
  var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
    zoom: 4,_x000D_
    center: myLatLng_x000D_
  });_x000D_
_x000D_
  var bounds = new google.maps.LatLngBounds();_x000D_
_x000D_
  markers.forEach(function(point) {_x000D_
      var pos = new google.maps.LatLng(point[1], point[2]);_x000D_
_x000D_
      new google.maps.Marker({_x000D_
        position: pos,_x000D_
        map: map,_x000D_
        icon: getMarkerIcon(point[0]),         _x000D_
      });_x000D_
_x000D_
      bounds.extend(pos);_x000D_
  });_x000D_
_x000D_
  map.fitBounds(bounds);_x000D_
}_x000D_
_x000D_
initializeMaps();
_x000D_
#map_canvas {_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
  <head>_x000D_
    <link rel="stylesheet" href="style.css">_x000D_
    _x000D_
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>        _x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="map_canvas"></div>_x000D_
  </body>_x000D_
  _x000D_
  <script src="script.js"></script>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

More info about inline SVG in Google Maps: https://robert.katzki.de/posts/inline-svg-as-google-maps-marker

Git Push error: refusing to update checked out branch

It's works for me

  1. git config --global receive.denyCurrentBranch updateInstead

  2. git push origin master

ssh: check if a tunnel is alive

Netcat is your friend:

nc -z localhost 6000 || echo "no tunnel open"

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Two of them always produce the same answer:

  • COUNT(*) counts the number of rows
  • COUNT(1) also counts the number of rows

Assuming the pk is a primary key and that no nulls are allowed in the values, then

  • COUNT(pk) also counts the number of rows

However, if pk is not constrained to be not null, then it produces a different answer:

  • COUNT(possibly_null) counts the number of rows with non-null values in the column possibly_null.

  • COUNT(DISTINCT pk) also counts the number of rows (because a primary key does not allow duplicates).

  • COUNT(DISTINCT possibly_null_or_dup) counts the number of distinct non-null values in the column possibly_null_or_dup.

  • COUNT(DISTINCT possibly_duplicated) counts the number of distinct (necessarily non-null) values in the column possibly_duplicated when that has the NOT NULL clause on it.

Normally, I write COUNT(*); it is the original recommended notation for SQL. Similarly, with the EXISTS clause, I normally write WHERE EXISTS(SELECT * FROM ...) because that was the original recommend notation. There should be no benefit to the alternatives; the optimizer should see through the more obscure notations.

curl: (6) Could not resolve host: google.com; Name or service not known

Perhaps you have some very weird and restrictive SELinux rules in place?

If not, try strace -o /tmp/wtf -fF curl -v google.com and try to spot from /tmp/wtf output file what's going on.

add item in array list of android

You're trying to assign the result of the add operation to resultArrGame, and add can either return true or false, depending on if the operation was successful or not. What you want is probably just:

resultArrGame.add(txt.Game.getText().toString());

Date format in the json output using spring boot

If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
In your case if you need your date into yyyy-MM-dd format you need to specify @JsonFormat above your field on which you want to apply this format.

For Example :

public class Subject {

     private String uid;
     private String number;
     private String initials;

     @JsonFormat(pattern="yyyy-MM-dd")
     private Date dateOfBirth;  

     //Other Code  

}  

From Docs :

annotation used for configuring details of how values of properties are to be serialized.

More Reference Doc

Hope this helps.

Insert string in beginning of another string

Other answers explain how to insert a string at the beginning of another String or StringBuilder (or StringBuffer).

However, strictly speaking, you cannot insert a string into the beginning of another one. Strings in Java are immutable1.

When you write:

String s = "Jam";
s = "Hello " + s;

you are actually causing a new String object to be created that is the concatenation of "Hello " and "Jam". You are not actually inserting characters into an existing String object at all.


1 - It is technically possible to use reflection to break abstraction on String objects and mutate them ... even though they are immutable by design. But it is a really bad idea to do this. Unless you know that a String object was created explicitly via new String(...) it could be shared, or it could share internal state with other String objects. Finally, the JVM spec clearly states that the behavior of code that uses reflection to change a final is undefined. Mutation of String objects is dangerous.

Search for all occurrences of a string in a mysql database

In unix machines, if the database is not too big:

mysqldump -u <username> -p <password> <database_name> --extended=FALSE | grep <String to search> | less -S

Getting the thread ID from a thread

You can use the deprecated AppDomain.GetCurrentThreadId to get the ID of the currently running thread. This method uses a PInvoke to the Win32 API method GetCurrentThreadID, and will return the Windows thread ID.

This method is marked as deprecated because the .NET Thread object does not correspond to a single Windows thread, and as such there is no stable ID which can be returned by Windows for a given .NET thread.

See configurator's answer for more reasons why this is the case.

Opening the Settings app from another app

You can use this on iOS 5.0 and later: This no longer works.

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs://"]];

how to get html content from a webview?

Actually this question has many answers. Here are 2 of them :

  • This first is almost the same as yours, I guess we got it from the same tutorial.

public class TestActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
        final WebView webview = (WebView) findViewById(R.id.browser);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                webview.loadUrl("javascript:window.HtmlViewer.showHTML" +
                        "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
            }
        });

        webview.loadUrl("http://android-in-action.com/index.php?post/" +
                "Common-errors-and-bugs-and-how-to-solve-avoid-them");
    }

    class MyJavaScriptInterface {

        private Context ctx;

        MyJavaScriptInterface(Context ctx) {
            this.ctx = ctx;
        }

        public void showHTML(String html) {
            new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
                    .setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
        }

    }
}

This way your grab the html through javascript. Not the prettiest way but when you have your javascript interface, you can add other methods to tinker it.


  • An other way is using an HttpClient like there.

The option you choose also depends, I think, on what you intend to do with the retrieved html...

Why can't I call a public method in another class?

You have to create a variable of the type of the class, and set it equal to a new instance of the object first.

GradeBook myGradeBook = new GradeBook();

Then call the method on the obect you just created.

myGradeBook.[method you want called]

PHP json_encode json_decode UTF-8

if you get "unexpected Character" error you should check if there is a BOM (Byte Order Marker saved into your utf-8 json. You can either remove the first character or save if without BOM.

How can I list all cookies for the current page with Javascript?

You can list cookies for current domain:

function listCookies() {
    var theCookies = document.cookie.split(';');
    var aString = '';
    for (var i = 1 ; i <= theCookies.length; i++) {
        aString += i + ' ' + theCookies[i-1] + "\n";
    }
    return aString;
}

But you cannot list cookies for other domains for security reasons

Using a PHP variable in a text input value = statement

Try something like this:

<input type="text" name="idtest" value="<?php echo htmlspecialchars($name); ?>" />

That is, the same as what thirtydot suggested, except preventing XSS attacks as well.

You could also use the <?= syntax (see the note), although that might not work on all servers. (It's enabled by a configuration option.)

Swift performSelector:withObject:afterDelay: is unavailable

You could do this:

var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)

func someSelector() {
    // Something after a delay
}

SWIFT 3

let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(someSelector), userInfo: nil, repeats: false)

func someSelector() {
    // Something after a delay
}

Sum all values in every column of a data.frame in R

We can use dplyr to select only numeric columns and purr to get sum for all columns. (can be used to get what ever value for all columns, such as mean, min, max, etc. )

library("dplyr")
library("purrr")

people %>%
    select_if(is.numeric) %>%
    map_dbl(sum)

Or another easy way by only using dplyr

library("dplyr")
people %>%
    summarize_if(is.numeric, sum, na.rm=TRUE)

C# string replace

Try this:

line.Replace("\",\"", ";")

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

SQLMenace said money is inexact. But you don't multiply/divide money by money! How much is 3 dollars times 50 cents? 150 dollarcents? You multiply/divide money by scalars, which should be decimal.

DECLARE
@mon1 MONEY,
@mon4 MONEY,
@num1 DECIMAL(19,4),
@num2 DECIMAL(19,4),
@num3 DECIMAL(19,4),
@num4 DECIMAL(19,4)

SELECT
@mon1 = 100,
@num1 = 100, @num2 = 339, @num3 = 10000

SET @mon4 = @mon1/@num2*@num3
SET @num4 = @num1/@num2*@num3

SELECT @mon4 AS moneyresult,
@num4 AS numericresult

Results in the correct result:

moneyresult           numericresult
--------------------- ---------------------------------------
2949.8525             2949.8525

money is good as long as you don't need more than 4 decimal digits, and you make sure your scalars - which do not represent money - are decimals.

"Press Any Key to Continue" function in C

You can try more system indeppended method: system("pause");

Loop through all the files with a specific extension

Recursively add subfolders,

for i in `find . -name "*.java" -type f`; do
    echo "$i"
done

How can I start PostgreSQL on Windows?

I found using

net start postgres_service_name

the only reliable way to operate Postgres on Windows

AsyncTask Android example

Sample Async Task with POST request:

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key1", "value1"));
params.add(new BasicNameValuePair("key1", "value2"));
new WEBSERVICEREQUESTOR(URL, params).execute();

class WEBSERVICEREQUESTOR extends AsyncTask<String, Integer, String>
{
    String URL;
    List<NameValuePair> parameters;

    private ProgressDialog pDialog;

    public WEBSERVICEREQUESTOR(String url, List<NameValuePair> params)
    {
        this.URL = url;
        this.parameters = params;
    }

    @Override
    protected void onPreExecute()
    {
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Processing Request...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params)
    {
        try
        {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            HttpPost httpPost = new HttpPost(URL);

            if (parameters != null)
            {
                httpPost.setEntity(new UrlEncodedFormEntity(parameters));
            }
            httpResponse = httpClient.execute(httpPost);

            httpEntity = httpResponse.getEntity();
            return EntityUtils.toString(httpEntity);

        }  catch (Exception e)
        {

        }
        return "";
    }

    @Override
    protected void onPostExecute(String result)
    {
        pDialog.dismiss();

        try
        {

        }
        catch (Exception e)
        {

        }
        super.onPostExecute(result);
    }
}

How to properly make a http web GET request

var request = (HttpWebRequest)WebRequest.Create("sendrequesturl");
var response = (HttpWebResponse)request.GetResponse();
string responseString;
using (var stream = response.GetResponseStream())
{
    using (var reader = new StreamReader(stream))
    {
        responseString = reader.ReadToEnd();
    }
}

split string only on first instance of specified character

Mark F's solution is awesome but it's not supported by old browsers. Kennebec's solution is awesome and supported by old browsers but doesn't support regex.

So, if you're looking for a solution that splits your string only once, that is supported by old browsers and supports regex, here's my solution:

_x000D_
_x000D_
String.prototype.splitOnce = function(regex)_x000D_
{_x000D_
    var match = this.match(regex);_x000D_
    if(match)_x000D_
    {_x000D_
        var match_i = this.indexOf(match[0]);_x000D_
        _x000D_
        return [this.substring(0, match_i),_x000D_
        this.substring(match_i + match[0].length)];_x000D_
    }_x000D_
    else_x000D_
    { return [this, ""]; }_x000D_
}_x000D_
_x000D_
var str = "something/////another thing///again";_x000D_
_x000D_
alert(str.splitOnce(/\/+/)[1]);
_x000D_
_x000D_
_x000D_

How can I create an utility class?

According to Joshua Bloch (Effective Java), you should use private constructor which always throws exception. That will finally discourage user to create instance of util class.

Marking class abstract is not recommended because is abstract suggests reader that class is designed for inheritance.

SQL Server: UPDATE a table by using ORDER BY

I ran into the same problem and was able to resolve it in very powerful way that allows unlimited sorting possibilities.

I created a View using (saving) 2 sort orders (*explanation on how to do so below).

After that I simply applied the update queries to the View created and it worked great.

Here are the 2 queries I used on the view:

1st Query:

Update  MyView
Set SortID=0


2nd Query:

DECLARE @sortID int
SET     @sortID = 0
UPDATE  MyView
SET     @sortID = sortID = @sortID + 1


*To be able to save the sorting on the View I put TOP into the SELECT statement. This very useful workaround allows the View results to be returned sorted as set when the View was created when the View is opened. In my case it looked like:

(NOTE: Using this workaround will place an big load on the server if using a large table and it is therefore recommended to include as few fields as possible in the view if working with large tables)

SELECT     TOP (600000) 
dbo.Items.ID, dbo.Items.Code, dbo.Items.SortID, dbo.Supplier.Date, 
dbo.Supplier.Code AS Expr1
FROM         dbo.Items INNER JOIN
                      dbo.Supplier ON dbo.Items.SupplierCode = dbo.Supplier.Code
ORDER BY dbo.Supplier.Date, dbo.Items.ID DESC



Running: SQL Server 2005 on a Windows Server 2003

Additional Keywords: How to Update a SQL column with Ascending or Descending Numbers - Numeric Values / how to set order in SQL update statement / how to save order by in sql view / increment sql update / auto autoincrement sql update / create sql field with ascending numbers

How to connect to Mysql Server inside VirtualBox Vagrant?

For anyone trying to do this using mysql workbench or sequel pro these are the inputs:

Mysql Host: 192.168.56.101 (or ip that you choose for it)
username: root (or mysql username u created)
password: **** (your mysql password)
database: optional
port: optional (unless you chose another port, defaults to 3306)

ssh host: 192.168.56.101 (or ip that you choose for this vm, like above)
ssh user: vagrant (vagrants default username)
ssh password: vagrant (vagrants default password)
ssh port: optional (unless you chose another)

source: https://coderwall.com/p/yzwqvg

How do I exit a WPF application programmatically?

Use any of the following as needed:

1.

 App.Current.Shutdown();
OR
 Application.Current.Shutdown();

2.

 App.Current.MainWindow.Close();
OR
 Application.Current.MainWindow.Close();

Above all methods will call closing event of Window class and execution may stop at some point (cause usually applications put dialogues like 'are you sure?' or 'Would you like to save data before closing?', before a window is closed completely)

3. But if you want to terminate the application without any warning immediately. Use below

   Environment.Exit(0);

Could not open input file: composer.phar

First try this: dont use the php composer.phar [parameters] simply use composer [parameters] if this doesn't work for you than try the rest. Hope it helps.

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

jQuery Cross Domain Ajax

When using "jsonp", you would basically be returning data wrapped in a function call, something like

jsonpCallback([{"id":1,"value":"testing"},{"id":2,"value":"test again"}])
where the function/callback name is 'jsonpCallback'.

If you have access to the server, please first verify that the response is in the correct "jsonp" format

For such a response coming from the server, you would need to specify something in the ajax call as well, something like

jsonpCallback: "jsonpCallback",  in your ajax call

Please note that the name of the callback does not need to be "jsonpCallback" its just a name picked as an example but it needs to match the name(wrapping) done on the server side.

My first guess to your problem is that the response from the server is not what it should be.

Easier way to debug a Windows service

I like to be able to debug every aspect of my service, including any initialization in OnStart(), while still executing it with full service behavior within the framework of the SCM... no "console" or "app" mode.

I do this by creating a second service, in the same project, to use for debugging. The debug service, when started as usual (i.e. in the services MMC plugin), creates the service host process. This gives you a process to attach the debugger to even though you haven't started your real service yet. After attaching the debugger to the process, start your real service and you can break into it anywhere in the service lifecycle, including OnStart().

Because it requires very minimal code intrusion, the debug service can easily be included in your service setup project, and is easily removed from your production release by commenting out a single line of code and deleting a single project installer.

Details:

1) Assuming you are implementing MyService, also create MyServiceDebug. Add both to the ServiceBase array in Program.cs like so:

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new MyService(),
            new MyServiceDebug()
        };
        ServiceBase.Run(ServicesToRun);
    }

2) Add the real service AND the debug service to the project installer for the service project:

enter image description here

Both services (real and debug) get included when you add the service project output to the setup project for the service. After installation, both services will appear in the service.msc MMC plugin.

3) Start the debug service in MMC.

4) In Visual Studio, attach the debugger to the process started by the debug service.

5) Start the real service and enjoy debugging.

What is the difference between <p> and <div>?

All good answers, but there's one difference I haven't seen mentioned yet, and that's how browsers render them by default. The major web browsers will render a <p> tag with margin above and below the paragraph. A <div> tag will be rendered without any margin at all.

TSQL select into Temp table from dynamic sql

A working example.

DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'YourTableName'

EXECUTE ('SELECT * INTO #TEMP  FROM ' + @TableName +'; SELECT * FROM #TEMP;')

Second solution with accessible temp table

DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'YOUR_TABLE_NAME'

EXECUTE ('CREATE VIEW vTemp AS
        SELECT *
        FROM ' + @TableName)
SELECT * INTO #TEMP  FROM vTemp 

--DROP THE VIEW HERE      
DROP VIEW vTemp

/*START USING TEMP TABLE
************************/
--EX:
SELECT * FROM #TEMP


--DROP YOUR TEMP TABLE HERE
DROP TABLE #TEMP

Pandas KeyError: value not in index

I had a very similar issue. I got the same error because the csv contained spaces in the header. My csv contained a header "Gender " and I had it listed as:

[['Gender']]

If it's easy enough for you to access your csv, you can use the excel formula trim() to clip any spaces of the cells.

or remove it like this

df.columns = df.columns.to_series().apply(lambda x: x.strip())

Pull request vs Merge request

GitLab's "merge request" feature is equivalent to GitHub's "pull request" feature. Both are means of pulling changes from another branch or fork into your branch and merging the changes with your existing code. They are useful tools for code review and change management.

An article from GitLab discusses the differences in naming the feature:

Merge or pull requests are created in a git management application and ask an assigned person to merge two branches. Tools such as GitHub and Bitbucket choose the name pull request since the first manual action would be to pull the feature branch. Tools such as GitLab and Gitorious choose the name merge request since that is the final action that is requested of the assignee. In this article we'll refer to them as merge requests.

A "merge request" should not be confused with the git merge command. Neither should a "pull request" be confused with the git pull command. Both git commands are used behind the scenes in both pull requests and merge requests, but a merge/pull request refers to a much broader topic than just these two commands.

How to POST URL in data of a curl request

I don't think it's necessary to use semi-quotes around the variables, try:

curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"

%2f is the escape code for a /.

http://www.december.com/html/spec/esccodes.html

Also, do you need to specify a port? ( just checking :) )

How to tackle daylight savings using TimeZone in Java

Other answers are correct, especially the one by Jon Skeet, but outdated.

java.time

These old date-time classes have been supplanted by the java.time framework built into Java 8 and later.

If you simply want the current time in UTC, use the Instant class.

Instant now = Instant.now();

EST is not a time zone, as explained in the correct Answer by Jon Skeet. Such 3-4 letter codes are neither standardized nor unique, and further the confusion over Daylight Saving Time (DST). Use a proper time zone name in the "continent/region" format.

Perhaps you meant Eastern Standard Time in east coast of north America? Or Egypt Standard Time? Or European Standard Time?

ZoneId zoneId = ZoneId.of( "America/New_York" );
ZoneId zoneId = ZoneId.of( "Africa/Cairo" );
ZoneId zoneId = ZoneId.of( "Europe/Lisbon" );

Use any such ZoneId object to get the current moment adjusted to a particular time zone to produce a ZonedDateTime object.

ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;

Adjust that ZonedDateTime into a different time zone by producing another ZonedDateTime object from the first. The java.time framework uses immutable objects rather than changing (mutating) existing objects.

ZonedDateTime zdtGuam = zdt.withZoneSameInstant( ZoneId.of( "Pacific/Guam" ) ) ;

Table of date-time types in Java, both modern and legacy.

The simplest way to resize an UIImage?

Here's a modification of the category written by iWasRobbed above. It keeps the aspect ratio of the original image instead of distorting it.

- (UIImage*)scaleToSizeKeepAspect:(CGSize)size {
    UIGraphicsBeginImageContext(size);

    CGFloat ws = size.width/self.size.width;
    CGFloat hs = size.height/self.size.height;

    if (ws > hs) {
        ws = hs/ws;
        hs = 1.0;
    } else {
        hs = ws/hs;
        ws = 1.0;
    }

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0.0, size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextDrawImage(context, CGRectMake(size.width/2-(size.width*ws)/2,
        size.height/2-(size.height*hs)/2, size.width*ws,
        size.height*hs), self.CGImage);

    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return scaledImage;
}

How to check for null in a single statement in scala?

Option(getObject) foreach (QueueManager add)

javascript cell number validation

Mobile number Validation using Java Script, This link will provide demo and more information.

_x000D_
_x000D_
function isNumber(evt) {_x000D_
  evt = (evt) ? evt : window.event;_x000D_
  var charCode = (evt.which) ? evt.which : evt.keyCode;_x000D_
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {_x000D_
    alert("Please enter only Numbers.");_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
  return true;_x000D_
}_x000D_
_x000D_
function ValidateNo() {_x000D_
  var phoneNo = document.getElementById('txtPhoneNo');_x000D_
_x000D_
  if (phoneNo.value == "" || phoneNo.value == null) {_x000D_
    alert("Please enter your Mobile No.");_x000D_
    return false;_x000D_
  }_x000D_
  if (phoneNo.value.length < 10 || phoneNo.value.length > 10) {_x000D_
    alert("Mobile No. is not valid, Please Enter 10 Digit Mobile No.");_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
  alert("Success ");_x000D_
  return true;_x000D_
}
_x000D_
<input id="txtPhoneNo" type="text" onkeypress="return isNumber(event)" />_x000D_
<input type="button" value="Submit" onclick="ValidateNo();">
_x000D_
_x000D_
_x000D_

How to force Laravel Project to use HTTPS for all routes?

Place this in the AppServiceProvider in the boot() method

if($this->app->environment('production')) {
    \URL::forceScheme('https');
}

ImportError: No module named request

from @Zzmilanzz's answer I used

try: #python3
    from urllib.request import urlopen
except: #python2
    from urllib2 import urlopen

Parsing JSON Array within JSON Object

mainJSON.getJSONArray("source") returns a JSONArray, hence you can remove the new JSONArray.

The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)

Try this:

JSONArray jsonMainArr = mainJSON.getJSONArray("source"); 

nvarchar(max) vs NText

ntext will always store its data in a separate database page, while nvarchar(max) will try to store the data within the database record itself.

So nvarchar(max) is somewhat faster (if you have text that is smaller as 8 kB). I also noticed that the database size will grow slightly slower, this is also good.

Go nvarchar(max).

How to download Google Play Services in an Android emulator?

For api 21+ you can use system image with Google Play as I describe below.

For api 19+ (Android 4.4 Kitkat) you can use system image x86 with Google Api (I was able to use it).

For api 17+ (Android 4.2.2) you can TRY to use system image ARM with Google Api (It didn't work for me).

I was able to install Google Play and Google Services as separate apks to pure system image api 16 and 17, but they don't really work after that (services crush and play not opens). So seems like it is not possible to make them work on pure AVD image because they should be installed with root access. The same for updating Google Services on AVD system image with Google API preinstalled - can't update because of incompatible certificates, can't uninstall even using adb because don't have access.


How to setup AVD system image with Google Play

Now even better solution exist: using AVD image with build-in Google Play Services. It will enable you to use Google Services including Google Play. Also you will be able update it without re-creating AVD image.

Open AVD manager and choose create new device. You should use device definition with play store icon.

1

Then choose system image for it. You should choose one with Google Play and NOT with Google API.

2

Then launch new device.

3

You can update Play Services as shown on screenshot, or manually on device..

4

How to enable scrolling of content inside a modal?

Set height for modal-body and not for the whole modal to get a perfect scroll on modal overlay. I get it work like this:

.MyModal {
    height: 450px;
    overflow-y: auto;
}

Here you can set height as per your requirements.

How to do tag wrapping in VS code?

  1. Open Keyboard Shortcuts by typing ? Command+k ? Command+s or Code > Preferences > Keyboard Shortcuts
  2. Type emmet wrap
  3. Click the plus sign to the left of "Emmet: Wrap with Abbreviation"
  4. Type ? Option+w
  5. Press Enter

Recommended add-ons/plugins for Microsoft Visual Studio

JustDecompile from telerik. Now that Reflector is no longer free. Its a necessity when digging through supplied libraries.

Convert double to BigDecimal and set BigDecimal Precision

The reason of such behaviour is that the string that is printed is the exact value - probably not what you expected, but that's the real value stored in memory - it's just a limitation of floating point representation.

According to javadoc, BigDecimal(double val) constructor behaviour can be unexpected if you don't take into consideration this limitation:

The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

So in your case, instead of using

double val = 77.48;
new BigDecimal(val);

use

BigDecimal.valueOf(val);

Value that is returned by BigDecimal.valueOf is equal to that resulting from invocation of Double.toString(double).

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

The meaning of NoInitialContextException error

Do this:

Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
Context initialContext = new InitialContext(props);

Also add this to the libraries of the project:

C:\installs\glassfish\glassfish-4.1\glassfish\lib\gf-client.jar adjust path accordingly

Determine if Python is running inside virtualenv

It's not bullet-proof but for UNIX environments simple test like

if run("which python3").find("venv") == -1:
    # something when not executed from venv

works great for me. It's simpler then testing existing of some attribute and, anyway, you should name your venv directory venv.

Get full path without filename from path that includes filename

Path.GetDirectoryName() returns the directory name, so for what you want (with the trailing reverse solidus character) you could call Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar.

Microsoft Web API: How do you do a Server.MapPath?

string root = HttpContext.Current.Server.MapPath("~/App_Data");

How to make VS Code to treat other file extensions as certain language?

The easiest way I've found for a global association is simply to ctrl+k m (or ctrl+shift+p and type "change language mode") with a file of the type you're associating open.

In the first selections will be "Configure File Association for 'x' " (whatever file type - see image attached) Selecting this makes the filetype association permanent

enter image description here

This may have changed (probably did) since the original question and accepted answer (and I don't know when it changed) but it's so much easier than the manual editing steps in the accepted and some of the other answers, and totaly avoids having to muss with IDs that may not be obvious.

How to use SearchView in Toolbar Android

Integrating SearchView with RecyclerView

1) Add SearchView Item in Menu

SearchView can be added as actionView in menu using

app:useActionClass = "android.support.v7.widget.SearchView" .

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
    android:id="@+id/searchBar"
    app:showAsAction="always"
    app:actionViewClass="android.support.v7.widget.SearchView"
    />
</menu>

2) Implement SearchView.OnQueryTextListener in your Activity

SearchView.OnQueryTextListener has two abstract methods. So your activity skeleton would now look like this after implementing SearchView text listener.

YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{

   public boolean onQueryTextSubmit(String query)

   public boolean onQueryTextChange(String newText) 

}

3) Set up SerchView Hint text, listener etc

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    MenuItem searchItem = menu.findItem(R.id.searchBar);

    SearchView searchView = (SearchView) searchItem.getActionView();
    searchView.setQueryHint("Search People");
    searchView.setOnQueryTextListener(this);
    searchView.setIconified(false);

    return true;
}

4) Implement SearchView.OnQueryTextListener

This is how you can implement abstract methods of the listener.

@Override
public boolean onQueryTextSubmit(String query) {

    // This method can be used when a query is submitted eg. creating search history using SQLite DB

    Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {

    adapter.filter(newText);
    return true;
}

5) Write a filter method in your RecyclerView Adapter.

You can come up with your own logic based on your requirement. Here is the sample code snippet to show the list of Name which contains the text typed in the SearchView.

public void filter(String queryText)
{
    list.clear();

    if(queryText.isEmpty())
    {
        list.addAll(copyList);
    }
    else
    {

        for(String name: copyList)
        {
            if(name.toLowerCase().contains(queryText.toLowerCase()))
            {
                list.add(name);
            }
        }

    }

    notifyDataSetChanged();
}

Full working code sample can be found > HERE
You can also check out the code on SearchView with an SQLite database in this Music App

enable or disable checkbox in html

<input type="checkbox" value="" ng-model="t.IsPullPoint" onclick="return false;" onkeydown="return false;"><span class="cr"></span></label>

Cannot make Project Lombok work on Eclipse

After adding lombok and restarting eclipse or spring tools my project still failed to recognize getters and setters. Red markers everywhere!

The solution: right-click your project, go to Maven and select Update Project

After hours of searching and trying random solution, I find this to be the only solution that worked for me.

enter image description here

How to check if a char is equal to an empty space?

My suggestion would be:

if (c == ' ')

"make clean" results in "No rule to make target `clean'"

You have fallen victim to the most common of errors in Makefiles. You always need to put a Tab at the beginning of each command. You've put spaces before the $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) and @rm -f $(PROGRAMS) *.o core lines. If you replace them with a Tab, you'll be fine.

However, this error doesn't lead to a "No rule to make target ..." error. That probably means your issue lies beyond your Makefile. Have you checked this is the correct Makefile, as in the one you want to be specifying your commands? Try explicitly passing it as a parameter to make, make -f Makefile and let us know what happens.

How do I read / convert an InputStream into a String in Java?

You can use Apache Commons.

In the IOUtils you can find the toString method with three helpful implementations.

public static String toString(InputStream input) throws IOException {
        return toString(input, Charset.defaultCharset());
}

public static String toString(InputStream input) throws IOException {
        return toString(input, Charset.defaultCharset());
}

public static String toString(InputStream input, String encoding)
            throws IOException {
        return toString(input, Charsets.toCharset(encoding));
}

sql select with column name like

You cannot with standard SQL. Column names are not treated like data in SQL.

If you use a SQL engine that has, say, meta-data tables storing column names, types, etc. you may select on that table instead.

Java Date - Insert into database

you can use this code date and time time is 24 h

INSERT INTO TABLE_NAME(
  date_column
)values(
  TO_DATE('2016-10-05 10:53:56', 'SYYYY-MM-DD HH24:MI:SS')
)

No Access-Control-Allow-Origin header is present on the requested resource

I find the solution in spring.io,like this:

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

target input by type and name (selector)

input[type='checkbox', name='ProductCode']

That's the CSS way and I'm almost sure it will work in jQuery.

No Android SDK found - Android Studio

i have just discovered, android studio 3.0.1 has no sdk during the installation. because during the installation, it doesn't give sdk as part of install able unlike in recent versions of android studio.

Visual Studio "Could not copy" .... during build

I have add the same problem various times and none of the answers from this treat could help or if they did it was by using a nasty work around.
What I figured is that there is always a good reason for this problem to occur (And is not a Microsoft bug! - Well, VS could get better at flagging it though :-)).

The main reason may simply be that your project dependencies are messed up!
As a simple example ():

  • You have multiple projects within a same solution
  • You clean + build all and assume everything went well as you see no error
  • You start running one of the project - All good so far!
  • Then start running a second one, but this one has dependencies also used by the previous project and tries to rebuild them
  • It then hangs for a while
  • It fails to build as the first project is already running and does not allow you to override ongoing processes

Now you can think of all the possible scenarios that could trigger an error of the sort:

Error Could not copy "obj\Debug\ProjectX.exe" to "..\bin\Debug\ProjectX.exe". Exceeded retry count of 10. Failed. The file is locked by: "ProjectX (17132)" ProjectX

Fixing this issue is usually a tedious process as you will have to perfectly understand all the dependencies in your system

T-SQL Substring - Last 3 Characters

if you want to specifically find strings which ends with desired characters then this would help you...

select * from tablename where col_name like '%190'

number several equations with only one number

How about something like:

\documentclass{article}

\usepackage{amssymb,amsmath}

\begin{document}

\begin{equation}\label{A_Label}
  \begin{split}
    w^T x_i + b \geqslant 1-\xi_i \text{ if } y_i &= 1, \\
    w^T x_i + b \leqslant -1+\xi_i \text{ if } y_i &= -1
  \end{split}
\end{equation}

\end{document}

which produces:

enter image description here

How to use passive FTP mode in Windows command prompt?

The Windows FTP command-line client (ftp.exe) does not support the passive mode, on any version of Windows. It makes it pretty useless nowadays due to ubiquitous firewalls and NATs.

Using the quote pasv won't help. It switches only the server to the passive mode, but not the client.


Use any thirdparty Windows FTP command-line client instead. Most other support the passive mode.

For example WinSCP defaults to the passive mode and there's a guide available for converting Windows FTP script to WinSCP script. If you are starting from the scratch, see the guide to automating file transfers to FTP using WinSCP. Also, WinSCP GUI can generate a script template for you.

(I'm the author of WinSCP)

SQL, How to convert VARCHAR to bigint?

I think your code is right. If you run the following code it converts the string '60' which is treated as varchar and it returns integer 60, if there is integer containing string in second it works.

select CONVERT(bigint,'60') as seconds 

and it returns

60

How to count rows with SELECT COUNT(*) with SQLAlchemy?

I needed to do a count of a very complex query with many joins. I was using the joins as filters, so I only wanted to know the count of the actual objects. count() was insufficient, but I found the answer in the docs here:

http://docs.sqlalchemy.org/en/latest/orm/tutorial.html

The code would look something like this (to count user objects):

from sqlalchemy import func

session.query(func.count(User.id)).scalar() 

Android : change button text and background color

Just use a MaterialButton and the app:backgroundTint and android:textColor attributes:

<MaterialButton
  app:backgroundTint="@color/my_color"
  android:textColor="@android:color/white"/>

Create thumbnail image

Here is an example to convert high res image into thumbnail size-

protected void Button1_Click(object sender, EventArgs e)
{
    //----------        Getting the Image File
    System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("~/profile/Avatar.jpg"));

    //----------        Getting Size of Original Image
    double imgHeight = img.Size.Height;
    double imgWidth = img.Size.Width;

    //----------        Getting Decreased Size
    double x = imgWidth / 200;
    int newWidth = Convert.ToInt32(imgWidth / x);
    int newHeight = Convert.ToInt32(imgHeight / x);

    //----------        Creating Small Image
    System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
    System.Drawing.Image myThumbnail = img.GetThumbnailImage(newWidth, newHeight, myCallback, IntPtr.Zero);

    //----------        Saving Image
    myThumbnail.Save(Server.MapPath("~/profile/NewImage.jpg"));
}
public bool ThumbnailCallback()
{
    return false;
}

Source- http://iknowledgeboy.blogspot.in/2014/03/c-creating-thumbnail-of-large-image-by.html

How to split a comma separated string and process in a loop using JavaScript

Like this:

var str = 'Hello, World, etc';
var myarray = str.split(',');

for(var i = 0; i < myarray.length; i++)
{
   console.log(myarray[i]);
}

Liquibase lock - reasons?

You can safely delete the table manually or using query. It will be recreated automatically.

DROP TABLE DATABASECHANGELOGLOCK;