Programs & Examples On #Xpath

The primary purpose of XPath is to address parts of an XML document. It also provides basic facilities for manipulation of strings, numbers and booleans. XPath uses a compact, non-XML syntax. XPath operates on the abstract, logical structure of an XML document, rather than its surface syntax.

Selenium and xpath: finding a div with a class/id and verifying text inside

To account for leading and trailing whitespace, you probably want to use normalize-space()

//div[contains(@class, 'Caption') and normalize-space(.)='Model saved']

and

//div[@id='alertLabel' and normalize-space(.)='Save to server successful']

Note that //div[contains(@class, 'Caption') and normalize-space(.//text())='Model saved'] also works.

Is there an XSLT name-of element?

<xsl:value-of select="name(.)" /> : <xsl:value-of select="."/>

XPath to get all child nodes (elements, comments, and text) without parent

Use this XPath expression:

/*/*/X/node()

This selects any node (element, text node, comment or processing instruction) that is a child of any X element that is a grand-child of the top element of the XML document.

To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
 <xsl:template match="/">
  <xsl:copy-of select="/*/*/X/node()"/>
 </xsl:template>
</xsl:stylesheet>

and it produces exactly the wanted, correct result:

   First Text Node #1            
    <y> Y can Have Child Nodes #                
        <child> deep to it </child>
    </y>            Second Text Node #2 
    <z />

Explanation:

  1. As defined in the W3 XPath 1.0 Spec, "child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

  2. node() is an abbreviation of child::node() (because child:: is the primary axis and is used when no axis is explicitly specified).

How to parse XML in Bash?

While there are quite a few ready-made console utilities that might do what you want, it will probably take less time to write a couple of lines of code in a general-purpose programming language such as Python which you can easily extend and adapt to your needs.

Here is a python script which uses lxml for parsing — it takes the name of a file or a URL as the first parameter, an XPath expression as the second parameter, and prints the strings/nodes matching the given expression.

Example 1

#!/usr/bin/env python
import sys
from lxml import etree

tree = etree.parse(sys.argv[1])
xpath_expression = sys.argv[2]

#  a hack allowing to access the
#  default namespace (if defined) via the 'p:' prefix    
#  E.g. given a default namespaces such as 'xmlns="http://maven.apache.org/POM/4.0.0"'
#  an XPath of '//p:module' will return all the 'module' nodes
ns = tree.getroot().nsmap
if ns.keys() and None in ns:
    ns['p'] = ns.pop(None)
#   end of hack    

for e in tree.xpath(xpath_expression, namespaces=ns):
    if isinstance(e, str):
        print(e)
    else:
        print(e.text and e.text.strip() or etree.tostring(e, pretty_print=True))

lxml can be installed with pip install lxml. On ubuntu you can use sudo apt install python-lxml.

Usage

python xpath.py myfile.xml "//mynode"

lxml also accepts a URL as input:

python xpath.py http://www.feedforall.com/sample.xml "//link"

Note: If your XML has a default namespace with no prefix (e.g. xmlns=http://abc...) then you have to use the p prefix (provided by the 'hack') in your expressions, e.g. //p:module to get the modules from a pom.xml file. In case the p prefix is already mapped in your XML, then you'll need to modify the script to use another prefix.


Example 2

A one-off script which serves the narrow purpose of extracting module names from an apache maven file. Note how the node name (module) is prefixed with the default namespace {http://maven.apache.org/POM/4.0.0}:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modules>
        <module>cherries</module>
        <module>bananas</module>
        <module>pears</module>
    </modules>
</project>

module_extractor.py:

from lxml import etree
for _, e in etree.iterparse(open("pom.xml"), tag="{http://maven.apache.org/POM/4.0.0}module"):
    print(e.text)

How to use XPath contains() here?

Paste my contains example here:

//table[contains(@class, "EC_result")]/tbody

Webdriver findElements By xpath

Your questions:

Q 1.) I would like to know why it returns all the texts that following the div?
It should not and I think in will not. It returns all div with 'id' attribute value equal 'containter' (and all children of this). But you are printing the results with ele.getText() Where getText will return all text content of all children of your result.

Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.

Q 2.) how should I modify the code so it just return first or first few nodes that follow the parent note
This is not really clear what you are looking for. Example:

<p1> <div/> </p1 <p2/> 

The following to parent of the div is p2. This would be:

 //div[@id='container'][1]/parent::*/following-sibling::* 

or shorter

 //div[@id='container'][1]/../following-sibling::* 

If you are only looking for the first one extent the expression with an "predicate" (e.g [1] - for the first one. or [position() &lt; 4]for the first three)

If your are looking for the first child of the first div:

//div[@id='container'][1]/*[1]

If there is only one div with id an you are looking for the first child:

   //div[@id='container']/*[1]

and so on.

xpath find if node exists

Patrick is correct, both in the use of the xsl:if, and in the syntax for checking for the existence of a node. However, as Patrick's response implies, there is no xsl equivalent to if-then-else, so if you are looking for something more like an if-then-else, you're normally better off using xsl:choose and xsl:otherwise. So, Patrick's example syntax will work, but this is an alternative:

<xsl:choose>
 <xsl:when test="/html/body">body node exists</xsl:when>
 <xsl:otherwise>body node missing</xsl:otherwise>
</xsl:choose>

How to read XML using XPath in Java

This shows you how to

  1. Read in an XML file to a DOM
  2. Filter out a set of Nodes with XPath
  3. Perform a certain action on each of the extracted Nodes.

We will call the code with the following statement

processFilteredXml(xmlIn, xpathExpr,(node) -> {/*Do something...*/;});

In our case we want to print some creatorNames from a book.xml using "//book/creators/creator/creatorName" as xpath to perform a printNode action on each Node that matches the XPath.

Full code

@Test
public void printXml() {
    try (InputStream in = readFile("book.xml")) {
        processFilteredXml(in, "//book/creators/creator/creatorName", (node) -> {
            printNode(node, System.out);
        });
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

private InputStream readFile(String yourSampleFile) {
    return Thread.currentThread().getContextClassLoader().getResourceAsStream(yourSampleFile);
}

private void processFilteredXml(InputStream in, String xpath, Consumer<Node> process) {
    Document doc = readXml(in);
    NodeList list = filterNodesByXPath(doc, xpath);
    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        process.accept(node);
    }
}

public Document readXml(InputStream xmlin) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        return db.parse(xmlin);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

private NodeList filterNodesByXPath(Document doc, String xpathExpr) {
    try {
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xpath = xPathFactory.newXPath();
        XPathExpression expr = xpath.compile(xpathExpr);
        Object eval = expr.evaluate(doc, XPathConstants.NODESET);
        return (NodeList) eval;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

private void printNode(Node node, PrintStream out) {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(node);
        transformer.transform(source, result);
        String xmlString = result.getWriter().toString();
        out.println(xmlString);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Prints

<creatorName>Fosmire, Michael</creatorName>

<creatorName>Wertz, Ruth</creatorName>

<creatorName>Purzer, Senay</creatorName>

For book.xml

<book>
  <creators>
    <creator>
      <creatorName>Fosmire, Michael</creatorName>
      <givenName>Michael</givenName>
      <familyName>Fosmire</familyName>
    </creator>
    <creator>
      <creatorName>Wertz, Ruth</creatorName>
      <givenName>Ruth</givenName>
      <familyName>Wertz</familyName>
    </creator>
    <creator>
      <creatorName>Purzer, Senay</creatorName>
       <givenName>Senay</givenName>
       <familyName>Purzer</familyName>
    </creator>
  </creators>
  <titles>
    <title>Critical Engineering Literacy Test (CELT)</title>
  </titles>
</book>

Locating child nodes of WebElements in selenium

The toString() method of Selenium's By-Class produces something like "By.xpath: //XpathFoo"

So you could take a substring starting at the colon with something like this:

String selector = divA.toString().substring(s.indexOf(":") + 2);

With this, you could find your element inside your other element with this:

WebElement input = driver.findElement( By.xpath( selector + "//input" ) );

Advantage: You have to search only once on the actual SUT, so it could give you a bonus in performance.

Disadvantage: Ugly... if you want to search for the parent element with css selectory and use xpath for it's childs, you have to check for types before you concatenate... In this case, Slanec's solution (using findElement on a WebElement) is much better.

SelectSingleNode returning null for known good xml node path using XPath

This should work in your case without removing namespaces:

XmlNode idNode = myXmlDoc.GetElementsByTagName("id")[0];

How to use XPath preceding-sibling correctly

I also like to build locators from up to bottom like:

//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']

It's pretty simple, as we just search btn-group with button[contains(.,'Arcade Reader')] and get it's button[@name='settings']

That's just another option to build xPath locators

What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:

getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");

or even simplify more

getGroupButton("Arcade Reader", "delete").click();

XPath: select text node

your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.

Both should work.

/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2


/node/text()[1] - should return Text1
/node/text()[2] - should return text2

case-insensitive matching in xpath?

XPath 2 has a lower-case (and upper-case) string function. That's not quite the same as case-insensitive, but hopefully it will be close enough:

//CD[lower-case(@title)='empire burlesque']

If you are using XPath 1, there is a hack using translate.

Xpath for href element

This will get you the generic link:

selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do')")).Click();

If you want to have it specify a parameter then you will have to test for each one:

...
int i = 1;

selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do?camp=" + i.ToString() + "')")).Click();
...

The above could utilize a for loop which navigates to and from each camp numbers' page, which could verify a static list of camps.

Please excuse if the code is not perfect, I have not tested myself.

How to select element using XPATH syntax on Selenium for Python?

Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.

> def get_browser():
>     """Get the browser (a "driver")."""
>     # find the path with 'which chromedriver'
>     path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
>                             'venv/bin/chromedriver')
>     download_dir = "/home/moose/selenium-download/"
>     print("Is directory: {}".format(os.path.isdir(download_dir)))
> 
>     from selenium.webdriver.chrome.options import Options
>     chrome_options = Options()
>     chrome_options.add_experimental_option('prefs', {
>         "plugins.plugins_list": [{"enabled": False,
>                                   "name": "Chrome PDF Viewer"}],
>         "download": {
>             "prompt_for_download": False,
>             "default_directory": download_dir
>         }
>     })
> 
>     browser = webdriver.Chrome(path_to_chromedriver,
>                                chrome_options=chrome_options)
>     return browser

XPath: How to select elements based on their value?

//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]

The reason why I add this answer is that I want to explain the relationship of . and text() .

The first thing is when using [], there are only two types of data:

  1. [number] to select a node from node-set
  2. [bool] to filter a node-set from node-set

In this case, the value is evaluated to boolean by function boolean(), and there is a rule:

Filters are always evaluated with respect to a context.

When you need to compare text() or . with a string "Data", it first uses string() function to transform those to string type, than gets a boolean result.

There are two important rule about string():

  1. The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.

    text() is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]. When it is evaluated by string(["Data"]), it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.

  2. If you want the string() function to concatenate all child text, you must then pass a single node instead of a node-set.

    For example, we get a node-set ['a', 'b'], you can pass there parent node to string(parent), this will return 'ab', and of cause string(.) in you case will return an concatenated string "Data".

Both way will get same result only when there is a text node.

XPath to select multiple tags

One correct answer is:

/a/b/*[self::c or self::d or self::e]

Do note that this

a/b/*[local-name()='c' or local-name()='d' or local-name()='e']

is both too-long and incorrect. This XPath expression will select nodes like:

OhMy:c

NotWanted:d 

QuiteDifferent:e

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//button[@class='btn btn-primary' and contains(text(), 'Submit')]") private WebElementFacade submitButton;

public void clickOnSubmitButton() {
    submitButton.click();
}   

How to use XPath in Python?

If you want to have the power of XPATH combined with the ability to also use CSS at any point you can use parsel:

>>> from parsel import Selector
>>> sel = Selector(text=u"""<html>
        <body>
            <h1>Hello, Parsel!</h1>
            <ul>
                <li><a href="http://example.com">Link 1</a></li>
                <li><a href="http://scrapy.org">Link 2</a></li>
            </ul
        </body>
        </html>""")
>>>
>>> sel.css('h1::text').extract_first()
'Hello, Parsel!'
>>> sel.xpath('//h1/text()').extract_first()
'Hello, Parsel!'

XPath to return only elements containing the text, and not its parents

Do you want to find elements that contain "match", or that equal "match"?

This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2):

//*[text()='match']

This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2):

//*[normalize-space(text())='match']

This will find all elements that contain 'match' in the text node value (matches random2 and random3):

//*[contains(text(),'match')]

This XPATH 2.0 solution uses the matches() function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^) or a word boundary (i.e. \W) and terminated by the end of the string (i.e. $) or a word boundary. The third parameter i evaluates the regex pattern case-insensitive. (matches random2)

//*[matches(text(),'(^|\W)match($|\W)','i')]

How to select specified node within Xpath node sets by index with Selenium?

This is a FAQ:

//someName[3]

means: all someName elements in the document, that are the third someName child of their parent -- there may be many such elements.

What you want is exactly the 3rd someName element:

(//someName)[3]

Explanation: the [] has a higher precedence (priority) than //. Remember always to put expressions of the type //someName in brackets when you need to specify the Nth node of their selected node-list.

Converting JSON to XML in Java

Transforming with XSLT 3.0 is the only proper way to do it, as far as I can tell. It is guaranteed to produce valid XML, and a nice structure at that. https://www.w3.org/TR/xslt/#json

How to execute XPath one-liners from shell?

Since this project is apparently fairly new, check out https://github.com/jeffbr13/xq , seems to be a wrapper around lxml, but that is all you really need (and posted ad hoc solutions using lxml in other answers as well)

XPath selecting a node with some attribute value equals to some other node's attribute value

This XPath is specific to the code snippet you've provided. To select <child> with id as #grand you can write //child[@id='#grand'].

To get age //child[@id='#grand']/@age

Hope this helps

XPath to select Element by attribute value

You need to remove the / before the [. Predicates (the parts in [ ]) shouldn't have slashes immediately before them. Also, to select the Employee element itself, you should leave off the /text() at the end or otherwise you'd just be selecting the whitespace text values immediately under the Employee element.

//Employee[@id='4']

Edit: As Jens points out in the comments, // can be very slow because it searches the entire document for matching nodes. If the structure of the documents you're working with is going to be consistent, you are probably best off using a full path, for example:

/Employees/Employee[@id='4']

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

XPath using starts-with function

Use:

/*/ITEM[starts-with(REVENUE_YEAR,'2552')]/REGION

Note: Unless your host language can't handle element instance as result, do not use text nodes specially in mixed content data model. Do not start expressions with // operator when the schema is well known.

XPath OR operator for different nodes

It the element has two xpath. Then you can write two xpaths like below:

xpath1 | xpath2

Eg:

//input[@name="username"] | //input[@id="wm_login-username"]

Select parent element of known element in Selenium

This might be useful for someone else: Using this sample html

<div class="ParentDiv">
    <label for="label">labelName</label>
    <input type="button" value="elementToSelect">
</div>
<div class="DontSelect">
    <label for="animal">pig</label>
    <input type="button" value="elementToSelect">
</div>

If for example, I want to select an element in the same section (e.g div) as a label, you can use this

//label[contains(., 'labelName')]/parent::*//input[@value='elementToSelect'] 

This just means, look for a label (it could anything like a, h2) called labelName. Navigate to the parent of that label (i.e. div class="ParentDiv"). Search within the descendants of that parent to find any child element with the value of elementToSelect. With this, it will not select the second elementToSelect with DontSelect div as parent.

The trick is that you can reduce search areas for an element by navigating to the parent first and then searching descendant of that parent for the element you need. Other Syntax like following-sibling::h2 can also be used in some cases. This means the sibling following element h2. This will work for elements at the same level, having the same parent.

How do I select child elements of any depth using XPath?

//form/descendant::input[@type='submit']

How can I select checkboxes using the Selenium Java WebDriver?

Step 1:

The object locator supposed to be used here is XPath. So derive the XPath for those two checkboxes.

String housingmoves="//label[contains(text(),'housingmoves')]/preceding-sibling::input";
String season_country_homes="//label[contains(text(),'Seaside & Country Homes')]/preceding-sibling::input";

Step 2:

Perform a click on the checkboxes

driver.findElement(By.xpath(housingmoves)).click();
driver.findElement(By.xpath(season_country_homes)).click();

how to use XPath with XDocument?

you can use the example from Microsoft - for you without namespace:

using System.Xml.Linq;
using System.Xml.XPath;
var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");     

should do it

XPath:: Get following Sibling

You can go for identifying a list of elements with xPath:

//td[text() = ' Color Digest ']/following-sibling::td[1]

This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:

List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))

Now, you can use the 2nd element as your intended element, which is elements.get(1)

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

It took me a little while but finally figured out. Custom xpath that contains some text below worked perfectly for me.

//a[contains(text(),'JB-')]

Find position of a node using xpath

You can do this with XSLT but I'm not sure about straight XPath.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="utf-8" indent="yes" 
              omit-xml-declaration="yes"/>
  <xsl:template match="a/*[text()='tsr']">
    <xsl:number value-of="position()"/>
  </xsl:template>
  <xsl:template match="text()"/>
</xsl:stylesheet>

How can I find an element by CSS class with XPath?

This selector should work but will be more efficient if you replace it with your suited markup:

//*[contains(@class, 'Test')]

Or, since we know the sought element is a div:

//div[contains(@class, 'Test')]

But since this will also match cases like class="Testvalue" or class="newTest", @Tomalak's version provided in the comments is better:

//div[contains(concat(' ', @class, ' '), ' Test ')]

If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry):

//div[contains(concat(' ', normalize-space(@class), ' '), ' Test ')]

Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.

Getting attribute using XPath

You can also get it by

