Programs & Examples On #Design rationale

Can Android Studio be used to run standard Java projects?

Here's exactly what the setup looks like.

enter image description here

Edit Configurations > '+' > Application: enter image description here

event.preventDefault() function not working in IE

preventDefault is a widespread standard; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:

if (typeof Event.prototype.preventDefault === 'undefined') {
    Event.prototype.preventDefault = function (e, callback) {
        this.returnValue = false;
    };
}

This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general. Now you can use e.preventDefault with no problem.

Looking for a 'cmake clean' command to clear up CMake output

CMake official FAQ states:

Some build trees created with GNU autotools have a "make distclean" target that cleans the build and also removes Makefiles and other parts of the generated build system. CMake does not generate a "make distclean" target because CMakeLists.txt files can run scripts and arbitrary commands; CMake has no way of tracking exactly which files are generated as part of running CMake. Providing a distclean target would give users the false impression that it would work as expected. (CMake does generate a "make clean" target to remove files generated by the compiler and linker.)

A "make distclean" target is only necessary if the user performs an in-source build. CMake supports in-source builds, but we strongly encourage users to adopt the notion of an out-of-source build. Using a build tree that is separate from the source tree will prevent CMake from generating any files in the source tree. Because CMake does not change the source tree, there is no need for a distclean target. One can start a fresh build by deleting the build tree or creating a separate build tree.

Android ListView Divider

Add android:dividerHeight="1px" and it will work:

<ListView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:id="@+id/cashItemsList"
     android:cacheColorHint="#00000000"
     android:divider="@drawable/list_divider" android:dividerHeight="1px"></ListView>

Install mysql-python (Windows)

For phpmydamin you can use following step

  1. Go to python install path like

     cd C:\Users\Enamul\AppData\Local\Programs\Python\Python37-32\Scripts
    
  2. Run the command pip install PyMySQL

  3. In the python shell import library like import pymysql

  4. connection to databasbe

     db = pymysql.connect(host='localhost',user='root',passwd='yourpassword', database="bd")
    
  5. get cursor cursor = db.cursor()

  6. Create table like

    cursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
    

Calculate correlation for more than two variables?

Use the same function (cor) on a data frame, e.g.:

> cor(VADeaths)
             Rural Male Rural Female Urban Male Urban Female
Rural Male    1.0000000    0.9979869  0.9841907    0.9934646
Rural Female  0.9979869    1.0000000  0.9739053    0.9867310
Urban Male    0.9841907    0.9739053  1.0000000    0.9918262
Urban Female  0.9934646    0.9867310  0.9918262    1.0000000

Or, on a data frame also holding discrete variables, (also sometimes referred to as factors), try something like the following:

> cor(mtcars[,unlist(lapply(mtcars, is.numeric))])
            mpg        cyl       disp         hp        drat         wt        qsec         vs          am       gear        carb
mpg   1.0000000 -0.8521620 -0.8475514 -0.7761684  0.68117191 -0.8676594  0.41868403  0.6640389  0.59983243  0.4802848 -0.55092507
cyl  -0.8521620  1.0000000  0.9020329  0.8324475 -0.69993811  0.7824958 -0.59124207 -0.8108118 -0.52260705 -0.4926866  0.52698829
disp -0.8475514  0.9020329  1.0000000  0.7909486 -0.71021393  0.8879799 -0.43369788 -0.7104159 -0.59122704 -0.5555692  0.39497686
hp   -0.7761684  0.8324475  0.7909486  1.0000000 -0.44875912  0.6587479 -0.70822339 -0.7230967 -0.24320426 -0.1257043  0.74981247
drat  0.6811719 -0.6999381 -0.7102139 -0.4487591  1.00000000 -0.7124406  0.09120476  0.4402785  0.71271113  0.6996101 -0.09078980
wt   -0.8676594  0.7824958  0.8879799  0.6587479 -0.71244065  1.0000000 -0.17471588 -0.5549157 -0.69249526 -0.5832870  0.42760594
qsec  0.4186840 -0.5912421 -0.4336979 -0.7082234  0.09120476 -0.1747159  1.00000000  0.7445354 -0.22986086 -0.2126822 -0.65624923
vs    0.6640389 -0.8108118 -0.7104159 -0.7230967  0.44027846 -0.5549157  0.74453544  1.0000000  0.16834512  0.2060233 -0.56960714
am    0.5998324 -0.5226070 -0.5912270 -0.2432043  0.71271113 -0.6924953 -0.22986086  0.1683451  1.00000000  0.7940588  0.05753435
gear  0.4802848 -0.4926866 -0.5555692 -0.1257043  0.69961013 -0.5832870 -0.21268223  0.2060233  0.79405876  1.0000000  0.27407284
carb -0.5509251  0.5269883  0.3949769  0.7498125 -0.09078980  0.4276059 -0.65624923 -0.5696071  0.05753435  0.2740728  1.00000000

How to handle Pop-up in Selenium WebDriver using Java

public void Test(){

     WebElement sign = fc.findElement(By.xpath(".//*[@id='login-scroll']/a"));
        sign.click();
        WebElement LoginAsGuest=fc.findElement(By.xpath(".//*[@id='guest-login-option']"));
        LoginAsGuest.click();
        WebElement email_id= fc.findElement(By.xpath(".//*[@id='guestemail']"));
        email_id.sendKeys("[email protected]");
        WebElement ContinueButton=fc.findElement(By.xpath(".//*[@id='contibutton']"));
        ContinueButton.click();

}

Is there a regular expression to detect a valid regular expression?

The following example by Paul McGuire, originally from the pyparsing wiki, but now available only through the Wayback Machine, gives a grammar for parsing some regexes, for the purposes of returning the set of matching strings. As such, it rejects those re's that include unbounded repetition terms, like '+' and '*'. But it should give you an idea about how to structure a parser that would process re's.

# 
# invRegex.py
#
# Copyright 2008, Paul McGuire
#
# pyparsing script to expand a regular expression into all possible matching strings
# Supports:
# - {n} and {m,n} repetition, but not unbounded + or * repetition
# - ? optional elements
# - [] character ranges
# - () grouping
# - | alternation
#
__all__ = ["count","invert"]

from pyparsing import (Literal, oneOf, printables, ParserElement, Combine, 
    SkipTo, operatorPrecedence, ParseFatalException, Word, nums, opAssoc,
    Suppress, ParseResults, srange)

class CharacterRangeEmitter(object):
    def __init__(self,chars):
        # remove duplicate chars in character range, but preserve original order
        seen = set()
        self.charset = "".join( seen.add(c) or c for c in chars if c not in seen )
    def __str__(self):
        return '['+self.charset+']'
    def __repr__(self):
        return '['+self.charset+']'
    def makeGenerator(self):
        def genChars():
            for s in self.charset:
                yield s
        return genChars

class OptionalEmitter(object):
    def __init__(self,expr):
        self.expr = expr
    def makeGenerator(self):
        def optionalGen():
            yield ""
            for s in self.expr.makeGenerator()():
                yield s
        return optionalGen

class DotEmitter(object):
    def makeGenerator(self):
        def dotGen():
            for c in printables:
                yield c
        return dotGen

class GroupEmitter(object):
    def __init__(self,exprs):
        self.exprs = ParseResults(exprs)
    def makeGenerator(self):
        def groupGen():
            def recurseList(elist):
                if len(elist)==1:
                    for s in elist[0].makeGenerator()():
                        yield s
                else:
                    for s in elist[0].makeGenerator()():
                        for s2 in recurseList(elist[1:]):
                            yield s + s2
            if self.exprs:
                for s in recurseList(self.exprs):
                    yield s
        return groupGen

class AlternativeEmitter(object):
    def __init__(self,exprs):
        self.exprs = exprs
    def makeGenerator(self):
        def altGen():
            for e in self.exprs:
                for s in e.makeGenerator()():
                    yield s
        return altGen

class LiteralEmitter(object):
    def __init__(self,lit):
        self.lit = lit
    def __str__(self):
        return "Lit:"+self.lit
    def __repr__(self):
        return "Lit:"+self.lit
    def makeGenerator(self):
        def litGen():
            yield self.lit
        return litGen

def handleRange(toks):
    return CharacterRangeEmitter(srange(toks[0]))

def handleRepetition(toks):
    toks=toks[0]
    if toks[1] in "*+":
        raise ParseFatalException("",0,"unbounded repetition operators not supported")
    if toks[1] == "?":
        return OptionalEmitter(toks[0])
    if "count" in toks:
        return GroupEmitter([toks[0]] * int(toks.count))
    if "minCount" in toks:
        mincount = int(toks.minCount)
        maxcount = int(toks.maxCount)
        optcount = maxcount - mincount
        if optcount:
            opt = OptionalEmitter(toks[0])
            for i in range(1,optcount):
                opt = OptionalEmitter(GroupEmitter([toks[0],opt]))
            return GroupEmitter([toks[0]] * mincount + [opt])
        else:
            return [toks[0]] * mincount

def handleLiteral(toks):
    lit = ""
    for t in toks:
        if t[0] == "\\":
            if t[1] == "t":
                lit += '\t'
            else:
                lit += t[1]
        else:
            lit += t
    return LiteralEmitter(lit)    

def handleMacro(toks):
    macroChar = toks[0][1]
    if macroChar == "d":
        return CharacterRangeEmitter("0123456789")
    elif macroChar == "w":
        return CharacterRangeEmitter(srange("[A-Za-z0-9_]"))
    elif macroChar == "s":
        return LiteralEmitter(" ")
    else:
        raise ParseFatalException("",0,"unsupported macro character (" + macroChar + ")")

def handleSequence(toks):
    return GroupEmitter(toks[0])

def handleDot():
    return CharacterRangeEmitter(printables)

def handleAlternative(toks):
    return AlternativeEmitter(toks[0])


_parser = None
def parser():
    global _parser
    if _parser is None:
        ParserElement.setDefaultWhitespaceChars("")
        lbrack,rbrack,lbrace,rbrace,lparen,rparen = map(Literal,"[]{}()")

        reMacro = Combine("\\" + oneOf(list("dws")))
        escapedChar = ~reMacro + Combine("\\" + oneOf(list(printables)))
        reLiteralChar = "".join(c for c in printables if c not in r"\[]{}().*?+|") + " \t"

        reRange = Combine(lbrack + SkipTo(rbrack,ignore=escapedChar) + rbrack)
        reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) )
        reDot = Literal(".")
        repetition = (
            ( lbrace + Word(nums).setResultsName("count") + rbrace ) |
            ( lbrace + Word(nums).setResultsName("minCount")+","+ Word(nums).setResultsName("maxCount") + rbrace ) |
            oneOf(list("*+?")) 
            )

        reRange.setParseAction(handleRange)
        reLiteral.setParseAction(handleLiteral)
        reMacro.setParseAction(handleMacro)
        reDot.setParseAction(handleDot)

        reTerm = ( reLiteral | reRange | reMacro | reDot )
        reExpr = operatorPrecedence( reTerm,
            [
            (repetition, 1, opAssoc.LEFT, handleRepetition),
            (None, 2, opAssoc.LEFT, handleSequence),
            (Suppress('|'), 2, opAssoc.LEFT, handleAlternative),
            ]
            )
        _parser = reExpr

    return _parser

def count(gen):
    """Simple function to count the number of elements returned by a generator."""
    i = 0
    for s in gen:
        i += 1
    return i

def invert(regex):
    """Call this routine as a generator to return all the strings that
       match the input regular expression.
           for s in invert("[A-Z]{3}\d{3}"):
               print s
    """
    invReGenerator = GroupEmitter(parser().parseString(regex)).makeGenerator()
    return invReGenerator()

def main():
    tests = r"""
    [A-EA]
    [A-D]*
    [A-D]{3}
    X[A-C]{3}Y
    X[A-C]{3}\(
    X\d
    foobar\d\d
    foobar{2}
    foobar{2,9}
    fooba[rz]{2}
    (foobar){2}
    ([01]\d)|(2[0-5])
    ([01]\d\d)|(2[0-4]\d)|(25[0-5])
    [A-C]{1,2}
    [A-C]{0,3}
    [A-C]\s[A-C]\s[A-C]
    [A-C]\s?[A-C][A-C]
    [A-C]\s([A-C][A-C])
    [A-C]\s([A-C][A-C])?
    [A-C]{2}\d{2}
    @|TH[12]
    @(@|TH[12])?
    @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?
    @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?|30?|[4-9]))?
    (([ECMP]|HA|AK)[SD]|HS)T
    [A-CV]{2}
    A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]
    (a|b)|(x|y)
    (a|b) (x|y)
    """.split('\n')

    for t in tests:
        t = t.strip()
        if not t: continue
        print '-'*50
        print t
        try:
            print count(invert(t))
            for s in invert(t):
                print s
        except ParseFatalException,pfe:
            print pfe.msg
            print
            continue
        print

if __name__ == "__main__":
    main()

What is a callback function?

Assume we have a function sort(int *arraytobesorted,void (*algorithmchosen)(void)) where it can accept a function pointer as its argument which can be used at some point in sort()'s implementation . Then , here the code that is being addressed by the function pointer algorithmchosen is called as callback function .

And see the advantage is that we can choose any algorithm like:

  1.    algorithmchosen = bubblesort
  2.    algorithmchosen = heapsort
  3.    algorithmchosen = mergesort   ...

Which were, say,have been implemented with the prototype:

  1.   `void bubblesort(void)`
  2.   `void heapsort(void)`
  3.   `void mergesort(void)`   ...

This is a concept used in achieving Polymorphism in Object Oriented Programming

Real-world examples of recursion

Recursion is often used in implementations of the Backtracking algorithm. For a "real-world" application of this, how about a Sudoku solver?

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

Given a function that has 3 items as argument

sum = lambda x, y, z: x + y + z
sum(1,2,3) # sum 3 items

sum([1,2,3]) # error, needs 3 items, not 1 list

x = [1,2,3][0]
y = [1,2,3][1]
z = [1,2,3][2]
sum(x,y,z) # ok

sum(*[1,2,3]) # ok, 1 list becomes 3 items

Imagine this toy with a bag of a triangle, a circle and a rectangle item. That bag does not directly fit. You need to unpack the bag to take those 3 items and now they fit. The Python * operator does this unpack process.

enter image description here

How to use radio buttons in ReactJS?

Bootstrap guys, we do it like this:


export default function RadioButton({ onChange, option }) {
    const handleChange = event => {
        onChange(event.target.value)
    }

    return (
        <>
            <div className="custom-control custom-radio">
                <input
                    type="radio"
                    id={ option.option }
                    name="customRadio"
                    className="custom-control-input"
                    onChange={ handleChange }
                    value = { option.id }
                    />
                    <label
                        className="custom-control-label"
                        htmlFor={ option.option }
                        >
                        { option.option }
                    </label>
            </div>
        </>
    )
}