string(//bookstore/book[1]/title/@lang)    
string(//bookstore/book[2]/title/@lang)

although if you are using XMLDOM with JavaScript you can code something like

var n1 = uXmlDoc.selectSingleNode("//bookstore/book[1]/title/@lang");

and n1.text will give you the value "eng"

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

How to click a href link using Selenium

 webDriver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();

The above line works fine. Please remove the space after href.

Is that element is visible in the page, if the element is not visible please scroll down the page then perform click action.

How to use not contains() in xpath?

I need to select every production with a category that doesn't contain "Business"

Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as

//production[category[not(contains(., 'Business'))]]

rather than

//production[not(contains(category, 'Business'))]

The latter selects every production whose first category child doesn't contain "Business". The two XPath expressions will behave differently when a production has no category children, or more than one.

It doesn't make any difference in practice as long as every <production> has exactly one <category> child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

Finding an elements XPath using IE Developer tool

If your goal is to find CSS selectors you can use MRI (once MRI is open, click any element to see various selectors for the element):

http://westciv.com/mri/

For Xpath:

http://functionaltestautomation.blogspot.com/2008/12/xpath-in-internet-explorer.html

How can I find the link URL by link text with XPath?

Too late for you, but for anyone else with the same question...

//a[contains(text(), 'programming')]/@href

Of course, 'programming' can be any text fragment.

Is there a JSON equivalent of XQuery/XPath?

Defiant.js looks also pretty cool, here's a simple example:

var obj = {
        "car": [
            {"id": 10, "color": "silver", "name": "Volvo"},
            {"id": 11, "color": "red",    "name": "Saab"},
            {"id": 12, "color": "red",    "name": "Peugeot"},
            {"id": 13, "color": "yellow", "name": "Porsche"}
        ],
        "bike": [
            {"id": 20, "color": "black", "name": "Cannondale"},
            {"id": 21, "color": "red",   "name": "Shimano"}
        ]
    },
    search = JSON.search(obj, '//car[color="yellow"]/name');

console.log( search );
// ["Porsche"]

var reds = JSON.search(obj, '//*[color="red"]');

for (var i=0; i<reds.length; i++) {
    console.log( reds[i].name );
}
// Saab
// Peugeot
// Shimano

Extract value of attribute node via XPath

Here is the standard formula to extract the values of attribute and text using XPath-

  1. To extract attribute value for Web Element-

    elementXPath/@attributeName

  2. To extract text value for Web Element-

    elementXPath/text()

In your case here is the xpath which will return

//parent[@name='Parent_1']//child/@name

It will return:

Child_2
Child_4
Child_1
Child_3

XPath test if node value is number

Test the value against NaN:

<xsl:if test="string(number(myNode)) != 'NaN'">
    <!-- myNode is a number -->
</xsl:if>

This is a shorter version (thanks @Alejandro):

<xsl:if test="number(myNode) = myNode">
    <!-- myNode is a number -->
</xsl:if>

Selenium WebDriver findElement(By.xpath()) not working for me

You haven't specified what kind of html element you are trying to do an absolute xpath search on. In your case, it's the input element.

Try this:

element = findElement(By.xpath("//input[@class='t-TextBox' and @type='email' and @test-    
id='test-username']");

XPath - Selecting elements that equal a value

Try

//*[text()='qwerty'] because . is your current element

jquery select element by xpath

If you are debugging or similar - In chrome developer tools, you can simply use

$x('/html/.//div[@id="text"]')

How to set "value" to input web element using selenium?

Use findElement instead of findElements

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).sendKeys("your value");

OR

driver.findElement(By.id("invoice_supplier_id")).sendKeys("value", "your value");

OR using JavascriptExecutor

WebElement element = driver.findElement(By.xpath("enter the xpath here")); // you can use any locator
 JavascriptExecutor jse = (JavascriptExecutor)driver;
 jse.executeScript("arguments[0].value='enter the value here';", element);

OR

(JavascriptExecutor) driver.executeScript("document.evaluate(xpathExpresion, document, null, 9, null).singleNodeValue.innerHTML="+ DesiredText);

OR (in javascript)

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).setAttribute("value", "your value")

Hope it will help you :)

XSLT string replace

Here is the XSLT function which will work similar to the String.Replace() function of C#.

This template has the 3 Parameters as below

text :- your main string

replace :- the string which you want to replace

by :- the string which will reply by new string

Below are the Template

<xsl:template name="string-replace-all">
  <xsl:param name="text" />
  <xsl:param name="replace" />
  <xsl:param name="by" />
  <xsl:choose>
    <xsl:when test="contains($text, $replace)">
      <xsl:value-of select="substring-before($text,$replace)" />
      <xsl:value-of select="$by" />
      <xsl:call-template name="string-replace-all">
        <xsl:with-param name="text" select="substring-after($text,$replace)" />
        <xsl:with-param name="replace" select="$replace" />
        <xsl:with-param name="by" select="$by" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$text" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

Below sample shows how to call it

<xsl:variable name="myVariable ">
  <xsl:call-template name="string-replace-all">
    <xsl:with-param name="text" select="'This is a {old} text'" />
    <xsl:with-param name="replace" select="'{old}'" />
    <xsl:with-param name="by" select="'New'" />
  </xsl:call-template>
</xsl:variable>

You can also refer the below URL for the details.

XSL substring and indexOf

It's not clear exactly what you want to do with the index of a substring [update: it is clearer now - thanks] but you may be able to use the function substring-after or substring-before:

substring-before('My name is Fred', 'Fred')

returns 'My name is '.

If you need more detailed control, the substring() function can take two or three arguments: string, starting-index, length. Omit length to get the whole rest of the string.

There is no index-of() function for strings in XPath (only for sequences, in XPath 2.0). You can use string-length(substring-before($string, $substring))+1 if you specifically need the position.

There is also contains($string, $substring). These are all documented here. In XPath 2.0 you can use regular expression matching.

(XSLT mostly uses XPath for selecting nodes and processing values, so this is actually more of an XPath question. I tagged it thus.)

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

You can use javascript's document.evaluate to run an XPath expression on the DOM. I think it's supported in one way or another in browsers back to IE 6.

MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate

IE supports selectNodes instead.

MSDN: https://msdn.microsoft.com/en-us/library/ms754523(v=vs.85).aspx

XPath: Get parent node from child node

Use the parent axes with the parent node's name.

//*[title="50"]/parent::store

This XPath will only select the parent node if it is a store.

But you can also use one of these

//*[title="50"]/parent::*
//*[title="50"]/..

These xpaths will select any parent node. So if the document changes you will always select a node, even if it is not the node you expect.

EDIT

What happens in the given example where the parent is a bicycle but the parent of the parent is a store?

Does it ascent?

No, it only selects the store if it is a parent of the node that matches //*[title="50"].

If not, is there a method to ascent in such cases and return None if there is no such parent?

Yes, you can use ancestor axes

//*[title="50"]/ancestor::store

This will select all ancestors of the node matching //*[title="50"] that are ` stores. E.g.

<data xmlns:d="defiant-namespace" d:mi="23">
    <store mi="1">
        <store mi="22">
            <book price="8.95" d:price="Number" d:mi="13">
                <title d:constr="String" d:mi="10">50</title>
                <category d:constr="String" d:mi="11">reference</category>
                <author d:constr="String" d:mi="12">Nigel Rees</author>
            </book>
        </store>
    </store>
</data>

XPath selection result

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

Another option to check your xpath is to use selenium IDE.

  1. Install Firefox Selenium IDE
  2. Open your application in FireFox and open IDE
  3. In IDE, on a new line, paste your xpath to the target and click Find. The corresponding element would be highlighted in your application

Selenium IDE

XPath with multiple conditions

Here, we can do this way as well:

//category [@name='category name']/author[contains(text(),'authorname')]

OR

//category [@name='category name']//author[contains(text(),'authorname')]

To Learn XPATH in detail please visit- selenium xpath in detail

Is there an "if -then - else " statement in XPath?

Unfortunately the previous answers were no option for me so i researched for a while and found this solution:

http://blog.alessio.marchetti.name/post/2011/02/12/the-Oliver-Becker-s-XPath-method

I use it to output text if a certain Node exists. 4 is the length of the text foo. So i guess a more elegant solution would be the use of a variable.

substring('foo',number(not(normalize-space(/elements/the/element/)))*4)

How to select following sibling/xml tag using xpath

For completeness - adding to accepted answer above - in case you are interested in any sibling regardless of the element type you can use variation:

following-sibling::*

How can I convert a string to upper- or lower-case with XSLT?

upper-case(string) and lower-case(string)

How to use regex in XPath "contains" function

If you're using Selenium with Firefox you should be able to use EXSLT extensions, and regexp:test()

Does this work for you?

String expr = "//*[regexp:test(@id, 'sometext[0-9]+_text')]";
driver.findElement(By.xpath(expr));

Select values from XML field in SQL Server 2008

SELECT 
cast(xmlField as xml).value('(/person//firstName/node())[1]', 'nvarchar(max)') as FirstName,
cast(xmlField as xml).value('(/person//lastName/node())[1]', 'nvarchar(max)') as LastName
FROM [myTable]

Concatenate multiple node values in xpath

If you need to join xpath-selected text nodes but can not use string-join (when you are stuck with XSL 1.0) this might help:

<xsl:variable name="x">
    <xsl:apply-templates select="..." mode="string-join-mode"/>
</xsl:variable>
joined and normalized: <xsl:value-of select="normalize-space($x)"/>

<xsl:template match="*" mode="string-join-mode">
    <xsl:apply-templates mode="string-join-mode"/>
</xsl:template>    

<xsl:template match="text()" mode="string-join-mode">
    <xsl:value-of select="."/>
</xsl:template>    

XPath - Difference between node() and text()

text() and node() are node tests, in XPath terminology (compare).

Node tests operate on a set (on an axis, to be exact) of nodes and return the ones that are of a certain type. When no axis is mentioned, the child axis is assumed by default.

There are all kinds of node tests:

  • node() matches any node (the least specific node test of them all)
  • text() matches text nodes only
  • comment() matches comment nodes
  • * matches any element node
  • foo matches any element node named "foo"
  • processing-instruction() matches PI nodes (they look like <?name value?>).
  • Side note: The * also matches attribute nodes, but only along the attribute axis. @* is a shorthand for attribute::*. Attributes are not part of the child axis, that's why a normal * does not select them.

This XML document:

<produce>
    <item>apple</item>
    <item>banana</item>
    <item>pepper</item>
</produce>

represents the following DOM (simplified):

root node
   element node (name="produce")
      text node (value="\n    ")
      element node (name="item")
         text node (value="apple")
      text node (value="\n    ")
      element node (name="item")
         text node (value="banana")
      text node (value="\n    ")
      element node (name="item")
         text node (value="pepper")
      text node (value="\n")

So with XPath:

  • / selects the root node
  • /produce selects a child element of the root node if it has the name "produce" (This is called the document element; it represents the document itself. Document element and root node are often confused, but they are not the same thing.)
  • /produce/node() selects any type of child node beneath /produce/ (i.e. all 7 children)
  • /produce/text() selects the 4 (!) whitespace-only text nodes
  • /produce/item[1] selects the first child element named "item"
  • /produce/item[1]/text() selects all child text nodes (there's only one - "apple" - in this case)

And so on.

So, your questions

  • "Select the text of all items under produce" /produce/item/text() (3 nodes selected)
  • "Select all the manager nodes in all departments" //department/manager (1 node selected)

Notes

  • The default axis in XPath is the child axis. You can change the axis by prefixing a different axis name. For example: //item/ancestor::produce
  • Element nodes have text values. When you evaluate an element node, its textual contents will be returned. In case of this example, /produce/item[1]/text() and string(/produce/item[1]) will be the same.
  • Also see this answer where I outline the individual parts of an XPath expression graphically.

How to check if an element exists in the xml using xpath?

Use:

boolean(/*/*[@subjectIdentifier="Primary"]/*/*/*/*
                           [name()='AttachedXml' 
                          and 
                            namespace-uri()='http://xml.mycompany.com/XMLSchema'
                           ]
       )

XPath Query: get attribute href from a tag

For the following HTML document:

<html>
  <body>
    <a href="http://www.example.com">Example</a> 
    <a href="http://www.stackoverflow.com">SO</a> 
  </body>
</html>

The xpath query /html/body//a/@href (or simply //a/@href) will return:

    http://www.example.com
    http://www.stackoverflow.com

To select a specific instance use /html/body//a[N]/@href,

    $ /html/body//a[2]/@href
    http://www.stackoverflow.com

To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:

    $ /html/body//a[contains(@href,'example')]/@href
    http://www.example.com

Mixing the two:

    $ /html/body//a[contains(@href,'com')][2]/@href
    http://www.stackoverflow.com

XPath to fetch SQL XML value

I think the xpath query you want goes something like this:

/xml/box[@stepId="$stepId"]/components/component[@id="$componentId"]/variables/variable[@nom="Enabled" and @valeur="Yes"]

This should get you the variables that are named "Enabled" with a value of "Yes" for the specified $stepId and $componentId. This is assuming that your xml starts with an tag like you show, and not

If the SQL Server 2005 XPath stuff is pretty straightforward (I've never used it), then the above query should work. Otherwise, someone else may have to help you with that.

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

If you want to compare to a string literal you need to put it in (single) quotes:

<xsl:if test="Count != 'N/A'">

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Absolute Xpath: It uses Complete path from the Root Element to the desire element.

Relative Xpath: You can simply start by referencing the element you want and go from there.

Relative Xpaths are always preferred as they are not the complete paths from the root element. (//html//body). Because in future, if any webelement is added/removed, then the absolute Xpath changes. So Always use Relative Xpaths in your Automation.

Below are Some Links which you can Refer for more Information on them.

How to query values from xml nodes?

if you have only one xml in your table, you can convert it in 2 steps:

CREATE TABLE Batches( 
   BatchID int,
   RawXml xml 
)

declare @xml xml=(select top 1 RawXml from @Batches)

SELECT  --b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    @xml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol)

Using XPATH to search text containing &nbsp;

It seems that OpenQA, guys behind Selenium, have already addressed this problem. They defined some variables to explicitely match whitespaces. In my case, I need to use an XPATH similar to //td[text()="${nbsp}"].

I reproduced here the text from OpenQA concerning this issue (found here):

HTML automatically normalizes whitespace within elements, ignoring leading/trailing spaces and converting extra spaces, tabs and newlines into a single space. When Selenium reads text out of the page, it attempts to duplicate this behavior, so you can ignore all the tabs and newlines in your HTML and do assertions based on how the text looks in the browser when rendered. We do this by replacing all non-visible whitespace (including the non-breaking space "&nbsp;") with a single space. All visible newlines (<br>, <p>, and <pre> formatted new lines) should be preserved.

We use the same normalization logic on the text of HTML Selenese test case tables. This has a number of advantages. First, you don't need to look at the HTML source of the page to figure out what your assertions should be; "&nbsp;" symbols are invisible to the end user, and so you shouldn't have to worry about them when writing Selenese tests. (You don't need to put "&nbsp;" markers in your test case to assertText on a field that contains "&nbsp;".) You may also put extra newlines and spaces in your Selenese <td> tags; since we use the same normalization logic on the test case as we do on the text, we can ensure that assertions and the extracted text will match exactly.

This creates a bit of a problem on those rare occasions when you really want/need to insert extra whitespace in your test case. For example, you may need to type text in a field like this: "foo ". But if you simply write <td>foo </td> in your Selenese test case, we'll replace your extra spaces with just one space.

This problem has a simple workaround. We've defined a variable in Selenese, ${space}, whose value is a single space. You can use ${space} to insert a space that won't be automatically trimmed, like this: <td>foo${space}${space}${space}</td>. We've also included a variable ${nbsp}, that you can use to insert a non-breaking space.

Note that XPaths do not normalize whitespace the way we do. If you need to write an XPath like //div[text()="hello world"] but the HTML of the link is really "hello&nbsp;world", you'll need to insert a real "&nbsp;" into your Selenese test case to get it to match, like this: //div[text()="hello${nbsp}world"].

XPath: difference between dot and text()

There is a difference between . and text(), but this difference might not surface because of your input document.

If your input document looked like (the simplest document one can imagine given your XPath expressions)

Example 1

<html>
  <a>Ask Question</a>
</html>

Then //a[text()="Ask Question"] and //a[.="Ask Question"] indeed return exactly the same result. But consider a different input document that looks like

Example 2

<html>
  <a>Ask Question<other/>
  </a>
</html>

where the a element also has a child element other that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"] still returns the a element, while //a[.="Ask Question"] does not return anything!


This is because the meaning of the two predicates (everything between [ and ]) is different. [text()="Ask Question"] actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"] means: return true if the string value of an element is identical to "Ask Question".

In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other element is between "Ask Question" and a newline character that also counts as text content.

To make an even clearer example, consider as an input document:

Example 3

<a>Ask Question<other/>more text</a>

Here, the a element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a. You can test this by running //a/text() on this document, which will return (individual results separated by ----):

Ask Question
-----------------------
more text

So, in such a scenario, text() returns a set of individual nodes, while . in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text'] which will successfully return the a element.


Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()) is given a sequence of nodes, it will only process the first node and silently ignore the rest.

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

XPath query to get nth instance of an element

This seems to work:

/descendant::input[@id="search_query"][2]

I go this from "XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition" by Michael Kay.

There is also a note in the "Abbreviated Syntax" section of the XML Path Language specification http://www.w3.org/TR/xpath/#path-abbrev that provided a clue.

Get nodes where child node contains an attribute

Years later, but a useful option would be to utilize XPath Axes (https://www.w3schools.com/xml/xpath_axes.asp). More specifically, you are looking to use the descendants axes.

I believe this example would do the trick:

//book[descendant::title[@lang='it']]

This allows you to select all book elements that contain a child title element (regardless of how deep it is nested) containing language attribute value equal to 'it'.

I cannot say for sure whether or not this answer is relevant to the year 2009 as I am not 100% certain that the XPath Axes existed at that time. What I can confirm is that they do exist today and I have found them to be extremely useful in XPath navigation and I am sure you will as well.

How to write an XPath query to match two attributes?

//div[@id='..' and @class='...]

should do the trick. That's selecting the div operators that have both attributes of the required value.

It's worth using one of the online XPath testbeds to try stuff out.

How to use "not" in xpath?

Use boolean function like below:

//a[(contains(@id, 'xx'))=false]

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

Xpath: select div that contains class AND whose specific child element contains text

You could use the xpath :

//div[@class="measure-tab" and .//span[contains(., "someText")]]

Input :

<root>
<div class="measure-tab">
  <td> someText</td>
</div>
<div class="measure-tab">
  <div>
    <div2>
       <span>someText2</span>
   </div2>
  </div>
</div>
</root>

Output :

    Element='<div class="measure-tab">
  <div>
    <div2>
      <span>someText2</span>
    </div2>
  </div>
</div>'

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

The debate between cssSelector vs XPath would remain as one of the most subjective debate in the Selenium Community. What we already know so far can be summarized as:

  • People in favor of cssSelector say that it is more readable and faster (especially when running against Internet Explorer).
  • While those in favor of XPath tout it's ability to transverse the page (while cssSelector cannot).
  • Traversing the DOM in older browsers like IE8 does not work with cssSelector but is fine with XPath.
  • XPath can walk up the DOM (e.g. from child to parent), whereas cssSelector can only traverse down the DOM (e.g. from parent to child)
  • However not being able to traverse the DOM with cssSelector in older browsers isn't necessarily a bad thing as it is more of an indicator that your page has poor design and could benefit from some helpful markup.
  • Ben Burton mentions you should use cssSelector because that's how applications are built. This makes the tests easier to write, talk about, and have others help maintain.
  • Adam Goucher says to adopt a more hybrid approach -- focusing first on IDs, then cssSelector, and leveraging XPath only when you need it (e.g. walking up the DOM) and that XPath will always be more powerful for advanced locators.

Dave Haeffner carried out a test on a page with two HTML data tables, one table is written without helpful attributes (ID and Class), and the other with them. I have analyzed the test procedure and the outcome of this experiment in details in the discussion Why should I ever use cssSelector selectors as opposed to XPath for automated testing?. While this experiment demonstrated that each Locator Strategy is reasonably equivalent across browsers, it didn't adequately paint the whole picture for us. Dave Haeffner in the other discussion Css Vs. X Path, Under a Microscope mentioned, in an an end-to-end test there were a lot of other variables at play Sauce startup, Browser start up, and latency to and from the application under test. The unfortunate takeaway from that experiment could be that one driver may be faster than the other (e.g. IE vs Firefox), when in fact, that's wasn't the case at all. To get a real taste of what the performance difference is between cssSelector and XPath, we needed to dig deeper. We did that by running everything from a local machine while using a performance benchmarking utility. We also focused on a specific Selenium action rather than the entire test run, and run things numerous times. I have analyzed the specific test procedure and the outcome of this experiment in details in the discussion cssSelector vs XPath for selenium. But the tests were still missing one aspect i.e. more browser coverage (e.g., Internet Explorer 9 and 10) and testing against a larger and deeper page.

Dave Haeffner in another discussion Css Vs. X Path, Under a Microscope (Part 2) mentions, in order to make sure the required benchmarks are covered in the best possible way we need to consider an example that demonstrates a large and deep page.


Test SetUp

To demonstrate this detailed example, a Windows XP virtual machine was setup and Ruby (1.9.3) was installed. All the available browsers and their equivalent browser drivers for Selenium was also installed. For benchmarking, Ruby's standard lib benchmark was used.


Test Code

require_relative 'base'
require 'benchmark'

class LargeDOM < Base

  LOCATORS = {
    nested_sibling_traversal: {
      css: "div#siblings > div:nth-of-type(1) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3)",
      xpath: "//div[@id='siblings']/div[1]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]"
    },
    nested_sibling_traversal_by_class: {
      css: "div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1",
      xpath: "//div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]"
    },
    table_header_id_and_class: {
      css: "table#large-table thead .column-50",
      xpath: "//table[@id='large-table']//thead//*[@class='column-50']"
    },
    table_header_id_class_and_direct_desc: {
      css: "table#large-table > thead .column-50",
      xpath: "//table[@id='large-table']/thead//*[@class='column-50']"
    },
    table_header_traversing: {
      css: "table#large-table thead tr th:nth-of-type(50)",
      xpath: "//table[@id='large-table']//thead//tr//th[50]"
    },
    table_header_traversing_and_direct_desc: {
      css: "table#large-table > thead > tr > th:nth-of-type(50)",
      xpath: "//table[@id='large-table']/thead/tr/th[50]"
    },
    table_cell_id_and_class: {
      css: "table#large-table tbody .column-50",
      xpath: "//table[@id='large-table']//tbody//*[@class='column-50']"
    },
    table_cell_id_class_and_direct_desc: {
      css: "table#large-table > tbody .column-50",
      xpath: "//table[@id='large-table']/tbody//*[@class='column-50']"
    },
    table_cell_traversing: {
      css: "table#large-table tbody tr td:nth-of-type(50)",
      xpath: "//table[@id='large-table']//tbody//tr//td[50]"
    },
    table_cell_traversing_and_direct_desc: {
      css: "table#large-table > tbody > tr > td:nth-of-type(50)",
      xpath: "//table[@id='large-table']/tbody/tr/td[50]"
    }
  }

  attr_reader :driver

  def initialize(driver)
    @driver = driver
    visit '/large'
    is_displayed?(id: 'siblings')
    super
  end

  # The benchmarking approach was borrowed from
  # http://rubylearning.com/blog/2013/06/19/how-do-i-benchmark-ruby-code/
  def benchmark
    Benchmark.bmbm(27) do |bm|
      LOCATORS.each do |example, data|
    data.each do |strategy, locator|
      bm.report(example.to_s + " using " + strategy.to_s) do
        begin
          ENV['iterations'].to_i.times do |count|
         find(strategy => locator)
          end
        rescue Selenium::WebDriver::Error::NoSuchElementError => error
          puts "( 0.0 )"
        end
      end
    end
      end
    end
  end

end

Results

NOTE: The output is in seconds, and the results are for the total run time of 100 executions.

In Table Form:

css_xpath_under_microscopev2

In Chart Form:

  • Chrome:

chart-chrome

  • Firefox:

chart-firefox

  • Internet Explorer 8:

chart-ie8

  • Internet Explorer 9:

chart-ie9

  • Internet Explorer 10:

chart-ie10

  • Opera:

chart-opera


Analyzing the Results

  • Chrome and Firefox are clearly tuned for faster cssSelector performance.
  • Internet Explorer 8 is a grab bag of cssSelector that won't work, an out of control XPath traversal that takes ~65 seconds, and a 38 second table traversal with no cssSelector result to compare it against.
  • In IE 9 and 10, XPath is faster overall. In Safari, it's a toss up, except for a couple of slower traversal runs with XPath. And across almost all browsers, the nested sibling traversal and table cell traversal done with XPath are an expensive operation.
  • These shouldn't be that surprising since the locators are brittle and inefficient and we need to avoid them.

Summary

  • Overall there are two circumstances where XPath is markedly slower than cssSelector. But they are easily avoidable.
  • The performance difference is slightly in favor of for non-IE browsers and slightly in favor of for IE browsers.

Trivia

You can perform the bench-marking on your own, using this library where Dave Haeffner wrapped up all the code.

How to select the first element with a specific attribute using XPath

    <bookstore>
     <book location="US">A1</book>
     <category>
      <book location="US">B1</book>
      <book location="FIN">B2</book>
     </category>
     <section>
      <book location="FIN">C1</book>
      <book location="US">C2</book>
     </section>
    </bookstore> 

So Given the above; you can select the first book with

(//book[@location='US'])[1]

And this will find the first one anywhere that has a location US. [A1]

//book[@location='US']

Would return the node set with all books with location US. [A1,B1,C2]

(//category/book[@location='US'])[1]

Would return the first book location US that exists in a category anywhere in the document. [B1]

(/bookstore//book[@location='US'])[1]

will return the first book with location US that exists anywhere under the root element bookstore; making the /bookstore part redundant really. [A1]

In direct answer:

/bookstore/book[@location='US'][1]

Will return you the first node for book element with location US that is under bookstore [A1]

Incidentally if you wanted, in this example to find the first US book that was not a direct child of bookstore:

(/bookstore/*//book[@location='US'])[1]

can we use xpath with BeautifulSoup?

Nope, BeautifulSoup, by itself, does not support XPath expressions.

An alternative library, lxml, does support XPath 1.0. It has a BeautifulSoup compatible mode where it'll try and parse broken HTML the way Soup does. However, the default lxml HTML parser does just as good a job of parsing broken HTML, and I believe is faster.

Once you've parsed your document into an lxml tree, you can use the .xpath() method to search for elements.

try:
    # Python 2
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen
from lxml import etree

url =  "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
tree.xpath(xpathselector)

There is also a dedicated lxml.html() module with additional functionality.

Note that in the above example I passed the response object directly to lxml, as having the parser read directly from the stream is more efficient than reading the response into a large string first. To do the same with the requests library, you want to set stream=True and pass in the response.raw object after enabling transparent transport decompression:

import lxml.html
import requests

url =  "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = requests.get(url, stream=True)
response.raw.decode_content = True
tree = lxml.html.parse(response.raw)

Of possible interest to you is the CSS Selector support; the CSSSelector class translates CSS statements into XPath expressions, making your search for td.empformbody that much easier:

from lxml.cssselect import CSSSelector

td_empformbody = CSSSelector('td.empformbody')
for elem in td_empformbody(tree):
    # Do something with these table cells.

Coming full circle: BeautifulSoup itself does have very complete CSS selector support:

for cell in soup.select('table#foobar td.empformbody'):
    # Do something with these table cells.

How to concat a string to xsl:value-of select="...?

Easiest method is

  <TD>
    <xsl:value-of select="concat(//author/first-name,' ',//author/last-name)"/>
  </TD>

when the XML Structure is

<title>The Confidence Man</title>
<author>
  <first-name>Herman</first-name>
  <last-name>Melville</last-name>
</author>
<price>11.99</price>

XSLT - How to select XML Attribute by Attribute?

There are two problems with your xpath - first you need to remove the child selector from after Data like phihag mentioned. Also you forgot to include root in your xpath. Here is what you want to do:

select="/root/DataSet/Data[@Value1='2']/@Value2"

How to call a method in another class in Java?

class A{
  public void methodA(){
    new B().methodB();
    //or
    B.methodB1();
  }
}

class B{
  //instance method
  public void methodB(){
  }
  //static method
  public static  void methodB1(){
  }
}

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

The shortest way is to directly add the below code as additional attributes in the input type that you want to change.

onfocus="if(this.value=='Search')this.value=''" 
onblur="if(this.value=='')this.value='Search'"

Please note: Change the text "Search" to "go" or any other text to suit your requirements.

How to disable Hyper-V in command line?

I tried all of stack overflow and all didn't works. But this works for me:

  1. Open System Configuration
  2. Click Service tab
  3. Uncheck all of Hyper-V related

Why boolean in Java takes only true or false? Why not 1 or 0 also?

Because booleans have two values: true or false. Note that these are not strings, but actual boolean literals.

1 and 0 are integers, and there is no reason to confuse things by making them "alternative true" and "alternative false" (or the other way round for those used to Unix exit codes?). With strong typing in Java there should only ever be exactly two primitive boolean values.

EDIT: Note that you can easily write a conversion function if you want:

public static boolean intToBool(int input)
{
   if (input < 0 || input > 1)
   {
      throw new IllegalArgumentException("input must be 0 or 1");
   }

   // Note we designate 1 as true and 0 as false though some may disagree
   return input == 1;
}

Though I wouldn't recommend this. Note how you cannot guarantee that an int variable really is 0 or 1; and there's no 100% obvious semantics of what one means true. On the other hand, a boolean variable is always either true or false and it's obvious which one means true. :-)

So instead of the conversion function, get used to using boolean variables for everything that represents a true/false concept. If you must use some kind of primitive text string (e.g. for storing in a flat file), "true" and "false" are much clearer in their meaning, and can be immediately turned into a boolean by the library method Boolean.valueOf.

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

Masking password input from the console : Java

A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)

import java.io.Console;
public class Main {

    public void passwordExample() {        
        Console console = System.console();
        if (console == null) {
            System.out.println("Couldn't get Console instance");
            System.exit(0);
        }

        console.printf("Testing password%n");
        char[] passwordArray = console.readPassword("Enter your secret password: ");
        console.printf("Password entered was: %s%n", new String(passwordArray));

    }

    public static void main(String[] args) {
        new Main().passwordExample();
    }
}

Retrieve version from maven pom.xml in code

To complement what @kieste has posted, which I think is the best way to have Maven build informations available in your code if you're using Spring-boot: the documentation at http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready-application-info is very useful.

You just need to activate actuators, and add the properties you need in your application.properties or application.yml

Automatic property expansion using Maven

You can automatically expand info properties from the Maven project using resource filtering. If you use the spring-boot-starter-parent you can then refer to your Maven ‘project properties’ via @..@ placeholders, e.g.

project.artifactId=myproject
project.name=Demo
project.version=X.X.X.X
project.description=Demo project for info endpoint
[email protected]@
[email protected]@
[email protected]@
[email protected]@

sql server Get the FULL month name from a date

Most answers are a bit more complicated than necessary, or don't provide the exact format requested.

select Format(getdate(), 'MMMM dd yyyy') --returns 'October 01 2020', note the leading zero
select Format(getdate(), 'MMMM d yyyy') --returns the desired format with out the leading zero: 'October 1 2020'

If you want a comma, as you normally would, use:

select Format(getdate(), 'MMMM d, yyyy') --returns 'October 1, 2020'

Note: even though there is only one 'd' for the day, it will become a 2 digit day when needed.

How to iterate through a list of objects in C++

You're close.

std::list<Student>::iterator it;
for (it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
}

Note that you can define it inside the for loop:

for (std::list<Student>::iterator it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
}

And if you are using C++11 then you can use a range-based for loop instead:

for (auto const& i : data) {
    std::cout << i.name;
}

Here auto automatically deduces the correct type. You could have written Student const& i instead.

Verifying a specific parameter with Moq

I believe that the problem in the fact that Moq will check for equality. And, since XmlElement does not override Equals, it's implementation will check for reference equality.

Can't you use a custom object, so you can override equals?

How do I count cells that are between two numbers in Excel?

=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")

How to Deep clone in javascript

My solution, deep clones objects, arrays and functions.

let superClone = (object) => {
  let cloning = {};

  Object.keys(object).map(prop => {
     if(Array.isArray(object[prop])) {
        cloning[prop] = [].concat(object[prop])
    } else if(typeof  object[prop] === 'object') {
      cloning[prop] = superClone(object[prop])
    } else cloning[prop] = object[prop]
  })

  return cloning
}

example

let obj = {
  a: 'a',
  b: 'b',
  c: {
    deep: 'try and copy me',
    d: {
      deeper: 'try me again',
      callDeeper() {
       return this.deeper
     }
    },
    arr: [1, 2, 3]
  },
  hi() {
    return this.a
  }
};


const cloned = superClone(obj)
obj.a = 'A' 
obj.c.deep = 'i changed'
obj.c.arr = [45,454]
obj.c.d.deeper = 'i changed'

console.log(cloned) // unchanged object

If your objects contain methods don't use JSON to deep clone, JSON deep cloning doesn't clone methods.

If you take a look at this, object person2 only clones the name, not person1's greet method.


const person1 = {
  name: 'John',
  greet() {
    return `HI, ${this.name}`
  }
}
 
const person2 = JSON.parse(JSON.stringify(person1))
 
console.log(person2)  // { name: 'John' }

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

Is it possible to opt-out of dark mode on iOS 13?

I think I've found the solution. I initially pieced it together from UIUserInterfaceStyle - Information Property List and UIUserInterfaceStyle - UIKit, but have now found it actually documented at Choosing a specific interface style for your iOS app.

In your info.plist, set UIUserInterfaceStyle (User Interface Style) to 1 (UIUserInterfaceStyle.light).

EDIT: As per dorbeetle's answer, a more appropriate setting for UIUserInterfaceStyle may be Light.

What does the restrict keyword mean in C++?

Nothing. It was added to the C99 standard.

What does <T> (angle brackets) mean in Java?

<T> is a generic and can usually be read as "of type T". It depends on the type to the left of the <> what it actually means.

I don't know what a Pool or PoolFactory is, but you also mention ArrayList<T>, which is a standard Java class, so I'll talk to that.

Usually, you won't see "T" in there, you'll see another type. So if you see ArrayList<Integer> for example, that means "An ArrayList of Integers." Many classes use generics to constrain the type of the elements in a container, for example. Another example is HashMap<String, Integer>, which means "a map with String keys and Integer values."

Your Pool example is a bit different, because there you are defining a class. So in that case, you are creating a class that somebody else could instantiate with a particular type in place of T. For example, I could create an object of type Pool<String> using your class definition. That would mean two things:

  • My Pool<String> would have an interface PoolFactory<String> with a createObject method that returns Strings.
  • Internally, the Pool<String> would contain an ArrayList of Strings.

This is great news, because at another time, I could come along and create a Pool<Integer> which would use the same code, but have Integer wherever you see T in the source.

UILabel - auto-size label to fit text?

Here's what I am finding works for my situation:

1) The height of the UILabel has a >= 0 constraint using autolayout. The width is fixed. 2) Assign the text into the UILabel, which already has a superview at that point (not sure how vital that is). 3) Then, do:

    label.sizeToFit()
    label.layoutIfNeeded()

The height of the label is now set appropriately.

Write a file in UTF-8 using FileWriter (Java)?

Since Java 7 there is an easy way to handle character encoding of BufferedWriter and BufferedReaders. You can create a BufferedWriter directly by using the Files class instead of creating various instances of Writer. You can simply create a BufferedWriter, which considers character encoding, by calling:

Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8);

You can find more about it in JavaDoc:

*ngIf else if in template

To avoid nesting and ngSwitch, there is also this possibility, which leverages the way logical operators work in Javascript:

<ng-container *ngIf="foo === 1; then first; else (foo === 2 && second) || (foo === 3 && third)"></ng-container>
  <ng-template #first>First</ng-template>
  <ng-template #second>Second</ng-template>
  <ng-template #third>Third</ng-template>

Hashing a dictionary?

I do it like this:

hash(str(my_dict))

Add vertical scroll bar to panel

Below is the code that implements custom vertical scrollbar. The important detail here is to know when scrollbar is needed by calculating how much space is consumed by the controls that you add to the panel.

panelUserInput.SuspendLayout();
panelUserInput.Controls.Clear();
panelUserInput.AutoScroll = false;
panelUserInput.VerticalScroll.Visible = false;

// here you'd be adding controls

int x = 20, y = 20, height = 0;
for (int inx = 0; inx < numControls; inx++ )
{
    // this example uses textbox control
    TextBox txt = new TextBox();
    txt.Location = new System.Drawing.Point(x, y);
    // add whatever details you need for this control
    // before adding it to the panel
    panelUserInput.Controls.Add(txt);
    height = y + txt.Height;
    y += 25;
}
if (height > panelUserInput.Height)
{
    VScrollBar bar = new VScrollBar();
    bar.Dock = DockStyle.Right;
    bar.Scroll += (sender, e) => { panelUserInput.VerticalScroll.Value =  bar.Value; };
    bar.Top = 0;
    bar.Left = panelUserInput.Width - bar.Width;
    bar.Height = panelUserInput.Height;
    bar.Visible = true;
    panelUserInput.Controls.Add(bar);
}
panelUserInput.ResumeLayout();

// then update the form
this.PerformLayout();

SQL Server stored procedure parameters

I'm going on a bit of an assumption here, but I'm assuming the logic inside the procedure gets split up via task. And you cant have nullable parameters as @Yuck suggested because of the dynamics of the parameters?

So going by my assumption

If TaskName = "Path1" Then Something

If TaskName = "Path2" Then Something Else

My initial thought is, if you have separate functions with business-logic you need to create, and you can determine that you have say 5-10 different scenarios, rather write individual stored procedures as needed, instead of trying one huge one solution fits all approach. Might get a bit messy to maintain.

But if you must...

Why not try dynamic SQL, as suggested by @E.J Brennan (Forgive me, i haven't touched SQL in a while so my syntax might be rusty) That being said i don't know if its the best approach, but could this could possibly meet your needs?

CREATE PROCEDURE GetTaskEvents
    @TaskName varchar(50)
    @Values varchar(200)
AS
BEGIN
  DECLARE @SQL VARCHAR(MAX)

  IF @TaskName = 'Something'
  BEGIN
    @SQL = 'INSERT INTO.....' + CHAR(13)
    @SQL += @Values + CHAR(13) 
  END

  IF @TaskName = 'Something Else'
  BEGIN
    @SQL = 'DELETE SOMETHING WHERE' + CHAR(13)
    @SQL += @Values + CHAR(13) 
  END

  PRINT(@SQL)
  EXEC(@SQL)    
END

(The CHAR(13) adds a new line.. an old habbit i picked up somewhere, used to help debugging/reading dynamic procedures when running SQL profiler.)

How to resize an image with OpenCV2.0 and Python2.6

Example doubling the image size

There are two ways to resize an image. The new size can be specified:

  1. Manually;

    height, width = src.shape[:2]

    dst = cv2.resize(src, (2*width, 2*height), interpolation = cv2.INTER_CUBIC)

  2. By a scaling factor.

    dst = cv2.resize(src, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC), where fx is the scaling factor along the horizontal axis and fy along the vertical axis.

To shrink an image, it will generally look best with INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with INTER_CUBIC (slow) or INTER_LINEAR (faster but still looks OK).

Example shrink image to fit a max height/width (keeping aspect ratio)

import cv2

img = cv2.imread('YOUR_PATH_TO_IMG')

height, width = img.shape[:2]
max_height = 300
max_width = 300

# only shrink if img is bigger than required
if max_height < height or max_width < width:
    # get scaling factor
    scaling_factor = max_height / float(height)
    if max_width/float(width) < scaling_factor:
        scaling_factor = max_width / float(width)
    # resize image
    img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)

cv2.imshow("Shrinked image", img)
key = cv2.waitKey()

Using your code with cv2

import cv2 as cv

im = cv.imread(path)

height, width = im.shape[:2]

thumbnail = cv.resize(im, (round(width / 10), round(height / 10)), interpolation=cv.INTER_AREA)

cv.imshow('exampleshq', thumbnail)
cv.waitKey(0)
cv.destroyAllWindows()

How to set thymeleaf th:field value from other variable

So what you need to do is replace th:field with th:name and add th:value, th:value will have the value of the variable you're passing across.

<div class="col-auto">
        <input type="text" th:value="${client.name}" th:name="clientName" 
        class="form control">
</div>

Format y axis as percent

For those who are looking for the quick one-liner:

plt.gca().set_yticklabels(['{:.0f}%'.format(x*100) for x in plt.gca().get_yticks()]) 

Or if you are using Latex as the axis text formatter, you have to add one backslash '\'