Mysql - How to quit/exit from stored procedure

MainLabel:BEGIN

IF (<condition>) IS NOT NULL THEN
    LEAVE MainLabel;
END IF; 

....code

i.e.
IF (@skipMe) IS NOT NULL THEN /* @skipMe returns Null if never set or set to NULL */
     LEAVE MainLabel;
END IF;

Rename Oracle Table or View

In order to rename a table in a different schema, try:

ALTER TABLE owner.mytable RENAME TO othertable;

The rename command (as in "rename mytable to othertable") only supports renaming a table in the same schema.

How to find list of possible words from a letter matrix [Boggle Solver]

I have solved this in C#, using a DFA algorithm. You can check out my code at

https://github.com/attilabicsko/wordshuffler/

In addition to finding words in a matrix, my algorithm saves the actual paths for the words, so for designing a word finder game, you can check wether there is a word on an actual path.

How to create PDFs in an Android app?

If you are developing for devices with API level 19 or higher you can use the built in PrintedPdfDocument: http://developer.android.com/reference/android/print/pdf/PrintedPdfDocument.html

// open a new document
PrintedPdfDocument document = new PrintedPdfDocument(context,
     printAttributes);

// start a page
Page page = document.startPage(0);

// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());

// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());

//close the document
document.close();

Visual Studio Code Tab Key does not insert a tab

All the above failed for me. But I noticed shift + ? Tab worked as expected (outdenting the line).

So I looked for the "Indent Line" shortcut (which was assigned to alt + ctrl + cmd + 0 ), assigned it to tab, and now I'm happy again.


Next morning edit...

I also use tab to accept snippet suggestions, so I've set the "when" of "Indent Line" to editorTextFocus && !editorReadonly && !inSnippetMode && !suggestWidgetVisible.

What is the best open XML parser for C++?

TinyXML, and also Boost.PropertyTree. The latter does not fulfill all official requirements, but is very simple.

I would like to see a hash_map example in C++

The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape of "unordered maps":

#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;

int main() {
    unordered_map <string, int> m;
    m["foo"] = 42;
    cout << m["foo"] << endl;
}

In order to get this compile, you need to tell g++ that you are using C++0x:

g++ -std=c++0x main.cpp

These maps work pretty much as std::map does, except that instead of providing a custom operator<() for your own types, you need to provide a custom hash function - suitable functions are provided for types like integers and strings.

Checking if element exists with Python Selenium

a)

from selenium.common.exceptions import NoSuchElementException        
def check_exists_by_xpath(xpath):
    try:
        webdriver.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False
    return True

b) use xpath - the most reliable. Moreover you can take the xpath as a standard throughout all your scripts and create functions as above mentions for universal use.

UPDATE: I wrote the initial answer over 4 years ago and at the time I thought xpath would be the best option. Now I recommend to use css selectors. I still recommend not to mix/use "by id", "by name" and etc and use one single approach instead.

Convert PDF to image with high resolution

One more suggestion is that you can use GIMP.

Just load the PDF file in GIMP->save as .xcf and then you can do whatever you want to the image.

Sort a two dimensional array based on one column

class ArrayComparator implements Comparator<Comparable[]> {
    private final int columnToSort;
    private final boolean ascending;

    public ArrayComparator(int columnToSort, boolean ascending) {
        this.columnToSort = columnToSort;
        this.ascending = ascending;
    }

    public int compare(Comparable[] c1, Comparable[] c2) {
        int cmp = c1[columnToSort].compareTo(c2[columnToSort]);
        return ascending ? cmp : -cmp;
    }
}

This way you can handle any type of data in those arrays (as long as they're Comparable) and you can sort any column in ascending or descending order.

String[][] data = getData();
Arrays.sort(data, new ArrayComparator(0, true));

PS: make sure you check for ArrayIndexOutOfBounds and others.

EDIT: The above solution would only be helpful if you are able to actually store a java.util.Date in the first column or if your date format allows you to use plain String comparison for those values. Otherwise, you need to convert that String to a Date, and you can achieve that using a callback interface (as a general solution). Here's an enhanced version:

class ArrayComparator implements Comparator<Object[]> {
    private static Converter DEFAULT_CONVERTER = new Converter() {
        @Override
        public Comparable convert(Object o) {
            // simply assume the object is Comparable
            return (Comparable) o;
        }
    };
    private final int columnToSort;
    private final boolean ascending;
    private final Converter converter;


    public ArrayComparator(int columnToSort, boolean ascending) {
        this(columnToSort, ascending, DEFAULT_CONVERTER);
    }

    public ArrayComparator(int columnToSort, boolean ascending, Converter converter) {
        this.columnToSort = columnToSort;
        this.ascending = ascending;
        this.converter = converter;
    }

    public int compare(Object[] o1, Object[] o2) {
        Comparable c1 = converter.convert(o1[columnToSort]);
        Comparable c2 = converter.convert(o2[columnToSort]);
        int cmp = c1.compareTo(c2);
        return ascending ? cmp : -cmp;
    }

}

interface Converter {
    Comparable convert(Object o);
}

class DateConverter implements Converter {
    private static final DateFormat df = new SimpleDateFormat("yyyy.MM.dd hh:mm");

    @Override
    public Comparable convert(Object o) {
        try {
            return df.parse(o.toString());
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

And at this point, you can sort on your first column with:

Arrays.sort(data, new ArrayComparator(0, true, new DateConverter());

I skipped the checks for nulls and other error handling issues.

I agree this is starting to look like a framework already. :)

Last (hopefully) edit: I only now realize that your date format allows you to use plain String comparison. If that is the case, you don't need the "enhanced version".

Get value from text area

$('textarea').val();

textarea.value would be pure JavaScript, but here you're trying to use JavaScript as a not-valid jQuery method (.value).

Ignoring directories in Git repositories on Windows

I assume the problem is that your working tree is like:

a-cache/foo
a-cache/index.html
b-cache/bar
b-cache/foo
b-cache/index.html
.gitignore

... with the .gitignore you describe. This will give you git status output like:

$ git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#    .gitignore
#    a-cache/
#    b-cache/

... if the index.html files have not yet been added to the repository. (Git sees that there are unignored files in the cache directories, but it only reports the directories.) To fix this, make sure that you have added and committed the index.html files:

git add *cache/index.html
git commit -m "Adding index.html files to the cache directories"

... and your git status will then look like:

$ git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#    .gitignore
nothing added to commit but untracked files present (use "git add" to track)

(Obviously you do want to commit .gitignore as well. I was just being lazy with this test case.)

What is the difference between Serialization and Marshaling?

Think of them as synonyms, both have a producer that sends stuff over to a consumer... In the end fields of instances are written into a byte stream and the other end foes the reverse ands up with the same instances.

NB - java RMI also contains support for transporting classes that are missing from the recipient...

How to Diff between local uncommitted changes and origin

To see non-staged (non-added) changes to existing files

git diff

Note that this does not track new files. To see staged, non-commited changes

git diff --cached

.NET Excel Library that can read/write .xls files

You may consider 3rd party tool that called Excel Jetcell .NET component for read/write excel files:

C# sample

// Create New Excel Workbook
ExcelWorkbook Wbook = new ExcelWorkbook();
ExcelCellCollection Cells = Wbook.Worksheets.Add("Sheet1").Cells;

Cells["A1"].Value = "Excel writer example (C#)";
Cells["A1"].Style.Font.Bold = true;
Cells["B1"].Value = "=550 + 5";

// Write Excel XLS file
Wbook.WriteXLS("excel_net.xls");

VB.NET sample

' Create New Excel Workbook
Dim Wbook As ExcelWorkbook = New ExcelWorkbook()
Dim Cells As ExcelCellCollection = Wbook.Worksheets.Add("Sheet1").Cells

Cells("A1").Value = "Excel writer example (C#)"
Cells("A1").Style.Font.Bold = True
Cells("B1").Value = "=550 + 5"

' Write Excel XLS file
Wbook.WriteXLS("excel_net.xls")

Difference between partition key, composite key and clustering key in Cassandra?

Worth to note, you will probably use those lots more than in similar concepts in relational world (composite keys).

Example - suppose you have to find last N users who recently joined user group X. How would you do this efficiently given reads are predominant in this case? Like that (from offical Cassandra guide):

CREATE TABLE group_join_dates (
    groupname text,
    joined timeuuid,
    join_date text,
    username text,
    email text,
    age int,
    PRIMARY KEY ((groupname, join_date), joined)
) WITH CLUSTERING ORDER BY (joined DESC)

Here, partitioning key is compound itself and the clustering key is a joined date. The reason why a clustering key is a join date is that results are already sorted (and stored, which makes lookups fast). But why do we use a compound key for partitioning key? Because we always want to read as few partitions as possible. How putting join_date in there helps? Now users from the same group and the same join date will reside in a single partition! This means we will always read as few partitions as possible (first start with the newest, then move to older and so on, rather than jumping between them).

In fact, in extreme cases you would also need to use the hash of a join_date rather than a join_date alone - so that if you query for last 3 days often those share the same hash and therefore are available from same partition!

OpenCV Python rotate image by X degrees around specific point

The cv2.warpAffine function takes the shape parameter in reverse order: (col,row) which the answers above do not mention. Here is what worked for me:

import numpy as np

def rotateImage(image, angle):
    row,col = image.shape
    center=tuple(np.array([row,col])/2)
    rot_mat = cv2.getRotationMatrix2D(center,angle,1.0)
    new_image = cv2.warpAffine(image, rot_mat, (col,row))
    return new_image

Generate an integer sequence in MySQL

Here is a compact binary version of the technique used in other answers here:

select ((((((b7.0 << 1 | b6.0) << 1 | b5.0) << 1 | b4.0) 
                  << 1 | b3.0) << 1 | b2.0) << 1 | b1.0) << 1 | b0.0 as n
from (select 0 union all select 1) as b0,
     (select 0 union all select 1) as b1,
     (select 0 union all select 1) as b2,
     (select 0 union all select 1) as b3,
     (select 0 union all select 1) as b4,
     (select 0 union all select 1) as b5,
     (select 0 union all select 1) as b6,
     (select 0 union all select 1) as b7

There are no unique or sorting phases, no string to number conversion, no arithmetic operations, and each dummy table only has 2 rows, so it should be pretty fast.

This version uses 8 "bits" so it counts from 0 to 255, but you can easily tweak that.

Replacing NULL and empty string within Select statement

Try this

COALESCE(NULLIF(Address.COUNTRY,''), 'United States')

Twitter-Bootstrap-2 logo image on top of navbar

If you do not increase the height of navbar..

 .navbar .brand {
 position: fixed;    
 overflow: visible;
 padding-left: 0;    
 padding-top: 0;
 }

see http://jsfiddle.net/petrfox/S84wP/

Xcode process launch failed: Security

Hey so the accepted answer works, except if you need to debug the initial launch of the app. However I think that answer is more of a work around, and not an actual solution. From my understanding this message occurs when you have some weirdness in your provisioning profile / cert setup so make extra sure everything is in tip-top shape in that dept. before ramming your head against the wall repeatedly.

What worked for me was as follows from the apple docs:

Provisioning Profiles Known Issue If you have upgraded to the GM seed from other betas you may see your apps crashing due to provisioning profile issues.

Workaround:

  1. Connect the device via USB to your Mac

  2. Launch Xcode Choose Window ->Devices

  3. Right click on the device in left column, choose "Show Provisioning Profiles"

  4. Click on the provisioning profile in question

  5. Press the "-" button Continue to removing all affected profiles.

  6. Re-install the app

Make sure you right click on the image of the device not the name of the device or you won't see the provisioning profiles option. I restored my new phone from an old backup and there was a lot of cruft hanging around, i also had 2 different dev. certs active (not sure why) but i deleted one, made a new profile got rid of all the profiles on device and it worked.

Hope this helps someone else.

How to drop a database with Mongoose?

To empty a particular collection in a database:

model.remove(function(err, p){
    if(err){ 
        throw err;
    } else{
        console.log('No Of Documents deleted:' + p);
    }
});

Note:

  1. Choose a model referring to particular schema(schema of collection you wish to delete).
  2. This operation will not delete collection name from database.
  3. This deletes all the documents in a collection.

jQuery - Illegal invocation

In my case (using webpack 4) within an anonymous function, that I was using as a callback.

I had to use window.$.ajax() instead of $.ajax() despite having:

import $ from 'jquery';
window.$ = window.jQuery = $;

Change color inside strings.xml

You do not set such attributes in strings.xml type of files. You need to set it in your code. or (which is better solution) create style with colors you want and apply to your TextView

Imported a csv-dataset to R but the values becomes factors

Both the data import function (here: read.csv()) as well as a global option offer you to say stringsAsFactors=FALSE which should fix this.

How to check if a subclass is an instance of a class at runtime?

You have to read the API carefully for this methods. Sometimes you can get confused very easily.

It is either:

if (B.class.isInstance(view))

API says: Determines if the specified Object (the parameter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at)

or:

if (B.class.isAssignableFrom(view.getClass()))

API says: Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter

or (without reflection and the recommended one):

if (view instanceof B)

C# string reference type?

Here's a good way to think about the difference between value-types, passing-by-value, reference-types, and passing-by-reference:

A variable is a container.

A value-type variable contains an instance. A reference-type variable contains a pointer to an instance stored elsewhere.

Modifying a value-type variable mutates the instance that it contains. Modifying a reference-type variable mutates the instance that it points to.

Separate reference-type variables can point to the same instance. Therefore, the same instance can be mutated via any variable that points to it.

A passed-by-value argument is a new container with a new copy of the content. A passed-by-reference argument is the original container with its original content.

When a value-type argument is passed-by-value: Reassigning the argument's content has no effect outside scope, because the container is unique. Modifying the argument has no effect outside scope, because the instance is an independent copy.

When a reference-type argument is passed-by-value: Reassigning the argument's content has no effect outside scope, because the container is unique. Modifying the argument's content affects the external scope, because the copied pointer points to a shared instance.

When any argument is passed-by-reference: Reassigning the argument's content affects the external scope, because the container is shared. Modifying the argument's content affects the external scope, because the content is shared.

In conclusion:

A string variable is a reference-type variable. Therefore, it contains a pointer to an instance stored elsewhere. When passed-by-value, its pointer is copied, so modifying a string argument should affect the shared instance. However, a string instance has no mutable properties, so a string argument cannot be modified anyway. When passed-by-reference, the pointer's container is shared, so reassignment will still affect the external scope.

How can I ssh directly to a particular directory?

going one step further with the -t idea. I keep a set of scripts calling the one below to go to specific places in my frequently visited hosts. I keep them all in ~/bin and keep that directory in my path.

#!/bin/bash

# does ssh session switching to particular directory
# $1, hostname from config file 
# $2, directory to move to after login
# can save this as say 'con' then
# make another script calling this one, e.g.
# con myhost repos/i2c

ssh -t $1 "cd $2; exec \$SHELL --login"

What is the C# version of VB.net's InputDialog?

I was able to achieve this by coding my own. I don't like extending into and relying on large library's for something rudimental.

Form and Designer:

public partial class InputBox 
    : Form
{

    public String Input
    {
        get { return textInput.Text; }
    }

    public InputBox()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        DialogResult = System.Windows.Forms.DialogResult.OK;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DialogResult = System.Windows.Forms.DialogResult.Cancel;
    }

    private void InputBox_Load(object sender, EventArgs e)
    {
        this.ActiveControl = textInput;
    }

    public static DialogResult Show(String title, String message, String inputTitle, out String inputValue)
    {
        InputBox inputBox = null;
        DialogResult results = DialogResult.None;

        using (inputBox = new InputBox() { Text = title })
        {
            inputBox.labelMessage.Text = message;
            inputBox.splitContainer2.SplitterDistance = inputBox.labelMessage.Width;
            inputBox.labelInput.Text = inputTitle;
            inputBox.splitContainer1.SplitterDistance = inputBox.labelInput.Width;
            inputBox.Size = new Size(
                inputBox.Width,
                8 + inputBox.labelMessage.Height + inputBox.splitContainer2.SplitterWidth + inputBox.splitContainer1.Height + 8 + inputBox.button2.Height + 12 + (50));
            results = inputBox.ShowDialog();
            inputValue = inputBox.Input;
        }

        return results;
    }

    void labelInput_TextChanged(object sender, System.EventArgs e)
    {
    }

}

partial class InputBox
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.labelMessage = new System.Windows.Forms.Label();
        this.button1 = new System.Windows.Forms.Button();
        this.button2 = new System.Windows.Forms.Button();
        this.labelInput = new System.Windows.Forms.Label();
        this.textInput = new System.Windows.Forms.TextBox();
        this.splitContainer1 = new System.Windows.Forms.SplitContainer();
        this.splitContainer2 = new System.Windows.Forms.SplitContainer();
        ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
        this.splitContainer1.Panel1.SuspendLayout();
        this.splitContainer1.Panel2.SuspendLayout();
        this.splitContainer1.SuspendLayout();
        ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();
        this.splitContainer2.Panel1.SuspendLayout();
        this.splitContainer2.Panel2.SuspendLayout();
        this.splitContainer2.SuspendLayout();
        this.SuspendLayout();
        // 
        // labelMessage
        // 
        this.labelMessage.AutoSize = true;
        this.labelMessage.Location = new System.Drawing.Point(3, 0);
        this.labelMessage.MaximumSize = new System.Drawing.Size(379, 0);
        this.labelMessage.Name = "labelMessage";
        this.labelMessage.Size = new System.Drawing.Size(50, 13);
        this.labelMessage.TabIndex = 99;
        this.labelMessage.Text = "Message";
        // 
        // button1
        // 
        this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
        this.button1.Location = new System.Drawing.Point(316, 126);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 23);
        this.button1.TabIndex = 3;
        this.button1.Text = "Cancel";
        this.button1.UseVisualStyleBackColor = true;
        this.button1.Click += new System.EventHandler(this.button1_Click);
        // 
        // button2
        // 
        this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
        this.button2.Location = new System.Drawing.Point(235, 126);
        this.button2.Name = "button2";
        this.button2.Size = new System.Drawing.Size(75, 23);
        this.button2.TabIndex = 2;
        this.button2.Text = "OK";
        this.button2.UseVisualStyleBackColor = true;
        this.button2.Click += new System.EventHandler(this.button2_Click);
        // 
        // labelInput
        // 
        this.labelInput.AutoSize = true;
        this.labelInput.Location = new System.Drawing.Point(3, 6);
        this.labelInput.Name = "labelInput";
        this.labelInput.Size = new System.Drawing.Size(31, 13);
        this.labelInput.TabIndex = 99;
        this.labelInput.Text = "Input";
        this.labelInput.TextChanged += new System.EventHandler(this.labelInput_TextChanged);
        // 
        // textInput
        // 
        this.textInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.textInput.Location = new System.Drawing.Point(3, 3);
        this.textInput.Name = "textInput";
        this.textInput.Size = new System.Drawing.Size(243, 20);
        this.textInput.TabIndex = 1;
        // 
        // splitContainer1
        // 
        this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
        this.splitContainer1.IsSplitterFixed = true;
        this.splitContainer1.Location = new System.Drawing.Point(0, 0);
        this.splitContainer1.Name = "splitContainer1";
        // 
        // splitContainer1.Panel1
        // 
        this.splitContainer1.Panel1.Controls.Add(this.labelInput);
        // 
        // splitContainer1.Panel2
        // 
        this.splitContainer1.Panel2.Controls.Add(this.textInput);
        this.splitContainer1.Size = new System.Drawing.Size(379, 50);
        this.splitContainer1.SplitterDistance = 126;
        this.splitContainer1.TabIndex = 99;
        // 
        // splitContainer2
        // 
        this.splitContainer2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.splitContainer2.IsSplitterFixed = true;
        this.splitContainer2.Location = new System.Drawing.Point(12, 12);
        this.splitContainer2.Name = "splitContainer2";
        this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
        // 
        // splitContainer2.Panel1
        // 
        this.splitContainer2.Panel1.Controls.Add(this.labelMessage);
        // 
        // splitContainer2.Panel2
        // 
        this.splitContainer2.Panel2.Controls.Add(this.splitContainer1);
        this.splitContainer2.Size = new System.Drawing.Size(379, 108);
        this.splitContainer2.SplitterDistance = 54;
        this.splitContainer2.TabIndex = 99;
        // 
        // InputBox
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(403, 161);
        this.Controls.Add(this.splitContainer2);
        this.Controls.Add(this.button2);
        this.Controls.Add(this.button1);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.Name = "InputBox";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "Title";
        this.TopMost = true;
        this.Load += new System.EventHandler(this.InputBox_Load);
        this.splitContainer1.Panel1.ResumeLayout(false);
        this.splitContainer1.Panel1.PerformLayout();
        this.splitContainer1.Panel2.ResumeLayout(false);
        this.splitContainer1.Panel2.PerformLayout();
        ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
        this.splitContainer1.ResumeLayout(false);
        this.splitContainer2.Panel1.ResumeLayout(false);
        this.splitContainer2.Panel1.PerformLayout();
        this.splitContainer2.Panel2.ResumeLayout(false);
        ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();
        this.splitContainer2.ResumeLayout(false);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.Label labelMessage;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.Label labelInput;
    private System.Windows.Forms.TextBox textInput;
    private System.Windows.Forms.SplitContainer splitContainer1;
    private System.Windows.Forms.SplitContainer splitContainer2;
}

Usage:

String output = "";

result = System.Windows.Forms.DialogResult.None;

result = InputBox.Show(
    "Input Required",
    "Please enter the value (if available) below.",
    "Value",
    out output);

if (result != System.Windows.Forms.DialogResult.OK)
{
    return;
}

Note this exhibits a bit of auto sizing to keep it pretty based on how much text you ask it display. I also know it's lacking the bells and whistles but it's a solid step forward for those facing this same dilemma.

How to use Git?

I think gitready is a great starting point. I'm using git for a project now and that site pretty much got the ball rolling for me.

jquery ajax get responsetext from http url

Actually, you can make cross domain requests with i.e. Firefox, se this for a overview: http://ajaxian.com/archives/cross-site-xmlhttprequest-in-firefox-3

Webkit and IE8 supports it as well in some fashion.

Can I use a :before or :after pseudo-element on an input field?

try next:

_x000D_
_x000D_
label[for="userName"] {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
label[for="userName"]::after {_x000D_
  content: '[after]';_x000D_
  width: 22px;_x000D_
  height: 22px;_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  right: -30px;_x000D_
}
_x000D_
<label for="userName">_x000D_
 Name: _x000D_
 <input type="text" name="userName" id="userName">_x000D_
 </label>
_x000D_
_x000D_
_x000D_

Swift - Integer conversion to Hours/Minutes/Seconds

Here is a more structured/flexible approach: (Swift 3)

struct StopWatch {

    var totalSeconds: Int

    var years: Int {
        return totalSeconds / 31536000
    }

    var days: Int {
        return (totalSeconds % 31536000) / 86400
    }

    var hours: Int {
        return (totalSeconds % 86400) / 3600
    }

    var minutes: Int {
        return (totalSeconds % 3600) / 60
    }

    var seconds: Int {
        return totalSeconds % 60
    }

    //simplified to what OP wanted
    var hoursMinutesAndSeconds: (hours: Int, minutes: Int, seconds: Int) {
        return (hours, minutes, seconds)
    }
}

let watch = StopWatch(totalSeconds: 27005 + 31536000 + 86400)
print(watch.years) // Prints 1
print(watch.days) // Prints 1
print(watch.hours) // Prints 7
print(watch.minutes) // Prints 30
print(watch.seconds) // Prints 5
print(watch.hoursMinutesAndSeconds) // Prints (7, 30, 5)

Having an approach like this allows the adding of convenience parsing like this:

extension StopWatch {

    var simpleTimeString: String {
        let hoursText = timeText(from: hours)
        let minutesText = timeText(from: minutes)
        let secondsText = timeText(from: seconds)
        return "\(hoursText):\(minutesText):\(secondsText)"
    }

    private func timeText(from number: Int) -> String {
        return number < 10 ? "0\(number)" : "\(number)"
    }
}
print(watch.simpleTimeString) // Prints 07:30:05

It should be noted that purely Integer based approaches don't take leap day/seconds into account. If the use case is dealing with real dates/times Date and Calendar should be used.

What is the difference between ELF files and bin files?

A Bin file is a pure binary file with no memory fix-ups or relocations, more than likely it has explicit instructions to be loaded at a specific memory address. Whereas....

ELF files are Executable Linkable Format which consists of a symbol look-ups and relocatable table, that is, it can be loaded at any memory address by the kernel and automatically, all symbols used, are adjusted to the offset from that memory address where it was loaded into. Usually ELF files have a number of sections, such as 'data', 'text', 'bss', to name but a few...it is within those sections where the run-time can calculate where to adjust the symbol's memory references dynamically at run-time.

Capture the Screen into a Bitmap

Try this code

Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics gr = Graphics.FromImage(bmp);
gr.CopyFromScreen(0, 0, 0, 0, bmp.Size);
pictureBox1.Image = bmp;
bmp.Save("img.png",System.Drawing.Imaging.ImageFormat.Png);

How can I make the cursor turn to the wait cursor?

With the class below you can make the suggestion of Donut "exception safe".

using (new CursorHandler())
{
    // Execute your time-intensive hashing code here...
}

the class CursorHandler

public class CursorHandler
    : IDisposable
{
    public CursorHandler(Cursor cursor = null)
    {
        _saved = Cursor.Current;
        Cursor.Current = cursor ?? Cursors.WaitCursor;
    }

    public void Dispose()
    {
        if (_saved != null)
        {
            Cursor.Current = _saved;
            _saved = null;
        }
    }

    private Cursor _saved;
}

What does the 'b' character do in front of a string literal?

Python 3.x makes a clear distinction between the types:

If you're familiar with:

  • Java or C#, think of str as String and bytes as byte[];
  • SQL, think of str as NVARCHAR and bytes as BINARY or BLOB;
  • Windows registry, think of str as REG_SZ and bytes as REG_BINARY.

If you're familiar with C(++), then forget everything you've learned about char and strings, because a character is not a byte. That idea is long obsolete.

You use str when you want to represent text.

print('???? ????')

You use bytes when you want to represent low-level binary data like structs.

NaN = struct.unpack('>d', b'\xff\xf8\x00\x00\x00\x00\x00\x00')[0]

You can encode a str to a bytes object.

>>> '\uFEFF'.encode('UTF-8')
b'\xef\xbb\xbf'

And you can decode a bytes into a str.

>>> b'\xE2\x82\xAC'.decode('UTF-8')
'€'

But you can't freely mix the two types.

>>> b'\xEF\xBB\xBF' + 'Text with a UTF-8 BOM'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't concat bytes to str

The b'...' notation is somewhat confusing in that it allows the bytes 0x01-0x7F to be specified with ASCII characters instead of hex numbers.

>>> b'A' == b'\x41'
True

But I must emphasize, a character is not a byte.

>>> 'A' == b'A'
False

In Python 2.x

Pre-3.0 versions of Python lacked this kind of distinction between text and binary data. Instead, there was:

  • unicode = u'...' literals = sequence of Unicode characters = 3.x str
  • str = '...' literals = sequences of confounded bytes/characters
    • Usually text, encoded in some unspecified encoding.
    • But also used to represent binary data like struct.pack output.

In order to ease the 2.x-to-3.x transition, the b'...' literal syntax was backported to Python 2.6, in order to allow distinguishing binary strings (which should be bytes in 3.x) from text strings (which should be str in 3.x). The b prefix does nothing in 2.x, but tells the 2to3 script not to convert it to a Unicode string in 3.x.

So yes, b'...' literals in Python have the same purpose that they do in PHP.

Also, just out of curiosity, are there more symbols than the b and u that do other things?

The r prefix creates a raw string (e.g., r'\t' is a backslash + t instead of a tab), and triple quotes '''...''' or """...""" allow multi-line string literals.

Convert from ASCII string encoded in Hex to plain ASCII?

>>> txt = '7061756c'
>>> ''.join([chr(int(''.join(c), 16)) for c in zip(txt[0::2],txt[1::2])])
'paul'                                                                          

i'm just having fun, but the important parts are:

>>> int('0a',16)         # parse hex
10
>>> ''.join(['a', 'b'])  # join characters
'ab'
>>> 'abcd'[0::2]         # alternates
'ac'
>>> zip('abc', '123')    # pair up
[('a', '1'), ('b', '2'), ('c', '3')]        
>>> chr(32)              # ascii to character
' '

will look at binascii now...

>>> print binascii.unhexlify('7061756c')
paul

cool (and i have no idea why other people want to make you jump through hoops before they'll help).

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

Same pdo error in sql query while trying to insert into database value from multidimential array:

$sql = "UPDATE test SET field=arr[$s][a] WHERE id = $id";
$sth = $db->prepare($sql);    
$sth->execute();

Extracting array arr[$s][a] from sql query, using instead variable containing it fixes the problem.

Using Axios GET with Authorization Header in React-Native App

For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request

Big thanks to @swapnil for trying to help me debug this.

   const data = {
      grant_type: USER_GRANT_TYPE,
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      scope: SCOPE_INT,
      username: DEMO_EMAIL,
      password: DEMO_PASSWORD
    };



  axios.post(TOKEN_URL, Querystring.stringify(data))   
   .then(response => {
      console.log(response.data);
      USER_TOKEN = response.data.access_token;
      console.log('userresponse ' + response.data.access_token); 
    })   
   .catch((error) => {
      console.log('error ' + error);   
   });



const AuthStr = 'Bearer '.concat(USER_TOKEN); 
axios.get(URL, { headers: { Authorization: AuthStr } })
 .then(response => {
     // If request is good...
     console.log(response.data);
  })
 .catch((error) => {
     console.log('error ' + error);
  });

Add Text on Image using PIL

I think ImageFont module available in PIL should be helpful in solving text font size problem. Just check what font type and size is appropriate for you and use following function to change font values.

# font = ImageFont.truetype(<font-file>, <font-size>)
# font-file should be present in provided path.
font = ImageFont.truetype("sans-serif.ttf", 16)

So your code will look something similar to:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 

img = Image.open("sample_in.jpg")
draw = ImageDraw.Draw(img)
# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype("sans-serif.ttf", 16)
# draw.text((x, y),"Sample Text",(r,g,b))
draw.text((0, 0),"Sample Text",(255,255,255),font=font)
img.save('sample-out.jpg')

You might need to put some extra effort to calculate font size. In case you want to change it based on amount of text user has provided in TextArea.

To add text wrapping (Multiline thing) just take a rough idea of how many characters can come in one line, Then you can probably write a pre-pprocessing function for your Text, Which basically finds the character which will be last in each line and converts white space before this character to new-line.

How to filter WooCommerce products by custom attribute

You can use WooCommerce AJAX Product Filter. You can also watch how the plugin is used for product filtering.

Here is a screenshot:

enter image description here

Spring data JPA query with parameter properties

    for using this, you can create a Repository for example this one:
    Member findByEmail(String email);

    List<Member> findByDate(Date date);
    // custom query example and return a member
   @Query("select m from Member m where m.username = :username and m.password=:password")
        Member findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);

Swift performSelector:withObject:afterDelay: is unavailable

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    // your function here
}

Swift 3

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
    // your function here
}