plt.gca().set_yticklabels(['{:.0f}\%'.format(x*100) for x in plt.gca().get_yticks()]) 

Prevent BODY from scrolling when a modal is opened

Based on this fiddle: http://jsfiddle.net/dh834zgw/1/

the following snippet (using jquery) will disable the window scroll:

 var curScrollTop = $(window).scrollTop();
 $('html').toggleClass('noscroll').css('top', '-' + curScrollTop + 'px');

And in your css:

html.noscroll{
    position: fixed;
    width: 100%;
    top:0;
    left: 0;
    height: 100%;
    overflow-y: scroll !important;
    z-index: 10;
 }

Now when you remove the modal, don't forget to remove the noscroll class on the html tag:

$('html').toggleClass('noscroll');

Cannot find libcrypto in Ubuntu

ld is trying to find libcrypto.sowhich is not present as seen in your locate output. You can make a copy of the libcrypto.so.0.9.8 and name it as libcrypto.so. Put this is your ld path. ( If you do not have root access then you can put it in a local path and specify the path manually )

javascript date to string

You will need to pad with "0" if its a single digit & note getMonth returns 0..11 not 1..12

function printDate() {
    var temp = new Date();
    var dateStr = padStr(temp.getFullYear()) +
                  padStr(1 + temp.getMonth()) +
                  padStr(temp.getDate()) +
                  padStr(temp.getHours()) +
                  padStr(temp.getMinutes()) +
                  padStr(temp.getSeconds());
    debug (dateStr );
}

function padStr(i) {
    return (i < 10) ? "0" + i : "" + i;
}

What operator is <> in VBA

It means not equal to, as the others said..

I just wanted to say that I read that as "greater than or lesser than".

e.g.

let x = 12

if x <> 0 then
    //code

In this case 'x' is greater than (that's the '>' symbol) 0.

Hope this helps. :D

SimpleXML - I/O warning : failed to load external entity

simplexml_load_file() interprets an XML file (either a file on your disk or a URL) into an object. What you have in $feed is a string.

You have two options:

  • Use file_get_contents() to get the XML feed as a string, and use e simplexml_load_string():

    $feed = file_get_contents('...');
    $items = simplexml_load_string($feed);
    
  • Load the XML feed directly using simplexml_load_file():

    $items = simplexml_load_file('...');
    

Check if a string contains a number

alp_num = [x for x in string.split() if x.isalnum() and re.search(r'\d',x) and 
re.search(r'[a-z]',x)]

print(alp_num)

This returns all the string that has both alphabets and numbers in it. isalpha() returns the string with all digits or all characters.

Found shared references to a collection org.hibernate.HibernateException

In my case, I was copying and pasting code from my other classes, so I did not notice that the getter code was bad written:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "credito")
public Set getConceptoses() {
    return this.letrases;
}

public void setConceptoses(Set conceptoses) {
    this.conceptoses = conceptoses;
}

All references conceptoses but if you look at the get says letrases

Laravel blade check empty foreach

You should use empty()

@if (!empty($status->replies)) 

<div class="media-body reply-body">
    @foreach ($status->replies as $reply)
        <p>{{ $reply->body }}</p>
    @endforeach
</div>

@endif

You can use count, but if the array is larger it takes longer, if you only need to know if its empty, empty is the better one to use.

Writing sqlplus output to a file

Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt). You can check where you are spooling by issuing spool command.

Highcharts - how to have a chart with dynamic height?

What if you hooked the window resize event:

$(window).resize(function() 
{    
    chart.setSize(
       $(document).width(), 
       $(document).height()/2,
       false
    );   
});

See example fiddle here.

Highcharts API Reference : setSize().

Color text in terminal applications in UNIX

Different solution that I find more elegant

Here's another way to do it. Some people will prefer this as the code is a bit cleaner. There are no %s and a RESET color to end the coloration.

#include <stdio.h>

#define RED   "\x1B[31m"
#define GRN   "\x1B[32m"
#define YEL   "\x1B[33m"
#define BLU   "\x1B[34m"
#define MAG   "\x1B[35m"
#define CYN   "\x1B[36m"
#define WHT   "\x1B[37m"
#define RESET "\x1B[0m"

int main() {
  printf(RED "red\n"     RESET);
  printf(GRN "green\n"   RESET);
  printf(YEL "yellow\n"  RESET);
  printf(BLU "blue\n"    RESET);
  printf(MAG "magenta\n" RESET);
  printf(CYN "cyan\n"    RESET);
  printf(WHT "white\n"   RESET);

  return 0;
}

This program gives the following output:

enter image description here


Simple example with multiple colors

This way, it's easy to do something like:

printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n");

This line produces the following output:

execution's output

How can I change the text inside my <span> with jQuery?

Try this

$("#abc").html('<span class = "xyz"> SAMPLE TEXT</span>');

Handle all the css relevant to that span within xyz

Access Enum value using EL with JSTL

You have 3 choices here, none of which is perfect:

  1. You can use a scriptlet in the test attribute:

    <c:when test="<%= dp.getStatus() == Status.VALID %>">

    This uses the enum, but it also uses a scriptlet, which is not the "right way" in JSP 2.0. But most importantly, this doesn't work when you want to add another condition to the same when using ${}. And this means all the variables you want to test have to be declared in a scriptlet, or kept in request, or session (pageContext variable is not available in .tag files).

  2. You can compare against string:

    <c:when test="${dp.status == 'VALID'}">

    This looks clean, but you're introducing a string that duplicates the enum value and cannot be validated by the compiler. So if you remove that value from the enum or rename it, you will not see that this part of code is not accessible anymore. You basically have to do a search/replace through the code each time.

  3. You can add each of the enum values you use into the page context:

    <c:set var="VALID" value="<%=Status.VALID%>"/>

    and then you can do this:

    <c:when test="${dp.status == VALID}">

I prefer the last option (3), even though it also uses a scriptlet. This is because it only uses it when you set the value. Later on you can use it in more complex EL expressions, together with other EL conditions. While in option (1) you cannot use a scriptlet and an EL expression in the test attribute of a single when tag.

Getting the closest string match

You might be interested in this blog post.

http://seatgeek.com/blog/dev/fuzzywuzzy-fuzzy-string-matching-in-python

Fuzzywuzzy is a Python library that provides easy distance measures such as Levenshtein distance for string matching. It is built on top of difflib in the standard library and will make use of the C implementation Python-levenshtein if available.

http://pypi.python.org/pypi/python-Levenshtein/

What is a NoReverseMatch error, and how do I fix it?

The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.

The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.

To start debugging it, you need to start by disecting the error message given to you.

  • NoReverseMatch at /my_url/

    This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched

  • Reverse for 'my_url_name'

    This is the name of the url that it cannot find

  • with arguments '()' and

    These are the non-keyword arguments its providing to the url

  • keyword arguments '{}' not found.

    These are the keyword arguments its providing to the url

  • n pattern(s) tried: []

    These are the patterns that it was able to find in your urls.py files that it tried to match against

Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.

Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you've recently changed.

Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.

The url name

  • Are there any typos?
  • Have you provided the url you're trying to access the given name?
  • If you have set app_name in the app's urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').

Arguments and Keyword Arguments

The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.

Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.

If they aren't correct:

  • The value is missing or an empty string

    This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.

  • The keyword argument has a typo

    Correct this either in the url pattern, or in the url you're constructing.

If they are correct:

  • Debug the regex

    You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.

    Common Mistakes:

    • Matching against the . wild card character or any other regex characters

      Remember to escape the specific characters with a \ prefix

    • Only matching against lower/upper case characters

      Try using either a-Z or \w instead of a-z or A-Z

  • Check that pattern you're matching is included within the patterns tried

    If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)

Django Version

In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.


If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.

POST unchecked HTML checkboxes

If you want to submit an array of checkbox values (including un-checked items) then you could try something like this:

<form>
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Dog
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Cat
</form>

$('form').submit(function(){
    $('input[type="checkbox"]:checked').prev().val(1);
});

AngularJS How to dynamically add HTML and bind to controller

For those, like me, who did not have the possibility to use angular directive and were "stuck" outside of the angular scope, here is something that might help you.

After hours searching on the web and on the angular doc, I have created a class that compiles HTML, place it inside a targets, and binds it to a scope ($rootScope if there is no $scope for that element)

/**
 * AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
 */
var AngularHelper = (function () {
    var AngularHelper = function () { };

    /**
     * ApplicationName : Default application name for the helper
     */
    var defaultApplicationName = "myApplicationName";

    /**
     * Compile : Compile html with the rootScope of an application
     *  and replace the content of a target element with the compiled html
     * @$targetDom : The dom in which the compiled html should be placed
     * @htmlToCompile : The html to compile using angular
     * @applicationName : (Optionnal) The name of the application (use the default one if empty)
     */
    AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
        var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);

        $injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
            //Get the scope of the target, use the rootScope if it does not exists
            var $scope = $targetDom.html(htmlToCompile).scope();
            $compile($targetDom)($scope || $rootScope);
            $rootScope.$digest();
        }]);
    }

    return AngularHelper;
})();

It covered all of my cases, but if you find something that I should add to it, feel free to comment or edit.

Hope it will help.

How to remove the first character of string in PHP?

The substr() function will probably help you here:

 $str = substr($str, 1);

Strings are indexed starting from 0, and this functions second parameter takes the cutstart. So make that 1, and the first char is gone.

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

Just solved the issue. After digging around for a while longer, I found this SO post which covers the exact same situation. It got me in the right track.

Basically, the XmlSerializer needs to know the default namespace if derived classes are included as extra types. The exact reason why this has to happen is still unknown but, still, serialization is working now.

Sorting Characters Of A C++ String

You have to include sort function which is in algorithm header file which is a standard template library in c++.

Usage: std::sort(str.begin(), str.end());

#include <iostream>
#include <algorithm>  // this header is required for std::sort to work
int main()
{
    std::string s = "dacb";
    std::sort(s.begin(), s.end());
    std::cout << s << std::endl;

    return 0;
}

OUTPUT:

abcd

How can I exclude all "permission denied" messages from "find"?

None of the above answers worked for me. Whatever I find on Internet focuses on: hide errors. None properly handles the process return-code / exit-code. I use command find within bash scripts to locate some directories and then inspect their content. I evaluate command find success using the exit-code: a value zero works, otherwise fails.

The answer provided above by Michael Brux works sometimes. But I have one scenario in which it fails! I discovered the problem and fixed it myself. I need to prune files when:

it is a directory AND has no read access AND/OR has no execute access

See the key issue here is: AND/OR. One good suggested condition sequence I read is:

-type d ! -readable ! -executable -prune

This does not work always. This means a prune is triggered when a match is:

it is directory AND no read access AND no execute access

This sequence of expressions fails when read access is granted but no execute access is.

After some testing I realized about that and changed my shell script solution to:

nice find /home*/ -maxdepth 5 -follow \
    \( -type d -a ! \( -readable -a -executable \) \) -prune \
    -o \
    \( -type d -a -readable -a -executable -a -name "${m_find_name}" \) -print

The key here is to place the "not true" for a combined expression:

has read access AND has execute access

Otherwise it has not full access, which means: prune it. This proved to work for me in one scenario which previous suggested solutions failed.

I provide below technical details for questions in the comments section. I apologize if details are excessive.

  • ¿Why using command nice? I got the idea here. Initially I thought it would be nice to reduce process priority when looking an entire filesystem. I realized it makes no sense to me, as my script is limited to few directories. I reduced -maxdepth to 3.
  • ¿Why search within /home*/? This it not relevant for this thread. I install all applications by hand via source code compile with non privileged users (not root). They are installed within "/home". I can have multiple binaries and versions living together. I need to locate all directories, inspect and backup in a master-slave fashion. I can have more than one "/home" (several disks running within a dedicated server).
  • ¿Why using -follow? Users might create symbolic links to directories. It's usefulness depends, I need to keep record of the absolute paths found.

Why is String immutable in Java?

From the Security point of view we can use this practical example:

DBCursor makeConnection(String IP,String PORT,String USER,String PASS,String TABLE) {

    // if strings were mutable IP,PORT,USER,PASS can be changed by validate function
    Boolean validated = validate(IP,PORT,USER,PASS);

    // here we are not sure if IP, PORT, USER, PASS changed or not ??
    if (validated) {
         DBConnection conn = doConnection(IP,PORT,USER,PASS);
    }

    // rest of the code goes here ....
}

How to get current class name including package name in Java?

The fully-qualified name is opbtained as follows:

String fqn = YourClass.class.getName();

But you need to read a classpath resource. So use

InputStream in = YourClass.getResourceAsStream("resource.txt");

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

NSDictionary   *dict = [NSDictionary dictionaryWithObject: @"String" forKey: @"Test"];
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionary];

[anotherDict setObject: dict forKey: "sub-dictionary-key"];
[anotherDict setObject: @"Another String" forKey: @"another test"];

NSLog(@"Dictionary: %@, Mutable Dictionary: %@", dict, anotherDict);

// now we can save these to a file
NSString   *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
[anotherDict writeToFile: savePath atomically: YES];

//and restore them
NSMutableDictionary  *restored = [NSDictionary dictionaryWithContentsOfFile: savePath];

git stash -> merge stashed change with current changes

Running git stash pop or git stash apply is essentially a merge. You shouldn't have needed to commit your current changes unless the files changed in the stash are also changed in the working copy, in which case you would've seen this error message:

error: Your local changes to the following files would be overwritten by merge:
       file.txt
Please, commit your changes or stash them before you can merge.
Aborting

In that case, you can't apply the stash to your current changes in one step. You can commit the changes, apply the stash, commit again, and squash those two commits using git rebase if you really don't want two commits, but that may be more trouble that it's worth.

What is the equivalent of the C# 'var' keyword in Java?

As of Java 10, the equivalent is ... var.

Getting started with OpenCV 2.4 and MinGW on Windows 7

As pointed out by @Nenad Bulatovic one has to be careful while adding libraries(19th step). one should not add any trailing spaces while adding each library line by line. otherwise mingw goes haywire.

How do I get countifs to select all non-blank cells in Excel?

If you are using multiple criteria, and want to count the number of non-blank cells in a particular column, you probably want to look at DCOUNTA.

e.g

  A   B   C   D  E   F   G
1 Dog Cat Cow    Dog Cat
2 x   1          x   1
3 x   2 
4 x   1   nb     Result:
5 x   2   nb     1

Formula in E5: =DCOUNTA(A1:C5,"Cow",E1:F2)

Dynamically load a JavaScript file

jquery resolved this for me with its .append() function - used this to load the complete jquery ui package

/*
 * FILENAME : project.library.js
 * USAGE    : loads any javascript library
 */
    var dirPath = "../js/";
    var library = ["functions.js","swfobject.js","jquery.jeditable.mini.js","jquery-ui-1.8.8.custom.min.js","ui/jquery.ui.core.min.js","ui/jquery.ui.widget.min.js","ui/jquery.ui.position.min.js","ui/jquery.ui.button.min.js","ui/jquery.ui.mouse.min.js","ui/jquery.ui.dialog.min.js","ui/jquery.effects.core.min.js","ui/jquery.effects.blind.min.js","ui/jquery.effects.fade.min.js","ui/jquery.effects.slide.min.js","ui/jquery.effects.transfer.min.js"];

    for(var script in library){
        $('head').append('<script type="text/javascript" src="' + dirPath + library[script] + '"></script>');
    }

To Use - in the head of your html/php/etc after you import jquery.js you would just include this one file like so to load in the entirety of your library appending it to the head...

<script type="text/javascript" src="project.library.js"></script>

Regex to get NUMBER only from String

Either [0-9] or \d1 should suffice if you only need a single digit. Append + if you need more.


1 The semantics are slightly different as \d potentially matches any decimal digit in any script out there that uses decimal digits.

How to access environment variable values?

If you are planning to use the code in a production web application code,
using any web framework like Django/Flask, use projects like envparse, using it you can read the value as your defined type.

from envparse import env
# will read WHITE_LIST=hello,world,hi to white_list = ["hello", "world", "hi"]
white_list = env.list("WHITE_LIST", default=[]) 
# Perfect for reading boolean
DEBUG = env.bool("DEBUG", default=False)

NOTE: kennethreitz's autoenv is a recommended tool for making project specific environment variables, please note that those who are using autoenv please keep the .env file private (inaccessible to public)

How do you copy and paste into Git Bash

Copy:

Long-term solution: Click on Topleft icon > Defaults > Select "QuickEdit Mode" under "Edit Options" > Okay

Then select the text you want to copy. Press Enter

Short-term solution: Click on Topleft icon > Edit > Mark. Press Enter.

Paste:

Press Insert

(If the "QuickEdit Mode" is on, Right clicking might work too.)

Find all table names with column name?

Try Like This: For SQL SERVER 2008+

SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyColumnaName%'

Or

SELECT COLUMN_NAME, TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE COLUMN_NAME LIKE '%MyName%'

Or Something Like This:

SELECT name  
FROM sys.tables 
WHERE OBJECT_ID IN ( SELECT id 
              FROM syscolumns 
              WHERE name like '%COlName%' )

How to delete files/subfolders in a specific directory at the command prompt in Windows

@ECHO OFF

SET THEDIR=path-to-folder

Echo Deleting all files from %THEDIR%
DEL "%THEDIR%\*" /F /Q /A

Echo Deleting all folders from %THEDIR%
FOR /F "eol=| delims=" %%I in ('dir "%THEDIR%\*" /AD /B 2^>nul') do rd /Q /S "%THEDIR%\%%I"
@ECHO Folder deleted.

EXIT

...deletes all files and folders underneath the given directory, but not the directory itself.

how to increase sqlplus column output length?

Try this

COLUMN col_name FORMAT A24

where 24 is you width.

How to change the sender's name or e-mail address in mutt?

One special case for this is if you have used a construction like the following in your ~/.muttrc:

# Reset From email to default
send-hook . "my_hdr From: Real Name <[email protected]>"

This send-hook will override either of these:

mutt -e "set [email protected]"
mutt -e "my_hdr From: Other Name <[email protected]>"

Your emails will still go out with the header:

From: Real Name <[email protected]>

In this case, the only command line solution I've found is actually overriding the send-hook itself:

mutt -e "send-hook . \"my_hdr From: Other Name <[email protected]>\""

How to transfer some data to another Fragment?

getArguments() is returning null because "Its doesn't get anything"

Try this code to handle this situation

if(getArguments()!=null)
{
int myInt = getArguments().getInt(key, defaultValue);
}

Generator expressions vs. list comprehensions

Python 3.7:

List comprehensions are faster.

enter image description here

Generators are more memory efficient. enter image description here

As all others have said, if you're looking to scale infinite data, you'll need a generator eventually. For relatively static small and medium-sized jobs where speed is necessary, a list comprehension is best.

Auto highlight text in a textbox control

It is very easy to achieve with built in method SelectAll

Simply cou can write this:

txtTextBox.Focus();
txtTextBox.SelectAll();

And everything in textBox will be selected :)

How do you express binary literals in Python?

For reference—future Python possibilities:
Starting with Python 2.6 you can express binary literals using the prefix 0b or 0B:

>>> 0b101111
47

You can also use the new bin function to get the binary representation of a number:

>>> bin(173)
'0b10101101'

Development version of the documentation: What's New in Python 2.6

SQL select everything in an array

// array of $ids that you need to select
$ids = array('1', '2', '3', '4', '5', '6', '7', '8');

// create sql part for IN condition by imploding comma after each id
$in = '(' . implode(',', $ids) .')';

// create sql
$sql = 'SELECT * FROM products WHERE catid IN ' . $in;

// see what you get
var_dump($sql);

Update: (a short version and update missing comma)