Swift 2

let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
    // your function here 
})

Get a random item from a JavaScript array

1. solution: define Array prototype

Array.prototype.random = function () {
  return this[Math.floor((Math.random()*this.length))];
}

that will work on inline arrays

[2,3,5].random()

and of course predefined arrays

list = [2,3,5]
list.random()

2. solution: define custom function that accepts list and returns element

get_random = function (list) {
  return list[Math.floor((Math.random()*list.length))];
} 

get_random([2,3,5])

Best way to select random rows PostgreSQL

select * from table order by random() limit 1000;

If you know how many rows you want, check out tsm_system_rows.

tsm_system_rows

module provides the table sampling method SYSTEM_ROWS, which can be used in the TABLESAMPLE clause of a SELECT command.

This table sampling method accepts a single integer argument that is the maximum number of rows to read. The resulting sample will always contain exactly that many rows, unless the table does not contain enough rows, in which case the whole table is selected. Like the built-in SYSTEM sampling method, SYSTEM_ROWS performs block-level sampling, so that the sample is not completely random but may be subject to clustering effects, especially if only a small number of rows are requested.

First install the extension

CREATE EXTENSION tsm_system_rows;

Then your query,

SELECT *
FROM table
TABLESAMPLE SYSTEM_ROWS(1000);

input() error - NameError: name '...' is not defined

For python 3 and above

s = raw_input()

it will solve the problem on pycharm IDE if you are solving on online site exactly hackerrank then use:

s = input()

C# Convert List<string> to Dictionary<string, string>

You can use:

var dictionary = myList.ToDictionary(x => x);

How to add a class to body tag?

$('body').toggleClass("className");

perfectly works

Php, wait 5 seconds before executing an action

In Jan2018 the only solution worked for me:

<?php

if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){

    echo "<br> Line to show.";
    echo str_pad('',4096)."\n";    

    ob_flush();
    flush();
    sleep(2);
}

echo "Done.";

ob_end_flush();

?>

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do this simply by using pandas drop duplicates function

df.drop_duplicates(['A','B'],keep= 'last')

Why doesn't Console.Writeline, Console.Write work in Visual Studio Express?

The output window isn't the console. Try the methods in System.Diagnostics.Debug

Write variable to file, including name

the repr function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.

>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'one': 1}"

writing to a file is pretty standard stuff, like any other file write:

f = open( 'file.py', 'w' )
f.write( 'dict = ' + repr(dict) + '\n' )
f.close()

Angular 6: saving data to local storage

you can use localStorage for storing the json data:

the example is given below:-

let JSONDatas = [
    {"id": "Open"},
    {"id": "OpenNew", "label": "Open New"},
    {"id": "ZoomIn", "label": "Zoom In"},
    {"id": "ZoomOut", "label": "Zoom Out"},
    {"id": "Find", "label": "Find..."},
    {"id": "FindAgain", "label": "Find Again"},
    {"id": "Copy"},
    {"id": "CopyAgain", "label": "Copy Again"},
    {"id": "CopySVG", "label": "Copy SVG"},
    {"id": "ViewSVG", "label": "View SVG"}
]

localStorage.setItem("datas", JSON.stringify(JSONDatas));

let data = JSON.parse(localStorage.getItem("datas"));

console.log(data);

How to determine if one array contains all elements of another array

If there are are no duplicate elements or you don't care about them, then you can use the Set class:

a1 = Set.new [5, 1, 6, 14, 2, 8]
a2 = Set.new [2, 6, 15]
a1.subset?(a2)
=> false

Behind the scenes this uses

all? { |o| set.include?(o) }

How to use Global Variables in C#?

In C# you cannot define true global variables (in the sense that they don't belong to any class).

This being said, the simplest approach that I know to mimic this feature consists in using a static class, as follows:

public static class Globals
{
    public const Int32 BUFFER_SIZE = 512; // Unmodifiable
    public static String FILE_NAME = "Output.txt"; // Modifiable
    public static readonly String CODE_PREFIX = "US-"; // Unmodifiable
}

You can then retrieve the defined values anywhere in your code (provided it's part of the same namespace):

String code = Globals.CODE_PREFIX + value.ToString();

In order to deal with different namespaces, you can either:

  • declare the Globals class without including it into a specific namespace (so that it will be placed in the global application namespace);
  • insert the proper using directive for retrieving the variables from another namespace.

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

Rails select helper - Default selected value, how?

Rails 3.0.9

select options_for_select([value1, value2, value3], default)

Passing Parameters JavaFX FXML

Here is an example for using a controller injected by Guice.

/**
 * Loads a FXML file and injects its controller from the given Guice {@code Provider}
 */
public abstract class GuiceFxmlLoader {

   public GuiceFxmlLoader(Stage stage, Provider<?> provider) {
      mStage = Objects.requireNonNull(stage);
      mProvider = Objects.requireNonNull(provider);
   }

   /**
    * @return the FXML file name
    */
   public abstract String getFileName();

   /**
    * Load FXML, set its controller with given {@code Provider}, and add it to {@code Stage}.
    */
   public void loadView() {
      try {
         FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource(getFileName()));
         loader.setControllerFactory(p -> mProvider.get());
         Node view = loader.load();
         setViewInStage(view);
      }
      catch (IOException ex) {
         LOGGER.error("Failed to load FXML: " + getFileName(), ex);
      }
   }

   private void setViewInStage(Node view) {
      BorderPane pane = (BorderPane)mStage.getScene().getRoot();
      pane.setCenter(view);
   }

   private static final Logger LOGGER = Logger.getLogger(GuiceFxmlLoader.class);

   private final Stage mStage;
   private final Provider<?> mProvider;
}

Here is a concrete implementation of the loader:

public class ConcreteViewLoader extends GuiceFxmlLoader {

   @Inject
   public ConcreteViewLoader(Stage stage, Provider<MyController> provider) {
      super(stage, provider);
   }

   @Override
   public String getFileName() {
      return "my_view.fxml";
   }
}

Note this example loads the view into the center of a BoarderPane that is the root of the Scene in the Stage. This is irrelevant to the example (implementation detail of my specific use case) but decided to leave it in as some may find it useful.

Is null reference possible?

Yes:

#include <iostream>
#include <functional>

struct null_ref_t {
   template <typename T>
   operator T&() {
      union TypeSafetyBreaker {
         T *ptr;

         // see https://stackoverflow.com/questions/38691282/use-of-union-with-reference
         std::reference_wrapper<T> ref; 
      };

      TypeSafetyBreaker ptr = {.ptr = nullptr};

      // unwrap the reference
      return ptr.ref.get();
   }
};

null_ref_t nullref;


int main() {
   int &a = nullref;

   // Segmentation fault
   a = 4;
   return 0;
}

Create table using Javascript

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Insert title here</title>
    </head>
    <body>
        <table id="myTable" cellpadding="2" cellspacing="2" border="1" onclick="tester()"></table>
        <script>
            var student;
            for (var j = 0; j < 10; j++) {
                student = {
                    name: "Name" + j,
                    rank: "Rank" + j,
                    stuclass: "Class" + j,
                };
                var table = document.getElementById("myTable");
                var row = table.insertRow(j);
                var cell1 = row.insertCell(0);
                var cell2 = row.insertCell(1);
                var cell3 = row.insertCell(2);

                cell1.innerHTML = student.name,
                cell2.innerHTML = student.rank,
                cell3.innerHTML = student.stuclass;
            }
        </script>
    </body>
</html>

Count number of columns in a table row

It's a bad idea to count the td elements to get the number of columns in your table, because td elements can span multiple columns with colspan.

Here's a simple solution using jquery:

_x000D_
_x000D_
var length = 0;_x000D_
$("tr:first").find("td,th").each(function(){_x000D_
 var colspan = $(this).attr("colspan");_x000D_
  if(typeof colspan !== "undefined" && colspan > 0){_x000D_
   length += parseInt(colspan);_x000D_
  }else{_x000D_
        length += 1;_x000D_
  }_x000D_
});_x000D_
_x000D_
$("div").html("number of columns: "+length);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<tr>_x000D_
  <td>single</td>_x000D_
  <td colspan="2">double</td>_x000D_
  <td>single</td>_x000D_
  <td>single</td>_x000D_
</tr>_x000D_
</table>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

For a plain Javascript solution, see Emilio's answer.

How to make the checkbox unchecked by default always

This is browser specific behavior and is a way for making filling up forms more convenient to users (like reloading the page when an error has been encountered and not losing what they just typed). So there is no sure way to disable this across browsers short of setting the default values on page load using javascript.

Firefox though seems to disable this feature when you specify the header:

Cache-Control: no-store

See this question.

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.

let's play a bit ;) :

import cv2
import numpy as np

>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168,  58,   2,   1],  # uninitialized memory counts as random, too ?  fun ;) 
       [  0, 100,   2,   0, 101],
       [  0,   0, 106,   2,   0],
       [131,   2,   0,  90,   3],
       [  0, 100,   1,   0,  83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99))         # normal
array([[  0,  76,   0, 129,   0],
       [  0,   0,   0, 188,  27],
       [  0, 152,   0,   0,   0],
       [  0,   0, 134,  79,   0],
       [  0, 181,  36, 128,   0]], dtype=uint8)
>>> cv2.randu(im,(0),(99))         # uniform
array([[19, 53,  2, 86, 82],
       [86, 73, 40, 64, 78],
       [34, 20, 62, 80,  7],
       [24, 92, 37, 60, 72],
       [40, 12, 27, 33, 18]], dtype=uint8)

to apply it to an existing image, just generate noise in the desired range, and add it:

img = ...
noise = ...

image = img + noise

How to force reloading php.ini file?

TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm service.

The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.

To restart the service:

Note: prepend sudo if not root

Using SysV Init scripts directly:

/etc/init.d/php-fpm restart        # typical
/etc/init.d/php5-fpm restart       # debian-style
/etc/init.d/php7.0-fpm restart     # debian-style PHP 7

Using service wrapper script

service php-fpm restart        # typical
service php5-fpm restart       # debian-style
service php7.0-fpm restart.    # debian-style PHP 7

Using Upstart (e.g. ubuntu):

restart php7.0-fpm         # typical (ubuntu is debian-based) PHP 7
restart php5-fpm           # typical (ubuntu is debian-based)
restart php-fpm            # uncommon

Using systemd (newer servers):

systemctl restart php-fpm.service        # typical
systemctl restart php5-fpm.service       # uncommon
systemctl restart php7.0-fpm.service     # uncommon PHP 7

Or whatever the equivalent is on your system.

The above commands taken directly from this server fault answer

on change event for file input element

For someone who want to use onchange event directly on file input, set onchange="somefunction(), example code from the link:

<html>
<body>
    <script language="JavaScript">
    function inform(){
        document.form1.msg.value = "Filename has been changed";
    }
    </script>
    <form name="form1">
    Please choose a file.
    <input type="file" name="uploadbox" size="35" onChange='inform()'>
    <br><br>
    Message:
    <input type="text" name="msg" size="40">
    </form>
</body>
</html>

Difference between ref and out parameters in .NET

ref will probably choke on null since it presumably expects to be modifying an existing object. out expects null, since it's returning a new object.

Android emulator: could not get wglGetExtensionsStringARB error

When you create the emulator, you need to choose properties CPU/ABI is Intel Atom (installed it in SDK manager )

How to open a different activity on recyclerView item onclick

This question has been asked long ago, anyway i would write an easy answer may it help someone.

The easiest way to attach a clickListener to items of RecyclerView is within the Adapter as below:

public class MyAdapter extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {

....

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(view.getContext(), YourActivity.Class);
                startActivity(intent);
            }
        });
}

Javascript onload not working

There's nothing wrong with include file in head. It seems you forgot to add;. Please try this one:

<body onload="imageRefreshBig();">

But as per my knowledge semicolons are optional. You can try with ; but better debug code and see if chrome console gives any error.

I hope this helps.

Angular update object in object array

I would rather create a map

export class item{
    name: string; 
    id: string
}

let caches = new Map<string, item>();

and then you can simply

this.caches[newitem.id] = newitem; 

even

this.caches.set(newitem.id, newitem); 

array is so 1999. :)