$ids = array('1','2','3','4');
$sql = 'SELECT * FROM products WHERE catid IN (' . implode(',', $ids) . ')';

How to access JSON Object name/value?

Try this code..

function (data) {


var json = jQuery.parseJSON(data);
alert( json.name );


}

Java Scanner class reading strings

The reason for the error is that the nextInt only pulls the integer, not the newline. If you add a in.nextLine() before your for loop, it will eat the empty new line and allow you to enter 3 names.

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();

names = new String[nnames];
in.nextLine();
for (int i = 0; i < names.length; i++){
        System.out.print("Type a name: ");
        names[i] = in.nextLine();
}

or just read the line and parse the value as an Integer.

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine().trim());

names = new String[nnames];
for (int i = 0; i < names.length; i++){
        System.out.print("Type a name: ");
        names[i] = in.nextLine();
}

How to edit default dark theme for Visual Studio Code?

The file you are looking for is at,

Microsoft VS Code\resources\app\extensions\theme-defaults\themes

on Windows and search for filename dark_vs.json to locate it on any other system.


Update:

With new versions of VSCode you don't need to hunt for the settings file to customize the theme. Now you can customize your color theme with the workbench.colorCustomizations and editor.tokenColorCustomizations user settings. Documentation on the matter can be found here.

Random color generator

With recursion:

var randomColor = (s='') => s.length === 6 ? '#' + s : randomColor(s + '0123456789ABCDEF'[Math.floor(Math.random() * 16)]);
randomColor();

Fatal error: Call to undefined function mb_strlen()

The function mb_strlen() is not enabled by default in PHP. Please read the manual for installation details:

http://www.php.net/manual/en/mbstring.installation.php

Ruby optional parameters

You are almost always better off using an options hash.

def ldap_get(base_dn, filter, options = {})
  options[:scope] ||= LDAP::LDAP_SCOPE_SUBTREE
  ...
end

ldap_get(base_dn, filter, :attrs => X)

Get a list of numbers as input from the user

a=[]
b=int(input())
for i in range(b):
    c=int(input())
    a.append(c)

The above code snippets is easy method to get values from the user.

CSS: On hover show and hide different div's at the same time?

http://jsfiddle.net/MBLZx/

Here is the code

_x000D_
_x000D_
 .showme{ _x000D_
   display: none;_x000D_
 }_x000D_
 .showhim:hover .showme{_x000D_
   display : block;_x000D_
 }_x000D_
 .showhim:hover .ok{_x000D_
   display : none;_x000D_
 }
_x000D_
 <div class="showhim">_x000D_
     HOVER ME_x000D_
     <div class="showme">hai</div>_x000D_
     <div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

jquery clear input default value

Just a shorthand

$(document).ready(function() {
    $(".input").val("Email Address");
        $(".input").on("focus click", function(){
            $(this).val("");
        });
    });
</script>

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

You could use pandas plot as @Bharath suggest:

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

Output:

enter image description here

Updated:

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

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

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

Output:

enter image description here

How do you get the process ID of a program in Unix or Linux using Python?

With psutil:

(can be installed with [sudo] pip install psutil)

import psutil

# Get current process pid
current_process_pid = psutil.Process().pid
print(current_process_pid)  # e.g 12971

# Get pids by program name
program_name = 'chrome'
process_pids = [process.pid for process in psutil.process_iter() if process.name == program_name]
print(process_pids)  # e.g [1059, 2343, ..., ..., 9645]

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/

illegal character in path

You seem to have the quote marks (") embedded in your string at the start and the end. These are not needed and are illegal characters in a path. How are you initializing the string with the path?

This can be seen from the debugger visualizer, as the string starts with "\" and ends with \"", it shows that the quotes are part of the string, when they shouldn't be.

You can do two thing - a regular escaped string (using \) or a verbatim string literal (that starts with a @):

  string str = "C:\\Program Files (x86)\\test software\\myapp\\demo.exe";

Or:

  string verbatim = @"C:\Program Files (x86)\test software\myapp\demo.exe";

Set Windows process (or user) memory limit

Depending on your applications, it might be easier to limit the memory the language interpreter uses. For example with Java you can set the amount of RAM the JVM will be allocated.

Otherwise it is possible to set it once for each process with the windows API

SetProcessWorkingSetSize Function

angular2 submit form by pressing enter without submit button

Edit:

  <form (submit)="submit()" >
    <input />
    <button type="submit" style="display:none">hidden submit</button>
  </form>

In order to use this method, you need to have a submit button even if it's not displayed "Thanks for Toolkit's answer"

Old Answer:

Yes, exactly as you wrote it, except the event name is (submit) instead of (ngSubmit):

<form [ngFormModel]="xxx" (submit)="xxxx()">
  <input [(ngModel)]="lxxR"   ngControl="xxxxx"/>
</form>

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

You need a web.config key to enable the pre 4.5 validation mode.

More Info on ValidationSettings:UnobtrusiveValidationMode:

Specifies how ASP.NET globally enables the built-in validator controls to use unobtrusive JavaScript for client-side validation logic.

Type: UnobtrusiveValidationMode

Default value: None

Remarks: If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic. If this key value is set to "WebForms", ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.

Example:

    <appSettings>
      <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    </appSettings>

Error: allowDefinition='MachineToApplication' beyond application level

I have a website project.

In my case I had moved the solution file to another path and that cause the problem. I restored it to the previous location and the problem went out.

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

UPDATE  table
SET     columnx = CASE WHEN condition THEN 25 ELSE columnx END,
        columny = CASE WHEN condition THEN columny ELSE 25 END

Format number to always show 2 decimal places

I do like:

var num = 12.749;
parseFloat((Math.round(num * 100) / 100).toFixed(2)); // 123.75

Round the number with 2 decimal points, then make sure to parse it with parseFloat() to return Number, not String unless you don't care if it is String or Number.

What is the difference between git clone and checkout?

Simply git checkout have 2 uses

  1. Switching between existing local branches like git checkout <existing_local_branch_name>
  2. Create a new branch from current branch using flag -b. Suppose if you are at master branch then git checkout -b <new_feature_branch_name> will create a new branch with the contents of master and switch to newly created branch

You can find more options at the official site

Java collections convert a string to a list of characters

You can do this without boxing if you use Eclipse Collections:

CharAdapter abc = Strings.asChars("abc");
CharList list = abc.toList();
CharSet set = abc.toSet();
CharBag bag = abc.toBag();

Because CharAdapter is an ImmutableCharList, calling collect on it will return an ImmutableList.

ImmutableList<Character> immutableList = abc.collect(Character::valueOf);

If you want to return a boxed List, Set or Bag of Character, the following will work:

LazyIterable<Character> lazyIterable = abc.asLazy().collect(Character::valueOf);
List<Character> list = lazyIterable.toList();
Set<Character> set = lazyIterable.toSet();
Bag<Character> set = lazyIterable.toBag();

Note: I am a committer for Eclipse Collections.

Sending HTTP POST Request In Java

Updated Answer:

Since some of the classes, in the original answer, are deprecated in the newer version of Apache HTTP Components, I'm posting this update.

By the way, you can access the full documentation for more examples here.

HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/");

// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

if (entity != null) {
    try (InputStream instream = entity.getContent()) {
        // do something useful
    }
}

Original Answer:

I recommend to use Apache HttpClient. its faster and easier to implement.

HttpPost post = new HttpPost("http://jakarata.apache.org/");
NameValuePair[] data = {
    new NameValuePair("user", "joe"),
    new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.

for more information check this url: http://hc.apache.org/

Is there a RegExp.escape function in JavaScript?

There has only ever been and ever will be 12 meta characters that need to be escaped to be considered a literal.

It doesn't matter what is done with the escaped string, inserted into a balanced regex wrapper or appended. It doesn't matter.

Do a string replace using this

var escaped_string = oldstring.replace(/[\\^$.|?*+()[{]/g, '\\$&');

Convert json data to a html table

I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.

Demo

_x000D_
_x000D_
var _table_ = document.createElement('table'),_x000D_
  _tr_ = document.createElement('tr'),_x000D_
  _th_ = document.createElement('th'),_x000D_
  _td_ = document.createElement('td');_x000D_
_x000D_
// Builds the HTML Table out of myList json data from Ivy restful service._x000D_
function buildHtmlTable(arr) {_x000D_
  var table = _table_.cloneNode(false),_x000D_
    columns = addAllColumnHeaders(arr, table);_x000D_
  for (var i = 0, maxi = arr.length; i < maxi; ++i) {_x000D_
    var tr = _tr_.cloneNode(false);_x000D_
    for (var j = 0, maxj = columns.length; j < maxj; ++j) {_x000D_
      var td = _td_.cloneNode(false);_x000D_
      cellValue = arr[i][columns[j]];_x000D_
      td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));_x000D_
      tr.appendChild(td);_x000D_
    }_x000D_
    table.appendChild(tr);_x000D_
  }_x000D_
  return table;_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records_x000D_
function addAllColumnHeaders(arr, table) {_x000D_
  var columnSet = [],_x000D_
    tr = _tr_.cloneNode(false);_x000D_
  for (var i = 0, l = arr.length; i < l; i++) {_x000D_
    for (var key in arr[i]) {_x000D_
      if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {_x000D_
        columnSet.push(key);_x000D_
        var th = _th_.cloneNode(false);_x000D_
        th.appendChild(document.createTextNode(key));_x000D_
        tr.appendChild(th);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  table.appendChild(tr);_x000D_
  return columnSet;_x000D_
}_x000D_
_x000D_
document.body.appendChild(buildHtmlTable([{_x000D_
    "name": "abc",_x000D_
    "age": 50_x000D_
  },_x000D_
  {_x000D_
    "age": "25",_x000D_
    "hobby": "swimming"_x000D_
  },_x000D_
  {_x000D_
    "name": "xyz",_x000D_
    "hobby": "programming"_x000D_
  }_x000D_
]));
_x000D_
_x000D_
_x000D_

HTTP Status 405 - Method Not Allowed Error for Rest API

You might be doing a PUT call for GET operation Please check once

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

How do I force git pull to overwrite everything on every pull?

You can change the hook to wipe everything clean.

# Danger! Wipes local data!

# Remove all local changes to tracked files
git reset --hard HEAD

# Remove all untracked files and directories
git clean -dfx

git pull ...

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

I had the same problem. For some reason --initialize did not work. After about 5 hours of trial and error with different parameters, configs and commands I found out that the problem was caused by the file system.

I wanted to run a database on a large USB HDD drive. Drives larger than 2 TB are GPT partitioned! Here is a bug report with a solution:

https://bugs.mysql.com/bug.php?id=28913

In short words: Add the following line to your my.ini:

innodb_flush_method=normal

I had this problem with mysql 5.7 on Windows.

Vim: faster way to select blocks of text in visual mode

It could come in handy to know:

In order to select the same ammount of lines for example use 1v You should have done some modification to be able to use 1v, blockwise or linewise.

Today I saw this amazing tip from here:

 :5mark < | 10mark > | normal gvV
 :5mark < | 10mark > | normal gv

You can also reset the visual block boundaries doing so:

m< .......... sets the visual mode start point
m> .......... sets the visual mode end point

How to hide a button programmatically?

Hidde:

BUTTON.setVisibility(View.GONE);

Show:

BUTTON.setVisibility(View.VISIBLE);

The thread has exited with code 0 (0x0) with no unhandled exception

Well, an application may have a lot of threads running in parallel. Some are run by you, the coder, some are run by framework classes (espacially if you are in a GUI environnement).

When a thread has finished its task, it exits and stops to exist. There ie nothing alarming in this and you should not care.

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

Live search through table rows

Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start. Check the mysql query in php. It matches the pattern starting from first.

See live demo and source code here.

http://purpledesign.in/blog/to-create-a-live-search-like-google/

Create a search box, may be an input field like this.

<input type="text" id="search" autocomplete="off">

Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.

Suppose we have the html like this. We have an input field and a list to display the results.

 <div class="icon"></div>
 <input type="text" id="search" autocomplete="off">
 <ul id="results"></ul>

We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.

Here is the JQuery.

$(document).ready(function() {  

    // Icon Click Focus
    $('div.icon').click(function(){
        $('input#search').focus();
    });

    //Listen for the event
    $("input#search").live("keyup", function(e) {
    // Set Timeout
    clearTimeout($.data(this, 'timer'));

    // Set Search String
    var search_string = $(this).val();

    // Do Search
    if (search_string == '') {
        $("ul#results").fadeOut();
        $('h4#results-text').fadeOut();
    }else{
        $("ul#results").fadeIn();
        $('h4#results-text').fadeIn();
        $(this).data('timer', setTimeout(search, 100));
    };
});


// Live Search
// On Search Submit and Get Results
function search() {
    var query_value = $('input#search').val();
    $('b#search-string').html(query_value);
    if(query_value !== ''){
        $.ajax({
            type: "POST",
            url: "search_st.php",
            data: { query: query_value },
            cache: false,
            success: function(html){
                $("ul#results").html(html);

            }
        });
    }return false;    
}

}); In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.

Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.

//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";

//  Connection
global $tutorial_db;

$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");

//  Check Connection
if ($tutorial_db->connect_errno) {
    printf("Connect failed: %s\n", $tutorial_db->connect_error);
    exit();

$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';

$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);

// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
    // Build Query
    $query = "SELECT *
        FROM animals
        WHERE type REGEXP '^".$search_string."'
        UNION ALL SELECT *
        FROM birf
        WHERE type REGEXP '^".$search_string."'"
        ;

$result = $tutorial_db->query($query);
    while($results = $result->fetch_array()) {
        $result_array[] = $results;
    }

    // Check If We Have Results
    if (isset($result_array)) {
        foreach ($result_array as $result) {

            // Format Output Strings And Hightlight Matches
            $display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
            $display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
        $display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';

            // Insert Name
            $output = str_replace('nameString', $display_name, $html);

            // Insert Description
            $output = str_replace('functionString', $display_function, $output);

            // Insert URL
            $output = str_replace('urlString', $display_url, $output);



            // Output
            echo($output);
        }
    }else{

        // Format No Results Output
        $output = str_replace('urlString', 'javascript:void(0);', $html);
        $output = str_replace('nameString', '<b>No Results Found.</b>', $output);
        $output = str_replace('functionString', 'Sorry :(', $output);

        // Output
        echo($output);
    }
}

Creating an instance of class

   /* 1 */ Foo* foo1 = new Foo ();

Creates an object of type Foo in dynamic memory. foo1 points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If Foo was a POD-type, this would perform value-initialization (it doesn't apply here).

   /* 2 */ Foo* foo2 = new Foo;

Identical to before, because Foo is not a POD type.

   /* 3 */ Foo foo3;

Creates a Foo object called foo3 in automatic storage.

   /* 4 */ Foo foo4 = Foo::Foo();

Uses copy-initialization to create a Foo object called foo4 in automatic storage.

   /* 5 */ Bar* bar1 = new Bar ( *new Foo() );

Uses Bar's conversion constructor to create an object of type Bar in dynamic storage. bar1 is a pointer to it.

   /* 6 */ Bar* bar2 = new Bar ( *new Foo );

Same as before.

   /* 7 */ Bar* bar3 = new Bar ( Foo foo5 );

This is just invalid syntax. You can't declare a variable there.

   /* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );

Would work and work by the same principle to 5 and 6 if bar3 wasn't declared on in 7.

5 & 6 contain memory leaks.

Syntax like new Bar ( Foo::Foo() ); is not usual. It's usually new Bar ( (Foo()) ); - extra parenthesis account for most-vexing parse. (corrected)

ExpressionChangedAfterItHasBeenCheckedError Explained

Here's my thoughts on what is happening. I have not read the documentation but am sure this is part of why the error is shown.

*ngIf="isProcessing()" 

When using *ngIf, it physically changes the DOM by adding or removing the element every time the condition changes. So if the condition changes before it is rendered to the view (which is highly possible in Angular's world), the error is thrown. See explanation here between development and production modes.

[hidden]="isProcessing()"

When using [hidden] it does not physically change the DOM but merely hiding the element from the view, most likely using CSS in the back. The element is still there in the DOM but not visible depending on the condition's value. That is why the error will not occur when using [hidden].

LINQ: Distinct values

Just use the Distinct() with your own comparer.

http://msdn.microsoft.com/en-us/library/bb338049.aspx

C# Error "The type initializer for ... threw an exception

I had this problem and like Anderson Imes said it had to do with app settings. My problem was the scope of one of my settings was set to "User" when it should have been "Application".

How to get all enum values in Java?

One can also use the java.util.EnumSet like this

@Test
void test(){
    Enum aEnum =DayOfWeek.MONDAY;
    printAll(aEnum);
}

void printAll(Enum value){
    Set allValues = EnumSet.allOf(value.getClass());
    System.out.println(allValues);
}

What's the difference between setWebViewClient vs. setWebChromeClient?

WebViewClient provides the following callback methods, with which you can interfere in how WebView makes a transition to the next content.

void doUpdateVisitedHistory (WebView view, String url, boolean isReload)
void onFormResubmission (WebView view, Message dontResend, Message resend)
void onLoadResource (WebView view, String url)
void onPageCommitVisible (WebView view, String url)
void onPageFinished (WebView view, String url)
void onPageStarted (WebView view, String url, Bitmap favicon)
void onReceivedClientCertRequest (WebView view, ClientCertRequest request)
void onReceivedError (WebView view, int errorCode, String description, String failingUrl)
void onReceivedError (WebView view, WebResourceRequest request, WebResourceError error)
void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm)
void onReceivedHttpError (WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
void onReceivedLoginRequest (WebView view, String realm, String account, String args)
void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error)
boolean onRenderProcessGone (WebView view, RenderProcessGoneDetail detail)
void onSafeBrowsingHit (WebView view, WebResourceRequest request, int threatType, SafeBrowsingResponse callback)
void onScaleChanged (WebView view, float oldScale, float newScale)
void onTooManyRedirects (WebView view, Message cancelMsg, Message continueMsg)
void onUnhandledKeyEvent (WebView view, KeyEvent event)
WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request)
WebResourceResponse shouldInterceptRequest (WebView view, String url)
boolean shouldOverrideKeyEvent (WebView view, KeyEvent event)
boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request)
boolean shouldOverrideUrlLoading (WebView view, String url)

WebChromeClient provides the following callback methods, with which your Activity or Fragment can update the surroundings of WebView.

Bitmap getDefaultVideoPoster ()
View getVideoLoadingProgressView ()
void getVisitedHistory (ValueCallback<String[]> callback)
void onCloseWindow (WebView window)
boolean onConsoleMessage (ConsoleMessage consoleMessage)
void onConsoleMessage (String message, int lineNumber, String sourceID)
boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg)
void onExceededDatabaseQuota (String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, WebStorage.QuotaUpdater quotaUpdater)
void onGeolocationPermissionsHidePrompt ()
void onGeolocationPermissionsShowPrompt (String origin, GeolocationPermissions.Callback callback)
void onHideCustomView ()
boolean onJsAlert (WebView view, String url, String message, JsResult result)
boolean onJsBeforeUnload (WebView view, String url, String message, JsResult result)
boolean onJsConfirm (WebView view, String url, String message, JsResult result)
boolean onJsPrompt (WebView view, String url, String message, String defaultValue, JsPromptResult result)
boolean onJsTimeout ()
void onPermissionRequest (PermissionRequest request)
void onPermissionRequestCanceled (PermissionRequest request)
void onProgressChanged (WebView view, int newProgress)
void onReachedMaxAppCacheSize (long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater)
void onReceivedIcon (WebView view, Bitmap icon)
void onReceivedTitle (WebView view, String title)
void onReceivedTouchIconUrl (WebView view, String url, boolean precomposed)
void onRequestFocus (WebView view)
void onShowCustomView (View view, int requestedOrientation, WebChromeClient.CustomViewCallback callback)
void onShowCustomView (View view, WebChromeClient.CustomViewCallback callback)
boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)

Convert string to title case with JavaScript

I wanted to add my own answer as I needed a robust toTitleCase function that takes into account grammar rules listed here (Google recommended article). There are various rules that depend on the length of the input string. Below is the function + unit tests.

The function also consolidates whitespace and removes special characters (modify regex for your needs)

toTitleCase Function

const toTitleCase = (str) => {
  const articles = ['a', 'an', 'the'];
  const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];
  const prepositions = [
    'with', 'at', 'from', 'into','upon', 'of', 'to', 'in', 'for',
    'on', 'by', 'like', 'over', 'plus', 'but', 'up', 'down', 'off', 'near'
  ];

  // The list of spacial characters can be tweaked here
  const replaceCharsWithSpace = (str) => str.replace(/[^0-9a-z&/\\]/gi, ' ').replace(/(\s\s+)/gi, ' ');
  const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.substr(1);
  const normalizeStr = (str) => str.toLowerCase().trim();
  const shouldCapitalize = (word, fullWordList, posWithinStr) => {
    if ((posWithinStr == 0) || (posWithinStr == fullWordList.length - 1)) {
      return true;
    }

    return !(articles.includes(word) || conjunctions.includes(word) || prepositions.includes(word));
  }

  str = replaceCharsWithSpace(str);
  str = normalizeStr(str);

  let words = str.split(' ');
  if (words.length <= 2) { // Strings less than 3 words long should always have first words capitalized
    words = words.map(w => capitalizeFirstLetter(w));
  }
  else {
    for (let i = 0; i < words.length; i++) {
      words[i] = (shouldCapitalize(words[i], words, i) ? capitalizeFirstLetter(words[i], words, i) : words[i]);
    }
  }

  return words.join(' ');
}

Unit Tests to Ensure Correctness

import { expect } from 'chai';
import { toTitleCase } from '../../src/lib/stringHelper';

describe('toTitleCase', () => {
  it('Capitalizes first letter of each word irrespective of articles, conjunctions or prepositions if string is no greater than two words long', function(){
    expect(toTitleCase('the dog')).to.equal('The Dog'); // Capitalize articles when only two words long
    expect(toTitleCase('for all')).to.equal('For All'); // Capitalize conjunctions when only two words long
    expect(toTitleCase('with cats')).to.equal('With Cats'); // Capitalize prepositions when only two words long
  });

  it('Always capitalize first and last words in a string irrespective of articles, conjunctions or prepositions', function(){
    expect(toTitleCase('the beautiful dog')).to.equal('The Beautiful Dog');
    expect(toTitleCase('for all the deadly ninjas, be it so')).to.equal('For All the Deadly Ninjas Be It So');
    expect(toTitleCase('with cats and dogs we are near')).to.equal('With Cats and Dogs We Are Near');
  });

  it('Replace special characters with space', function(){
    expect(toTitleCase('[wolves & lions]: be careful')).to.equal('Wolves & Lions Be Careful');
    expect(toTitleCase('wolves & lions, be careful')).to.equal('Wolves & Lions Be Careful');
  });

  it('Trim whitespace at beginning and end', function(){
    expect(toTitleCase(' mario & Luigi superstar saga ')).to.equal('Mario & Luigi Superstar Saga');
  });

  it('articles, conjunctions and prepositions should not be capitalized in strings of 3+ words', function(){
    expect(toTitleCase('The wolf and the lion: a tale of two like animals')).to.equal('The Wolf and the Lion a Tale of Two like Animals');
    expect(toTitleCase('the  three Musketeers  And plus ')).to.equal('The Three Musketeers and Plus');
  });
});

Please note that I am removing quite a bit of special characters from the strings provided. You will need to tweak the regex to address the requirements of your project.

Using isKindOfClass with Swift

The proper Swift operator is is:

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}

Of course, if you also need to assign the view to a new constant, then the if let ... as? ... syntax is your boy, as Kevin mentioned. But if you don't need the value and only need to check the type, then you should use the is operator.

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

add this:

 ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;}

right before the line that you're calling the service

HTML CSS Invisible Button

button {
    background:transparent;
    border:none;
    outline:none;
    display:block;
    height:200px;
    width:200px;
    cursor:pointer;
}

Give the height and width with respect to the image in the background.This removes the borders and color of a button.You might also need to position it absolute so you can correctly place it where you need.I cant help you further without posting you code

To make it truly invisible you have to set outline:none; otherwise there would be a blue outline in some browsers and you have to set display:block if you need to click it and set dimensions to it

String split on new line, tab and some number of spaces

>>> for line in s.splitlines():
...     line = line.strip()
...     if not line:continue
...     ary.append(line.split(":"))
...
>>> ary
[['Name', ' John Smith'], ['Home', ' Anytown USA'], ['Misc', ' Data with spaces'
]]
>>> dict(ary)
{'Home': ' Anytown USA', 'Misc': ' Data with spaces', 'Name': ' John Smith'}
>>>

Remove last character of a StringBuilder?

Another alternative

for(String serverId : serverIds) {
   sb.append(",");
   sb.append(serverId); 
}
sb.deleteCharAt(0);

Django - limiting query results

As an addition and observation to the other useful answers, it's worth noticing that actually doing [:10] as slicing will return the first 10 elements of the list, not the last 10...

To get the last 10 you should do [-10:] instead (see here). This will help you avoid using order_by('-id') with the - to reverse the elements.

Why would we call cin.clear() and cin.ignore() after reading input?

Why do we use:

1) cin.ignore

2) cin.clear

?

Simply:

1) To ignore (extract and discard) values that we don't want on the stream

2) To clear the internal state of stream. After using cin.clear internal state is set again back to goodbit, which means that there are no 'errors'.

Long version:

If something is put on 'stream' (cin) then it must be taken from there. By 'taken' we mean 'used', 'removed', 'extracted' from stream. Stream has a flow. The data is flowing on cin like water on stream. You simply cannot stop the flow of water ;)

Look at the example:

string name; //line 1
cout << "Give me your name and surname:"<<endl;//line 2
cin >> name;//line 3
int age;//line 4
cout << "Give me your age:" <<endl;//line 5
cin >> age;//line 6

What happens if the user answers: "Arkadiusz Wlodarczyk" for first question?

Run the program to see for yourself.

You will see on console "Arkadiusz" but program won't ask you for 'age'. It will just finish immediately right after printing "Arkadiusz".

And "Wlodarczyk" is not shown. It seems like if it was gone (?)*

What happened? ;-)

Because there is a space between "Arkadiusz" and "Wlodarczyk".

"space" character between the name and surname is a sign for computer that there are two variables waiting to be extracted on 'input' stream.

The computer thinks that you are tying to send to input more than one variable. That "space" sign is a sign for him to interpret it that way.

So computer assigns "Arkadiusz" to 'name' (2) and because you put more than one string on stream (input) computer will try to assign value "Wlodarczyk" to variable 'age' (!). The user won't have a chance to put anything on the 'cin' in line 6 because that instruction was already executed(!). Why? Because there was still something left on stream. And as I said earlier stream is in a flow so everything must be removed from it as soon as possible. And the possibility came when computer saw instruction cin >> age;

Computer doesn't know that you created a variable that stores age of somebody (line 4). 'age' is merely a label. For computer 'age' could be as well called: 'afsfasgfsagasggas' and it would be the same. For him it's just a variable that he will try to assign "Wlodarczyk" to because you ordered/instructed computer to do so in line (6).

It's wrong to do so, but hey it's you who did it! It's your fault! Well, maybe user, but still...


All right all right. But how to fix it?!

Let's try to play with that example a bit before we fix it properly to learn a few more interesting things :-)

I prefer to make an approach where we understand things. Fixing something without knowledge how we did it doesn't give satisfaction, don't you think? :)

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate(); //new line is here :-)

After invoking above code you will notice that the state of your stream (cin) is equal to 4 (line 7). Which means its internal state is no longer equal to goodbit. Something is messed up. It's pretty obvious, isn't it? You tried to assign string type value ("Wlodarczyk") to int type variable 'age'. Types doesn't match. It's time to inform that something is wrong. And computer does it by changing internal state of stream. It's like: "You f**** up man, fix me please. I inform you 'kindly' ;-)"

You simply cannot use 'cin' (stream) anymore. It's stuck. Like if you had put big wood logs on water stream. You must fix it before you can use it. Data (water) cannot be obtained from that stream(cin) anymore because log of wood (internal state) doesn't allow you to do so.

Oh so if there is an obstacle (wood logs) we can just remove it using tools that is made to do so?

Yes!

internal state of cin set to 4 is like an alarm that is howling and making noise.

cin.clear clears the state back to normal (goodbit). It's like if you had come and silenced the alarm. You just put it off. You know something happened so you say: "It's OK to stop making noise, I know something is wrong already, shut up (clear)".

All right let's do so! Let's use cin.clear().

Invoke below code using "Arkadiusz Wlodarczyk" as first input:

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl; 
cin.clear(); //new line is here :-)
cout << cin.rdstate()<< endl;  //new line is here :-)

We can surely see after executing above code that the state is equal to goodbit.

Great so the problem is solved?

Invoke below code using "Arkadiusz Wlodarczyk" as first input:

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;; 
cin.clear(); 
cout << cin.rdstate() << endl; 
cin >> age;//new line is here :-)

Even tho the state is set to goodbit after line 9 the user is not asked for "age". The program stops.

WHY?!

Oh man... You've just put off alarm, what about the wood log inside a water?* Go back to text where we talked about "Wlodarczyk" how it supposedly was gone.

You need to remove "Wlodarczyk" that piece of wood from stream. Turning off alarms doesn't solve the problem at all. You've just silenced it and you think the problem is gone? ;)

So it's time for another tool:

cin.ignore can be compared to a special truck with ropes that comes and removes the wood logs that got the stream stuck. It clears the problem the user of your program created.

So could we use it even before making the alarm goes off?

Yes:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;

The "Wlodarczyk" is gonna be removed before making the noise in line 7.

What is 10000 and '\n'?

It says remove 10000 characters (just in case) until '\n' is met (ENTER). BTW It can be done better using numeric_limits but it's not the topic of this answer.


So the main cause of problem is gone before noise was made...

Why do we need 'clear' then?

What if someone had asked for 'give me your age' question in line 6 for example: "twenty years old" instead of writing 20?

Types doesn't match again. Computer tries to assign string to int. And alarm starts. You don't have a chance to even react on situation like that. cin.ignore won't help you in case like that.

So we must use clear in case like that:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow

But should you clear the state 'just in case'?

Of course not.

If something goes wrong (cin >> age;) instruction is gonna inform you about it by returning false.

So we can use conditional statement to check if the user put wrong type on the stream

int age;
if (cin >> age) //it's gonna return false if types doesn't match
    cout << "You put integer";
else
    cout << "You bad boy! it was supposed to be int";

All right so we can fix our initial problem like for example that:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow

int age;
cout << "Give me your age:" << endl;
if (cin >> age)
  cout << "Your age is equal to:" << endl;
else
{
 cin.clear();
 cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
 cout << "Give me your age name as string I dare you";
 cin >> age;
}

Of course this can be improved by for example doing what you did in question using loop while.

BONUS:

You might be wondering. What about if I wanted to get name and surname in the same line from the user? Is it even possible using cin if cin interprets each value separated by "space" as different variable?

Sure, you can do it two ways:

1)

string name, surname;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin >> surname;

cout << "Hello, " << name << " " << surname << endl;

2) or by using getline function.

getline(cin, nameOfStringVariable);

and that's how to do it:

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

The second option might backfire you in case you use it after you use 'cin' before the getline.

Let's check it out:

a)

int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endl;

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

If you put "20" as age you won't be asked for nameAndSurname.

But if you do it that way:

b)

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endll

everything is fine.

WHAT?!

Every time you put something on input (stream) you leave at the end white character which is ENTER ('\n') You have to somehow enter values to console. So it must happen if the data comes from user.

b) cin characteristics is that it ignores whitespace, so when you are reading in information from cin, the newline character '\n' doesn't matter. It gets ignored.

a) getline function gets the entire line up to the newline character ('\n'), and when the newline char is the first thing the getline function gets '\n', and that's all to get. You extract newline character that was left on stream by user who put "20" on stream in line 3.

So in order to fix it is to always invoke cin.ignore(); each time you use cin to get any value if you are ever going to use getline() inside your program.

So the proper code would be:

int age;
cout << "Give me your age:" <<endl;
cin >> age;
cin.ignore(); // it ignores just enter without arguments being sent. it's same as cin.ignore(1, '\n') 
cout << "Your age is" << age << endl;


string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

I hope streams are more clear to you know.

Hah silence me please! :-)

Uploading both data and files in one form using Ajax?

For me following code work

$(function () {
    debugger;
    document.getElementById("FormId").addEventListener("submit", function (e) {
        debugger;
        if (ValidDateFrom()) { // Check Validation 
            var form = e.target;
            if (form.getAttribute("enctype") === "multipart/form-data") {
                debugger;
                if (form.dataset.ajax) {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    var xhr = new XMLHttpRequest();
                    xhr.open(form.method, form.action);
                    xhr.onreadystatechange = function (result) {
                        debugger;
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            debugger;
                            var responseData = JSON.parse(xhr.responseText);
                            SuccessMethod(responseData); // Redirect to your Success method 
                        }
                    };
                    xhr.send(new FormData(form));
                }
            }
        }
    }, true);
});

In your Action Post Method, pass parameter as HttpPostedFileBase UploadFile and make sure your file input has same as mentioned in your parameter of the Action Method. It should work with AJAX Begin form as well.

Remember over here that your AJAX BEGIN Form will not work over here since you make your post call defined in the code mentioned above and you can reference your method in the code as per the Requirement

I know I am answering late but this is what worked for me

Better way of getting time in milliseconds in javascript?

As far that I know you only can get time with Date.

Date.now is the solution but is not available everywhere : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now.

var currentTime = +new Date();

This gives you the current time in milliseconds.

For your jumps. If you compute interpolations correctly according to the delta frame time and you don't have some rounding number error, I bet for the garbage collector (GC).

If there is a lot of created temporary object in your loop, garbage collection has to lock the thread to make some cleanup and memory re-organization.

With Chrome you can see how much time the GC is spending in the Timeline panel.

EDIT: Since my answer, Date.now() should be considered as the best option as it is supported everywhere and on IE >= 9.

Declaring and initializing arrays in C

Why can't you initialize when you declare?

Which C compiler are you using? Does it support C99?

If it does support C99, you can declare the variable where you need it and initialize it when you declare it.

The only excuse I can think of for not doing that would be because you need to declare it but do an early exit before using it, so the initializer would be wasted. However, I suspect that any such code is not as cleanly organized as it should be and could be written so it was not a problem.

What is IllegalStateException?

Usually, IllegalStateException is used to indicate that "a method has been invoked at an illegal or inappropriate time." However, this doesn't look like a particularly typical use of it.

The code you've linked to shows that it can be thrown within that code at line 259 - but only after dumping a SQLException to standard output.

We can't tell what's wrong just from that exception - and better code would have used the original SQLException as a "cause" exception (or just let the original exception propagate up the stack) - but you should be able to see more details on standard output. Look at that information, and you should be able to see what caused the exception, and fix it.

How to update RecyclerView Adapter Data?

If nothing mentioned in the above comments is working for you. It might mean the problem lies somewhere else.

One place I found the solution was in the way I was setting the list to the adapter. In my activity the list was a instance variable and I was changing it directly when any data changed. Due to it being a reference variable there was something weird going on. So I changed the reference variable to a local one and used another variable to update data and then pass to addAll() function mentioned in above answers.

How to measure the a time-span in seconds using System.currentTimeMillis()?

TimeUnit

Use the TimeUnit enum built into Java 5 and later.

long timeMillis = System.currentTimeMillis();
long timeSeconds = TimeUnit.MILLISECONDS.toSeconds(timeMillis);

Safe String to BigDecimal conversion

Here is how I would do it:

public String cleanDecimalString(String input, boolean americanFormat) {
    if (americanFormat)
        return input.replaceAll(",", "");
    else
        return input.replaceAll(".", "");
}

Obviously, if this were going in production code, it wouldn't be that simple.

I see no issue with simply removing the commas from the String.

Expected block end YAML error

This error also occurs if you use four-space instead of two-space indentation.

e.g., the following would throw the error:

fields:
    - metadata: {}
        name: colName
        nullable: true

whereas changing indentation to two-spaces would fix it:

fields:
  - metadata: {}
    name: colName
    nullable: true

Using set_facts and with_items together in Ansible

As mentioned in other people's comments, the top solution given here was not working for me in Ansible 2.2, particularly when also using with_items.

It appears that OP's intended approach does work now with a slight change to the quoting of item.

- set_fact: something="{{ something + [ item ] }}"
  with_items:
    - one
    - two
    - three

And a longer example where I've handled the initial case of the list being undefined and added an optional when because that was also causing me grief:

- set_fact: something="{{ something|default([]) + [ item ] }}"
  with_items:
    - one
    - two
    - three
  when: item.name in allowed_things.item_list

Command to list all files in a folder as well as sub-folders in windows

The below post gives the solution for your scenario.

dir /s /b /o:gn

/S Displays files in specified directory and all subdirectories.

/B Uses bare format (no heading information or summary).

/O List by files in sorted order.

SQL: How do I SELECT only the rows with a unique value on certain column?

Here is another option using sql servers count distinct:

DECLARE  @T TABLE( [contract] INT, project INT, activity INT )
INSERT INTO @T VALUES( 1000,    8000,    10 )
INSERT INTO @T VALUES( 1000,    8000,    20 )
INSERT INTO @T VALUES( 1000,    8001,    10 )
INSERT INTO @T VALUES( 2000,    9000,    49 )
INSERT INTO @T VALUES( 2000,    9001,    49 )
INSERT INTO @T VALUES( 3000,    9000,    79 )
INSERT INTO @T VALUES( 3000,    9000,    78 )



SELECT DISTINCT [contract], activity FROM @T AS A WHERE
    (SELECT COUNT( DISTINCT activity ) 
     FROM @T AS B WHERE B.[contract] = A.[contract]) = 1

Node.js global proxy setting

I finally created a module to get this question (partially) resolved. Basically this module rewrites http.request function, added the proxy setting then fire. Check my blog post: https://web.archive.org/web/20160110023732/http://blog.shaunxu.me:80/archive/2013/09/05/semi-global-proxy-setting-for-node.js.aspx

How to style a disabled checkbox?

Checkboxes (radio buttons and <select>) are OS-level components, not browser-level. You cannot reliably style them in a manner that will be consistent across browsers and operating systems.

Your best bet it to put an overlay on top and style that instead.

How do I set the value property in AngularJS' ng-options?

For me the answer by Bruno Gomes is the best answer.

But actually, you need not worry about setting the value property of select options. AngularJS will take care of that. Let me explain in detail.

Please consider this fiddle

angular.module('mySettings', []).controller('appSettingsCtrl', function ($scope) {

    $scope.timeFormatTemplates = [{
        label: "Seconds",
        value: 'ss'
    }, {
        label: "Minutes",
        value: 'mm'
    }, {
        label: "Hours",
        value: 'hh'
    }];


    $scope.inactivity_settings = {
        status: false,
        inactive_time: 60 * 5 * 3, // 15 min (default value), that is, 900 seconds
        //time_format: 'ss', // Second (default value)
        time_format: $scope.timeFormatTemplates[0], // Default seconds object
    };

    $scope.activity_settings = {
        status: false,
        active_time: 60 * 5 * 3, // 15 min (default value), that is,  900 seconds
        //time_format: 'ss', // Second (default value)
        time_format: $scope.timeFormatTemplates[0], // Default seconds object
    };

    $scope.changedTimeFormat = function (time_format) {
        'use strict';

        console.log('time changed');
        console.log(time_format);
        var newValue = time_format.value;

        // do your update settings stuffs
    }
});

As you can see in the fiddle output, whatever you choose for select box options, it is your custom value, or the 0, 1, 2 auto generated value by AngularJS, it does not matter in your output unless you are using jQuery or any other library to access the value of that select combo box options and manipulate it accordingly.

Combining two expressions (Expression<Func<T, bool>>)

Well, you can use Expression.AndAlso / OrElse etc to combine logical expressions, but the problem is the parameters; are you working with the same ParameterExpression in expr1 and expr2? If so, it is easier:

var body = Expression.AndAlso(expr1.Body, expr2.Body);
var lambda = Expression.Lambda<Func<T,bool>>(body, expr1.Parameters[0]);

This also works well to negate a single operation:

static Expression<Func<T, bool>> Not<T>(
    this Expression<Func<T, bool>> expr)
{
    return Expression.Lambda<Func<T, bool>>(
        Expression.Not(expr.Body), expr.Parameters[0]);
}

Otherwise, depending on the LINQ provider, you might be able to combine them with Invoke:

// OrElse is very similar...
static Expression<Func<T, bool>> AndAlso<T>(
    this Expression<Func<T, bool>> left,
    Expression<Func<T, bool>> right)
{
    var param = Expression.Parameter(typeof(T), "x");
    var body = Expression.AndAlso(
            Expression.Invoke(left, param),
            Expression.Invoke(right, param)
        );
    var lambda = Expression.Lambda<Func<T, bool>>(body, param);
    return lambda;
}

Somewhere, I have got some code that re-writes an expression-tree replacing nodes to remove the need for Invoke, but it is quite lengthy (and I can't remember where I left it...)


Generalized version that picks the simplest route:

static Expression<Func<T, bool>> AndAlso<T>(
    this Expression<Func<T, bool>> expr1,
    Expression<Func<T, bool>> expr2)
{
    // need to detect whether they use the same
    // parameter instance; if not, they need fixing
    ParameterExpression param = expr1.Parameters[0];
    if (ReferenceEquals(param, expr2.Parameters[0]))
    {
        // simple version
        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(expr1.Body, expr2.Body), param);
    }
    // otherwise, keep expr1 "as is" and invoke expr2
    return Expression.Lambda<Func<T, bool>>(
        Expression.AndAlso(
            expr1.Body,
            Expression.Invoke(expr2, param)), param);
}

Starting from .NET 4.0, there is the ExpressionVisitor class which allows you to build expressions that are EF safe.

    public static Expression<Func<T, bool>> AndAlso<T>(
        this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var parameter = Expression.Parameter(typeof (T));

        var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
        var left = leftVisitor.Visit(expr1.Body);

        var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
        var right = rightVisitor.Visit(expr2.Body);

        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(left, right), parameter);
    }



    private class ReplaceExpressionVisitor
        : ExpressionVisitor
    {
        private readonly Expression _oldValue;
        private readonly Expression _newValue;

        public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
        {
            _oldValue = oldValue;
            _newValue = newValue;
        }

        public override Expression Visit(Expression node)
        {
            if (node == _oldValue)
                return _newValue;
            return base.Visit(node);
        }
    }

Spring profiles and testing

Can I recommend doing it this way, define your test like this:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
    TestPreperationExecutionListener.class
    })
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {

  @Test
  public void testContext(){

  }

  @Configuration
  @PropertySource("classpath:/myprops.properties")
  @ImportResource({"classpath:context.xml" })
  public static class MyContextConfiguration{

  }
}

with the following content in myprops.properties file:

spring.profiles.active=localtest

With this your second properties file should get resolved:

META-INF/spring/config_${spring.profiles.active}.properties

Efficiently replace all accented characters in a string?

The correct terminology for such accents is Diacritics. After Googling this term, I found this function which is part of backbone.paginator. It has a very complete collection of Diacritics and replaces them with their most intuitive ascii character. I found this to be the most complete Javascript solution available today.

The full function for future reference:

function removeDiacritics (str) {

  var defaultDiacriticsRemovalMap = [
    {'base':'A', 'letters':/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},
    {'base':'AA','letters':/[\uA732]/g},
    {'base':'AE','letters':/[\u00C6\u01FC\u01E2]/g},
    {'base':'AO','letters':/[\uA734]/g},
    {'base':'AU','letters':/[\uA736]/g},
    {'base':'AV','letters':/[\uA738\uA73A]/g},
    {'base':'AY','letters':/[\uA73C]/g},
    {'base':'B', 'letters':/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},
    {'base':'C', 'letters':/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},
    {'base':'D', 'letters':/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},
    {'base':'DZ','letters':/[\u01F1\u01C4]/g},
    {'base':'Dz','letters':/[\u01F2\u01C5]/g},
    {'base':'E', 'letters':/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},
    {'base':'F', 'letters':/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},
    {'base':'G', 'letters':/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},
    {'base':'H', 'letters':/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},
    {'base':'I', 'letters':/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},
    {'base':'J', 'letters':/[\u004A\u24BF\uFF2A\u0134\u0248]/g},
    {'base':'K', 'letters':/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},
    {'base':'L', 'letters':/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},
    {'base':'LJ','letters':/[\u01C7]/g},
    {'base':'Lj','letters':/[\u01C8]/g},
    {'base':'M', 'letters':/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},
    {'base':'N', 'letters':/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},
    {'base':'NJ','letters':/[\u01CA]/g},
    {'base':'Nj','letters':/[\u01CB]/g},
    {'base':'O', 'letters':/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},
    {'base':'OI','letters':/[\u01A2]/g},
    {'base':'OO','letters':/[\uA74E]/g},
    {'base':'OU','letters':/[\u0222]/g},
    {'base':'P', 'letters':/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},
    {'base':'Q', 'letters':/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},
    {'base':'R', 'letters':/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},
    {'base':'S', 'letters':/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},
    {'base':'T', 'letters':/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},
    {'base':'TZ','letters':/[\uA728]/g},
    {'base':'U', 'letters':/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},
    {'base':'V', 'letters':/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},
    {'base':'VY','letters':/[\uA760]/g},
    {'base':'W', 'letters':/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},
    {'base':'X', 'letters':/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},
    {'base':'Y', 'letters':/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},
    {'base':'Z', 'letters':/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},
    {'base':'a', 'letters':/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},
    {'base':'aa','letters':/[\uA733]/g},
    {'base':'ae','letters':/[\u00E6\u01FD\u01E3]/g},
    {'base':'ao','letters':/[\uA735]/g},
    {'base':'au','letters':/[\uA737]/g},
    {'base':'av','letters':/[\uA739\uA73B]/g},
    {'base':'ay','letters':/[\uA73D]/g},
    {'base':'b', 'letters':/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},
    {'base':'c', 'letters':/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},
    {'base':'d', 'letters':/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},
    {'base':'dz','letters':/[\u01F3\u01C6]/g},
    {'base':'e', 'letters':/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},
    {'base':'f', 'letters':/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},
    {'base':'g', 'letters':/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},
    {'base':'h', 'letters':/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},
    {'base':'hv','letters':/[\u0195]/g},
    {'base':'i', 'letters':/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},
    {'base':'j', 'letters':/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},
    {'base':'k', 'letters':/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},
    {'base':'l', 'letters':/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},
    {'base':'lj','letters':/[\u01C9]/g},
    {'base':'m', 'letters':/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},
    {'base':'n', 'letters':/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},
    {'base':'nj','letters':/[\u01CC]/g},
    {'base':'o', 'letters':/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},
    {'base':'oi','letters':/[\u01A3]/g},
    {'base':'ou','letters':/[\u0223]/g},
    {'base':'oo','letters':/[\uA74F]/g},
    {'base':'p','letters':/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},
    {'base':'q','letters':/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},
    {'base':'r','letters':/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},
    {'base':'s','letters':/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},
    {'base':'t','letters':/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},
    {'base':'tz','letters':/[\uA729]/g},
    {'base':'u','letters':/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g},
    {'base':'v','letters':/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},
    {'base':'vy','letters':/[\uA761]/g},
    {'base':'w','letters':/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},
    {'base':'x','letters':/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},
    {'base':'y','letters':/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},
    {'base':'z','letters':/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}
  ];

  for(var i=0; i<defaultDiacriticsRemovalMap.length; i++) {
    str = str.replace(defaultDiacriticsRemovalMap[i].letters, defaultDiacriticsRemovalMap[i].base);
  }

  return str;

}

Finding the index of elements based on a condition using python list comprehension

For me it works well:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 1, 2, 3])
>>> np.where(a > 2)[0]
[2 5]

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

You should use html():

SEE DEMO

$(document).ready(function(){
    $("#date").html('<span>'+$("#date").text().substring(0, 2) + '</span><br />'+$("#date").text().substring(3));     
});

simple vba code gives me run time error 91 object variable or with block not set

Also you are trying to set value2 using Set keyword, which is not required. You can directly use rng.value2 = 1

below test code for ref.

Sub test()
    Dim rng As Range
    Set rng = Range("A1")
    rng.Value2 = 1
End Sub

How to drop a database with Mongoose?

The difficulty I've had with the other solutions is they rely on restarting your application if you want to get the indexes working again.

For my needs (i.e. being able to run a unit test the nukes all collections, then recreates them along with their indexes), I ended up implementing this solution:

This relies on the underscore.js and async.js libraries to assemble the indexes in parellel, it could be unwound if you're against that library but I leave that as an exerciser for the developer.

mongoose.connection.db.executeDbCommand( {dropDatabase:1}, function(err, result) {
  var mongoPath = mongoose.connections[0].host + ':' + mongoose.connections[0].port + '/' + mongoose.connections[0].name
  //Kill the current connection, then re-establish it
  mongoose.connection.close()
  mongoose.connect('mongodb://' + mongoPath, function(err){
    var asyncFunctions = []

    //Loop through all the known schemas, and execute an ensureIndex to make sure we're clean
    _.each(mongoose.connections[0].base.modelSchemas, function(schema, key) {
      asyncFunctions.push(function(cb){
        mongoose.model(key, schema).ensureIndexes(function(){
          return cb()
        })
      })
    })

    async.parallel(asyncFunctions, function(err) {
      console.log('Done dumping all collections and recreating indexes')
    })
  })
})

Pass Javascript Variable to PHP POST

You can do this using Ajax. I have a function that I use for something like this:

function ajax(elementID,filename,str,post)
{
    var ajax;
    if (window.XMLHttpRequest)
    {
        ajax=new XMLHttpRequest();//IE7+, Firefox, Chrome, Opera, Safari
    }
    else if (ActiveXObject("Microsoft.XMLHTTP"))
    {
        ajax=new ActiveXObject("Microsoft.XMLHTTP");//IE6/5
    }
    else if (ActiveXObject("Msxml2.XMLHTTP"))
    {
        ajax=new ActiveXObject("Msxml2.XMLHTTP");//other
    }
    else
    {
        alert("Error: Your browser does not support AJAX.");
        return false;
    }
    ajax.onreadystatechange=function()
    {
        if (ajax.readyState==4&&ajax.status==200)
        {
            document.getElementById(elementID).innerHTML=ajax.responseText;
        }
    }
    if (post==false)
    {
        ajax.open("GET",filename+str,true);
        ajax.send(null);
    }
    else
    {
        ajax.open("POST",filename,true);
        ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        ajax.send(str);
    }
    return ajax;
}

The first parameter is the element you want to change. The second parameter is the name of the filename you're loading into the element you're changing. The third parameter is the GET or POST data you're using, so for example "total=10000&othernumber=999". The last parameter is true if you want use POST or false if you want to GET.

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

You can't save things to Hibernate until you've also told Hibernate about all the other objects referenced by this newly saved object. So in this case, you're telling Hibernate about a User, but haven't told it about the Country.

You can solve problems like this in two ways.

Manually

Call session.save(country) before you save the User.

CascadeType

You can specify to Hibernate that this relationship should propagate some operations using CascadeType. In this case CascadeType.PERSIST would do the job, as would CascadeType.ALL.

Referencing existing countries

Based on your response to @zerocool though, you have a second problem, which is that when you have two User objects with the same Country, you are not making sure it's the same Country. To do this, you have to get the appropriate Country from the database, set it on the new user, and then save the User. Then, both of your User objects will refer to the same Country, not just two Country instances that happen to have the same name. Review the Criteria API as one way of fetching existing instances.

Get names of all keys in the collection

This works fine for me:

var arrayOfFieldNames = [];

var items = db.NAMECOLLECTION.find();

while(items.hasNext()) {
  var item = items.next();
  for(var index in item) {
    arrayOfFieldNames[index] = index;
   }
}

for (var index in arrayOfFieldNames) {
  print(index);
}

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

Import txt file and having each line as a list

Do not create separate lists; create a list of lists:

results = []
with open('inputfile.txt') as inputfile:
    for line in inputfile:
        results.append(line.strip().split(','))

or better still, use the csv module:

import csv

results = []
with open('inputfile.txt', newline='') as inputfile:
    for row in csv.reader(inputfile):
        results.append(row)

Lists or dictionaries are far superiour structures to keep track of an arbitrary number of things read from a file.

Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append() just process that line right there.

Just for completeness sake, here's the one-liner compact version to read in a CSV file into a list in one go:

import csv

with open('inputfile.txt', newline='') as inputfile:
    results = list(csv.reader(inputfile))

Defined Edges With CSS3 Filter Blur

I was able to make this work with the

transform: scale(1.03);

Property applied on the image. For some reason, on Chrome, the other solutions provided wouldn't work if there was any relatively positioned parent element.

Check http://jsfiddle.net/ud5ya7jt/

This way the image will be slightly zoomed in by 3% and the edges will be cropped which shouldn't be a problem on a blurred image anyway. It worked well in my case because I was using a high res image as a background. Good luck!

How to stop docker under Linux

if you have no systemctl and started the docker daemon by:

sudo service docker start

you can stop it by:

sudo service docker stop

Detect click outside Angular component

Binding to document click through @Hostlistener is costly. It can and will have a visible performance impact if you overuse(for example, when building a custom dropdown component and you have multiple instances created in a form).

I suggest adding a @Hostlistener() to the document click event only once inside your main app component. The event should push the value of the clicked target element inside a public subject stored in a global utility service.

@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent {

  constructor(private utilitiesService: UtilitiesService) {}

  @HostListener('document:click', ['$event'])
  documentClick(event: any): void {
    this.utilitiesService.documentClickedTarget.next(event.target)
  }
}

@Injectable({ providedIn: 'root' })
export class UtilitiesService {
   documentClickedTarget: Subject<HTMLElement> = new Subject<HTMLElement>()
}

Whoever is interested for the clicked target element should subscribe to the public subject of our utilities service and unsubscribe when the component is destroyed.

export class AnotherComponent implements OnInit {

  @ViewChild('somePopup', { read: ElementRef, static: false }) somePopup: ElementRef

  constructor(private utilitiesService: UtilitiesService) { }

  ngOnInit() {
      this.utilitiesService.documentClickedTarget
           .subscribe(target => this.documentClickListener(target))
  }

  documentClickListener(target: any): void {
     if (this.somePopup.nativeElement.contains(target))
        // Clicked inside  
     else
        // Clicked outside
  }

how can I set visible back to true in jquery

Use style="display:none" in your dropdown list tag and in jquery use the following to display and hide.

$("#yourdropdownid").css('display', 'inline');

OR

$("#yourdropdownid").css('display', 'none');

Spring Data and Native Query with pagination

Replacing /#pageable/ with ?#{#pageable} allow to do pagination. Adding PageableDefault allow you to set size of page Elements.

How to customize the configuration file of the official PostgreSQL Docker image?

I looked through all answers and there is another option left. You can change your CMD value in docker file (it is not the best one, but still possible way to achieve your goal).

Basically we need to

  • Copy config file in docker container
  • Override postgres start options

Docker file example:

FROM postgres:9.6
USER postgres

# Copy postgres config file into container
COPY postgresql.conf /etc/postgresql

# Override default postgres config file
CMD ["postgres", "-c", "config_file=/etc/postgresql/postgresql.conf"]

Though I think using command: postgres -c config_file=/etc/postgresql/postgresql.confin your docker-compose.yml file proposed by Matthias Braun is the best option.

Installing NumPy and SciPy on 64-bit Windows (with Pip)

You can install scipy and numpy using their wheels.

First install wheel package if it's already not there...

pip install wheel

Just select the package you want from http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

Example: if you're running python3.5 32 bit on Windows choose scipy-0.18.1-cp35-cp35m-win_amd64.whl then it will automatically download.

Then go to the command line and change the directory to the downloads folder and install the above wheel using pip.

Example:

cd C:\Users\[user]\Downloads
pip install scipy-0.18.1-cp35-cp35m-win_amd64.whl

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

Two Divs on the same row and center align both of them

I would vote against display: inline-block since its not supported across browsers, IE < 8 specifically.

.wrapper {
    width:500px; /* Adjust to a total width of both .left and .right */
    margin: 0 auto;
}
.left {
    float: left;
    width: 49%; /* Not 50% because of 1px border. */
    border: 1px solid #000;
}
.right {
    float: right;
    width: 49%; /* Not 50% because of 1px border. */
    border: 1px solid #F00;
}

<div class="wrapper">
    <div class="left">Div 1</div>
    <div class="right">Div 2</div>
</div>

EDIT: If no spacing between the cells is desired just change both .left and .right to use float: left;

Hiding user input on terminal in Linux script

for a solution that works without bash or certain features from read you can use stty to disable echo

stty_orig=$(stty -g)
stty -echo
read password
stty $stty_orig

Fit website background image to screen size

you can do this with this plugin http://dev.andreaseberhard.de/jquery/superbgimage/

or

   background-image:url(../IMAGES/background.jpg);

   background-repeat:no-repeat;

   background-size:cover;

with no need the prefixes of browsers. it's all ready suporterd in both of browers

What are the minimum margins most printers can handle?

You shouldn't need to let the users specify the margin on your website - Let them do it on their computer. Print dialogs usually (Adobe and Preview, at least) give you an option to scale and center the output on the printable area of the page:

Adobe
alt text

Preview
alt text

Of course, this assumes that you have computer literate users, which may or may not be the case.

What is Bit Masking?

A mask defines which bits you want to keep, and which bits you want to clear.

Masking is the act of applying a mask to a value. This is accomplished by doing:

  • Bitwise ANDing in order to extract a subset of the bits in the value
  • Bitwise ORing in order to set a subset of the bits in the value
  • Bitwise XORing in order to toggle a subset of the bits in the value

Below is an example of extracting a subset of the bits in the value:

Mask:   00001111b
Value:  01010101b

Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:

Mask:   00001111b
Value:  01010101b
Result: 00000101b

Masking is implemented using AND, so in C we get:

uint8_t stuff(...) {
  uint8_t mask = 0x0f;   // 00001111b
  uint8_t value = 0x55;  // 01010101b
  return mask & value;
}

Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &, and >> (shift right). This is how we can extract the four bytes from a 32-bit integer:

void more_stuff(uint32_t value) {             // Example value: 0x01020304
    uint32_t byte1 = (value >> 24);           // 0x01020304 >> 24 is 0x01 so
                                              // no masking is necessary
    uint32_t byte2 = (value >> 16) & 0xff;    // 0x01020304 >> 16 is 0x0102 so
                                              // we must mask to get 0x02
    uint32_t byte3 = (value >> 8)  & 0xff;    // 0x01020304 >> 8 is 0x010203 so
                                              // we must mask to get 0x03
    uint32_t byte4 = value & 0xff;            // here we only mask, no shifting
                                              // is necessary
    ...
}

Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:

uint32_t byte3 = (value & 0xff00) >> 8;

Get source JARs from Maven repository

NetBeans, Context-Click

In NetBeans 8 with a Maven-driven project, merely context-click on the jar file list item of the dependency in which you are interested. Choose Download Sources. Wait a moment and NetBeans will automatically download and install the source code, if available.

Similarly you can choose Download Javadoc to get the doc locally installed. Then you can context-click some code in the editor and choose to see the JavaDoc.

screen shot of context-menu item "Download Sources" being chosen in a NetBeans 8 project driven by Maven

how to set mongod --dbpath

Have only tried this on Mac:

  • Create a data directory in the root folder of your app
  • cd into your wherever you placed your mongo directory when you installed it
  • run this command:

    mongod --dbpath ~/path/to/your/app/data

You should be good to go!

How can I detect the encoding/codepage of a text file

10Y (!) had passed since this was asked, and still I see no mention of MS's good, non-GPL'ed solution: IMultiLanguage2 API.

Most libraries already mentioned are based on Mozilla's UDE - and it seems reasonable that browsers have already tackled similar problems. I don't know what is chrome's solution, but since IE 5.0 MS have released theirs, and it is:

  1. Free of GPL-and-the-like licensing issues,
  2. Backed and maintained probably forever,
  3. Gives rich output - all valid candidates for encoding/codepages along with confidence scores,
  4. Surprisingly easy to use (it is a single function call).

It is a native COM call, but here's some very nice work by Carsten Zeumer, that handles the interop mess for .net usage. There are some others around, but by and large this library doesn't get the attention it deserves.

I want to truncate a text or line with ellipsis using JavaScript

This will put the ellipsis in the center of the line:

function truncate( str, max, sep ) {

    // Default to 10 characters
    max = max || 10;

    var len = str.length;
    if(len > max){

        // Default to elipsis
        sep = sep || "...";

        var seplen = sep.length;

        // If seperator is larger than character limit,
        // well then we don't want to just show the seperator,
        // so just show right hand side of the string.
        if(seplen > max) {
            return str.substr(len - max);
        }

        // Half the difference between max and string length.
        // Multiply negative because small minus big.
        // Must account for length of separator too.
        var n = -0.5 * (max - len - seplen);

        // This gives us the centerline.
        var center = len/2;

        var front = str.substr(0, center - n);
        var back = str.substr(len - center + n); // without second arg, will automatically go to end of line.

        return front + sep + back;

    }

    return str;
}

console.log( truncate("123456789abcde") ); // 123...bcde (using built-in defaults) 
console.log( truncate("123456789abcde", 8) ); // 12...cde (max of 8 characters) 
console.log( truncate("123456789abcde", 12, "_") ); // 12345_9abcde (customize the separator) 

For example:

1234567890 --> 1234...8910

And:

A really long string --> A real...string

Not perfect, but functional. Forgive the over-commenting... for the noobs.

Postgresql SELECT if string contains

You should use 'tag_name' outside of quotes; then its interpreted as a field of the record. Concatenate using '||' with the literal percent signs:

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || tag_name || '%';

How To Set A JS object property name from a variable

With ECMAScript 6, you can use variable property names with the object literal syntax, like this:

var keyName = 'myKey';
var obj = {
              [keyName]: 1
          };
obj.myKey;//1

This syntax is available in the following newer browsers:

Edge 12+ (No IE support), FF34+, Chrome 44+, Opera 31+, Safari 7.1+

(https://kangax.github.io/compat-table/es6/)

You can add support to older browsers by using a transpiler such as babel. It is easy to transpile an entire project if you are using a module bundler such as rollup or webpack.

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

I tried everything but still this error won't go, until I changed my JDK version.

My JDK version was 7, and after I changed it to 8, the error went away, you can try it if nothing else works.

How to pass credentials to the Send-MailMessage command for sending emails

in addition to UseSsl, you have to include smtp port 587 to make it work.

Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'

How to get arguments with flags in Bash

If you're familiar with Python argparse, and don't mind calling python to parse bash arguments, there is a piece of code I found really helpful and super easy to use called argparse-bash https://github.com/nhoffman/argparse-bash

Example take from their example.sh script:

#!/bin/bash

source $(dirname $0)/argparse.bash || exit 1
argparse "$@" <<EOF || exit 1
parser.add_argument('infile')
parser.add_argument('outfile')
parser.add_argument('-a', '--the-answer', default=42, type=int,
                    help='Pick a number [default %(default)s]')
parser.add_argument('-d', '--do-the-thing', action='store_true',
                    default=False, help='store a boolean [default %(default)s]')
parser.add_argument('-m', '--multiple', nargs='+',
                    help='multiple values allowed')
EOF

echo required infile: "$INFILE"
echo required outfile: "$OUTFILE"
echo the answer: "$THE_ANSWER"
echo -n do the thing?
if [[ $DO_THE_THING ]]; then
    echo " yes, do it"
else
    echo " no, do not do it"
fi
echo -n "arg with multiple values: "
for a in "${MULTIPLE[@]}"; do
    echo -n "[$a] "
done
echo

Including external HTML file to another HTML file

You're looking for the <iframe> tag, or, better yet, a server-side templating language.

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

You can increase the size of the memory through the use of commandline arguments.

See this link.

eclipse -vmargs -Xmx1024m

Edit: Also see see this excellent question

where is create-react-app webpack config and files?

Try ejecting the config files, by running:

npm run eject

then you'll find a config folder created in your project. You will find your webpack config files init.

How to add empty spaces into MD markdown readme on GitHub?

As a workaround, you can use a code block to render the code literally. Just surround your text with triple backticks ```. It will look like this:

2018-07-20 Wrote this answer Can format it without &nbsp; Also don't need <br /> for new line

Note that using <pre> and <code> you get slightly different behaviour: &nbsp and <br /> will be parsed rather than inserted literally.

<pre>:

2018-07-20 Wrote this answer
           Can format it without  
    Also don't need 
for new line

<code>: 2018-07-20 Wrote this answer Can format it without   Also don't need
for new line

Converting a JToken (or string) to a given Type

System.Convert.ChangeType(jtoken.ToString(), targetType);

or

JsonConvert.DeserializeObject(jtoken.ToString(), targetType);

--EDIT--

Uzair, Here is a complete example just to show you they work

string json = @"{
        ""id"" : 77239923,
        ""username"" : ""UzEE"",
        ""email"" : ""[email protected]"",
        ""name"" : ""Uzair Sajid"",
        ""twitter_screen_name"" : ""UzEE"",
        ""join_date"" : ""2012-08-13T05:30:23Z05+00"",
        ""timezone"" : 5.5,
        ""access_token"" : {
            ""token"" : ""nkjanIUI8983nkSj)*#)(kjb@K"",
            ""scope"" : [ ""read"", ""write"", ""bake pies"" ],
            ""expires"" : 57723
        },
        ""friends"" : [{
            ""id"" : 2347484,
            ""name"" : ""Bruce Wayne""
        },
        {
            ""id"" : 996236,
            ""name"" : ""Clark Kent""
        }]
    }";

var obj = (JObject)JsonConvert.DeserializeObject(json);
Type type = typeof(int);
var i1 = System.Convert.ChangeType(obj["id"].ToString(), type);
var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);

CSS - How to Style a Selected Radio Buttons Label?

You can add a span to your html and css .

Here's an example from my code ...

HTML ( JSX ):

<input type="radio" name="AMPM" id="radiostyle1" value="AM" checked={this.state.AMPM==="AM"} onChange={this.handleChange}/>  
<label for="radiostyle1"><span></span> am  </label>

<input type="radio" name="AMPM" id="radiostyle2" value="PM" checked={this.state.AMPM==="PM"} onChange={this.handleChange}/>
<label for="radiostyle2"><span></span> pm  </label>

CSS to make standard radio button vanish on screen and superimpose custom button image:

input[type="radio"] {  
    opacity:0;                                      
}

input[type="radio"] + label {
    font-size:1em;
    text-transform: uppercase;
    color: white ;  
    cursor: pointer;
    margin:auto 15px auto auto;                    
}

input[type="radio"] + label span {
    display:inline-block;
    width:30px;
    height:10px;
    margin:1px 0px 0 -30px;                       
    cursor:pointer;
    border-radius: 20%;
}


input[type="radio"] + label span {
    background-color: #FFFFFF 
}


input[type="radio"]:checked + label span{
     background-color: #660006;  
}

Append Char To String in C?

The Original poster didn't mean to write:

  char* str = "blablabla";

but

  char str[128] = "blablabla";

Now, adding a single character would seem more efficient than adding a whole string with strcat. Going the strcat way, you could:

  char tmpstr[2];
  tmpstr[0] = c;
  tmpstr[1] = 0;
  strcat (str, tmpstr);

but you can also easily write your own function (as several have done before me):

  void strcat_c (char *str, char c)
  {
    for (;*str;str++); // note the terminating semicolon here. 
    *str++ = c; 
    *str++ = 0;
  }

What exactly does stringstream do?

To answer the question. stringstream basically allows you to treat a string object like a stream, and use all stream functions and operators on it.

I saw it used mainly for the formatted output/input goodness.

One good example would be c++ implementation of converting number to stream object.

Possible example:

template <class T>
string num2str(const T& num, unsigned int prec = 12) {
    string ret;
    stringstream ss;
    ios_base::fmtflags ff = ss.flags();
    ff |= ios_base::floatfield;
    ff |= ios_base::fixed;
    ss.flags(ff);
    ss.precision(prec);
    ss << num;
    ret = ss.str();
    return ret;
};

Maybe it's a bit complicated but it is quite complex. You create stringstream object ss, modify its flags, put a number into it with operator<<, and extract it via str(). I guess that operator>> could be used.

Also in this example the string buffer is hidden and not used explicitly. But it would be too long of a post to write about every possible aspect and use-case.

Note: I probably stole it from someone on SO and refined, but I don't have original author noted.

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

You are checking Parent properties for null in your delegate. The same should work with lambda expressions too.

List<AnalysisObject> analysisObjects = analysisObjectRepository
        .FindAll()
        .Where(x => 
            (x.ID == packageId) || 
            (x.Parent != null &&
                (x.Parent.ID == packageId || 
                (x.Parent.Parent != null && x.Parent.Parent.ID == packageId)))
        .ToList();

Valid characters of a hostname?

Checkout this wiki, specifically the section Restrictions on valid host names

Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, "en.wikipedia.org" is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.

The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9', and the hyphen ('-'). The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

From what I understand, You have to save a user's input locally to a text file.

Check this link. See if this helps.

Saving user input to a text file locally

Rename file with Git

As far as I can tell, GitHub does not provide shell access, so I'm curious about how you managed to log in in the first place.

$ ssh -T [email protected]
Hi username! You've successfully authenticated, but GitHub does not provide
shell access.

You have to clone your repository locally, make the change there, and push the change to GitHub.

$ git clone [email protected]:username/reponame.git
$ cd reponame
$ git mv README README.md
$ git commit -m "renamed"
$ git push origin master

jquery.ajax Access-Control-Allow-Origin

At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON AJAX method because it easily returns JSONP using the ?callback=? without having any issues with CORS.

data ='USER=<?echo trim($USER)?>' +
         '&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();

        //Call the REST program/method returns: JSONP 
        $.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
        .done(function( json ) {        

              //  loading...
                if ($.trim(json.ERROR) != '') {
                    $("#error-msg").text(message).show();
                }
                else{
                    $(".error").hide();
                    $("#jsonp").text(json.whatever);

                }

        })  
        .fail(function( jqXHR, textStatus, error ) {
        var err = textStatus + ", " + error;
        alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
        });     

Disable Enable Trigger SQL server for a table

Below is the Dynamic Script to enable or disable the Triggers.

select 'alter table '+ (select Schema_name(schema_id) from sys.objects o 
where o.object_id = parent_id) + '.'+object_name(parent_id) + ' ENABLE TRIGGER '+
Name as EnableScript,*
from sys.triggers t 
where is_disabled = 1

JavaScript associative array to JSON

You might want to push the object into the array

enter code here

var AssocArray = new Array();

AssocArray.push( "The letter A");

console.log("a = " + AssocArray[0]);

// result: "a = The letter A"

console.log( AssocArray[0]);

JSON.stringify(AssocArray);

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

For line chart, I use the following codes.

First create custom style

.boxx{
    position: relative;
    width: 20px;
    height: 20px;
    border-radius: 3px;
}

Then add this on your line options

var lineOptions = {
            legendTemplate : '<table>'
                            +'<% for (var i=0; i<datasets.length; i++) { %>'
                            +'<tr><td><div class=\"boxx\" style=\"background-color:<%=datasets[i].fillColor %>\"></div></td>'
                            +'<% if (datasets[i].label) { %><td><%= datasets[i].label %></td><% } %></tr><tr height="5"></tr>'
                            +'<% } %>'
                            +'</table>',
            multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"

var ctx = document.getElementById("lineChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
document.getElementById('legendDiv').innerHTML = myNewChart.generateLegend();

Don't forget to add

<div id="legendDiv"></div>

on your html where do you want to place your legend. That's it!

How to get old Value with onchange() event in text box

I would suggest:

function onChange(field){
  field.old=field.recent;
  field.recent=field.value;

  //we have available old value here;
}

Javascript/Jquery to change class onclick?

I think you mean that you want want an onclick event that changes a class.

Here is the answer if someone visits this question and is literally looking to assign a class and it's onclick with JQUERY.

It is somewhat counter-intuitive, but if you want to change the onclick event by changing the class you need to declare the onclick event to apply to elements of a parent object.

HTML

<div id="containerid">
     Text <a class="myClass" href="#" />info</a>
     Other Text <div class="myClass">other info</div>
</div>
<div id="showhide" class="meta-info">hide info</div>

Document Ready

$(function() {
     $("#containerid").on("click",".myclass",function(e){ /*do stuff*/ }
     $("#containerid").on("click",".mynewclass",function(e){ /*do different stuff*/ }
     $("#showhide").click(function() {changeclass()}
});

Slight Tweak to Your Javascript

<script>
function changeclass() {
        $(".myClass,.myNewClass").toggleClass('myNewClass').toggleClass('myClass');
} 
</script>

If you can't reliably identify a parent object you can do something like this.

$(function() {
     $(document).on("click",".myclass",function(e){}
     $(document).on("click",".mynewclass",function(e){}
});

If you just want to hide the items you might find it simpler to use .hide() and .show().

Reading the selected value from asp:RadioButtonList using jQuery

Why so complex?

$('#id:checked').val();

Will work just fine!

What data type to use in MySQL to store images?

Perfect answer for your question can be found on MYSQL site itself.refer their manual(without using PHP)

http://forums.mysql.com/read.php?20,17671,27914

According to them use LONGBLOB datatype. with that you can only store images less than 1MB only by default,although it can be changed by editing server config file.i would also recommend using MySQL workBench for ease of database management

Class Not Found: Empty Test Suite in IntelliJ

Deleting .idea and re-importing the SBT project solved this issue for me.

How to check if a function exists on a SQL database

This is what SSMS uses when you script using the DROP and CREATE option

IF EXISTS (SELECT *
           FROM   sys.objects
           WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                  AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
  DROP FUNCTION [dbo].[foo]

GO 

This approach to deploying changes means that you need to recreate all permissions on the object so you might consider ALTER-ing if Exists instead.

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

Is there a way to break a list into columns?

This answer doesn't necessarily scale but only requires minor adjustments as the list grows. Semantically it might seem a little counter-intuitive since it is two lists, but aside from that it'll look the way you want in any browser ever made.

_x000D_
_x000D_
ul {_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
ul > li {_x000D_
  width: 6em;_x000D_
}
_x000D_
<!-- Column 1 -->_x000D_
<ul>_x000D_
  <li>Item 1</li>_x000D_
  <li>Item 2</li>_x000D_
  <li>Item 3</li>_x000D_
</ul>_x000D_
<!-- Column 2 -->_x000D_
<ul>_x000D_
  <li>Item 4</li>_x000D_
  <li>Item 5</li>_x000D_
  <li>Item 6</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to change the font color in the textbox in C#?

Assuming WinForms, the ForeColor property allows to change all the text in the TextBox (not just what you're about to add):

TextBox.ForeColor = Color.Red;

To only change the color of certain words, look at RichTextBox.

Eclipse can't find / load main class

Move your file into a subdirectory called cont

Converting String to "Character" array in Java

I hope the code below will help you.

String s="Welcome to Java Programming";
char arr[]=s.toCharArray();
for(int i=0;i<arr.length;i++){
    System.out.println("Data at ["+i+"]="+arr[i]);
}

It's working and the output is:

Data at [0]=W
Data at [1]=e
Data at [2]=l
Data at [3]=c
Data at [4]=o
Data at [5]=m
Data at [6]=e
Data at [7]= 
Data at [8]=t
Data at [9]=o
Data at [10]= 
Data at [11]=J
Data at [12]=a
Data at [13]=v
Data at [14]=a
Data at [15]= 
Data at [16]=P
Data at [17]=r
Data at [18]=o
Data at [19]=g
Data at [20]=r
Data at [21]=a
Data at [22]=m
Data at [23]=m
Data at [24]=i
Data at [25]=n
Data at [26]=g

Extract first item of each sublist

You could use zip:

>>> lst=[[1,2,3],[11,12,13],[21,22,23]]
>>> zip(*lst)[0]
(1, 11, 21)

Or, Python 3 where zip does not produce a list:

>>> list(zip(*lst))[0]
(1, 11, 21)

Or,

>>> next(zip(*lst))
(1, 11, 21)

Or, (my favorite) use numpy:

>>> import numpy as np
>>> a=np.array([[1,2,3],[11,12,13],[21,22,23]])
>>> a
array([[ 1,  2,  3],
       [11, 12, 13],
       [21, 22, 23]])
>>> a[:,0]
array([ 1, 11, 21])

Split page vertically using CSS

Check out this fiddle:

http://jsfiddle.net/G6N5T/1574/

CSS/HTML code:

_x000D_
_x000D_
.wrap {_x000D_
    width: 100%;_x000D_
    overflow:auto;_x000D_
}_x000D_
_x000D_
.fleft {_x000D_
    float:left; _x000D_
    width: 33%;_x000D_
background:lightblue;_x000D_
    height: 400px;_x000D_
}_x000D_
_x000D_
.fcenter{_x000D_
    float:left;_x000D_
    width: 33%;_x000D_
    background:lightgreen;_x000D_
    height:400px;_x000D_
    margin-left:0.25%;_x000D_
}_x000D_
_x000D_
.fright {_x000D_
float: right;_x000D_
    background:pink;_x000D_
    height: 400px;_x000D_
    width: 33.5%;_x000D_
    _x000D_
}
_x000D_
<div class="wrap">_x000D_
    <!--Updated on 10/8/2016; fixed center alignment percentage-->_x000D_
    <div class="fleft">Left</div>_x000D_
    <div class="fcenter">Center</div>_x000D_
    <div class="fright">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This uses the CSS float property for left, right, and center alignments of divs on a page.

What is the difference between #include <filename> and #include "filename"?

Many of the answers here focus on the paths the compiler will search in order to find the file. While this is what most compilers do, a conforming compiler is allowed to be preprogrammed with the effects of the standard headers, and to treat, say, #include <list> as a switch, and it need not exist as a file at all.

This is not purely hypothetical. There is at least one compiler that work that way. Using #include <xxx> only with standard headers is recommended.