AngularJS - Trigger when radio button is selected

Another approach is using Object.defineProperty to set valueas a getter setter property in the controller scope, then each change on the value property will trigger a function specified in the setter:

The HTML file:

<input type="radio" ng-model="value" value="one"/>
<input type="radio" ng-model="value" value="two"/>
<input type="radio" ng-model="value" value="three"/>

The javascript file:

var _value = null;
Object.defineProperty($scope, 'value', {
  get: function () {
    return _value;
  },         
  set: function (value) {
    _value = value;
    someFunction();
  }
});

see this plunker for the implementation

Where to find the win32api module for Python?

I've found that UC Irvine has a great collection of python modules, pywin32 (win32api) being one of many listed there. I'm not sure how they do with keeping up with the latest versions of these modules but it hasn't let me down yet.

UC Irvine Python Extension Repository - http://www.lfd.uci.edu/~gohlke/pythonlibs

pywin32 module - http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32

CSS background image URL failing to load

source URL for image can be a URL on a website like http://www.google.co.il/images/srpr/nav_logo73.png or https://https.openbsd.org/images/tshirt-26_front.gif or if you want to use a local file try this: url("file:///MacintoshHDOriginal/Users/lowri/Desktop/acgnx/image s/images/acgn-site-background-X_07.jpg")

How to run sql script using SQL Server Management Studio?

Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.

How to map to multiple elements with Java 8 streams?

To do this, I had to come up with an intermediate data structure:

class KeyDataPoint {
    String key;
    DateTime timestamp;
    Number data;
    // obvious constructor and getters
}

With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.

Then, we apply a groupingBy operation on the string key in order to gather the data for each key together. Note that a simple groupingBy would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy which is a mapping operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping operation is simply toList which collects the DataPoint objects of the same group into a list.

Now we have a Map<String, List<DataPoint>> and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.

The code ends up looking like this:

Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.getData().entrySet().stream()
                           .map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
        .collect(groupingBy(KeyDataPoint::getKey,
                    mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

I took some liberties with constructors and getters, but I think they should be obvious.

Binding an Image in WPF MVVM

@Sheridan thx.. if I try your example with "DisplayedImagePath" on both sides, it works with absolute path as you show.

As for the relative paths, this is how I always connect relative paths, I first include the subdirectory (!) and the image file in my project.. then I use ~ character to denote the bin-path..

    public string DisplayedImagePath
    {
        get { return @"~\..\images\osc.png"; }
    }

This was tested, see below my Solution Explorer in VS2015..

example of image binding in VS2015)

Note: if you want a Click event, use the Button tag around the image,

_x000D_
_x000D_
<Button Click="image_Click" Width="128" Height="128"  Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Left">_x000D_
  <Image x:Name="image" Source="{Binding DisplayedImagePath}" Margin="0,0,0,0" />_x000D_
</Button>
_x000D_
_x000D_
_x000D_

jquery input select all on focus

This version works on ios and also fixes standard drag-to-select on windows chrome

var srcEvent = null;

$("input[type=text],input[type=number]")

    .mousedown(function (event) {
        srcEvent = event;
    })

    .mouseup(function (event) {
        var delta = Math.abs(event.clientX - srcEvent.clientX) 
                  + Math.abs(event.clientY - srcEvent.clientY);

        var threshold = 2;
        if (delta <= threshold) {
                   try {
                        // ios likes this but windows-chrome does not on number fields
                        $(this)[0].selectionStart = 0;
                        $(this)[0].selectionEnd = 1000;
                    } catch (e) {
                        // windows-chrome likes this
                        $(this).select();
                    }
        }
    });

http://jsfiddle.net/Zx2sc/2/

How do I install Python packages on Windows?

PS D:\simcut>  C:\Python27\Scripts\pip.exe install networkx
Collecting networkx
c:\python27\lib\site-packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:318: SNIMissingWarning: An HTTPS reques
t has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may caus
e the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer ve
rsion of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissi
ngwarning.
  SNIMissingWarning
c:\python27\lib\site-packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:122: InsecurePlatformWarning: A true SS
LContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL con
nections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.
readthedocs.io/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
  Downloading networkx-1.11-py2.py3-none-any.whl (1.3MB)
    100% |################################| 1.3MB 664kB/s
Collecting decorator>=3.4.0 (from networkx)
  Downloading decorator-4.0.11-py2.py3-none-any.whl
Installing collected packages: decorator, networkx
Successfully installed decorator-4.0.11 networkx-1.11
c:\python27\lib\site-packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:122: InsecurePlatformWarning: A true SSLContext object i
s not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade
to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplat
formwarning.
  InsecurePlatformWarning

Or just put the directory to your pip executable in your system path.

Convert Enum to String

Enum.GetName(...)

This is the most elegant method that is meant for it.

var enumValueString = Enum.GetName(typeof (MyEnum), MyEnum.MyValue);

Although I don't see any issues with calling .ToString() as it is simply shorter.

var enumValueString = MyEnum.MyValue.ToString();

With new C# 6 syntax you can use:

nameof(MyEnum.MyValue)

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

Try to add ReactiveFormsModule in your component as well.

import { FormGroup, FormArray, FormBuilder,
          Validators,ReactiveFormsModule  } from '@angular/forms';

Iterate through pairs of items in a Python list

To do that you should do:

a =  [5, 7, 11, 4, 5]
for i in range(len(a)-1):
    print [a[i], a[i+1]]

How can I check out a GitHub pull request with git?

That gist does describe what happend when you do a git fetch:

Obviously, change the github url to match your project's URL. It ends up looking like this:

[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    url = [email protected]:joyent/node.git
    fetch = +refs/pull/*/head:refs/remotes/origin/pr/*

Now fetch all the pull requests:

$ git fetch origin
From github.com:joyent/node
 * [new ref]         refs/pull/1000/head -> origin/pr/1000
 * [new ref]         refs/pull/1002/head -> origin/pr/1002
 * [new ref]         refs/pull/1004/head -> origin/pr/1004
 * [new ref]         refs/pull/1009/head -> origin/pr/1009
...

To check out a particular pull request:

$ git checkout pr/999
Branch pr/999 set up to track remote branch pr/999 from origin.
Switched to a new branch 'pr/999'

You have various scripts listed in issues 259 to automate that task.
The git-extras project proposes the command git-pr (implemented in PR 262)

git-pr(1) -- Checks out a pull request locally

SYNOPSIS

git-pr <number> [<remote>]
git-pr clean

DESCRIPTION

Creates a local branch based on a GitHub pull request number, and switch to that branch afterwards.

The name of the remote to fetch from. Defaults to origin.

EXAMPLES

This checks out the pull request 226 from origin:

$ git pr 226

remote: Counting objects: 12, done.
remote: Compressing objects: 100% (9/9), done.
remote: Total 12 (delta 3), reused 9 (delta 3)
Unpacking objects: 100% (12/12), done.
From https://github.com/visionmedia/git-extras
  * [new ref] refs/pull/226/head -> pr/226
Switched to branch 'pr/226'

How does the FetchMode work in Spring Data JPA

http://jdpgrailsdev.github.io/blog/2014/09/09/spring_data_hibernate_join.html
from this link:

if you are using JPA on top of Hibernate, there is no way to set the FetchMode used by Hibernate to JOINHowever, if you are using JPA on top of Hibernate, there is no way to set the FetchMode used by Hibernate to JOIN.

The Spring Data JPA library provides a Domain Driven Design Specifications API that allows you to control the behavior of the generated query.

final long userId = 1;

final Specification<User> spec = new Specification<User>() {
   @Override
    public Predicate toPredicate(final Root<User> root, final 
     CriteriaQuery<?> query, final CriteriaBuilder cb) {
    query.distinct(true);
    root.fetch("permissions", JoinType.LEFT);
    return cb.equal(root.get("id"), userId);
 }
};

List<User> users = userRepository.findAll(spec);

How to SUM two fields within an SQL query

ID  VALUE1  VALUE2
===================
1   1       2

1   2       2
2   3       4
2   4       5

select ID, (coalesce(VALUE1 ,0) + coalesce(VALUE2 ,0) as Total from TableName

Launch an app from within another (iPhone)

As Kevin points out, URL Schemes are the only way to communicate between apps. So, no, it's not possible to launch arbitrary apps.

But it is possible to launch any app that registers a URL Scheme, whether it's Apple's, yours, or another developer's. The docs are here:

Defining a Custom URL Scheme for Your App

As for launching the phone, looks like your tel: link needs to have least three digits before the phone will launch. So you can't just drop into the app without dialing a number.

Changing navigation bar color in Swift

Navigation Bar:

navigationController?.navigationBar.barTintColor = UIColor.green

Replace greenColor with whatever UIColor you want, you can use an RGB too if you prefer.

Navigation Bar Text:

navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.orange]

Replace orangeColor with whatever color you like.

Tab Bar:

tabBarController?.tabBar.barTintColor = UIColor.brown

Tab Bar Text:

tabBarController?.tabBar.tintColor = UIColor.yellow

On the last two, replace brownColor and yellowColor with the color of your choice.

How to Round to the nearest whole number in C#

Write your own round method. Something like,

function round(x) rx = Math.ceil(x) if (rx - x <= .000001) return int(rx) else return int(x) end

How can I make my custom objects Parcelable?

I have found simplest way to create Parcelable class

enter image description here

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

XAMPP - Port 80 in use by “Unable to open process” with PID 4! 12

run the comment in cmd tasklist

and find which the PID and process name related to this now open window task manager

you can also open window task manager by using CTRL+ALT+DEL

now click on the process tab and find the name which using PID and right click on that and end process

now again restart the xampp

How can I find all of the distinct file extensions in a folder hierarchy?

Adding my own variation to the mix. I think it's the simplest of the lot and can be useful when efficiency is not a big concern.

find . -type f | grep -o -E '\.[^\.]+$' | sort -u

Submitting HTML form using Jquery AJAX

Quick Description of AJAX

AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.

Really quickly there are 4 general web actions GET, POST, PUT, and DELETE; these directly correspond with SELECT/Retreiving DATA, INSERTING DATA, UPDATING/UPSERTING DATA, and DELETING DATA. A default HTML/ASP.Net webform/PHP/Python or any other form action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax.

My code specifically for you (described in code comments):

_x000D_
_x000D_
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get the action attribute from the <form action=""> element */
  var $form = $(this),
    url = $form.attr('action');

  /* Send the data using post with element id name and name2*/
  var posting = $.post(url, {
    name: $('#name').val(),
    name2: $('#name2').val()
  });

  /* Alerts the results */
  posting.done(function(data) {
    $('#result').text('success');
  });
  posting.fail(function() {
    $('#result').text('failed');
  });
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="formoid" action="studentFormInsert.php" title="" method="post">
  <div>
    <label class="title">First Name</label>
    <input type="text" id="name" name="name">
  </div>
  <div>
    <label class="title">Last Name</label>
    <input type="text" id="name2" name="name2">
  </div>
  <div>
    <input type="submit" id="submitButton" name="submitButton" value="Submit">
  </div>
</form>

<div id="result"></div>
_x000D_
_x000D_
_x000D_


Documentation

From jQuery website $.post documentation.

Example: Send form data using ajax requests

$.post("test.php", $("#testform").serialize());

Example: Post a form using ajax and put results in a div

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form action="/" id="searchForm">
            <input type="text" name="s" placeholder="Search..." />
            <input type="submit" value="Search" />
        </form>
        <!-- the result of the search will be rendered inside this div -->
        <div id="result"></div>
        <script>
            /* attach a submit handler to the form */
            $("#searchForm").submit(function(event) {

                /* stop form from submitting normally */
                event.preventDefault();

                /* get some values from elements on the page: */
                var $form = $(this),
                    term = $form.find('input[name="s"]').val(),
                    url = $form.attr('action');

                /* Send the data using post */
                var posting = $.post(url, {
                    s: term
                });

                /* Put the results in a div */
                posting.done(function(data) {
                    var content = $(data).find('#content');
                    $("#result").empty().append(content);
                });
            });
        </script>
    </body>
</html>

Important Note

Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)

What is the easiest way to clear a database from the CLI with manage.py in Django?

If you don't care about data:

Best way would be to drop the database and run syncdb again. Or you can run:

For Django >= 1.5

python manage.py flush

For Django < 1.5

python manage.py reset appname

(you can add --no-input to the end of the command for it to skip the interactive prompt.)

If you do care about data:

From the docs:

syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.

If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.

https://docs.djangoproject.com/en/dev/ref/django-admin/

Reference: FAQ - https://docs.djangoproject.com/en/dev/faq/models/#if-i-make-changes-to-a-model-how-do-i-update-the-database

People also recommend South ( http://south.aeracode.org/docs/about.html#key-features ), but I haven't tried it.

Apache and IIS side by side (both listening to port 80) on windows2003

Either two different IP addresses (like recommended) or one web server is reverse-proxying the other (which is listening on a port <>80).

For instance: Apache listens on port 80, IIS on port 8080. Every http request goes to Apache first (of course). You can then decide to forward every request to a particular (named virtual) domain or every request that contains a particular directory (e.g. http://www.example.com/winapp/) to the IIS.

Advantage of this concept is that you have only one server listening to the public instead of two, you are more flexible as with two distinct servers.

Drawbacks: some webapps are crappily designed and a real pain in the ass to integrate into a reverse-proxy infrastructure. A working IIS webapp is dependent on a working Apache, so we have some inter-dependencies.

How to remove old Docker containers

For Windows you can run this to stop and delete all containers:

@echo off
FOR /f "tokens=*" %%i IN ('docker ps -q') DO docker stop %%i
FOR /f "tokens=*" %%i IN ('docker ps -aq') DO docker rm %%i
FOR /f "tokens=*" %%i IN ('docker images --format "{{.ID}}"') DO docker rmi %%i

You can save it as a .bat file and can run to do that:

enter image description here

Style input type file?

use uniform js plugin to style input of any type, select, textarea.

The URL is http://uniformjs.com/

python: how to get information about a function?

Or

help(list.append)

if you're generally poking around.

AutoComplete TextBox in WPF

I have published a WPF Auto Complete Text Box in WPF at CodePlex.com. You can download and try it from https://wpfautocomplete.codeplex.com/.

Conditional Formatting using Excel VBA code

I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!

This is my working example:

Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
'               in duplicated formatting rules that in turn will significantly slow down
'               the spreadsheet.
'               This macro is designed to reset all formatting rules to default.
' ---------------------------------------------------------------------------------------- 

On Error GoTo ErrHandler

' Make sure we are positioned in the correct sheet
WS_PROMO.Select

' Disable Events
Application.EnableEvents = False

' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete

' CREATE ALL THE CONDITIONAL FORMATTING RULES:

' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
    .Font.Bold = True
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
    .Font.Bold = True
    .Font.Color = -10092544
    .StopIfTrue = False
End With

' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
    .DupeUnique = xlDuplicate
    .Font.Color = -16383844
    .Interior.Color = 13551615
    .StopIfTrue = False
End With

' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
    .Font.Bold = True
    .Interior.Color = 13434879
    .StopIfTrue = False
End With

' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")


ErrHandler:
Application.EnableEvents = False

End Sub

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

Declare and Initialize String Array in VBA

In the specific case of a String array you could initialize the array using the Split Function as it returns a String array rather than a Variant array:

Dim arrWsNames() As String
arrWsNames = Split("Value1,Value2,Value3", ",")

This allows you to avoid using the Variant data type and preserve the desired type for arrWsNames.

AWS S3: how do I see how much disk space is using

Cloud watch also allows you to create metrics for your S3 bucket. It shows you metrics by the size and object count. Services> Management Tools> Cloud watch. Pick the region where your S3 bucket is and the size and object count metrics would be among those available metrics.

Difference between left join and right join in SQL Server

select * from Table1 left join Table2 on Table1.id = Table2.id

In the first query Left join compares left-sided table table1 to right-sided table table2.

In Which all the properties of table1 will be shown, whereas in table2 only those properties will be shown in which condition get true.

select * from Table2 right join Table1 on Table1.id = Table2.id

In the first query Right join compares right-sided table table1 to left-sided table table2.

In Which all the properties of table1 will be shown, whereas in table2 only those properties will be shown in which condition get true.

Both queries will give the same result because the order of table declaration in query are different like you are declaring table1 and table2 in left and right respectively in first left join query, and also declaring table1 and table2 in right and left respectively in second right join query.

This is the reason why you are getting the same result in both queries. So if you want different result then execute this two queries respectively,

select * from Table1 left join Table2 on Table1.id = Table2.id

select * from Table1 right join Table2 on Table1.id = Table2.id

Creating a thumbnail from an uploaded image

I know this is an old question, but I stumbled upon the same problem and tried to use the function given in Alex's answer.

But the quality in the jpeg result was too low. So I changed the function a little bit to become more usable in my project and changed the "imagecopyresized" to "imagecopyresampled" (according to this recomendation).

If you are having questions about how to use this function, then try taking a look at the well documented version here.

function createThumbnail($filepath, $thumbpath, $thumbnail_width, $thumbnail_height, $background=false) {
    list($original_width, $original_height, $original_type) = getimagesize($filepath);
    if ($original_width > $original_height) {
        $new_width = $thumbnail_width;
        $new_height = intval($original_height * $new_width / $original_width);
    } else {
        $new_height = $thumbnail_height;
        $new_width = intval($original_width * $new_height / $original_height);
    }
    $dest_x = intval(($thumbnail_width - $new_width) / 2);
    $dest_y = intval(($thumbnail_height - $new_height) / 2);

    if ($original_type === 1) {
        $imgt = "ImageGIF";
        $imgcreatefrom = "ImageCreateFromGIF";
    } else if ($original_type === 2) {
        $imgt = "ImageJPEG";
        $imgcreatefrom = "ImageCreateFromJPEG";
    } else if ($original_type === 3) {
        $imgt = "ImagePNG";
        $imgcreatefrom = "ImageCreateFromPNG";
    } else {
        return false;
    }

    $old_image = $imgcreatefrom($filepath);
    $new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); // creates new image, but with a black background

    // figuring out the color for the background
    if(is_array($background) && count($background) === 3) {
      list($red, $green, $blue) = $background;
      $color = imagecolorallocate($new_image, $red, $green, $blue);
      imagefill($new_image, 0, 0, $color);
    // apply transparent background only if is a png image
    } else if($background === 'transparent' && $original_type === 3) {
      imagesavealpha($new_image, TRUE);
      $color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
      imagefill($new_image, 0, 0, $color);
    }

    imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
    $imgt($new_image, $thumbpath);
    return file_exists($thumbpath);
}

How to split the filename from a full path in batch?

@echo off
Set filename="C:\Documents and Settings\All Users\Desktop\Dostips.cmd"
call :expand %filename%
:expand
set filename=%~nx1
echo The name of the file is %filename%
set folder=%~dp1
echo It's path is %folder%

How do I grep recursively?

globbing **

Using grep -r works, but it may overkill, especially in large folders.

For more practical usage, here is the syntax which uses globbing syntax (**):

grep "texthere" **/*.txt

which greps only specific files with pattern selected pattern. It works for supported shells such as Bash +4 or zsh.

To activate this feature, run: shopt -s globstar.

See also: How do I find all files containing specific text on Linux?

git grep

For projects under Git version control, use:

git grep "pattern"

which is much quicker.

ripgrep

For larger projects, the quickest grepping tool is ripgrep which greps files recursively by default:

rg "pattern" .

It's built on top of Rust's regex engine which uses finite automata, SIMD and aggressive literal optimizations to make searching very fast. Check the detailed analysis here.

Detect click outside element

  <button 
    class="dropdown"
    @click.prevent="toggle"
    ref="toggle"
    :class="{'is-active': isActiveEl}"
  >
    Click me
  </button>

  data() {
   return {
     isActiveEl: false
   }
  }, 
  created() {
    window.addEventListener('click', this.close);
  },
  beforeDestroy() {
    window.removeEventListener('click', this.close);
  },
  methods: {
    toggle: function() {
      this.isActiveEl = !this.isActiveEl;
    },
    close(e) {
      if (!this.$refs.toggle.contains(e.target)) {
        this.isActiveEl = false;
      }
    },
  },

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

1.To install the virtualization driver:

Start the Android SDK Manager, select Extras and then select Intel Hardware Accelerated Execution Manager. After the download completes, execute /extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.exe. Follow the on-screen instructions to complete installation.

2.If it show any problem restart your computer and inter in BIOS an enable Virtualization Technology ...

3.To see your possessor is capable to virtualization go to the bellow link http://ark.intel.com/Products/VirtualizationTechnology

Where is the .NET Framework 4.5 directory?

The official way to find out if you have 4.5 installed (and not 4.0) is in the registry keys :

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full

Relesae DWORD needs to be bigger than 378675 Here is the Microsoft doc for it

all the other answers of checking the minor version after 4.0.30319.xxxxx seem correct though (msbuild.exe -version , or properties of clr.dll), i just needed something documented (not a blog)

Initializing multiple variables to the same value in Java

Works for primitives and immutable classes like String, Wrapper classes Character, Byte.

int i=0,j=2   
String s1,s2  
s1 = s2 = "java rocks"

For mutable classes

Reference r1 = Reference r2 = Reference r3 = new Object();`  

Three references + one object are created. All references point to the same object and your program will misbehave.

Convert array of strings into a string in Java

Try the Arrays.deepToString method.

Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings

How do I find an element position in std::vector?

Get rid of the notion of vector entirely

template< typename IT, typename VT>
int index_of(IT begin, IT end, const VT& val)
{
    int index = 0;
    for (; begin != end; ++begin)
    {
        if (*begin == val) return index;
    }
    return -1;
}

This will allow you more flexibility and let you use constructs like

int squid[] = {5,2,7,4,1,6,3,0};
int sponge[] = {4,2,4,2,4,6,2,6};
int squidlen = sizeof(squid)/sizeof(squid[0]);
int position = index_of(&squid[0], &squid[squidlen], 3);
if (position >= 0) { std::cout << sponge[position] << std::endl; }

You could also search any other container sequentially as well.

How to disable a particular checkstyle rule for a particular line of code?

Every answer refering to SuppressWarningsFilter is missing an important detail. You can only use the all-lowercase id if it's defined as such in your checkstyle-config.xml. If not you must use the original module name.

For instance, if in my checkstyle-config.xml I have:

<module name="NoWhitespaceBefore"/>

I cannot use:

@SuppressWarnings({"nowhitespacebefore"})

I must, however, use:

@SuppressWarnings({"NoWhitespaceBefore"})

In order for the first syntax to work, the checkstyle-config.xml should have:

<module name="NoWhitespaceBefore">
  <property name="id" value="nowhitespacebefore"/>
</module>

This is what worked for me, at least in the CheckStyle version 6.17.

Compare a date string to datetime in SQL Server?

In SQL Server 2008, you could use the new DATE datatype

DECLARE @pDate DATE='2008-08-14'  

SELECT colA, colB
FROM table1
WHERE convert(date, colDateTime) = @pDate  

@Guy. I think you will find that this solution scales just fine. Have a look at the query execution plan of your original query.

And for mine:

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

A popular Linux library which has similar functionality would be ncurses.

Invisible characters - ASCII

Other answers are correct -- whether a character is invisible or not depends on what font you use. This seems to be a pretty good list to me of characters that are truly invisible (not even space). It contains some chars that the other lists are missing.

            '\u2060', // Word Joiner
            '\u2061', // FUNCTION APPLICATION
            '\u2062', // INVISIBLE TIMES
            '\u2063', // INVISIBLE SEPARATOR
            '\u2064', // INVISIBLE PLUS
            '\u2066', // LEFT - TO - RIGHT ISOLATE
            '\u2067', // RIGHT - TO - LEFT ISOLATE
            '\u2068', // FIRST STRONG ISOLATE
            '\u2069', // POP DIRECTIONAL ISOLATE
            '\u206A', // INHIBIT SYMMETRIC SWAPPING
            '\u206B', // ACTIVATE SYMMETRIC SWAPPING
            '\u206C', // INHIBIT ARABIC FORM SHAPING
            '\u206D', // ACTIVATE ARABIC FORM SHAPING
            '\u206E', // NATIONAL DIGIT SHAPES
            '\u206F', // NOMINAL DIGIT SHAPES
            '\u200B', // Zero-Width Space
            '\u200C', // Zero Width Non-Joiner
            '\u200D', // Zero Width Joiner
            '\u200E', // Left-To-Right Mark
            '\u200F', // Right-To-Left Mark
            '\u061C', // Arabic Letter Mark
            '\uFEFF', // Byte Order Mark
            '\u180E', // Mongolian Vowel Separator
            '\u00AD'  // soft-hyphen

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

LPCSTR, LPCTSTR and LPTSTR

Adding to John and Tim's answer.

Unless you are coding for Win98, there are only two of the 6+ string types you should be using in your application

  • LPWSTR
  • LPCWSTR

The rest are meant to support ANSI platforms or dual compilations. Those are not as relevant today as they used to be.

How to validate a file upload field using Javascript/jquery

My function will check if the user has selected the file or not and you can also check whether you want to allow that file extension or not.

Try this:

<input type="file" name="fileUpload" onchange="validate_fileupload(this.value);">

function validate_fileupload(fileName)
{
    var allowed_extensions = new Array("jpg","png","gif");
    var file_extension = fileName.split('.').pop().toLowerCase(); // split function will split the filename by dot(.), and pop function will pop the last element from the array which will give you the extension as well. If there will be no extension then it will return the filename.

    for(var i = 0; i <= allowed_extensions.length; i++)
    {
        if(allowed_extensions[i]==file_extension)
        {
            return true; // valid file extension
        }
    }

    return false;
}

"python" not recognized as a command

Go to Control Panel / System / "Advanced" tab / Enviromental Variables

Find variable called PATH in the lower list, and edit it. Add to the end C:\Python27

Open a new cmd window and try now.

AppFabric installation failed because installer MSI returned with error code : 1603

May be I am really late for reply, Seriously guys this error resolution took hours of time, i tried every possible solution.

  1. installing IIS
  2. changing Power Shell from environment variable.
  3. Deleting the local group

While, the solution is really really simple. If you look closely in environment variable PSModulePath there will be commas at end of the value simply remove those and enjoy

Passing parameter using onclick or a click binding with KnockoutJS

A generic answer on how to handle click events with KnockoutJS...

Not a straight up answer to the question as asked, but probably an answer to the question most Googlers landing here have: use the click binding from KnockoutJS instead of onclick. Like this:

_x000D_
_x000D_
function Item(parent, txt) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.doOtherStuff = function(customParam, data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data) + ", customParam = " + customParam);_x000D_
  };_x000D_
  _x000D_
  self.txt = ko.observable(txt);_x000D_
}_x000D_
_x000D_
function RootVm(items) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doParentStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    self.log(self.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.items = ko.observableArray([_x000D_
    new Item(self, "John Doe"),_x000D_
    new Item(self, "Marcus Aurelius")_x000D_
  ]);_x000D_
  self.log = ko.observable("Started logging...");_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
.parent { background: rgba(150, 150, 200, 0.5); padding: 2px; margin: 5px; }_x000D_
button { margin: 2px 0; font-family: consolas; font-size: 11px; }_x000D_
pre { background: #eee; border: 1px solid #ccc; padding: 5px; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div data-bind="foreach: items">_x000D_
  <div class="parent">_x000D_
    <span data-bind="text: txt"></span><br>_x000D_
    <button data-bind="click: doStuff">click: doStuff</button><br>_x000D_
    <button data-bind="click: $parent.doParentStuff">click: $parent.doParentStuff</button><br>_x000D_
    <button data-bind="click: $root.doParentStuff">click: $root.doParentStuff</button><br>_x000D_
    <button data-bind="click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }">click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }</button><br>_x000D_
    <button data-bind="click: doOtherStuff.bind($data, 'test 123')">click: doOtherStuff.bind($data, 'test 123')</button><br>_x000D_
    <button data-bind="click: function(data, event) { doOtherStuff('test 123', $data, event); }">click: function(data, event) { doOtherStuff($data, 'test 123', event); }</button><br>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
Click log:_x000D_
<pre data-bind="text: log"></pre>
_x000D_
_x000D_
_x000D_


**A note about the actual question...*

The actual question has one interesting bit:

// Uh oh! Modifying the DOM....
place.innerHTML = "somthing"

Don't do that! Don't modify the DOM like that when using an MVVM framework like KnockoutJS, especially not the piece of the DOM that is your own parent. If you would do this the button would disappear (if you replace your parent's innerHTML you yourself will be gone forever ever!).

Instead, modify the View Model in your handler instead, and have the View respond. For example:

_x000D_
_x000D_
function RootVm() {_x000D_
  var self = this;_x000D_
  self.buttonWasClickedOnce = ko.observable(false);_x000D_
  self.toggle = function(data, event) {_x000D_
    self.buttonWasClickedOnce(!self.buttonWasClickedOnce());_x000D_
  };_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div  data-bind="visible: !buttonWasClickedOnce()">_x000D_
    <button data-bind="click: toggle">Toggle!</button>_x000D_
  </div>_x000D_
  <div data-bind="visible: buttonWasClickedOnce">_x000D_
    Can be made visible with toggle..._x000D_
    <button data-bind="click: toggle">Untoggle!</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Show tables, describe tables equivalent in redshift

Shortcut

\d for show all tables

\d tablename to describe table

\? for more shortcuts for redshift

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

I have faced this problem and I made research and didn't get anything, so I was trying and finally, I knew the cause of this problem. the problem on the API, make sure you have a good variable name I used $start_date and it caused the problem, so I try $startdate and it works!

as well make sure you send all parameter that declare on API, for example, $startdate = $_POST['startdate']; $enddate = $_POST['enddate'];

you have to pass this two variable from the retrofit.

as well if you use date on SQL statement, try to put it inside '' like '2017-07-24'

I hope it helps you.

Is there a way to force npm to generate package-lock.json?

This is answered in the comments; package-lock.json is a feature in npm v5 and higher. npm shrinkwrap is how you create a lockfile in all versions of npm.

Is there an Eclipse plugin to run system shell in the Console?

I just found out about WickedShell, but it seems to work wrong with GNU/Linux and bash. Seems like some sort of encoding issue, all the characters in my prompt are displayed wrong.

Seems to be the best (only) tool for the job anyways, so I'll give it some more testing and see if it's good enough. I'll contact the developer anyways about this issue.

Embed image in a <button> element

Why don't you use an image with an onclick attribute?

For example:

<script>
function myfunction() {
}
</script>
<img src='Myimg.jpg' onclick='myfunction()'>

How to check if activity is in foreground or in visible background?

If you want to know if any activity of your app is visible on the screen, you can do something like this:

public class MyAppActivityCallbacks implements Application.ActivityLifecycleCallbacks {
private Set<Class<Activity>> visibleActivities = new HashSet<>();

@Override
public void onActivityResumed(Activity activity) {
    visibleActivities.add((Class<Activity>) activity.getClass());
}

@Override
public void onActivityStopped(Activity activity) {
     visibleActivities.remove(activity.getClass());
}

public boolean isAnyActivityVisible() {
    return !visibleActivities.isEmpty();
}

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}

@Override
public void onActivityStarted(Activity activity) {}

@Override
public void onActivityPaused(Activity activity) {}

@Override
public void onActivityDestroyed(Activity activity) {}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}}

Just create a singleton of this class and set it in your Application instance like below:

class App extends Application{
     @Override
     public void onCreate() {
         registerActivityLifecycleCallbacks(myAppActivityCallbacks);
     }
}

Then you can use isAnyActivityVisible() method of your MyAppActivityCallbacks instance everywhere!

How to kill/stop a long SQL query immediately?

A simple answer, if the red "stop" box is not working, is to try pressing the "Ctrl + Break" buttons on the keyboard.

If you are running SQL Server on Linux, there is an app you can add to your systray called "killall" Just click on the "killall" button and then click on the program that is caught in a loop and it will terminate the program. Hope that helps.

iOS - Calling App Delegate method from ViewController

Even if technically feasible, is NOT a good approach. When You say: "The splash screen would have buttons for each room that would allow you to jump to any point on the walk through." So you want to pass through appdelegate to call these controllers via tohc events on buttons?

This approach does not follow Apple guidelines and has a lot of drawbacks.

Merge unequal dataframes and replace missing rows with 0

Take a look at the help page for merge. The all parameter lets you specify different types of merges. Here we want to set all = TRUE. This will make merge return NA for the values that don't match, which we can update to 0 with is.na():

zz <- merge(df1, df2, all = TRUE)
zz[is.na(zz)] <- 0

> zz
  x y
1 a 0
2 b 1
3 c 0
4 d 0
5 e 0

Updated many years later to address follow up question

You need to identify the variable names in the second data table that you aren't merging on - I use setdiff() for this. Check out the following:

df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e', NA))
df2 = data.frame(x=c('a', 'b', 'c'),y1 = c(0,1,0), y2 = c(0,1,0))

#merge as before
df3 <- merge(df1, df2, all = TRUE)
#columns in df2 not in df1
unique_df2_names <- setdiff(names(df2), names(df1))
df3[unique_df2_names][is.na(df3[, unique_df2_names])] <- 0 

Created on 2019-01-03 by the reprex package (v0.2.1)

Adding Buttons To Google Sheets and Set value to Cells on clicking

It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.

You can use following code to insert an image through script.

  function insertImageOnSpreadsheet() {
  var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
  // Name of the specific sheet in the spreadsheet.
  var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';

  var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var sheet = ss.getSheetByName(SHEET_NAME);

  var response = UrlFetchApp.fetch(
      'https://developers.google.com/adwords/scripts/images/reports.png');
  var binaryData = response.getContent();

  // Insert the image in cell A1.
  var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
  sheet.insertImage(blob, 1, 1);
}

Above example has been copied from this link. Check noogui's reply for details.

In case you need to insert image from Google Drive, please check this link for current updates.

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.

$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);

EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)

<?php
if(!isset($_GET['json']))
    die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>

Openssl : error "self signed certificate in certificate chain"

The solution for the error is to add this line at the top of the code:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

builder for HashMap

A simple map builder is trivial to write:

public class Maps {

    public static <Q,W> MapWrapper<Q,W> map(Q q, W w) {
        return new MapWrapper<Q, W>(q, w);
    }

    public static final class MapWrapper<Q,W> {
        private final HashMap<Q,W> map;
        public MapWrapper(Q q, W w) {
            map = new HashMap<Q, W>();
            map.put(q, w);
        }
        public MapWrapper<Q,W> map(Q q, W w) {
            map.put(q, w);
            return this;
        }
        public Map<Q,W> getMap() {
            return map;
        }
    }

    public static void main(String[] args) {
        Map<String, Integer> map = Maps.map("one", 1).map("two", 2).map("three", 3).getMap();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

How to disable textbox from editing?

The TextBox has a property called ReadOnly. If you set that property to true then the TextBox will still be able to scroll but the user wont be able to change the value.

How to use NSJSONSerialization

The issue seems to be with autorelease of objects. NSJSONSerialization JSONObjectWithData is obviously creating some autoreleased objects and passing it back to you. If you try to take that on to a different thread, it will not work since it cannot be deallocated on a different thread.

Trick might be to try doing a mutable copy of that dictionary or array and use it.

NSError *e = nil;
id jsonObject = [NSJSONSerialization 
JSONObjectWithData: data 
options: NSJSONReadingMutableContainers 
error: &e] mutableCopy];

Treating a NSDictionary as NSArray will not result in Bad access exception but instead will probably crash when a method call is made.

Also, may be the options do not really matter here but it is better to give NSJSONReadingMutableContainers | NSJSONReadingMutableContainers | NSJSONReadingAllowFragments but even if they are autoreleased objects it may not solve this issue.

Preventing SQL injection in Node.js

The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:

Edit: node-mysql-native is also a pure-Javascript solution.

  • Numbers are left untouched
  • Booleans are converted to true / false strings
  • Date objects are converted to YYYY-mm-dd HH:ii:ss strings
  • Buffers are converted to hex strings, e.g. X'0fa5'
  • Strings are safely escaped
  • Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
  • Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')
  • Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
  • undefined / null are converted to NULL
  • NaN / Infinity are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.

This allows for you to do things like so:

var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  //query.sql returns SELECT * FROM users WHERE id = '5'
});

As well as this:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  //query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});

Aside from those functions, you can also use the escape functions:

connection.escape(query);
mysql.escape(query);

To escape query identifiers:

mysql.escapeId(identifier);

And as a response to your comment on prepared statements:

From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.

The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

This changes the query format of the connection so you can use queries like this:

connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");

Link to a section of a webpage

Hashtags at the end of the URL bring a visitor to the element with the ID: e.g.

http://stackoverflow.com/questions/8424785/link-to-a-section-of-a-webpage#answers 

Would bring you to where the DIV with the ID 'answers' begins. Also, you can use the name attribute in anchor tags, to create the same effect.

Resource

How do I create a message box with "Yes", "No" choices and a DialogResult?

The MessageBox does produce a DialogResults

DialogResult r = MessageBox.Show("Some question here");

You can also specify the buttons easily enough. More documentation can be found at http://msdn.microsoft.com/en-us/library/ba2a6d06.aspx

Find unused code

ReSharper does a great job of finding unused code.

In the VS IDE, you can right click on the definition and choose 'Find All References', although this only works at the solution level.

Values of disabled inputs will not be submitted

Yes, all browsers should not submit the disabled inputs, as they are read-only.

More information (section 17.12.1)

Attribute definitions

disabled [CI] When set for a form control, this Boolean attribute disables the control for user input. When set, the disabled attribute has the following effects on an element:

  • Disabled controls do not receive focus.
  • Disabled controls are skipped in tabbing navigation.
  • Disabled controls cannot be successful.

The following elements support the disabled attribute: BUTTON, INPUT, OPTGROUP, OPTION, SELECT, and TEXTAREA.

This attribute is inherited but local declarations override the inherited value.

How disabled elements are rendered depends on the user agent. For example, some user agents "gray out" disabled menu items, button labels, etc.

In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.

<INPUT disabled name="fred" value="stone">

Note. The only way to modify dynamically the value of the disabled attribute is through a script.

Set formula to a range of cells

Range("C1:C10").Formula = "=A1+B1"

Simple as that.

It autofills (FillDown) the range with the formula.

Eclipse: All my projects disappeared from Project Explorer

None of the answers provided here worked for me. My Enterprise Explorer was completely grey and I couldn't even import or reimport projects.

In my .metadata.log I saw this error:

assertion failed: working set with same name already registered

So I deleted these file:

.metadata.plugins\org.eclipse.ui.workbench\workingsets.xml

Now I can see all my projects. I didn't have to add them back again.

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

How does Go update third-party packages?

go get will install the package in the first directory listed at GOPATH (an environment variable which might contain a colon separated list of directories). You can use go get -u to update existing packages.

You can also use go get -u all to update all packages in your GOPATH

For larger projects, it might be reasonable to create different GOPATHs for each project, so that updating a library in project A wont cause issues in project B.

Type go help gopath to find out more about the GOPATH environment variable.

JRE installation directory in Windows

Not as a command, but this information is in the registry:

  • Open the key HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  • Read the CurrentVersion REG_SZ
  • Open the subkey under Java Runtime Environment named with the CurrentVersion value
  • Read the JavaHome REG_SZ to get the path

For example on my workstation i have

HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
  JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
  JavaHome = "C:\Program Files\Java\jre6"

So my current JRE is in C:\Program Files\Java\jre6

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

The JAX-WS dependency library “jaxws-rt.jar” is missing.

Go here http://jax-ws.java.net/. Download JAX-WS RI distribution. Unzip it and copy “jaxws-rt.jar” to Tomcat library folder “{$TOMCAT}/lib“. Restart Tomcat.

How to use Oracle ORDER BY and ROWNUM correctly?

Documented couple of design issues with this in a comment above. Short story, in Oracle, you need to limit the results manually when you have large tables and/or tables with same column names (and you don't want to explicit type them all out and rename them all). Easy solution is to figure out your breakpoint and limit that in your query. Or you could also do this in the inner query if you don't have the conflicting column names constraint. E.g.

WHERE m_api_log.created_date BETWEEN TO_DATE('10/23/2015 05:00', 'MM/DD/YYYY HH24:MI') 
                                 AND TO_DATE('10/30/2015 23:59', 'MM/DD/YYYY HH24:MI')  

will cut down the results substantially. Then you can ORDER BY or even do the outer query to limit rows.

Also, I think TOAD has a feature to limit rows; but, not sure that does limiting within the actual query on Oracle. Not sure.

Cannot find "Package Explorer" view in Eclipse

Try this

Window > Show View > Package Explorer

it will display the hidden 'Package Explorer' on your eclipse IDE.

• 'Window' is in your Eclipse' menubar.

What is the difference between RTP or RTSP in a streaming server?

RTSP (actually RTP) can be used for streaming video, but also many other types of media including live presentations. Rtsp is just the protocol used to setup the RTP session.

For all the details you can check out my open source RTSP Server implementation on the following address: https://net7mma.codeplex.com/

Or my article @ http://www.codeproject.com/Articles/507218/Managed-Media-Aggregation-using-Rtsp-and-Rtp

It supports re-sourcing streams as well as the dynamic creation of streams, various RFC's are implemented and the library achieves better performance and less memory then FFMPEG and just about any other solutions in the transport layer and thus makes it a good candidate to use as a centralized point of access for most scenarios.

Why is document.write considered a "bad practice"?

Here's my twopence worth, in general you shouldn't use document.write for heavy lifting, but there is one instance where it is definitely useful:

http://www.quirksmode.org/blog/archives/2005/06/three_javascrip_1.html

I discovered this recently trying to create an AJAX slider gallery. I created two nested divs, and applied width/height and overflow: hidden to the outer <div> with JS. This was so that in the event that the browser had JS disabled, the div would float to accommodate the images in the gallery - some nice graceful degradation.

Thing is, as with the article above, this JS hijacking of the CSS didn't kick in until the page had loaded, causing a momentary flash as the div was loaded. So I needed to write a CSS rule, or include a sheet, as the page loaded.

Obviously, this won't work in XHTML, but since XHTML appears to be something of a dead duck (and renders as tag soup in IE) it might be worth re-evaluating your choice of DOCTYPE...

Extending from two classes

You can only Extend a single class. And implement Interfaces from many sources.

Extending multiple classes is not available. The only solution I can think of is not inheriting either class but instead having an internal variable of each class and doing more of a proxy by redirecting the requests to your object to the object that you want them to go to.

 public class CustomActivity extends Activity {

     private AnotherClass mClass;

     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         mClass = new AnotherClass(this);
     }

     //Implement each method you want to use.
     public String getInfoFromOtherClass()
     {
        return mClass.getInfoFromOtherClass();
     }
 }

this is the best solution I have come up with. You can get the functionality from both classes and Still only actually be of one class type.

The drawback is that you cannot fit into the Mold of the Internal class using a cast.

How do I connect to mongodb with node.js (and authenticate)?

Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:

   var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
    assert = require('assert');

var user = 'user';
var password = 'password';

MongoClient.connect('mongodb://'+user+':'+password+'@localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
    if(err){
        console.log("Auth Failed");
        return;
    }
    console.log("Connected");
    db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
        docs.each(function(err, doc) {
          if(doc) {
            console.log(doc['_id']);
          }
        });
    });

    db.close();

}); 

Removing whitespace from strings in Java

there are many ways to solve this problem. you can use split function or replace function of Strings.

for more info refer smilliar problem http://techno-terminal.blogspot.in/2015/10/how-to-remove-spaces-from-given-string.html

Wrapping long text without white space inside of a div

white-space: pre-wrap

is what worked for me for <span> and <div>.

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

How to clear a textbox using javascript

Use the onfocus and onblur events like this:

<input type="text" name="yourName" value="A new value" onfocus="if (this.value == 'A new value') this.value = '';" onblur="if (this.value == '') this.value = 'A new value';">

AJAX reload page with POST

There's another way with post instead of ajax

var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });

how to fix java.lang.IndexOutOfBoundsException

for ( int i=0 ; i<=list.size() ; i++){
....}

By executing this for loop , the loop will execute with a thrown exception as IndexOutOfBoundException cause, suppose list size is 10 , so when index i will get to 10 i.e when i=10 the exception will be thrown cause index=size, i.e. i=size and as known that Java considers index starting from 0,1,2...etc the expression which Java agrees upon is index < size. So the solution for such exception is to make the statement in loop as i<list.size()

for ( int i=0 ; i<list.size() ; i++){
...}

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

What is the cleanest way to ssh and run multiple commands in Bash?

SSH and Run Multiple Commands in Bash.

Separate commands with semicolons within a string, passed to echo, all piped into the ssh command. For example:

echo "df -k;uname -a" | ssh 192.168.79.134

Pseudo-terminal will not be allocated because stdin is not a terminal.
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sda2       18274628 2546476  14799848  15% /
tmpfs             183620      72    183548   1% /dev/shm
/dev/sda1         297485   39074    243051  14% /boot
Linux newserv 2.6.32-431.el6.x86_64 #1 SMP Sun Nov 10 22:19:54 EST 2013 x86_64 x86_64 x86_64 GNU/Linux

javascript: detect scroll end

This worked for me:

$(window).scroll(function() {
  buffer = 40 // # of pixels from bottom of scroll to fire your function. Can be 0
  if ($(".myDiv").prop('scrollHeight') - $(".myDiv").scrollTop() <= $(".myDiv").height() + buffer )   {
    doThing();
  }
});

Must use jQuery 1.6 or higher

ISO time (ISO 8601) in Python

ISO 8601 allows a compact representation with no separators except for the T, so I like to use this one-liner to get a quick timestamp string:

>>> datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%S.%fZ")
'20180905T140903.591680Z'

If you don't need the microseconds, just leave out the .%f part:

>>> datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
'20180905T140903Z'

For local time:

>>> datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
'20180905T140903'

Edit:

After reading up on this some more, I recommend you leave the punctuation in. RFC 3339 recommends that style because if everyone uses punctuation, there isn't a risk of things like multiple ISO 8601 strings being sorted in groups on their punctuation. So the one liner for a compliant string would be:

>>> datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
'2018-09-05T14:09:03Z'

Ignoring new fields on JSON objects using Jackson

it can be achieved 2 ways:

  1. Mark the POJO to ignore unknown properties

    @JsonIgnoreProperties(ignoreUnknown = true)
    
  2. Configure ObjectMapper that serializes/De-serializes the POJO/json as below:

    ObjectMapper mapper =new ObjectMapper();            
    // for Jackson version 1.X        
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // for Jackson version 2.X
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) 
    

Command copy exited with code 4 when building - Visual Studio restart solves it

In my case my $(OutDir) was simply ..\..\Build\ i.e. some relative path. And, when I was trying to xcopy as follows xcopy /y "$(OutDir)Proj1.dll" "Anypath\anyfolder\" I was getting the exit code error 4.

What's happening was, this command was getting executed in the $(OutDir) (in my case build folder) itself and not the directory where the csproj file of the project was located (as we would normally expect). Hence, I kept getting File not found error (corresponding to exit code 4).

I couldn't figure this out until I wrote cd in the Post Build events, to print which directory this was getting executed in.

So, to summarize, if we're wishing to copy / xcopy files from the $(OutDir), either use "$(TargetDir)" (which is complete path for output directory) or need not specify any path at all.

Sending email from Command-line via outlook without having to click send

You can use cURL and CRON to run .php files at set times.

Here's an example of what cURL needs to run the .php file:

curl http://localhost/myscript.php

Then setup the CRON job to run the above cURL:

nano -w /var/spool/cron/root
or
crontab -e

Followed by:

01 * * * * /usr/bin/curl http://www.yoursite.com/script.php

For more info about, check out this post: https://www.scalescale.com/tips/nginx/execute-php-scripts-automatically-using-cron-curl/

For more info about cURL: What is cURL in PHP?

For more info about CRON: http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800

Also, if you would like to learn about setting up a CRON job on your hosted server, just inquire with your host provider, and they may have a GUI for setting it up in the c-panel (such as http://godaddy.com, or http://1and1.com/ )

NOTE: Technically I believe you can setup a CRON job to run the .php file directly, but I'm not certain.

Best of luck with the automatic PHP running :-)

Complex nesting of partials and templates

You may use ng-include to avoid using nested ng-views.

http://docs.angularjs.org/api/ng/directive/ngInclude
http://plnkr.co/edit/ngdoc:example-example39@snapshot?p=preview

My index page I use ng-view. Then on my sub pages which I need to have nested frames. I use ng-include. The demo shows a dropdown. I replaced mine with a link ng-click. In the function I would put $scope.template = $scope.templates[0]; or $scope.template = $scope.templates[1];

$scope.clickToSomePage= function(){
  $scope.template = $scope.templates[0];
};

Hidden Features of Java

Didn't read about this

Integer a = 1;
Integer b = 1;
Integer c = new Integer(1);
Integer d = new Integer(1);

Integer e = 128;
Integer f = 128;

assertTrue (a == b);   // again: this is true!
assertFalse(e == f); // again: this is false!
assertFalse(c == d);   // again: this is false!

read more about this by searching java's pool of integer (internal 'cache' from -128 to 127 for autoboxing) or look into Integer.valueOf

Writing a dict to txt file and reading it back?

You can iterate through the key-value pair and write it into file

pair = {'name': name,'location': location}
with open('F:\\twitter.json', 'a') as f:
     f.writelines('{}:{}'.format(k,v) for k, v in pair.items())
     f.write('\n')

Android Fragment no view found for ID?

Just in case someone's made the same stupid mistake I did; check that you're not overwriting the activity content somewhere (i.e. look for additional calls to setContentView)

In my case, due to careless copy and pasting, I used DataBindingUtil.setContentView in my fragment, instead of DataBindingUtil.inflate, which messed up the state of the activity.

How to update large table with millions of rows in SQL Server?

First of all, thank you all for your inputs. I tweak my Query - 1 and got my desired result. Gordon Linoff is right, PRINT was messing up my query so I modified it as following:

Modified Query - 1:

SET ROWCOUNT 5
WHILE (1 = 1)
  BEGIN
    BEGIN TRANSACTION

        UPDATE TableName 
        SET Value = 'abc1' 
        WHERE Parameter1 = 'abc' AND Parameter2 = 123

        IF @@ROWCOUNT = 0
          BEGIN
                COMMIT TRANSACTION
                BREAK
          END
    COMMIT TRANSACTION
  END
SET ROWCOUNT  0

Output:

(5 row(s) affected)

(5 row(s) affected)

(4 row(s) affected)

(0 row(s) affected)

PHP unable to load php_curl.dll extension

Solution:

Step1: Uncomment the php_curl.dll from php.ini

Step2: Copy the following three files from php installed directory.i.e "C:\\php7".

libeay32.dll,
libssh2.dll,
ssleay32.dll

Step3: Paste the files under two place

httpd.conf's ServerRoot directive. i.e "C\Apache24"
apache bin directory. i.e "C\Apache24\bin"

Step4: Restart apache.

That's all. I solve the problem by this way.Hope it might work for you.

The solution is given here. https://abcofcomputing.blogspot.com/2017/06/php7-unable-to-load-phpcurldll.html

input[type='text'] CSS selector does not apply to default-type text inputs?

By CSS specifications, browsers may or may not use information about default attributes; mostly the don’t. The relevant clause in the CSS 2.1 spec is 5.8.2 Default attribute values in DTDs. In CSS 3 Selectors, it’s clause 6.3.4, with the same name. It recommends: “Selectors should be designed so that they work whether or not the default values are included in the document tree.”

It is generally best to explicitly specify essential attributes such as type=text instead of defaulting them. The reason is that there is no simple reliable way to refer to the input elements with defaulted type attribute.

How to get size in bytes of a CLOB column in Oracle?

Try this one for CLOB sizes bigger than VARCHAR2:

We have to split the CLOB in parts of "VARCHAR2 compatible" sizes, run lengthb through every part of the CLOB data, and summarize all results.

declare
   my_sum int;
begin
   for x in ( select COLUMN, ceil(DBMS_LOB.getlength(COLUMN) / 2000) steps from TABLE ) 
   loop
       my_sum := 0;
       for y in 1 .. x.steps
       loop
          my_sum := my_sum + lengthb(dbms_lob.substr( x.COLUMN, 2000, (y-1)*2000+1 ));
          -- some additional output
          dbms_output.put_line('step:' || y );
          dbms_output.put_line('char length:' || DBMS_LOB.getlength(dbms_lob.substr( x.COLUMN, 2000 , (y-1)*2000+1 )));
          dbms_output.put_line('byte length:' || lengthb(dbms_lob.substr( x.COLUMN, 2000, (y-1)*2000+1 )));
          continue;
        end loop;
        dbms_output.put_line('char summary:' || DBMS_LOB.getlength(x.COLUMN));
        dbms_output.put_line('byte summary:' || my_sum);
        continue;
    end loop;
end;
/

Get index of array element faster than O(n)

Still I wonder if there's a more convenient way of finding index of en element without caching (or there's a good caching technique that will boost up the performance).

You can use binary search (if your array is ordered and the values you store in the array are comparable in some way). For that to work you need to be able to tell the binary search whether it should be looking "to the left" or "to the right" of the current element. But I believe there is nothing wrong with storing the index at insertion time and then using it if you are getting the element from the same array.

Is it better to use "is" or "==" for number comparison in Python?

>>> a = 255556
>>> a == 255556
True
>>> a is 255556
False

I think that should answer it ;-)

The reason is that some often-used objects, such as the booleans True and False, all 1-letter strings and short numbers are allocated once by the interpreter, and each variable containing that object refers to it. Other numbers and larger strings are allocated on demand. The 255556 for instance is allocated three times, every time a different object is created. And therefore, according to is, they are not the same.

In PHP, what is a closure and why does it use the "use" identifier?

This is how PHP expresses a closure. This is not evil at all and in fact it is quite powerful and useful.

Basically what this means is that you are allowing the anonymous function to "capture" local variables (in this case, $tax and a reference to $total) outside of it scope and preserve their values (or in the case of $total the reference to $total itself) as state within the anonymous function itself.

Make content horizontally scroll inside a div

The problem is that your imgs will always bump down to the next line because of the containing div.

In order to get around this, you need to place the imgs in their own div with a width wide enough to hold all of them. Then you can use your styles as is.

So, when I set the imgs to 120px each and place them inside a

div#insideDiv{
    width:800px;
}

it all works.

Adjust width as necessary.

See http://jsfiddle.net/jasongennaro/8YfRe/

WPF Data Binding and Validation Rules Best Practices

I think the new preferred way might be to use IDataErrorInfo

Read more here

How do I manually configure a DataSource in Java?

One thing you might want to look at is the Commons DBCP project. It provides a BasicDataSource that is configured fairly similarly to your example. To use that you need the database vendor's JDBC JAR in your classpath and you have to specify the vendor's driver class name and the database URL in the proper format.

Edit:

If you want to configure a BasicDataSource for MySQL, you would do something like this:

BasicDataSource dataSource = new BasicDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setUrl("jdbc:mysql://<host>:<port>/<database>");
dataSource.setMaxActive(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");

Code that needs a DataSource can then use that.

How to normalize a 2-dimensional numpy array in python less verbose?

it appears that this also works

def normalizeRows(M):
    row_sums = M.sum(axis=1)
    return M / row_sums

How to update values in a specific row in a Python Pandas DataFrame?

If you have one large dataframe and only a few update values I would use apply like this:

import pandas as pd

df = pd.DataFrame({'filename' :  ['test0.dat', 'test2.dat'], 
                                  'm': [12, 13], 'n' : [None, None]})

data = {'filename' :  'test2.dat', 'n':16}

def update_vals(row, data=data):
    if row.filename == data['filename']:
        row.n = data['n']
    return row

df.apply(update_vals, axis=1)

How to enable scrolling of content inside a modal?

I'm having this issue on Mobile Safari on my iPhone6

Bootstrap adds the class .modal-open to the body when a modal is opened.

I've tried to make minimal overrides to Bootstrap 3.2.0, and came up with the following:

.modal-open {
    position: fixed;
}

.modal {
    overflow-y: auto;
}

For comparison, I've included the associated Bootstrap styles below.

Selected extract from bootstrap/less/modals.less (don't include this in your fix):

// Kill the scroll on the body
.modal-open {
  overflow: hidden;
}

// Container that the modal scrolls within
.modal {
  display: none;
  overflow: hidden;
  position: fixed;
  -webkit-overflow-scrolling: touch;
}

.modal-open .modal {
  overflow-x: hidden;
  overflow-y: auto;
}

Mobile Safari version used: User-Agent Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B411 Safari/600.1.4

Why do we have to normalize the input for an artificial neural network?

When you use unnormalized input features, the loss function is likely to have very elongated valleys. When optimizing with gradient descent, this becomes an issue because the gradient will be steep with respect some of the parameters. That leads to large oscillations in the search space, as you are bouncing between steep slopes. To compensate, you have to stabilize optimization with small learning rates.

Consider features x1 and x2, where range from 0 to 1 and 0 to 1 million, respectively. It turns out the ratios for the corresponding parameters (say, w1 and w2) will also be large.

Normalizing tends to make the loss function more symmetrical/spherical. These are easier to optimize because the gradients tend to point towards the global minimum and you can take larger steps.

Why am I getting InputMismatchException?

Are you providing write input to the console ?

Scanner reader = new Scanner(System.in);
num = reader.nextDouble();  

This is return double if you just enter number like 456. In case you enter a string or character instead,it will throw java.util.InputMismatchException when it tries to do num = reader.nextDouble() .

MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine

I had the same error and it occured when changing the mysql/data folder to another folder.
I just copied all folders inside mysql/data folder to a new location except for two files. Those are ib_logfile0 and ib_logfile1; those are automatically created when starting the MySQL server. That worked for me.