Programs & Examples On #Xml

Extensible Markup Language (XML) is a flexible, structured document format that defines human- and machine-readable encoding rules.

Android layout replacing a view with another view on run time

it work in my case, oldSensor and newSnsor - oldView and newView:

private void replaceSensors(View oldSensor, View newSensor) {
            ViewGroup parent = (ViewGroup) oldSensor.getParent();

            if (parent == null) {
                return;
            }

            int indexOldSensor = parent.indexOfChild(oldSensor);
            int indexNewSensor = parent.indexOfChild(newSensor);
            parent.removeView(oldSensor);
            parent.addView(oldSensor, indexNewSensor);
            parent.removeView(newSensor);
            parent.addView(newSensor, indexOldSensor);
        }

Scraping html tables into R data frames using the XML package

The rvest along with xml2 is another popular package for parsing html web pages.

library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

The syntax is easier to use than the xml package and for most web pages the package provides all of the options ones needs.

Create a custom View by inflating a layout?

A bit old, but I thought sharing how I'd do it, based on chubbsondubs' answer: I use FrameLayout (see Documentation), since it is used to contain a single view, and inflate into it the view from the xml.

Code following:

public class MyView extends FrameLayout {
    public MyView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView();
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public MyView(Context context) {
        super(context);
        initView();
    }

    private void initView() {
        inflate(getContext(), R.layout.my_view_layout, this);
    }
}

Creating a simple XML file using python

These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5.

The available options for that are:

  • ElementTree (Basic, pure-Python implementation of ElementTree. Part of the standard library since 2.5)
  • cElementTree (Optimized C implementation of ElementTree. Also offered in the standard library since 2.5)
  • LXML (Based on libxml2. Offers a rich superset of the ElementTree API as well XPath, CSS Selectors, and more)

Here's an example of how to generate your example document using the in-stdlib cElementTree:

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

I've tested it and it works, but I'm assuming whitespace isn't significant. If you need "prettyprint" indentation, let me know and I'll look up how to do that. (It may be an LXML-specific option. I don't use the stdlib implementation much)

For further reading, here are some useful links:

As a final note, either cElementTree or LXML should be fast enough for all your needs (both are optimized C code), but in the event you're in a situation where you need to squeeze out every last bit of performance, the benchmarks on the LXML site indicate that:

  • LXML clearly wins for serializing (generating) XML
  • As a side-effect of implementing proper parent traversal, LXML is a bit slower than cElementTree for parsing.

Modify XML existing content in C#

Forming a XML file

XmlTextWriter xmlw = new XmlTextWriter(@"C:\WINDOWS\Temp\exm.xml",System.Text.Encoding.UTF8);
xmlw.WriteStartDocument();            
xmlw.WriteStartElement("examtimes");
xmlw.WriteStartElement("Starttime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Changetime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Endtime");
xmlw.WriteString(DateTime.Now.AddHours(1).ToString());
xmlw.WriteEndElement();
xmlw.WriteEndElement();
xmlw.WriteEndDocument();  
xmlw.Close();           

To edit the Xml nodes use the below code

XmlDocument doc = new XmlDocument(); 
doc.Load(@"C:\WINDOWS\Temp\exm.xml"); 
XmlNode root = doc.DocumentElement["Starttime"]; 
root.FirstChild.InnerText = "First"; 
XmlNode root1 = doc.DocumentElement["Changetime"]; 
root1.FirstChild.InnerText = "Second"; 
doc.Save(@"C:\WINDOWS\Temp\exm.xml"); 

Try this. It's C# code.

How to parse XML using vba

This is an example OPML parser working with FeedDemon opml files:

Sub debugPrintOPML()

' http://msdn.microsoft.com/en-us/library/ms763720(v=VS.85).aspx
' http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectnodes.aspx
' http://msdn.microsoft.com/en-us/library/ms256086(v=VS.85).aspx ' expressions
' References: Microsoft XML

Dim xmldoc As New DOMDocument60
Dim oNodeList As IXMLDOMSelection
Dim oNodeList2 As IXMLDOMSelection
Dim curNode As IXMLDOMNode
Dim n As Long, n2 As Long, x As Long

Dim strXPathQuery As String
Dim attrLength As Byte
Dim FilePath As String

FilePath = "rss.opml"

xmldoc.Load CurrentProject.Path & "\" & FilePath

strXPathQuery = "opml/body/outline"
Set oNodeList = xmldoc.selectNodes(strXPathQuery)

For n = 0 To (oNodeList.length - 1)
    Set curNode = oNodeList.Item(n)
    attrLength = curNode.Attributes.length
    If attrLength > 1 Then ' or 2 or 3
        Call processNode(curNode)
    Else
        Call processNode(curNode)
        strXPathQuery = "opml/body/outline[position() = " & n + 1 & "]/outline"
        Set oNodeList2 = xmldoc.selectNodes(strXPathQuery)
        For n2 = 0 To (oNodeList2.length - 1)
            Set curNode = oNodeList2.Item(n2)
            Call processNode(curNode)
        Next
    End If
        Debug.Print "----------------------"
Next

Set xmldoc = Nothing

End Sub

Sub processNode(curNode As IXMLDOMNode)

Dim sAttrName As String
Dim sAttrValue As String
Dim attrLength As Byte
Dim x As Long

attrLength = curNode.Attributes.length

For x = 0 To (attrLength - 1)
    sAttrName = curNode.Attributes.Item(x).nodeName
    sAttrValue = curNode.Attributes.Item(x).nodeValue
    Debug.Print sAttrName & " = " & sAttrValue
Next
    Debug.Print "-----------"

End Sub

This one takes multilevel trees of folders (Awasu, NewzCrawler):

...
Call xmldocOpen4
Call debugPrintOPML4(Null)
...

Dim sText4 As String

Sub debugPrintOPML4(strXPathQuery As Variant)

Dim xmldoc4 As New DOMDocument60
'Dim xmldoc4 As New MSXML2.DOMDocument60 ' ?
Dim oNodeList As IXMLDOMSelection
Dim curNode As IXMLDOMNode
Dim n4 As Long

If IsNull(strXPathQuery) Then strXPathQuery = "opml/body/outline"

' http://msdn.microsoft.com/en-us/library/ms754585(v=VS.85).aspx
xmldoc4.async = False
xmldoc4.loadXML sText4
If (xmldoc4.parseError.errorCode <> 0) Then
   Dim myErr
   Set myErr = xmldoc4.parseError
   MsgBox ("You have error " & myErr.reason)
Else
'   MsgBox xmldoc4.xml
End If

Set oNodeList = xmldoc4.selectNodes(strXPathQuery)

For n4 = 0 To (oNodeList.length - 1)
    Set curNode = oNodeList.Item(n4)
    Call processNode4(strXPathQuery, curNode, n4)
Next

Set xmldoc4 = Nothing

End Sub

Sub processNode4(strXPathQuery As Variant, curNode As IXMLDOMNode, n4 As Long)

Dim sAttrName As String
Dim sAttrValue As String
Dim x As Long

For x = 0 To (curNode.Attributes.length - 1)
    sAttrName = curNode.Attributes.Item(x).nodeName
    sAttrValue = curNode.Attributes.Item(x).nodeValue
    'If sAttrName = "text"
    Debug.Print strXPathQuery & " :: " & sAttrName & " = " & sAttrValue
    'End If
Next
    Debug.Print ""

If curNode.childNodes.length > 0 Then
    Call debugPrintOPML4(strXPathQuery & "[position() = " & n4 + 1 & "]/" & curNode.nodeName)
End If

End Sub

Sub xmldocOpen4()

Dim oFSO As New FileSystemObject ' Microsoft Scripting Runtime Reference
Dim oFS
Dim FilePath As String

FilePath = "rss_awasu.opml"
Set oFS = oFSO.OpenTextFile(CurrentProject.Path & "\" & FilePath)
sText4 = oFS.ReadAll
oFS.Close

End Sub

or better:

Sub xmldocOpen4()

Dim FilePath As String

FilePath = "rss.opml"

' function ConvertUTF8File(sUTF8File):
' http://www.vbmonster.com/Uwe/Forum.aspx/vb/24947/How-to-read-UTF-8-chars-using-VBA
' loading and conversion from Utf-8 to UTF
sText8 = ConvertUTF8File(CurrentProject.Path & "\" & FilePath)

End Sub

but I don't understand, why xmldoc4 should be loaded each time.

XML Schema minOccurs / maxOccurs default values

New, expanded answer to an old, commonly asked question...

Default Values

  • Occurrence constraints minOccurs and maxOccurs default to 1.

Common Cases Explained

<xsd:element name="A"/>

means A is required and must appear exactly once.


<xsd:element name="A" minOccurs="0"/>

means A is optional and may appear at most once.


 <xsd:element name="A" maxOccurs="unbounded"/>

means A is required and may repeat an unlimited number of times.


 <xsd:element name="A" minOccurs="0" maxOccurs="unbounded"/>

means A is optional and may repeat an unlimited number of times.


See Also

  • W3C XML Schema Part 0: Primer

    In general, an element is required to appear when the value of minOccurs is 1 or more. The maximum number of times an element may appear is determined by the value of a maxOccurs attribute in its declaration. This value may be a positive integer such as 41, or the term unbounded to indicate there is no maximum number of occurrences. The default value for both the minOccurs and the maxOccurs attributes is 1. Thus, when an element such as comment is declared without a maxOccurs attribute, the element may not occur more than once. Be sure that if you specify a value for only the minOccurs attribute, it is less than or equal to the default value of maxOccurs, i.e. it is 0 or 1. Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs, i.e. 1 or more. If both attributes are omitted, the element must appear exactly once.

  • W3C XML Schema Part 1: Structures Second Edition

    <element
      maxOccurs = (nonNegativeInteger | unbounded)  : 1
      minOccurs = nonNegativeInteger : 1
      >
    
    </element>
    

XML Parser for C

Two examples with expat and libxml2. The second one is, IMHO, much easier to use since it creates a tree in memory, a data structure which is easy to work with. expat, on the other hand, does not build anything (you have to do it yourself), it just allows you to call handlers at specific events during the parsing. But expat may be faster (I didn't measure).

With expat, reading a XML file and displaying the elements indented:

/* 
   A simple test program to parse XML documents with expat
   <http://expat.sourceforge.net/>. It just displays the element
   names.

   On Debian, compile with:

   gcc -Wall -o expat-test -lexpat expat-test.c  

   Inspired from <http://www.xml.com/pub/a/1999/09/expat/index.html> 
*/

#include <expat.h>
#include <stdio.h>
#include <string.h>

/* Keep track of the current level in the XML tree */
int             Depth;

#define MAXCHARS 1000000

void
start(void *data, const char *el, const char **attr)
{
    int             i;

    for (i = 0; i < Depth; i++)
        printf("  ");

    printf("%s", el);

    for (i = 0; attr[i]; i += 2) {
        printf(" %s='%s'", attr[i], attr[i + 1]);
    }

    printf("\n");
    Depth++;
}               /* End of start handler */

void
end(void *data, const char *el)
{
    Depth--;
}               /* End of end handler */

int
main(int argc, char **argv)
{

    char           *filename;
    FILE           *f;
    size_t          size;
    char           *xmltext;
    XML_Parser      parser;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s filename\n", argv[0]);
        return (1);
    }
    filename = argv[1];
    parser = XML_ParserCreate(NULL);
    if (parser == NULL) {
        fprintf(stderr, "Parser not created\n");
        return (1);
    }
    /* Tell expat to use functions start() and end() each times it encounters
     * the start or end of an element. */
    XML_SetElementHandler(parser, start, end);
    f = fopen(filename, "r");
    xmltext = malloc(MAXCHARS);
    /* Slurp the XML file in the buffer xmltext */
    size = fread(xmltext, sizeof(char), MAXCHARS, f);
    if (XML_Parse(parser, xmltext, strlen(xmltext), XML_TRUE) ==
        XML_STATUS_ERROR) {
        fprintf(stderr,
            "Cannot parse %s, file may be too large or not well-formed XML\n",
            filename);
        return (1);
    }
    fclose(f);
    XML_ParserFree(parser);
    fprintf(stdout, "Successfully parsed %i characters in file %s\n", size,
        filename);
    return (0);
}

With libxml2, a program which displays the name of the root element and the names of its children:

/*
   Simple test with libxml2 <http://xmlsoft.org>. It displays the name
   of the root element and the names of all its children (not
   descendents, just children).

   On Debian, compiles with:
   gcc -Wall -o read-xml2 $(xml2-config --cflags) $(xml2-config --libs) \
                    read-xml2.c    

*/

#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>

int
main(int argc, char **argv)
{
    xmlDoc         *document;
    xmlNode        *root, *first_child, *node;
    char           *filename;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s filename.xml\n", argv[0]);
        return 1;
    }
    filename = argv[1];

    document = xmlReadFile(filename, NULL, 0);
    root = xmlDocGetRootElement(document);
    fprintf(stdout, "Root is <%s> (%i)\n", root->name, root->type);
    first_child = root->children;
    for (node = first_child; node; node = node->next) {
        fprintf(stdout, "\t Child is <%s> (%i)\n", node->name, node->type);
    }
    fprintf(stdout, "...\n");
    return 0;
}

How to use XPath contains() here?

Paste my contains example here:

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

Free XML Formatting tool

Advanced Conventional Formatting [Update]

XMLSpectrum is an open source syntax-highlighter. Supporting XML - but with special features for XSLT 2.0, XSD 1.1 and XPath 2.0. I'm mentioning this here because it also has special formatting capabilities for XML: it vertically aligns attributes and their contents as well as elements - to enhance XML readability.

The output HTML is suitable for reviewing in a browser or if the XML needs further editing it can be copied and pasted into an XML editor of your choice

Because xmlspectrum.xsl uses its own XML text parser, all content such as entity references and CDATA sections are preserved - as in an editor.

enter image description here

Note on usage: this is just an XSLT 2.0 stylesheet so you would need to enclose the required command-line (samples provided) in a small script so you could automatically transform the XML source.

Virtual Formatting

XMLQuire is a free XML editor that has special formatting capabilities - it formats XML properly, including multi-line attributes, attribute-values, word-wrap indentation and even XML comments.

All XML indentation is done without inserting tabs or spaces, ensuring the integrity of the XML is maintained. For versions of Windows later than XP, no installation is needed, its just a 3MB .exe file.

If you need to print out the formatted XML there are special options within the print-preview, such as line-numbering that follows the indentation. If you need to copy the formatted XML to a word processor as rich text, that's available too.

[Disclosure: I maintain both XMLQuire and XMLSpectrum as 'home projects']

XDocument or XmlDocument

As mentioned elsewhere, undoubtedly, Linq to Xml makes creation and alteration of xml documents a breeze in comparison to XmlDocument, and the XNamespace ns + "elementName" syntax makes for pleasurable reading when dealing with namespaces.

One thing worth mentioning for xsl and xpath die hards to note is that it IS possible to still execute arbitrary xpath 1.0 expressions on Linq 2 Xml XNodes by including:

using System.Xml.XPath;

and then we can navigate and project data using xpath via these extension methods:

For instance, given the Xml document:

<xml>
    <foo>
        <baz id="1">10</baz>
        <bar id="2" special="1">baa baa</bar>
        <baz id="3">20</baz>
        <bar id="4" />
        <bar id="5" />
    </foo>
    <foo id="123">Text 1<moo />Text 2
    </foo>
</xml>

We can evaluate:

var node = xele.XPathSelectElement("/xml/foo[@id='123']");
var nodes = xele.XPathSelectElements(
"//moo/ancestor::xml/descendant::baz[@id='1']/following-sibling::bar[not(@special='1')]");
var sum = xele.XPathEvaluate("sum(//foo[not(moo)]/baz)");

Using a custom typeface in Android

@majinboo's answer is revised for performance and memory management. Any more than one font need related Activity can use this Font class by giving the constructor itself as a parameter.

@Override
public void onCreate(Bundle savedInstanceState)
{
    Font font = new Font(this);
}

Revised Fonts class is as below:

public class Fonts
{
    private HashMap<AssetTypefaces, Typeface> hashMapFonts;

    private enum AssetTypefaces
    {
        RobotoLight,
        RobotoThin,
        RobotoCondensedBold,
        RobotoCondensedLight,
        RobotoCondensedRegular
    }

    public Fonts(Context context)
    {
        AssetManager mngr = context.getAssets();

        hashMapFonts = new HashMap<AssetTypefaces, Typeface>();
        hashMapFonts.put(AssetTypefaces.RobotoLight, Typeface.createFromAsset(mngr, "fonts/Roboto-Light.ttf"));
        hashMapFonts.put(AssetTypefaces.RobotoThin, Typeface.createFromAsset(mngr, "fonts/Roboto-Thin.ttf"));
        hashMapFonts.put(AssetTypefaces.RobotoCondensedBold, Typeface.createFromAsset(mngr, "fonts/RobotoCondensed-Bold.ttf"));
        hashMapFonts.put(AssetTypefaces.RobotoCondensedLight, Typeface.createFromAsset(mngr, "fonts/RobotoCondensed-Light.ttf"));
        hashMapFonts.put(AssetTypefaces.RobotoCondensedRegular, Typeface.createFromAsset(mngr, "fonts/RobotoCondensed-Regular.ttf"));
    }

    private Typeface getTypeface(String fontName)
    {
        try
        {
            AssetTypefaces typeface = AssetTypefaces.valueOf(fontName);
            return hashMapFonts.get(typeface);
        }
        catch (IllegalArgumentException e)
        {
            // e.printStackTrace();
            return Typeface.DEFAULT;
        }
    }

    public void setupLayoutTypefaces(View v)
    {
        try
        {
            if (v instanceof ViewGroup)
            {
                ViewGroup vg = (ViewGroup) v;
                for (int i = 0; i < vg.getChildCount(); i++)
                {
                    View child = vg.getChildAt(i);
                    setupLayoutTypefaces(child);
                }
            }
            else if (v instanceof TextView)
            {
                ((TextView) v).setTypeface(getTypeface(v.getTag().toString()));
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            // ignore
        }
    }
}

Converting JSON to XML in Java

If you have a valid dtd file for the xml then you can easily transform json to xml and xml to json using the eclipselink jar binary.

Refer this: http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html

The article also has a sample project (including the supporting third party jars) as a zip file which can be downloaded for reference purpose.

PHP: Call to undefined function: simplexml_load_string()

I also faced this issue. My Operating system is Ubuntu 18.04 and my PHP version is PHP 7.2.

Here's how I solved it:

Install Simplexml on your Ubuntu Server:

sudo apt-get install php7.2-simplexml

Restart Apache Server

sudo systemctl restart apache2

That's all.

I hope this helps

Toolbar overlapping below status bar

Remove below lines from style or style(21)

<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/colorPrimaryDark</item>
<item name="android:windowTranslucentStatus">false</item>

Getting attribute using XPath

Thanks! This solved a similar problem I had with a data attribute inside a Div.

<div id="prop_sample" data-want="data I want">data I do not want</div>

Use this xpath: //*[@id="prop_sample"]/@data-want

Hope this helps someone else!

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

PHP XML Extension: Not installed

I solved this issue with commands bellow:

$ sudo apt-get install php7.3-intl

$ sudo /etc/init.d/php7.3-fpm restart

These commands works for me in homestead with php7.3

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

You can use ExtendedXmlSerializer. If you have a class:

public class TestClass
{
    public Dictionary<int, string> Dictionary { get; set; }
}

and create instance of this class:

var obj = new TestClass
{
    Dictionary = new Dictionary<int, string>
    {
        {1, "First"},
        {2, "Second"},
        {3, "Other"},
    }
};

You can serialize this object using ExtendedXmlSerializer:

var serializer = new ConfigurationContainer()
    .UseOptimizedNamespaces() //If you want to have all namespaces in root element
    .Create();

var xml = serializer.Serialize(
    new XmlWriterSettings { Indent = true }, //If you want to formated xml
    obj);

Output xml will look like:

<?xml version="1.0" encoding="utf-8"?>
<TestClass xmlns:sys="https://extendedxmlserializer.github.io/system" xmlns:exs="https://extendedxmlserializer.github.io/v2" xmlns="clr-namespace:ExtendedXmlSerializer.Samples;assembly=ExtendedXmlSerializer.Samples">
  <Dictionary>
    <sys:Item>
      <Key>1</Key>
      <Value>First</Value>
    </sys:Item>
    <sys:Item>
      <Key>2</Key>
      <Value>Second</Value>
    </sys:Item>
    <sys:Item>
      <Key>3</Key>
      <Value>Other</Value>
    </sys:Item>
  </Dictionary>
</TestClass>

You can install ExtendedXmlSerializer from nuget or run the following command:

Install-Package ExtendedXmlSerializer

Put buttons at bottom of screen with LinearLayout?

first create file name it as footer.xml put this code inside it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="78dp"
    android:layout_gravity="bottom"
    android:gravity="bottom"
 android:layout_weight=".15"
    android:orientation="horizontal"
    android:background="@drawable/actionbar_dark_background_tile" >
    <ImageView
        android:id="@+id/lborder"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/overlay" />
    <ImageView
        android:id="@+id/unknown"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/notcolor" />
    <ImageView
        android:id="@+id/open"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/openit"
        />
    <ImageView
        android:id="@+id/color"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/colored" />
        <ImageView
        android:id="@+id/rborder"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/frames"
        android:layout_weight=".14" />


</LinearLayout>  

then create header.xml and put this code inside it.:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="@dimen/action_bar_height"
    android:layout_gravity="top"
    android:baselineAligned="true"
    android:orientation="horizontal"
    android:background="@drawable/actionbar_dark_background_tile" >
    <ImageView
        android:id="@+id/contact"
        android:layout_width="37dp"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:layout_weight=".18"
        android:scaleType="fitCenter"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/logo"/>

    <ImageView
        android:id="@+id/share"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/share" />

    <ImageView
        android:id="@+id/save"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/save" />

    <ImageView
        android:id="@+id/set"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/set" />

    <ImageView
        android:id="@+id/fix"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/light" />

    <ImageView
        android:id="@+id/rotate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/ic_menu_rotate" />

    <ImageView
        android:id="@+id/stock"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/stock" />

</LinearLayout>

and then in your main_activity.xml and put this code inside it :-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity"
android:id="@+id/relt"
android:background="@drawable/background" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="78dp"
    android:id="@+id/down"
    android:layout_alignParentBottom="true" >

    <include
        android:layout_width="fill_parent"
        android:layout_height="78dp"
        layout="@layout/footer" >
    </include>
</LinearLayout>
<ImageView
    android:id="@+id/view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/down"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/inc"
   >  
    </ImageView> 
    <include layout="@layout/header"
        android:id="@+id/inc"
        android:layout_width="fill_parent"
        android:layout_height="50dp"></include> 

happy coding :)

how to parse xml to java object?

One thing that is really important to understand considering you have an XML file as :

<customer id="100">
    <Age>29</Age>
    <NAME>mkyong</NAME>
</customer>

I am sorry to inform you but :

@XmlElement
public void setAge(int age) {
    this.age = age;
}

will not help you, as it tries to look for "age" instead of "Age" element name from the XML.

I encourage you to manually specify the element name matching the one in the XML file :

@XmlElement(name="Age")
public void setAge(int age) {
    this.age = age;
}

And if you have for example :

@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)
public class Customer {
...

It means it will use java beans by default, and at this time if you specify that you must not set another

@XmlElement(name="NAME")

annotation above a setter method for an element <NAME>..</NAME> it will fail saying that there cannot be two elements on one single variables.

I hope that it helps.

How do I align views at the bottom of the screen?

In a ScrollView this doesn't work, as the RelativeLayout would then overlap whatever is in the ScrollView at the bottom of the page.

I fixed it using a dynamically stretching FrameLayout :

<ScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent" 
    android:layout_width="match_parent"
    android:fillViewport="true">
    <LinearLayout 
        android:id="@+id/LinearLayout01"
        android:layout_width="match_parent" 
        android:layout_height="match_parent"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical">

                <!-- content goes here -->

                <!-- stretching frame layout, using layout_weight -->
        <FrameLayout
            android:layout_width="match_parent" 
            android:layout_height="0dp"
            android:layout_weight="1">
        </FrameLayout>

                <!-- content fixated to the bottom of the screen -->
        <LinearLayout 
            android:layout_width="match_parent" 
            android:layout_height="wrap_content"
            android:orientation="horizontal">
                                   <!-- your bottom content -->
        </LinearLayout>
    </LinearLayout>
</ScrollView>

The 'packages' element is not declared

You can also find a copy of the nuspec.xsd here as it seems to no longer be available:

https://gist.github.com/sharwell/6131243

How do I get HTTP Request body content in Laravel?

For those who are still getting blank response with $request->getContent(), you can use:

$request->all()

e.g:

public function foo(Request $request){
   $bodyContent = $request->all();
}

Convert an object to an XML string

    public static string Serialize(object dataToSerialize)
    {
        if(dataToSerialize==null) return null;

        using (StringWriter stringwriter = new System.IO.StringWriter())
        {
            var serializer = new XmlSerializer(dataToSerialize.GetType());
            serializer.Serialize(stringwriter, dataToSerialize);
            return stringwriter.ToString();
        }
    }

    public static T Deserialize<T>(string xmlText)
    {
        if(String.IsNullOrWhiteSpace(xmlText)) return default(T);

        using (StringReader stringReader = new System.IO.StringReader(xmlText))
        {
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
    }

Get nodes where child node contains an attribute

Try

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

This reads:

  • get all book elements
    • that have at least one title
      • which has an attribute lang
        • with a value of "it"

You may find this helpful — it's an article entitled "XPath in Five Paragraphs" by Ronald Bourret.

But in all honesty, //book[title[@lang='it']] and the above should be equivalent, unless your XPath engine has "issues." So it could be something in the code or sample XML that you're not showing us -- for example, your sample is an XML fragment. Could it be that the root element has a namespace, and you aren't counting for that in your query? And you only told us that it didn't work, but you didn't tell us what results you did get.

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

In our case it was an empty AndroidManifest.xml.

While upgrading Eclispe we ran into the usual trouble, and AndroidManifest.xml must have been checked into SVN by the build script after being clobbered.

Found it by compiling from inside Eclipse, instead of from the command line.

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

Most easy way..

//div[@class="Test"]

Assuming you want to find <div class="Test"> as described.

How to change line color in EditText

You can change the color of EditText programmatically just using this line of code:edittext.setBackgroundTintList(ColorStateList.valueOf(yourcolor));

preg_match(); - Unknown modifier '+'

This happened to me because I put a variable in the regex and sometimes its string value included a slash. Solution: preg_quote.

Convert XML String to Object

public string Serialize<T>(T settings)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    StringWriter outStream = new StringWriter();
    serializer.Serialize(outStream, settings);
    return outStream.ToString();
}

align text center with android

Just add these 2 lines;

android:gravity="center_horizontal"
android:textAlignment="center"

XML Schema Validation : Cannot find the declaration of element

cvc-elt.1: Cannot find the declaration of element 'Root'. [7]

Your schemaLocation attribute on the root element should be xsi:schemaLocation, and you need to fix it to use the right namespace.

You should probably change the targetNamespace of the schema and the xmlns of the document to http://myNameSpace.com (since namespaces are supposed to be valid URIs, which Test.Namespace isn't, though urn:Test.Namespace would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.

(though it still won't validate as your <element2> contains an <element3> in the document where the schema expects item)

JAXB: how to marshall map into <key>value</key>

There may be a valid reason why you want to do this, but generating this kind of XML is generally best avoided. Why? Because it means that the XML elements of your map are dependent on the runtime contents of your map. And since XML is usually used as an external interface or interface layer this is not desirable. Let me explain.

The Xml Schema (xsd) defines the interface contract of your XML documents. In addition to being able to generate code from the XSD, JAXB can also generate the XML schema for you from the code. This allows you to restrict the data exchanged over the interface to the pre-agreed structures defined in the XSD.

In the default case for a Map<String, String>, the generated XSD will restrict the map element to contain multiple entry elements each of which must contain one xs:string key and one xs:string value. That's a pretty clear interface contract.

What you describe is that you want the xml map to contain elements whose name will be determined by the content of the map at runtime. Then the generated XSD can only specify that the map must contain a list of elements whose type is unknown at compile time. This is something that you should generally avoid when defining an interface contract.

To achieve a strict contract in this case, you should use an enumerated type as the key of the map instead of a String. E.g.

public enum KeyType {
 KEY, KEY2;
}

@XmlJavaTypeAdapter(MapAdapter.class)
Map<KeyType , String> mapProperty;

That way the keys which you want to become elements in XML are known at compile time so JAXB should be able to generate a schema that would restrict the elements of map to elements using one of the predefined keys KEY or KEY2.

On the other hand, if you wish to simplify the default generated structure

<map>
    <entry>
        <key>KEY</key>
        <value>VALUE</value>
    </entry>
    <entry>
        <key>KEY2</key>
        <value>VALUE2</value>
    </entry>
</map>

To something simpler like this

<map>
    <item key="KEY" value="VALUE"/>
    <item key="KEY2" value="VALUE2"/>
</map>

You can use a MapAdapter that converts the Map to an array of MapElements as follows:

class MapElements {
    @XmlAttribute
    public String key;
    @XmlAttribute
    public String value;

    private MapElements() {
    } //Required by JAXB

    public MapElements(String key, String value) {
        this.key = key;
        this.value = value;
    }
}


public class MapAdapter extends XmlAdapter<MapElements[], Map<String, String>> {
    public MapAdapter() {
    }

    public MapElements[] marshal(Map<String, String> arg0) throws Exception {
        MapElements[] mapElements = new MapElements[arg0.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : arg0.entrySet())
            mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());

        return mapElements;
    }

    public Map<String, String> unmarshal(MapElements[] arg0) throws Exception {
        Map<String, String> r = new TreeMap<String, String>();
        for (MapElements mapelement : arg0)
            r.put(mapelement.key, mapelement.value);
        return r;
    }
}

How to make layout with rounded corners..?

If you would like to make your layout rounded, it is best to use the CardView, it provided many features to make the design beautiful.

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="5dp">
      <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight=".3"
                android:text="@string/quote_code"
                android:textColor="@color/white"
                android:textSize="@dimen/text_head_size" />
      </LinearLayout>
</android.support.v7.widget.CardView>

With this card_view:cardCornerRadius="5dp", you can change the radius.

How can I query a value in SQL Server XML column

select
  Roles
from
  MyTable
where
  Roles.value('(/root/role)[1]', 'varchar(max)') like 'StringToSearchFor'

In case your column is not XML, you need to convert it. You can also use other syntax to query certain attributes of your XML data. Here is an example...

Let's suppose that data column has this:

<Utilities.CodeSystems.CodeSystemCodes iid="107" CodeSystem="2" Code="0001F" CodeTags="-19-"..../>

... and you only want the ones where CodeSystem = 2 then your query will be:

select 
  [data] 
from
  [dbo].[CodeSystemCodes_data]
  
where
  CAST([data] as XML).value('(/Utilities.CodeSystems.CodeSystemCodes/@CodeSystem)[1]', 'varchar(max)') = '2'

These pages will show you more about how to query XML in T-SQL:

Querying XML fields using t-sql

Flattening XML Data in SQL Server

EDIT

After playing with it a little bit more, I ended up with this amazing query that uses CROSS APPLY. This one will search every row (role) for the value you put in your like expression...

Given this table structure:

create table MyTable (Roles XML)

insert into MyTable values
('<root>
   <role>Alpha</role>
   <role>Gamma</role>
   <role>Beta</role>
</root>')

We can query it like this:

select * from 

(select 
       pref.value('(text())[1]', 'varchar(32)') as RoleName
from 
       MyTable CROSS APPLY

       Roles.nodes('/root/role') AS Roles(pref)
)  as Result

where RoleName like '%ga%'

You can check the SQL Fiddle here: http://sqlfiddle.com/#!18/dc4d2/1/0

'xmlParseEntityRef: no name' warnings while loading xml into a php file

Try to clean the HTML first using this function:

$html = htmlspecialchars($html);

Special chars are usually represented differently in HTML and it might be confusing for the compiler. Like & becomes &amp;.

How to convert an xml string to a dictionary?

Here's a link to an ActiveState solution - and the code in case it disappears again.

==================================================
xmlreader.py:
==================================================
from xml.dom.minidom import parse


class NotTextNodeError:
    pass


def getTextFromNode(node):
    """
    scans through all children of node and gathers the
    text. if node has non-text child-nodes, then
    NotTextNodeError is raised.
    """
    t = ""
    for n in node.childNodes:
    if n.nodeType == n.TEXT_NODE:
        t += n.nodeValue
    else:
        raise NotTextNodeError
    return t


def nodeToDic(node):
    """
    nodeToDic() scans through the children of node and makes a
    dictionary from the content.
    three cases are differentiated:
    - if the node contains no other nodes, it is a text-node
    and {nodeName:text} is merged into the dictionary.
    - if the node has the attribute "method" set to "true",
    then it's children will be appended to a list and this
    list is merged to the dictionary in the form: {nodeName:list}.
    - else, nodeToDic() will call itself recursively on
    the nodes children (merging {nodeName:nodeToDic()} to
    the dictionary).
    """
    dic = {} 
    for n in node.childNodes:
    if n.nodeType != n.ELEMENT_NODE:
        continue
    if n.getAttribute("multiple") == "true":
        # node with multiple children:
        # put them in a list
        l = []
        for c in n.childNodes:
            if c.nodeType != n.ELEMENT_NODE:
            continue
        l.append(nodeToDic(c))
            dic.update({n.nodeName:l})
        continue

    try:
        text = getTextFromNode(n)
    except NotTextNodeError:
            # 'normal' node
            dic.update({n.nodeName:nodeToDic(n)})
            continue

        # text node
        dic.update({n.nodeName:text})
    continue
    return dic


def readConfig(filename):
    dom = parse(filename)
    return nodeToDic(dom)





def test():
    dic = readConfig("sample.xml")

    print dic["Config"]["Name"]
    print
    for item in dic["Config"]["Items"]:
    print "Item's Name:", item["Name"]
    print "Item's Value:", item["Value"]

test()



==================================================
sample.xml:
==================================================
<?xml version="1.0" encoding="UTF-8"?>

<Config>
    <Name>My Config File</Name>

    <Items multiple="true">
    <Item>
        <Name>First Item</Name>
        <Value>Value 1</Value>
    </Item>
    <Item>
        <Name>Second Item</Name>
        <Value>Value 2</Value>
    </Item>
    </Items>

</Config>



==================================================
output:
==================================================
My Config File

Item's Name: First Item
Item's Value: Value 1
Item's Name: Second Item
Item's Value: Value 2

Use of Greater Than Symbol in XML

CDATA is a better general solution.

Send XML data to webservice using php curl

If you are using shared hosting, then there are chances that outbound port might be disabled by your hosting provider. So please contact your hosting provider and they will open the outbound port for you

How to convert XML to JSON in Python?

Soviut's advice for lxml objectify is good. With a specially subclassed simplejson, you can turn an lxml objectify result into json.

import simplejson as json
import lxml

class objectJSONEncoder(json.JSONEncoder):
  """A specialized JSON encoder that can handle simple lxml objectify types
      >>> from lxml import objectify
      >>> obj = objectify.fromstring("<Book><price>1.50</price><author>W. Shakespeare</author></Book>")       
      >>> objectJSONEncoder().encode(obj)
      '{"price": 1.5, "author": "W. Shakespeare"}'       
 """


    def default(self,o):
        if isinstance(o, lxml.objectify.IntElement):
            return int(o)
        if isinstance(o, lxml.objectify.NumberElement) or isinstance(o, lxml.objectify.FloatElement):
            return float(o)
        if isinstance(o, lxml.objectify.ObjectifiedDataElement):
            return str(o)
        if hasattr(o, '__dict__'):
            #For objects with a __dict__, return the encoding of the __dict__
            return o.__dict__
        return json.JSONEncoder.default(self, o)

See the docstring for example of usage, essentially you pass the result of lxml objectify to the encode method of an instance of objectJSONEncoder

Note that Koen's point is very valid here, the solution above only works for simply nested xml and doesn't include the name of root elements. This could be fixed.

I've included this class in a gist here: http://gist.github.com/345559

What's the best way to validate an XML file against an XSD file?

We build our project using ant, so we can use the schemavalidate task to check our config files:

<schemavalidate> 
    <fileset dir="${configdir}" includes="**/*.xml" />
</schemavalidate>

Now naughty config files will fail our build!

http://ant.apache.org/manual/Tasks/schemavalidate.html

Android getting value from selected radiobutton

In case, if you want to do some job on the selection of one of the radio buttons (without having any additional OK button or something), your code is fine, updated little.

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() 
        {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId){
                    case R.id.radio0:
                        // do operations specific to this selection
                        break;
                    case R.id.radio1:
                        // do operations specific to this selection
                        break;
                    case R.id.radio2:
                        // do operations specific to this selection
                        break;
                }   
            }
        });
    }
}

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

insert data into database using servlet and jsp in eclipse

Can you check value of i by putting logger or println(). and check with closing db conn at the end. Rest your code looks fine and it should work.

XML Parsing - Read a Simple XML File and Retrieve Values

Easy way to parse the xml is to use the LINQ to XML

for example you have the following xml file

<library>
    <track id="1" genre="Rap" time="3:24">
        <name>Who We Be RMX (feat. 2Pac)</name>
        <artist>DMX</artist>
        <album>The Dogz Mixtape: Who's Next?!</album>
    </track>
    <track id="2" genre="Rap" time="5:06">
        <name>Angel (ft. Regina Bell)</name>
        <artist>DMX</artist>
        <album>...And Then There Was X</album>
    </track>
    <track id="3" genre="Break Beat" time="6:16">
        <name>Dreaming Your Dreams</name>
        <artist>Hybrid</artist>
        <album>Wide Angle</album>
    </track>
    <track id="4" genre="Break Beat" time="9:38">
        <name>Finished Symphony</name>
        <artist>Hybrid</artist>
        <album>Wide Angle</album>
    </track>
<library>

For reading this file, you can use the following code:

public void Read(string  fileName)
{
    XDocument doc = XDocument.Load(fileName);

    foreach (XElement el in doc.Root.Elements())
    {
        Console.WriteLine("{0} {1}", el.Name, el.Attribute("id").Value);
        Console.WriteLine("  Attributes:");
        foreach (XAttribute attr in el.Attributes())
            Console.WriteLine("    {0}", attr);
        Console.WriteLine("  Elements:");

        foreach (XElement element in el.Elements())
            Console.WriteLine("    {0}: {1}", element.Name, element.Value);
    }
}

XMLHttpRequest (Ajax) Error

So there might be a few things wrong here.

First start by reading how to use XMLHttpRequest.open() because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send(). Here's an example from MDN:

var oXHR = new XMLHttpRequest();

oXHR.open("GET", "http://www.mozilla.org/", true);

oXHR.onreadystatechange = function (oEvent) {
    if (oXHR.readyState === 4) {
        if (oXHR.status === 200) {
          console.log(oXHR.responseText)
        } else {
           console.log("Error", oXHR.statusText);
        }
    }
};

oXHR.send(null);

Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml file.

You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:

var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false); 
request.send(null);

if (request.status == 0)
    console.log(request.responseText);

Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.

Query an XDocument for elements by name at any depth

You can do it this way:

xml.Descendants().Where(p => p.Name.LocalName == "Name of the node to find")

where xml is a XDocument.

Be aware that the property Name returns an object that has a LocalName and a Namespace. That's why you have to use Name.LocalName if you want to compare by name.

XML Schema How to Restrict Attribute by Enumeration

The numerical value seems to be missing from your price definition. Try the following:

<xs:simpleType name="curr">
  <xs:restriction base="xs:string">
    <xs:enumeration value="pounds" />
    <xs:enumeration value="euros" />
    <xs:enumeration value="dollars" />
  </xs:restriction>
</xs:simpleType>



<xs:element name="price">
        <xs:complexType>
            <xs:extension base="xs:decimal">
              <xs:attribute name="currency" type="curr"/>
            </xs:extension>
        </xs:complexType>
</xs:element>

SVG rounded corner

As referenced in my answer to Applying rounded corners to paths/polygons, I have written a routine in javascript for generically rounding corners of SVG paths, with examples, here: http://plnkr.co/edit/kGnGGyoOCKil02k04snu.

It will work independently from any stroke effects you may have. To use, include the rounding.js file from the Plnkr and call the function like so:

roundPathCorners(pathString, radius, useFractionalRadius)

The result will be the rounded path.

The results look like this:

SVG Path Rounding Examples

Finding element in XDocument?

The Elements() method returns an IEnumerable<XElement> containing all child elements of the current node. For an XDocument, that collection only contains the Root element. Therefore the following is required:

var query = from c in xmlFile.Root.Elements("Band")
            select c;

How can I comment a single line in XML?

No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.

XML has only one definition for a comment:

'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'

XML forbids -- in comments to maintain compatibility with SGML.

How does one parse XML files?

If you're processing a large amount of data (many megabytes) then you want to be using XmlReader to stream parse the XML.

Anything else (XPathNavigator, XElement, XmlDocument and even XmlSerializer if you keep the full generated object graph) will result in high memory usage and also a very slow load time.

Of course, if you need all the data in memory anyway, then you may not have much choice.

send/post xml file using curl command line

You can using option --data with file.

Write xml content to a file named is soap_get.xml and using curl command to send request:

curl -X POST --header "Content-Type:text/xml;charset=UTF-8" --data @soap_get.xml your_url

What are invalid characters in XML

For XSL (on really lazy days) I use:

capture="&amp;(?!amp;)" capturereplace="&amp;amp;"

to translate all &-signs that aren't follwed på amp; to proper ones.

We have cases where the input is in CDATA but the system which uses the XML doesn't take it into account. It's a sloppy fix, beware...

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

What is difference between XML Schema and DTD?

As many people have mentioned before, XML Schema utilize an XML-based syntax and DTDs have a unique syntax. DTD doesn't support datatypes, which does matter.

Lets see a very simple example in which university has multiple students and each student has two elements "name" and "year". Please note that I have uses "// --> " in my code just for comments.

enter image description here

Now I will write this example both in DTD and in XSD.

DTD

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE university[              // --> university as root element 
<!ELEMENT university (student*)>   // --> university has  * = Multiple students
<!ELEMENT student (name,year)>     // --> Student has elements name and year
<!ELEMENT name (#PCDATA)>          // --> name as Parsed character data
<!ELEMENT year (#PCDATA)>          // --> year as Parsed character data
]>

<university>
    <student>
        <name>
            John Niel             //---> I can also use an Integer,not good
        </name>
        <year>
            2000                 //---> I can also use a string,not good
        </year>
    </student>
</university>

XML Schema Definition (XSD)

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<xsd:complexType name ="uniType">                    //--> complex datatype uniType
 <xsd:sequence>
  <xsd:element ref="student" maxOccurs="unbounded"/> //--> has unbounded no.of students
 </xsd:sequence>
</xsd:complexType>

<xsd:complexType name="stuType">                     //--> complex datatype stuType
 <xsd:sequence>
  <xsd:element ref="name"/>                          //--> has element name
  <xsd:element ref="year"/>                          //--> has element year
 </xsd:sequence>
</xsd:complexType>

<xsd:element name="university" type="uniType"/>       //--> university of type UniType 
<xsd:element name="student" type="stuType"/>          //--> student of type stuType
<xsd:element name="name" type="xsd:string"/>          //--> name of datatype string
<xsd:element name="year" type="xsd:integer"/>         //--> year of datatype integer
</xsd:schema>



<?xml version="1.0" encoding="UTF-8"?>
<university>
    <student>
        <name>
            John Niel          
        </name>
        <year>
            2000                      //--> only an Integer value is allowed
        </year>
    </student>
</university>

How to create an XML document using XmlDocument?

Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here

and edited my code: (xmlDoc.DocumentElement.AppendChild(body))

//a dictionary:
Dictionary<string, string> Level2Data 
{
    {"level2", "text"},
    {"level2", "other text"},
    {"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR



foreach (KeyValuePair<string, string> entry in Level2Data)
{
    //write to xml: - it works version 1.
    XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
    keyNode.InnerText = entry.Value;
    body.AppendChild(keyNode); //close TAB

    //Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
    //XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
    //XmlText value = xmlDoc.CreateTextNode(entry.Value);
    //key.AppendChild(value);
    //body.AppendChild(key);
}

Both versions (1 and 2 inside foreach loop) give the output:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <level1>
        <level2>text</level2>
        <level2>ther text</level2>
         <same_level2>more text</same_level2>
    </level1>
</body>

(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.

Simple conversion between java.util.Date and XMLGregorianCalendar

You can use the this customization to change the default mapping to java.util.Date

<xsd:annotation>
<xsd:appinfo>
    <jaxb:globalBindings>
        <jaxb:javaType name="java.util.Date" xmlType="xsd:dateTime"
                 parseMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.parseDateTime"
                 printMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.printDateTime"/>
    </jaxb:globalBindings>
</xsd:appinfo>

JAXB: How to ignore namespace during unmarshalling XML document?

In my situation, I have many namespaces and after some debug I find another solution just changing the NamespaceFitler class. For my situation (just unmarshall) this work fine.

 import javax.xml.namespace.QName;
 import org.xml.sax.Attributes;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.SAXException;
 import org.xml.sax.helpers.XMLFilterImpl;
 import com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector;

 public class NamespaceFilter extends XMLFilterImpl {
    private SAXConnector saxConnector;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
        if(saxConnector != null) {
            Collection<QName> expected = saxConnector.getContext().getCurrentExpectedElements();
            for(QName expectedQname : expected) {
                if(localName.equals(expectedQname.getLocalPart())) {
                    super.startElement(expectedQname.getNamespaceURI(), localName, qName, atts);
                    return;
                }
            }
        }
        super.startElement(uri, localName, qName, atts);
    }

    @Override
    public void setContentHandler(ContentHandler handler) {
        super.setContentHandler(handler);
        if(handler instanceof SAXConnector) {
            saxConnector = (SAXConnector) handler;
        }
    }
}

How to capitalize the first letter of text in a TextView in an Android Application

For Kotlin, if you want to be sure that the format is "Aaaaaaaaa" you can use :

myString.toLowerCase(Locale.getDefault()).capitalize()

Escape double quote character in XML

No there isn't an escape character as such, instead you can use &quot; or even <![CDATA["]]> to represent the " character.

How to retrieve element value of XML using Java?

If you are just looking to get a single value from the XML you may want to use Java's XPath library. For an example see my answer to a previous question:

It would look something like:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

    public static void main(String[] args) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document dDoc = builder.parse("E:/test.xml");

            XPath xPath = XPathFactory.newInstance().newXPath();
            Node node = (Node) xPath.evaluate("/Request/@name", dDoc, XPathConstants.NODE);
            System.out.println(node.getNodeValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Java: How to Indent XML Generated by Transformer

You need to enable 'INDENT' and set the indent amount for the transformer:

t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

Update:


Reference : How to strip whitespace-only text nodes from a DOM before serialization?

(Many thanks to all members especially @marc-novakowski, @james-murty and @saad):

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

Launch chrome like so to bypass this restriction: open -a "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --args --allow-file-access-from-files.

Derived from Josh Lee's comment but I needed to specify the full path to Google Chrome so as to avoid having Google Chrome opening from my Windows partition (in Parallels).

Converting XML to JSON using Python?

I found for simple XML snips, use regular expression would save troubles. For example:

# <user><name>Happy Man</name>...</user>
import re
names = re.findall(r'<name>(\w+)<\/name>', xml_string)
# do some thing to names

To do it by XML parsing, as @Dan said, there is not one-for-all solution because the data is different. My suggestion is to use lxml. Although not finished to json, lxml.objectify give quiet good results:

>>> from lxml import objectify
>>> root = objectify.fromstring("""
... <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
...   <a attr1="foo" attr2="bar">1</a>
...   <a>1.2</a>
...   <b>1</b>
...   <b>true</b>
...   <c>what?</c>
...   <d xsi:nil="true"/>
... </root>
... """)

>>> print(str(root))
root = None [ObjectifiedElement]
    a = 1 [IntElement]
      * attr1 = 'foo'
      * attr2 = 'bar'
    a = 1.2 [FloatElement]
    b = 1 [IntElement]
    b = True [BoolElement]
    c = 'what?' [StringElement]
    d = None [NoneElement]
      * xsi:nil = 'true'

What is the difference between XML and XSD?

XSD:
XSD (XML Schema Definition) specifies how to formally describe the elements in an Extensible Markup Language (XML) document.
Xml:
XML was designed to describe data.It is independent from software as well as hardware.
It enhances the following things.
-Data sharing.
-Platform independent.
-Increasing the availability of Data.

Differences:

  1. XSD is based and written on XML.

  2. XSD defines elements and structures that can appear in the document, while XML does not.

  3. XSD ensures that the data is properly interpreted, while XML does not.

  4. An XSD document is validated as XML, but the opposite may not always be true.

  5. XSD is better at catching errors than XML.

An XSD defines elements that can be used in the documents, relating to the actual data with which it is to be encoded.
for eg:
A date that is expressed as 1/12/2010 can either mean January 12 or December 1st. Declaring a date data type in an XSD document, ensures that it follows the format dictated by XSD.

Error in strings.xml file in Android

The best answer of simply escaping the ' with \' works but I do not like the solution because when using replace all with ' to \', it only works once. The second time you'll be left with \\'.

Therefore, use: \u0027.

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

I eventually figured out there was a byte mark exception and removed it using this code:

 string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
    if (xml.StartsWith(_byteOrderMarkUtf8))
    {
        var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length-1;
        xml = xml.Remove(0, lastIndexOfUtf8);
    }

Making a triangle shape using xml definitions?

Google provides a Equilateral triangle here.
Choose VectorDrawable so the size is flexible.
It' integrated into Android Studio as plugin.

If you have an SVG image, you can use this to convert it to VectorDrawable too.

Once you have a VectorDrawable, changing its colour and rotation is easy like others have mentioned.

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

How to convert an XML file to nice pandas dataframe?

Chiming in to recommend the use of the xmltodict library. It handled your xml text pretty well and I've used it for ingesting an xml file with almost a million records. xmltodict handling xml load

In Java, how do I parse XML as a String instead of a file?

I have this function in my code base, this should work for you.

public static Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    return builder.parse(is);
}

also see this similar question

How to make an element in XML schema optional?

Try this

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />

if you want 0 or 1 "description" elements, Or

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />

if you want 0 to infinity number of "description" elements.

How to generate sample XML documents from their DTD or XSD?

The OpenXSD library mentions that they have support for generating XML instances based on the XSD. Check that out.

Disable XML validation in Eclipse

The other answers may work for you, but they did not cover my case. I wanted some XML to be validated, and others not. This image shows how to exclude certain folders (or files) for XML validation.

Begin by right clicking the root of your Eclipse project. Select the last item: Properties...

enter image description here

(If your browser scales this image very small, right click and open in a new window or tab.)

  • Eclipse appears to be very sensitive if you click the **Browse File...* or **Browser Folder...* button. This dialog needs some work!
  • This was done using Eclipse 4.3 (Kepler).

Read a XML (from a string) and get some fields - Problems reading XML

You should use LoadXml method, not Load:

xmlDoc.LoadXml(myXML); 

Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);

string xpath = "myDataz/listS/sog";
var nodes = xmlDoc.SelectNodes(xpath);

foreach (XmlNode childrenNode in nodes)
{
    HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value);
} 

Best way to generate xml?

I would use the yattag library. I think it's the most pythonic way:

from yattag import Doc

doc, tag, text = Doc().tagtext()

with tag('food'):
    with tag('name'):
        text('French Breakfast')
    with tag('price', currency='USD'):
        text('6.95')
    with tag('ingredients'):
        for ingredient in ('baguettes', 'jam', 'butter', 'croissants'):
            with tag('ingredient'):
                text(ingredient)


print(doc.getvalue())

Comments in Android Layout xml

<!-- comment here -->

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 generate XML file dynamically using PHP?

Take a look at the Tiny But Strong templating system. It's generally used for templating HTML but there's an extension that works with XML files. I use this extensively for creating reports where I can have one code file and two template files - htm and xml - and the user can then choose whether to send a report to screen or spreadsheet.

Another advantage is you don't have to code the xml from scratch, in some cases I've been wanting to export very large complex spreadsheets, and instead of having to code all the export all that is required is to save an existing spreadsheet in xml and substitute in code tags where data output is required. It's a quick and a very efficient way to work.

Android EditText for password with android:hint

I had the same issue and found a solution :

Previous code:

    <EditText 
    android:layout_height="wrap_content"
    android:gravity="center" 
    android:inputType ="password" 
    android:layout_width="fill_parent"
    android:id="@+id/password" 
    android:hint="password" 
    android:maxLines="1">
    </EditText>

Solution:

<EditText 
android:layout_height="wrap_content"
android:gravity="center" 
android:password="true" 
android:layout_width="fill_parent"
android:id="@+id/password" 
android:hint="password" 
android:maxLines="1">
</EditText>

The previous code does not show the 'hint', but when I changed it to the last one it started showing...

hope this be helpful to someone...

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

ImageView in circular through xml

I hope this will help you.

1) CircleImageView

enter image description here

 <de.hdodenhof.circleimageview.CircleImageView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/profile_image"
    android:layout_width="96dp"
    android:layout_height="96dp"
    android:src="@drawable/profile"
    app:civ_border_width="2dp"
    app:civ_border_color="#FF000000"/>

Don't forget implementation: Gradle Scripts > build.gradle (Module: app) > dependencies

     implementation 'de.hdodenhof:circleimageview:3.1.0'   

For complete description please check here : The Source here.

2) CircularImageView

enter image description here

<com.mikhaellopez.circularimageview.CircularImageView
    android:layout_width="250dp"
    android:layout_height="250dp"
    android:src="@drawable/image"
    app:civ_border_color="#3f51b5"
    app:civ_border_width="4dp"
    app:civ_shadow="true"
    app:civ_shadow_radius="10"
    app:civ_shadow_color="#3f51b5"/>

Don't forget implementation: Gradle Scripts > build.gradle (Module: app) > dependencies

     implementation 'com.mikhaellopez:circularimageview:4.2.0'   

For complete description please check here : The Source here.

Accessing @attribute from SimpleXML

Unfortunately I have a unique build (stuck with Gentoo for the moment) of PHP 5.5, and what I found was that

 $xml->tagName['attribute']

was the only solution that worked. I tried all of Bora's methods above, including the 'Right & Quick' format, and they all failed.

The fact that this is the easiest format is a plus, but didn't enjoy thinking I was insane trying all of the formats others were saying worked.

Njoy for what its worth (did I mention unique build?).

JAXB :Need Namespace Prefix to all the elements

MSK,

Have you tried setting a namespace declaration to your member variables like this? :

@XmlElement(required = true, namespace = "http://example.com/a")
protected String username;

@XmlElement(required = true, namespace = "http://example.com/a")
protected String password;

For our project, it solved namespace issues. We also had to create NameSpacePrefixMappers.

oracle plsql: how to parse XML and insert into table

You can load an XML document into an XMLType, then query it, e.g.:

DECLARE
  x XMLType := XMLType(
    '<?xml version="1.0" ?> 
<person>
   <row>
       <name>Tom</name>
       <Address>
           <State>California</State>
           <City>Los angeles</City>
       </Address>
   </row>
   <row>
       <name>Jim</name>
       <Address>
           <State>California</State>
           <City>Los angeles</City>
       </Address>
   </row>
</person>');
BEGIN
  FOR r IN (
    SELECT ExtractValue(Value(p),'/row/name/text()') as name
          ,ExtractValue(Value(p),'/row/Address/State/text()') as state
          ,ExtractValue(Value(p),'/row/Address/City/text()') as city
    FROM   TABLE(XMLSequence(Extract(x,'/person/row'))) p
    ) LOOP
    -- do whatever you want with r.name, r.state, r.city
  END LOOP;
END;

How to parse XML in Bash?

Command-line tools that can be called from shell scripts include:

  • 4xpath - command-line wrapper around Python's 4Suite package

  • XMLStarlet

  • xpath - command-line wrapper around Perl's XPath library

    sudo apt-get install libxml-xpath-perl
    
  • Xidel - Works with URLs as well as files. Also works with JSON

I also use xmllint and xsltproc with little XSL transform scripts to do XML processing from the command line or in shell scripts.

What's the difference between text/xml vs application/xml for webservice response

application/xml is seen by svn as binary type whereas text/xml as text file for which a diff can be displayed.

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

In XML there can be only one root element - you have two - heading and song.

If you restructure to something like:

<?xml version="1.0" encoding="UTF-8"?>
<song> 
 <heading>
 The Twelve Days of Christmas
 </heading>
 ....
</song>

The error about well-formed XML on the root level should disappear (though there may be other issues).

PHP convert XML to JSON

Optimizing Antonio Max answer:

$xmlfile = 'yourfile.xml';
$xmlparser = xml_parser_create();

// open a file and read data
$fp = fopen($xmlfile, 'r');
//9999999 is the length which fread stops to read.
$xmldata = fread($fp, 9999999);

// converting to XML
$xml = simplexml_load_string($xmldata, "SimpleXMLElement", LIBXML_NOCDATA);

// converting to JSON
$json = json_encode($xml);
$array = json_decode($json,TRUE);

How do I load an org.w3c.dom.Document from XML in a string?

Whoa there!

There's a potentially serious problem with this code, because it ignores the character encoding specified in the String (which is UTF-8 by default). When you call String.getBytes() the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 data when in fact it's getting EBCDIC or something… not pretty!

Instead, use the parse method that takes an InputSource, which can be constructed with a Reader, like this:

import java.io.StringReader;
import org.xml.sax.InputSource;
…
        return builder.parse(new InputSource(new StringReader(xml)));

It may not seem like a big deal, but ignorance of character encoding issues leads to insidious code rot akin to y2k.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

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

Use the boolean() XPath function

The boolean function converts its argument to a boolean as follows:

  • a number is true if and only if it is neither positive or negative zero nor NaN

  • a node-set is true if and only if it is non-empty

  • a string is true if and only if its length is non-zero

  • an object of a type other than the four basic types is converted to a boolean in a way that is dependent on that type

If there is an AttachedXml in the CreditReport of primary Consumer, then it will return true().

boolean(/mc:Consumers
          /mc:Consumer[@subjectIdentifier='Primary']
            //mc:CreditReport/mc:AttachedXml)

SimpleXml to string

You can use casting:

<?php

$string = "<element><child>Hello World</child></element>";
$xml = new SimpleXMLElement($string);

$text = (string)$xml->child;

$text will be 'Hello World'

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

Your 0xED 0x6E 0x2C 0x20 bytes correspond to "ín, " in ISO-8859-1, so it looks like your content is in ISO-8859-1, not UTF-8. Tell your data provider about it and ask them to fix it, because if it doesn't work for you it probably doesn't work for other people either.

Now there are a few ways to work it around, which you should only use if you cannot load the XML normally. One of them would be to use utf8_encode(). The downside is that if that XML contains both valid UTF-8 and some ISO-8859-1 then the result will contain mojibake. Or you can try to convert the string from UTF-8 to UTF-8 using iconv() or mbstring, and hope they'll fix it for you. (they won't, but you can at least ignore the invalid characters so you can load your XML)

Or you can take the long, long road and validate/fix the sequences by yourself. That will take you a while depending on how familiar you are with UTF-8. Perhaps there are libraries out there that would do that, although I don't know any.

Either way, notify your data provider that they're sending invalid data so that they can fix it.


Here's a partial fix. It will definitely not fix everything, but will fix some of it. Hopefully enough for you to get by until your provider fix their stuff.

function fix_latin1_mangled_with_utf8_maybe_hopefully_most_of_the_time($str)
{
    return preg_replace_callback('#[\\xA1-\\xFF](?![\\x80-\\xBF]{2,})#', 'utf8_encode_callback', $str);
}

function utf8_encode_callback($m)
{
    return utf8_encode($m[0]);
}

How do I compare two string variables in an 'if' statement in Bash?

This question has already great answers, but here it appears that there is a slight confusion between using single equal (=) and double equals (==) in

if [ "$s1" == "$s2" ]

The main difference lies in which scripting language you are using. If you are using Bash then include #!/bin/bash in the starting of the script and save your script as filename.bash. To execute, use bash filename.bash - then you have to use ==.

If you are using sh then use #!/bin/sh and save your script as filename.sh. To execute use sh filename.sh - then you have to use single =. Avoid intermixing them.

How to get a list of installed android applications and pick one to run

context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA); Should return the list of all the installed apps but in android 11 it'll only return the list of system apps. To get the list of all the applications(system+user) we need to provide an additional permission to the application i.e

<uses-permission android:name"android.permission.QUERY_ALL_PACKAGES">

The POM for project is missing, no dependency information available

Change:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

To:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

How to use conditional breakpoint in Eclipse?

Put your breakpoint. Right-click the breakpoint image on the margin and choose Breakpoint Properties:

enter image description here

Configure condition as you see fit:

enter image description here

SQL Server SELECT INTO @variable?

I found your question looking for a solution to the same problem; and what other answers fail to point is a way to use a variable to change the name of the table for every execution of your procedure in a permanent form, not temporary.

So far what I do is concatenate the entire SQL code with the variables to use. Like this:

declare @table_name as varchar(30)
select @table_name = CONVERT(varchar(30), getdate(), 112)
set @table_name = 'DAILY_SNAPSHOT_' + @table_name

EXEC('
        SELECT var1, var2, var3
        INTO '+@table_name+'
        FROM my_view
        WHERE string = ''Strings must use double apostrophe''
    ');

I hope it helps, but it could be cumbersome if the code is too large, so if you've found a better way, please share!

REST API error code 500 handling

You suggested "Catching any unexpected errors and return some error code signaling "unexpected situation" " but couldn't find an appropriate error code.

Guess what: That's what 5xx is there for.

How to find top three highest salary in emp table in oracle?

select top 3 * from emp  order by sal desc

flutter run: No connected devices

Flutter supports both iOS and Android device/simulators.

In terminal, run the flutter devices command to verify that Flutter recognizes your connected Android device.

Here is a reference document, How you can setup Device/Simulator to run your application.

For, Android (on mac system)

Set up your Android device

To prepare to run and test your Flutter app on an Android device, you’ll need an Android device running Android 4.1 (API level 16) or higher.

  1. Enable Developer options and USB debugging on your device. Detailed instructions are available in the Android documentation.
  2. Using a USB cable, plug your phone into your computer. If prompted on your device, authorize your computer to access your device.
  3. In the terminal, run the flutter devices command to verify that Flutter recognizes your connected Android device.
  4. Start your app by running flutter run.

By default, Flutter uses the version of the Android SDK where your adb tool is based. If you want Flutter to use a different installation of the Android SDK, you must set the ANDROID_HOME environment variable to that installation directory.

Set up the Android emulator

To prepare to run and test your Flutter app on the Android emulator, follow these steps:

  1. Enable VM acceleration on your machine.
  2. Launch Android Studio>Tools>Android>AVD Manager and select Create Virtual Device.
  3. Choose a device definition and select Next.
  4. Select one or more system images for the Android versions you want to emulate, and select Next. An x86 or x86_64 image is recommended.
  5. Under Emulated Performance, select Hardware - GLES 2.0 to enable hardware acceleration.
  6. Verify the AVD configuration is correct, and select Finish.

    For details on the above steps, see Managing AVDs.

  7. In Android Virtual Device Manager, click Run in the toolbar. The emulator starts up and displays the default canvas for your selected OS version and device.

  8. Start your app by running flutter run. The connected device name is Android SDK built for , where platform is the chip family, such as x86.

-

Open & Connect Device using Android Studio:

Here is an easier way to open and connect simulators/devices.

Android Studio shows a list of emulators/simulators (installed in your system) or devices (connected to your system). Just select a device, you want to open, from a list, and run project.

enter image description here

Change the Theme in Jupyter Notebook?

conda install jupyterthemes

did not worked for me in Windows. I am using Anaconda.

But,

pip install jupyterthemes

worked in Anaconda Prompt.

How to convert Java String to JSON Object

The string that you pass to the constructor JSONObject has to be escaped with quote():

public static java.lang.String quote(java.lang.String string)

Your code would now be:

JSONObject jsonObj = new JSONObject.quote(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);

How can I run a directive after the dom has finished rendering?

It depends on how your $('site-header') is constructed.

You can try to use $timeout with 0 delay. Something like:

return function(scope, element, attrs) {
    $timeout(function(){
        $('.main').height( $('.site-header').height() -  $('.site-footer').height() );
    });        
}

Explanations how it works: one, two.

Don't forget to inject $timeout in your directive:

.directive('sticky', function($timeout)

Calculate time difference in minutes in SQL Server

Try this..

select starttime,endtime, case
  when DATEDIFF(minute,starttime,endtime) < 60  then DATEDIFF(minute,starttime,endtime) 
  when DATEDIFF(minute,starttime,endtime) >= 60
  then '60,'+ cast( (cast(DATEDIFF(minute,starttime,endtime) as int )-60) as nvarchar(50) )
end from TestTable123416

All You need is DateDiff..

Ascii/Hex convert in bash

Text2Conv="Aa"
for letter in $(echo "$Text2Conv" | sed "s/\(.\)/'\1 /g");do printf '%x' "$letter";done

4161

The trick is using sed to parse the Text2Conv to format we can then seperate anf loop using for.

How to use Git?

To answer your questions directly rather than pointing you at documentation:

1) In order to keep it up to date, do a git pull and that will pull down the latest changes in the repository, on the branch that you're currently using (which is generally master)

2) I don't think there's something (widely available) that'll do this for you. To update them follow 1) for all projects.

Concatenate two NumPy arrays vertically

If the actual problem at hand is to concatenate two 1-D arrays vertically, and we are not fixated on using concatenate to perform this operation, I would suggest the use of np.column_stack:

In []: a = np.array([1,2,3])
In []: b = np.array([4,5,6])
In []: np.column_stack((a, b))
array([[1, 4],
       [2, 5],
       [3, 6]])

Simplest way to display current month and year like "Aug 2016" in PHP?

Here is a simple and more update format of getting the data:

   $now = new \DateTime('now');
   $month = $now->format('m');
   $year = $now->format('Y');

How to create a dynamic array of integers

int main()
{
  int size;

  std::cin >> size;

  int *array = new int[size];

  delete [] array;

  return 0;
}

Don't forget to delete every array you allocate with new.

Why plt.imshow() doesn't display the image?

The solution was as simple as adding plt.show() at the end of the code snippet:

import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
print X_train.shape
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()

Finding whether a point lies inside a rectangle or not

# Pseudo code
# Corners in ax,ay,bx,by,dx,dy
# Point in x, y

bax = bx - ax
bay = by - ay
dax = dx - ax
day = dy - ay

if ((x - ax) * bax + (y - ay) * bay < 0.0) return false
if ((x - bx) * bax + (y - by) * bay > 0.0) return false
if ((x - ax) * dax + (y - ay) * day < 0.0) return false
if ((x - dx) * dax + (y - dy) * day > 0.0) return false

return true

Get a random item from a JavaScript array

Use underscore (or loDash :)):

var randomArray = [
   '#cc0000','#00cc00', '#0000cc'
];

// use _.sample
var randomElement = _.sample(randomArray);

// manually use _.random
var randomElement = randomArray[_.random(randomArray.length-1)];

Or to shuffle an entire array:

// use underscore's shuffle function
var firstRandomElement = _.shuffle(randomArray)[0];

Call int() function on every list element?

In Python 2.x another approach is to use map:

numbers = map(int, numbers)

Note: in Python 3.x map returns a map object which you can convert to a list if you want:

numbers = list(map(int, numbers))

When do you use map vs flatMap in RxJava?

In that scenario use map, you don't need a new Observable for it.

you should use Exceptions.propagate, which is a wrapper so you can send those checked exceptions to the rx mechanism

Observable<String> obs = Observable.from(jsonFile).map(new Func1<File, String>() { 
    @Override public String call(File file) {
        try { 
            return new Gson().toJson(new FileReader(file), Object.class);
        } catch (FileNotFoundException e) {
            throw Exceptions.propagate(t); /will propagate it as error
        } 
    } 
});

You then should handle this error in the subscriber

obs.subscribe(new Subscriber<String>() {
    @Override 
    public void onNext(String s) { //valid result }

    @Override 
    public void onCompleted() { } 

    @Override 
    public void onError(Throwable e) { //e might be the FileNotFoundException you got }
};); 

There is an excellent post for it: http://blog.danlew.net/2015/12/08/error-handling-in-rxjava/

How to remove components created with Angular-CLI

version control is your friend here, do a diff or equivalent and you should see what's been added/modified.

In fact, removing the component folder might not be enough; with Angular-CLI v1.0, the command ng generate component my-new-component also edits your app.module.ts file by adding the respective import line and the component to the providers array.

List all tables in postgresql information_schema

For private schema 'xxx' in postgresql :

SELECT table_name FROM information_schema.tables 
 WHERE table_schema = 'xxx' AND table_type = 'BASE TABLE'

Without table_type = 'BASE TABLE' , you will list tables and views

Markdown to create pages and table of contents?

Here is a short PHP code I use to generate the TOC, and enrich any headings with anchor:

$toc = []; //initialize the toc to an empty array
$markdown = "... your mardown content here...";

$markdown = preg_replace_callback("/(#+)\s*([^\n]+)/",function($matches) use (&$toc){
    static $section = [];
    $h = strlen($matches[1]);

    @$section[$h-1]++;
    $i = $h;
    while(isset($section[$i])) unset($section[$i++]);

    $anchor = preg_replace('/\s+/','-', strtolower(trim($matches[2])));

    $toc[] = str_repeat('  ',$h-1)."* [".implode('.',$section).". {$matches[2]}](#$anchor)";
    return str_repeat('#',$h)." <strong>".implode('.',$section).".</strong> ".$matches[2]."\n<a name=\"$anchor\"></a>\n";
}, $markdown);

You can then print the processed markdown and toc:

   print(implode("\n",$toc));
   print("\n\n");
   print($markdown);

How to loop through each and every row, column and cells in a GridView and get its value

As it's said by "Tim Schmelter" this is the best way : just change in it's code the seconde loop ( GridView2.Columns[i].Count by row.Cells.Count ) so it looks seem's that:

foreach(GridViewRow row in GridView2.Rows)
{
    for(int i = 0; i < GridView2.Columns.Count; i++)
    {
        String header = GridView2.Columns[i].HeaderText;
        String cellText = row.Cells[i].Text;
    }
}

thank you.

How to extract extension from filename string in Javascript?

A variant that works with all of the following inputs:

  • "file.name.with.dots.txt"
  • "file.txt"
  • "file"
  • ""
  • null
  • undefined

would be:

var re = /(?:\.([^.]+))?$/;

var ext = re.exec("file.name.with.dots.txt")[1];   // "txt"
var ext = re.exec("file.txt")[1];                  // "txt"
var ext = re.exec("file")[1];                      // undefined
var ext = re.exec("")[1];                          // undefined
var ext = re.exec(null)[1];                        // undefined
var ext = re.exec(undefined)[1];                   // undefined

Explanation

(?:         # begin non-capturing group
  \.        #   a dot
  (         #   begin capturing group (captures the actual extension)
    [^.]+   #     anything except a dot, multiple times
  )         #   end capturing group
)?          # end non-capturing group, make it optional
$           # anchor to the end of the string

Excel tab sheet names vs. Visual Basic sheet names

Using the sheet codename was the answer I needed too to stop a series of macros falling over - ccampj's answer above mirrors this solution (with screen pics)

SQL Server convert string to datetime

UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)

For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:

https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

How do I separate an integer into separate digits in an array in JavaScript?

This will work for a number greater than 0. You don't need to convert the number into string:

function convertNumberToDigitArray(number) {
    const arr = [];
    while (number > 0) {
        let lastDigit = number % 10;
        arr.push(lastDigit);
        number = Math.floor(number / 10);
    }
    return arr;
}

How can I print a circular structure in a JSON-like format?

You could try the JSON parser library: treedoc. it supports circular references and also dedupes the repeated objects with references.

yarn add treedoc

import {TD} from 'treedoc'
TD.stringify(obj);

If you want more customization

import {TD, TDEncodeOption} from 'treedoc'

const opt = new TDEncodeOption();
opt.coderOption.setShowType(true).setShowFunction(true);
opt.jsonOption.setIndentFactor(2);
return TD.stringify(obj, opt);

The generated JSON file can be viewed by the viewer http://treedoc.org, which supports the navigation through JSON node references.

[shameless plug] I'm the author of this library

How to select all the columns of a table except one column?

You can retrieve the list of column name by simple query and then remove those column by apply where query like this.

SELECT * FROM (
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TableName'
) AS allColumns
WHERE allColumns.COLUMN_NAME NOT IN ('unwantedCol1', 'unwantedCol2')

How to deal with persistent storage (e.g. databases) in Docker

When using Docker Compose, simply attach a named volume, for example:

version: '2'
services:
  db:
    image: mysql:5.6
    volumes:
      - db_data:/var/lib/mysql:rw
    environment:
      MYSQL_ROOT_PASSWORD: root
volumes:
  db_data:

How does the JPA @SequenceGenerator annotation work

Now, back to your questions:

Q1. Does this sequence generator make use of the database's increasing numeric value generating capability or generates the number on its own?

By using the GenerationType.SEQUENCE strategy on the @GeneratedValue annotation, the JPA provider will try to use a database sequence object of the underlying database that supports this feature (e.g., Oracle, SQL Server, PostgreSQL, MariaDB).

If you are using MySQL, which doesn't support database sequence objects, then Hibernate is going to fall back to using the GenerationType.TABLE instead, which is undesirable since the TABLE generation performs badly.

So, don't use the GenerationType.SEQUENCE strategy with MySQL.

Q2. If JPA uses a database auto-increment feature, then will it work with datastores that don't have auto-increment feature?

I assume you are talking about the GenerationType.IDENTITY when you say database auto-increment feature.

To use an AUTO_INCREMENT or IDENTITY column, you need to use the GenerationType.IDENTITYstrategy on the @GeneratedValue annotation.

Q3. If JPA generates numeric value on its own, then how does the JPA implementation know which value to generate next? Does it consult with the database first to see what value was stored last in order to generate the value (last + 1)?

The only time when the JPA provider generates values on its own is when you are using the sequence-based optimizers, like:

These optimizers are meat to reduce the number of database sequence calls, so they multiply the number of identifier values that can be generated using a single database sequence call.

To avoid conflicts between Hibernate identifier optimizers and other 3rd-party clients, you should use pooled or pooled-lo instead of hi/lo. Even if you are using a legacy application that was designed to use hi/lo, you can migrate to the pooled or pooled-lo optimizers.

Q4. Please also shed some light on sequenceName and allocationSize properties of @SequenceGenerator annotation.

The sequenceName attribute defines the database sequence object to be used to generate the identifier values. IT's the object you created using the CREATE SEQUENCE DDL statement.

So, if you provide this mapping:

@Id
@GeneratedValue(
    strategy = GenerationType.SEQUENCE,
    generator = "seq_post"
)
@SequenceGenerator(
    name = "seq_post"
)
private Long id;

Hibernate is going to use the seq_post database object to generate the identifier values:

SELECT nextval('hibernate_sequence')

The allocationSize defines the identifier value multiplier, and if you provide a value that's greater than 1, then Hibernate is going to use the pooled optimizer, to reduce the number of database sequence calls.

So, if you provide this mapping:

@Id
@GeneratedValue(
    strategy = GenerationType.SEQUENCE,
    generator = "seq_post"
)
@SequenceGenerator(
    name = "seq_post",
    allocationSize = 5
)
private Long id;

Then, when you persist 5 entities:

for (int i = 1; i <= 5; i++) {
    entityManager.persist(
        new Post().setTitle(
            String.format(
                "High-Performance Java Persistence, Part %d",
                i
            )
        )
    );
}

Only 2 database sequence calls will be executed, instead of 5:

SELECT nextval('hibernate_sequence')
SELECT nextval('hibernate_sequence')
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 1', 1)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 2', 2)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 3', 3)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 4', 4)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 5', 5)

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

If you are looking for Simple/quicker way, you can follow this solution.

  1. Right click on your project.
  2. Goto > Build Path > Configure Build Path > Java Build Path
  3. Goto 'Source' tab, there, you can see like <<your_project_name>>/src/main/java(missing).
  4. Click on it and remove.
  5. Click on Apply and Close.
  6. Now, right click on project and >New > Source folder > add source folder "src/main/java".

happy learning and do not forget to upvote :)

"Input string was not in a correct format."

Problems

There are some possible cases why the error occurs:

  1. Because textBox1.Text contains only number, but the number is too big/too small

  2. Because textBox1.Text contains:

    • a) non-number (except space in the beginning/end, - in the beginning) and/or
    • b) thousand separators in the applied culture for your code without specifying NumberStyles.AllowThousands or you specify NumberStyles.AllowThousands but put wrong thousand separator in the culture and/or
    • c) decimal separator (which should not exist in int parsing)

NOT OK Examples:

Case 1

a = Int32.Parse("5000000000"); //5 billions, too large
b = Int32.Parse("-5000000000"); //-5 billions, too small
//The limit for int (32-bit integer) is only from -2,147,483,648 to 2,147,483,647

Case 2 a)

a = Int32.Parse("a189"); //having a 
a = Int32.Parse("1-89"); //having - but not in the beginning
a = Int32.Parse("18 9"); //having space, but not in the beginning or end

Case 2 b)

NumberStyles styles = NumberStyles.AllowThousands;
a = Int32.Parse("1,189"); //not OK, no NumberStyles.AllowThousands
b = Int32.Parse("1,189", styles, new CultureInfo("fr-FR")); //not OK, having NumberStyles.AllowThousands but the culture specified use different thousand separator

Case 2 c)

NumberStyles styles = NumberStyles.AllowDecimalPoint;
a = Int32.Parse("1.189", styles); //wrong, int parse cannot parse decimal point at all!

Seemingly NOT OK, but actually OK Examples:

Case 2 a) OK

a = Int32.Parse("-189"); //having - but in the beginning
b = Int32.Parse(" 189 "); //having space, but in the beginning or end

Case 2 b) OK

NumberStyles styles = NumberStyles.AllowThousands;
a = Int32.Parse("1,189", styles); //ok, having NumberStyles.AllowThousands in the correct culture
b = Int32.Parse("1 189", styles, new CultureInfo("fr-FR")); //ok, having NumberStyles.AllowThousands and correct thousand separator is used for "fr-FR" culture

Solutions

In all cases, please check the value of textBox1.Text with your Visual Studio debugger and make sure that it has purely-acceptable numerical format for int range. Something like this:

1234

Also, you may consider of

  1. using TryParse instead of Parse to ensure that the non-parsed number does not cause you exception problem.
  2. check the result of TryParse and handle it if not true

    int val;
    bool result = int.TryParse(textbox1.Text, out val);
    if (!result)
        return; //something has gone wrong
    //OK, continue using val
    

Initializing C dynamic arrays

You need to allocate a block of memory and use it as an array as:

int *arr = malloc (sizeof (int) * n); /* n is the length of the array */
int i;

for (i=0; i<n; i++)
{
  arr[i] = 0;
}

If you need to initialize the array with zeros you can also use the memset function from C standard library (declared in string.h).

memset (arr, 0, sizeof (int) * n);

Here 0 is the constant with which every locatoin of the array will be set. Note that the last argument is the number of bytes to be set the the constant. Because each location of the array stores an integer therefore we need to pass the total number of bytes as this parameter.

Also if you want to clear the array to zeros, then you may want to use calloc instead of malloc. calloc will return the memory block after setting the allocated byte locations to zero.

After you have finished, free the memory block free (arr).

EDIT1

Note that if you want to assign a particular integer in locations of an integer array using memset then it will be a problem. This is because memset will interpret the array as a byte array and assign the byte you have given, to every byte of the array. So if you want to store say 11243 in each location then it will not be possible.

EDIT2

Also note why every time setting an int array to 0 with memset may not work: Why does "memset(arr, -1, sizeof(arr)/sizeof(int))" not clear an integer array to -1? as pointed out by @Shafik Yaghmour

What is the iOS 6 user agent string?

Some more:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

Page redirect after certain time PHP

You can use javascript to redirect after some time

setTimeout(function () {
   window.location.href= 'http://www.google.com'; // the redirect goes here

},5000); // 5 seconds

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

How to convert buffered image to image and vice-versa?

The right way is to use SwingFXUtils.toFXImage(bufferedImage,null) to convert a BufferedImage to a JavaFX Image instance and SwingFXUtils.fromFXImage(image,null) for the inverse operation.

Optionally the second parameter can be a WritableImage to avoid further object allocation.

Count number of occurrences by month

I would add another column on the data sheet with equation =month(A2), then run the countif on that column... If you still wanted to use text month('APRIL'), you would need a lookup table to reference the name to the month number. Otherwise, just use 4 instead of April on your metric sheet.

PHP replacing special characters like à->a, è->e

CodeIgniter way:

$this->load->helper('text');

$string = convert_accented_characters($string);

This function uses a companion config file application/config/foreign_chars.php to define the to and from array for transliteration.

https://www.codeigniter.com/user_guide/helpers/text_helper.html#ascii_to_entities

How to prevent favicon.ico requests?

A very simple solution is put the below code in your .htaccess. I had the same issue and it solve my problem.

<IfModule mod_alias.c>
    RedirectMatch 403 favicon.ico
</IfModule>

Reference: http://perishablepress.com/block-favicon-url-404-requests/

What is the meaning of "this" in Java?

If the instance variables are same as the variables that are declared in the constructor then we use "this" to assign data.

class Example{
     int assign;// instance variable

     Example(int assign){ // variable inside constructor
          this.assign=assign;
     }
}

Hope this helps.

Python spacing and aligning strings

As of Python 3.6, we have a better option, f-strings!

>>> print(f"{'Location: ' + location:<25} Revision: {revision}")
>>> print(f"{'District: ' + district:<25} Date: {date}")
>>> print(f"{'User: ' + user:<25} Time: {time}")

Output:

Location: 10-10-10-10     Revision: 1
District: Tower           Date: May 16, 2012
User: LOD                 Time: 10:15

Since everything within the curly brackets is evaluated at runtime, we can enter both the string 'Location: ' concatenated with the variable location. Using :<25 places the entire concatenated string into a box 25 characters long, and the < designates that you want it left aligned. That way, the second column always starts after those 25 characters reserved for the first column.

Another benefit here is that you don't have to count the characters in your format string. Using 25 will work for all of them, provided that 25 is long enough to contain all of the characters in your left column.

https://realpython.com/python-f-strings/ explains the benefits of f-strings over previous options. https://medium.com/@NirantK/best-of-python3-6-f-strings-41f9154983e explains how to use <, >, and ^ for left, right, and center aligned.

Retrieve last 100 lines logs

I know this is very old, but, for whoever it may helps.

less +F my_log_file.log

that's just basic, with less you can do lot more powerful things. once you start seeing logs you can do search, go to line number, search for pattern, much more plus it is faster for large files.

its like vim for logs[totally my opinion]

original less's documentation : https://linux.die.net/man/1/less

less cheatsheet : https://gist.github.com/glnds/8862214

Laravel Pagination links not including other GET parameters

for who one in laravel 5 or greater in blade:

{{ $table->appends(['id' => $something ])->links() }}

you can get the passed item with

$passed_item=$request->id;

test it with

dd($passed_item);

you must get $something value

How to use WHERE IN with Doctrine 2

I found that, despite what the docs indicate, the only way to get this to work is like this:

$ids = array(...); // Array of your values
$qb->add('where', $qb->expr()->in('r.winner', $ids));

http://groups.google.com/group/doctrine-dev/browse_thread/thread/fbf70837293676fb

How to count TRUE values in a logical vector

I've just had a particular problem where I had to count the number of true statements from a logical vector and this worked best for me...

length(grep(TRUE, (gene.rep.matrix[i,1:6] > 1))) > 5

So This takes a subset of the gene.rep.matrix object, and applies a logical test, returning a logical vector. This vector is put as an argument to grep, which returns the locations of any TRUE entries. Length then calculates how many entries grep finds, thus giving the number of TRUE entries.

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

git: updates were rejected because the remote contains work that you do not have locally

I fixed it, I'm not exactly sure what I did. I tried simply pushing and pulling using:

git pull <remote> dev instead of git pull <remote> master:dev

Hope this helps out someone if they are having the same issue.

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

I had this problem with my datasource in WildFly and Tomcat, connecting to a Oracle 10g.

I found that under certain conditions the statement wasn't closed even when the statement.close() was invoked. The problem was with the Oracle Driver we were using: ojdbc7.jar. This driver is intended for Oracle 12c and 11g, and it seems has some issues when is used with Oracle 10g, so I downgrade to ojdbc5.jar and now everything is running fine.

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

Python import csv to list

As said already in the comments you can use the csv library in python. csv means comma separated values which seems exactly your case: a label and a value separated by a comma.

Being a category and value type I would rather use a dictionary type instead of a list of tuples.

Anyway in the code below I show both ways: d is the dictionary and l is the list of tuples.

import csv

file_name = "test.txt"
try:
    csvfile = open(file_name, 'rt')
except:
    print("File not found")
csvReader = csv.reader(csvfile, delimiter=",")
d = dict()
l =  list()
for row in csvReader:
    d[row[1]] = row[0]
    l.append((row[0], row[1]))
print(d)
print(l)

What is an optional value in Swift?

Let's take the example of an NSError, if there isn't an error being returned you'd want to make it optional to return Nil. There's no point in assigning a value to it if there isn't an error..

var error: NSError? = nil

This also allows you to have a default value. So you can set a method a default value if the function isn't passed anything

func doesntEnterNumber(x: Int? = 5) -> Bool {
    if (x == 5){
        return true
    } else {
        return false
    }
}

Why do we always prefer using parameters in SQL statements?

In Sql when any word contain @ sign it means it is variable and we use this variable to set value in it and use it on number area on the same sql script because it is only restricted on the single script while you can declare lot of variables of same type and name on many script. We use this variable in stored procedure lot because stored procedure are pre-compiled queries and we can pass values in these variable from script, desktop and websites for further information read Declare Local Variable, Sql Stored Procedure and sql injections.

Also read Protect from sql injection it will guide how you can protect your database.

Hope it help you to understand also any question comment me.

How to Find And Replace Text In A File With C#

i tend to use simple forward code as much as i can ,below code worked fine with me

using System;
using System.IO;
using System.Text.RegularExpressions;

/// <summary>
/// Replaces text in a file.
/// </summary>
/// <param name="filePath">Path of the text file.</param>
/// <param name="searchText">Text to search for.</param>
/// <param name="replaceText">Text to replace the search text.</param>
static public void ReplaceInFile( string filePath, string searchText, string replaceText )
{
    StreamReader reader = new StreamReader( filePath );
    string content = reader.ReadToEnd();
    reader.Close();

    content = Regex.Replace( content, searchText, replaceText );

    StreamWriter writer = new StreamWriter( filePath );
    writer.Write( content );
    writer.Close();
}

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

As something of an aside, MAXDOP can apparently be used as a workaround to a potentially nasty bug:

Returned identity values not always correct

Creating an empty list in Python

Here is how you can test which piece of code is faster:

% python -mtimeit  "l=[]"
10000000 loops, best of 3: 0.0711 usec per loop

% python -mtimeit  "l=list()"
1000000 loops, best of 3: 0.297 usec per loop

However, in practice, this initialization is most likely an extremely small part of your program, so worrying about this is probably wrong-headed.

Readability is very subjective. I prefer [], but some very knowledgable people, like Alex Martelli, prefer list() because it is pronounceable.

Counter in foreach loop in C#

The sequence being iterated in a foreach loop might not support indexing or know such a concept it just needs to implement a method called GetEnumerator that returns an object that as a minimum has the interface of IEnumerator though implmenting it is not required. If you know that what you iterate does support indexing and you need the index then I suggest to use a for loop instead.

An example class that can be used in foreach:

    class Foo {

        public iterator GetEnumerator() {
            return new iterator();
        }

        public class iterator {
            public Bar Current {
                get{magic}
            }

            public bool MoveNext() {
                incantation
            }
        }
    }

How to generate random positive and negative numbers in Java

([my double-compatible primitive type here])(Math.random() * [my max value here] * (Math.random() > 0.5 ? 1 : -1))

example:

// need a random number between -500 and +500
long myRandomLong = (long)(Math.random() * 500 * (Math.random() > 0.5 ? 1 : -1));

Padding a table row

Option 1

You could also solve it by adding a transparent border to the row (tr), like this

HTML

<table>
    <tr> 
         <td>1</td>
    </tr>
    <tr> 
         <td>2</td>
    </tr>
</table>

CSS

tr {
    border-top: 12px solid transparent;
    border-bottom: 12px solid transparent;
}

Works like a charm, although if you need regular borders, then this method will sadly not work.

Option 2

Since rows act as a way to group cells, the correct way to do this, would be to use

table {
    border-collapse: inherit;
    border-spacing: 0 10px;
}

Android: combining text & image on a Button or ImageButton

<Button
     android:id="@+id/groups_button_bg"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="Groups"
     android:drawableTop="@drawable/[image]" />


android:drawableLeft
android:drawableRight
android:drawableBottom
android:drawableTop

http://www.mokasocial.com/2010/04/create-a-button-with-an-image-and-text-android/

msvcr110.dll is missing from computer error while installing PHP

Since link to this question shows up on very top of returned results when you search for "php MSVCR110.dll" (not to mention it got 100k+ views and growing), here're some additional notes that you may find handy in your quest to solve MSVCR110.dll mistery...

The approach described in the answer is valid not only for MSVCR110.dll case but also applies when you are looking for other versions, like newer MSVCR71.dll and I updated the answer to include VC15 even it's beyond scope of the original question.


On http://windows.php.net/ you can read:

VC9, VC11 and VC15

More recent versions of PHP are built with VC9, VC11 or VC15 (Visual Studio 2008, 2012 or 2015 compiler respectively) and include improvements in performance and stability.

The VC9 builds require you to have the Visual C++ Redistributable for Visual Studio 2008 SP1 x86 or x64 installed.

The VC11 builds require to have the Visual C++ Redistributable for Visual Studio 2012 x86 or x64 installed.

The VC15 builds require to have the Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed.

This is quite crucial as you not only need to get Visual C++ Redistributable installed but you also need the right version of it, and which one is right and correct, depends on what PHP build you are actually going to use. Pay attention to what version of PHP for Windows you are fetching, especially pay attention to this "VCxx" suffix, because if you install PHP that requires VC9 while having redistributables VC11 installed it is not going to work as run-time dependency is simply not fulfilled. Contrary to what some may think, you need exactly the version required, as newer (higher) releases does NOT cover older (lower) versions. so i.e. VC11 is not providing VC9 compatibility. Also VC15 is neither fulfilling VC11 nor VC9 dependency. It is just VC15 and NOTHING ELSE. Deal with it :)

For example, archive name php-5.6.4-nts-Win32-VC11-x86 tells us the following

enter image description here

  1. it provides PHP v5.6.4,
  2. PHP build is Non-Thread Safe (nts),
  3. it provides binaries for Windows (Win32),
  4. to run, Visual Studio 2012 redistributable (VC11) is required,
  5. binaries are 32-bit (x86),

Most searches I did lead to VC9 of redistributables, so in case of constant failures to make thing works, if possible, try installing different PHP build, to see if you by any chance do not face mismatching versions.


Download links

Note that you are using 32-bit version of PHP, so you need 32-bit redistributable (x86) even if your version of Windows is 64-bit!

  • VC9: Visual C++ Redistributable for Visual Studio 2008: x86 or x64
  • VC11: Visual C++ Redistributable for Visual Studio 2012: x86 or x64
  • VC15: Visual C++ Redistributable for Visual Studio 2015: x86 or x64
  • VC17: Visual C++ Redistributable for Visual Studio 2017: x86 or x64

Bash integer comparison

This script works!

#/bin/bash
if [[ ( "$#" < 1 ) || ( !( "$1" == 1 ) && !( "$1" == 0 ) ) ]] ; then
    echo this script requires a 1 or 0 as first parameter.
else
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
fi

But this also works, and in addition keeps the logic of the OP, since the question is about calculations. Here it is with only arithmetic expressions:

#/bin/bash
if (( $# )) && (( $1 == 0 || $1 == 1 )); then
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
else
    echo this script requires a 1 or 0 as first parameter.
fi

The output is the same1:

$ ./tmp.sh 
this script requires a 1 or 0 as first parameter.

$ ./tmp.sh 0
first parameter is 0

$ ./tmp.sh 1
first parameter is 1

$ ./tmp.sh 2
this script requires a 1 or 0 as first parameter.

[1] the second fails if the first argument is a string

How to parse float with two decimal places in javascript?

You can use toFixed() to do that

var twoPlacedFloat = parseFloat(yourString).toFixed(2)

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

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

Pretty printing JSON from Jackson 2.2's ObjectMapper

The jackson API has changed:

new ObjectMapper()
.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(new HashMap<String, Object>());

How do I escape double and single quotes in sed?

Regarding the single quote, see the code below used to replace the string let's with let us:

command:

echo "hello, let's go"|sed 's/let'"'"'s/let us/g'

result:

hello, let us go

Creating an empty file in C#

System.IO.File.Create(@"C:\Temp.txt");

As others have pointed out, you should dispose of this object or wrap it in an empty using statement.

using (System.IO.File.Create(@"C:\Temp.txt"));

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

I write out a rule in web.config after $locationProvider.html5Mode(true) is set in app.js.

Hope, helps someone out.

  <system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

In my index.html I added this to <head>

<base href="/">

Don't forget to install IIS URL Rewrite on server.

Also if you use Web API and IIS, this will work if your API is at www.yourdomain.com/api because of the third input (third line of condition).

Go back button in a page

Here is the code

<input type="button" value="Back" onclick="window.history.back()" /> 

How to set selected item of Spinner by value, not by position?

if you are using string array this is the best way:

int selectionPosition= adapter.getPosition("YOUR_VALUE");
spinner.setSelection(selectionPosition);

How to change the datetime format in pandas

Changing the format but not changing the type:

df['date'] = pd.to_datetime(df["date"].dt.strftime('%Y-%m'))

Default username password for Tomcat Application Manager

The admin and manager apps are two separate things. Here's a snapshot of a tomcat-users.xml file that works, try this:

<?xml version='1.0' encoding='utf-8'?>  
<tomcat-users>  
    <role rolename="tomcat"/>  
    <role rolename="role1"/>  
    <role rolename="manager"/>  
    <user username="tomcat" password="tomcat" roles="tomcat"/>  
    <user username="both" password="tomcat" roles="tomcat,role1"/>  
    <user username="role1" password="tomcat" roles="role1"/>  
    <user username="USERNAME" password="PASSWORD" roles="manager,tomcat,role1"/>  
</tomcat-users>  

It works for me very well

Check mySQL version on Mac 10.8.5

You should be able to open terminal and just type

mysql -v

How can I change the value of the elements in a vector?

You might want to consider using some algorithms instead:

// read in the data:
std::copy(std::istream_iterator<double>(input), 
          std::istream_iterator<double>(),
          std::back_inserter(v));

sum = std::accumulate(v.begin(), v.end(), 0);
average = sum / v.size();

You can modify the values with std::transform, though until we get lambda expressions (C++0x) it may be more trouble than it's worth:

class difference { 
    double base;
public:
    difference(double b) : base(b) {}
    double operator()(double v) { return v-base; }
};

std::transform(v.begin(), v.end(), v.begin(), difference(average));

Hide Text with CSS, Best Practice?

I realize this is an old question, but the Bootstrap framework has a built in class (sr-only) to handle hiding text on everything but screen readers:

<a href="/" class="navbar-brand"><span class="sr-only">Home</span></a>

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

To understand, let's consider below code snippet:

struct Foo{};
struct Bar{};

int main(int argc, char** argv)
{
    Foo* f = new Foo;

    Bar* b1 = f;                              // (1)
    Bar* b2 = static_cast<Bar*>(f);           // (2)
    Bar* b3 = dynamic_cast<Bar*>(f);          // (3)
    Bar* b4 = reinterpret_cast<Bar*>(f);      // (4)
    Bar* b5 = const_cast<Bar*>(f);            // (5)

    return 0;
}

Only line (4) compiles without error. Only reinterpret_cast can be used to convert a pointer to an object to a pointer to an any unrelated object type.

One this to be noted is: The dynamic_cast would fail at run-time, however on most compilers it will also fail to compile because there are no virtual functions in the struct of the pointer being casted, meaning dynamic_cast will work with only polymorphic class pointers.

When to use C++ cast:

  • Use static_cast as the equivalent of a C-style cast that does value conversion, or when we need to explicitly up-cast a pointer from a class to its superclass.
  • Use const_cast to remove the const qualifier.
  • Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if we know what we are doing and we understand the aliasing issues.

How to select data of a table from another database in SQL Server?

In SQL Server 2012 and above, you don't need to create a link. You can execute directly

SELECT * FROM [TARGET_DATABASE].dbo.[TABLE] AS _TARGET

I don't know whether previous versions of SQL Server work as well

How to connect to remote Oracle DB with PL/SQL Developer?

In the "database" section of the logon dialog box, enter //hostname.domain:port/database, in your case //123.45.67.89:1521/TEST - this assumes that you don't want to set up a tnsnames.ora file/entry for some reason.

Also make sure the firewall settings on your server are not blocking port 1521.

How to call function of one php file from another php file and pass parameters to it?

you can write the function in a separate file (say common-functions.php) and include it wherever needed.

function getEmployeeFullName($employeeId) {
// Write code to return full name based on $employeeId
}

You can include common-functions.php in another file as below.

include('common-functions.php');
echo 'Name of first employee is ' . getEmployeeFullName(1);

You can include any number of files to another file. But including comes with a little performance cost. Therefore include only the files which are really required.

Javascript change color of text and background to input value

document.getElementById("fname").style.borderTopColor = 'red';
document.getElementById("fname").style.borderBottomColor = 'red';

How to get numeric position of alphabets in java?

char letter;
for(int i=0; i<text.length(); i++)
{
    letter = text.charAt(i);
    if(letter>='A' && letter<='Z')
        System.out.println((int)letter - 'A'+1);
    if(letter>='a' && letter<= 'z')
        System.out.println((int)letter - 'a'+1);
}

Best way to determine user's locale within browser

You can use http or https.

https://ip2c.org/XXX.XXX.XXX.XXX or https://ip2c.org/?ip=XXX.XXX.XXX.XXX |

  • standard IPv4 from 0.0.0.0 to 255.255.255.255

https://ip2c.org/s or https://ip2c.org/self or https://ip2c.org/?self |

  • processes caller's IP
  • faster than ?dec= option but limited to one purpose - give info about yourself

Reference: https://about.ip2c.org/#inputs

converting CSV/XLS to JSON?

Instead of hard-coded converters, how about CSV support for Jackson (JSON processor): https://github.com/FasterXML/jackson-dataformat-csv. So core Jackson can read JSON in as POJOs, Maps, JsonNode, almost anything. And CSV support can do the same with CSV. Combine the two and it's very powerful but simple converter between multiple formats (there are backends for XML, YAML already, and more being added).

An article that shows how to do this can be found here.

iOS: Modal ViewController with transparent background

Create a segue to present modally and set Presentation property of that segue to over current context it will work 100 %

enter image description here

WebSocket with SSL

To support the answer by @oberstet, if the cert is not trusted by the browser (for example you get a "this site is not secure, do you want to continue?") one solution is to open the browser options, navigate to the certificates settings and add the host and post that the websocket server is being served from to the certificate provider as an exception.

for example add 'example-wss-domain.org:6001' as an exception to 'Certificate Provider Ltd'.

In firefox, this can be done from 'about:preferences' and searching for 'Certificates'

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

How to interpolate variables in strings in JavaScript, without concatenation?

If you like to write CoffeeScript you could do:

hello = "foo"
my_string = "I pity the #{hello}"

CoffeeScript actually IS javascript, but with a much better syntax.

For an overview of CoffeeScript check this beginner's guide.

How to create a batch file to run cmd as administrator

this might be a solution, i have done something similar but this one does not seem to work for example if the necessary function requires administrator privileges it should ask you to restart it as admin.

@echo off
mkdir C:\Users\cmdfolder

if echo=="Access is denied." (goto :1A) else (goto :A4)

:A1
cls 
color 0d
echo restart this program as administator

:A4
pause

including parameters in OPENQUERY

In the following example I'm passing a department parameter to a stored procedure(spIncreaseTotalsRpt) and at the same time I'm creating a temp table all from an OPENQUERY. The Temp table needs to be a global Temp (##) so it can be referenced outside it's intance. By using exec sp_executesql you can pass the department parameter.

Note: be careful when using sp_executeSQL. Also your admin might not have this option available to you.

Hope this helps someone.

 IF OBJECT_ID('tempdb..##Temp') IS NOT NULL
/*Then it exists*/
    begin
       DROP TABLE ##Temp
    end 
 Declare @Dept as nvarchar(20) ='''47'''

 declare @OPENQUERY  as nvarchar(max)
set @OPENQUERY = 'Select ' + @Dept + ' AS Dept,  * into ##Temp from openquery(SQL_AWSPROD01,''' 

declare @sql nvarchar(max)= @openquery +  'SET FMTONLY OFF EXECUTE SalaryCompensation.dbo.spIncreaseTotalsRpts ' + '''' + @Dept + ''''  + ''')'
declare @parmdef nvarchar(25) 
DECLARE @param nvarchar(20) 

SET @parmdef = N'@Dept varchar(20)'
-- select @sql
-- Print @sql + @parmdef  + @dept
exec sp_executesql @sql,@parmdef, @Dept  
Select * from ##Temp

Results

Dept increase Cnt 0 1 2 3 4 5 6 0.0000 1.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000

(HTML) Download a PDF file instead of opening them in browser when clicked

you can add the following code

_x000D_
_x000D_
<a href='http://v2.immo-facile.com/catalog/admin-v2/product_info.pdf' class='btnPdf' title='pdf'  target='_blank' type='application/pdf' >Télécharger la fiche du bien</a>
_x000D_
_x000D_
_x000D_

Auto margins don't center image in page

add display:block; and it'll work. Images are inline by default

To clarify, the default width for a block element is auto, which of course fills the entire available width of the containing element.

By setting the margin to auto, the browser assigns half the remaining space to margin-left and the other half to margin-right.

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

How to view the Folder and Files in GAC?

Install:

gacutil -i "path_to_the_assembly"

View:

Open in Windows Explorer folder

  • .NET 1.0 - NET 3.5: c:\windows\assembly (%systemroot%\assembly)
  • .NET 4.x: %windir%\Microsoft.NET\assembly

OR gacutil –l

When you are going to install an assembly you have to specify where gacutil can find it, so you have to provide a full path as well. But when an assembly already is in GAC - gacutil know a folder path so it just need an assembly name.

MSDN:

Read CSV file column by column

I sugges to use the Apache Commons CSV https://commons.apache.org/proper/commons-csv/

Here is one example:

    Path currentRelativePath = Paths.get("");
    String currentPath = currentRelativePath.toAbsolutePath().toString();
    String csvFile = currentPath + "/pathInYourProject/test.csv";

    Reader in;
    Iterable<CSVRecord> records = null;
    try
    {
        in = new FileReader(csvFile);
        records = CSVFormat.EXCEL.withHeader().parse(in); // header will be ignored
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    for (CSVRecord record : records) {
        String line = "";
        for ( int i=0; i < record.size(); i++)
        {
            if ( line == "" )
                line = line.concat(record.get(i));
            else
                line = line.concat("," + record.get(i));
        }
        System.out.println("read line: " + line);
    }

It automaticly recognize , and " but not ; (maybe it can be configured...).

My example file is:

col1,col2,col3
val1,"val2",val3
"val4",val5
val6;val7;"val8"

And output is:

read line: val1,val2,val3
read line: val4,val5
read line: val6;val7;"val8"

Last line is considered like one value.

Change font-weight of FontAwesome icons?

Webkit browsers support the ability to add "stroke" to fonts. This bit of style makes fonts look thinner (assuming a white background):

-webkit-text-stroke: 2px white;

Example on codepen here: http://codepen.io/mackdoyle/pen/yrgEH Some people are using SVG for a cross-platform "stroke" solution: http://codepen.io/CrocoDillon/pen/dGIsK

How can I get a channel ID from YouTube?

To get Channel id

Ex: Apple channel ID

enter image description here

Select any of the video in that channel

enter image description here

Select iPhone - Share photos (video)

Now click on channel name Apple bottom of the video.

enter image description here

Now you will get channel id in browser url

enter image description here

Here this is Apple channel id : UCE_M8A5yxnLfW0KghEeajjw

How to remove focus border (outline) around text/input boxes? (Chrome)

Please use the following syntax to remove the border of text box and remove the highlighted border of browser style.

input {
    background-color:transparent;
    border: 0px solid;
    height:30px;
    width:260px;
}
input:focus {
    outline:none;
}

py2exe - generate single executable file

PyInstaller will create a single .exe file with no dependencies; use the --onefile option. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see minty's answer)

I use the version of PyInstaller from svn, since the latest release (1.3) is somewhat outdated. It's been working really well for an app which depends on PyQt, PyQwt, numpy, scipy and a few more.

Create a variable name with "paste" in R?

See ?assign.

> assign(paste("tra.", 1, sep = ""), 5)
> tra.1
  [1] 5

Using an HTTP PROXY - Python

You can do it even without the HTTP_PROXY environment variable. Try this sample:

import urllib2

proxy_support = urllib2.ProxyHandler({"http":"http://61.233.25.166:80"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)

html = urllib2.urlopen("http://www.google.com").read()
print html

In your case it really seems that the proxy server is refusing the connection.


Something more to try:

import urllib2

#proxy = "61.233.25.166:80"
proxy = "YOUR_PROXY_GOES_HERE"

proxies = {"http":"http://%s" % proxy}
url = "http://www.google.com/search?q=test"
headers={'User-agent' : 'Mozilla/5.0'}

proxy_support = urllib2.ProxyHandler(proxies)
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)

req = urllib2.Request(url, None, headers)
html = urllib2.urlopen(req).read()
print html

Edit 2014: This seems to be a popular question / answer. However today I would use third party requests module instead.

For one request just do:

import requests

r = requests.get("http://www.google.com", 
                 proxies={"http": "http://61.233.25.166:80"})
print(r.text)

For multiple requests use Session object so you do not have to add proxies parameter in all your requests:

import requests

s = requests.Session()
s.proxies = {"http": "http://61.233.25.166:80"}

r = s.get("http://www.google.com")
print(r.text)

Find if current time falls in a time range

The TimeOfDay property returns a TimeSpan value.

Try the following code:

TimeSpan time = DateTime.Now.TimeOfDay;

if (time > new TimeSpan(11, 59, 00)        //Hours, Minutes, Seconds
 && time < new TimeSpan(13, 01, 00)) {
    //match found
}

Also, new DateTime() is the same as DateTime.MinValue and will always be equal to 1/1/0001 12:00:00 AM. (Value types cannot have non-empty default values) You want to use DateTime.Now.

Activity has leaked window that was originally added

I have another solution for this, and would like to know if it seems valid to you: instead of dismissing in the onDestroy, which seems to be the leading solution, I'm extending ProgressDialog...

public class MyProgressDialog extends ProgressDialog {

  private boolean isDismissed;

  public MyProgressDialog(Context context) {
    super(context);
  }

  @Override
  public void onDetachedFromWindow() {
    super.onDetachedFromWindow();
    dismiss();
  }

  @Override
  public void dismiss() {
    if (isDismissed) {
      return;
    }
    try {
      super.dismiss();
    } catch (IllegalArgumentException e) {
      // ignore
    }
    isDismissed = true;
  }

This is preferable, AFAIC, because you don't have to hold the progress dialog as a member, just fire(show) and forget

Git resolve conflict using --ours/--theirs for all files

You can -Xours or -Xtheirs with git merge as well. So:

  1. abort the current merge (for instance with git reset --hard HEAD)
  2. merge using the strategy you prefer (git merge -Xours or git merge -Xtheirs)

DISCLAIMER: of course you can choose only one option, either -Xours or -Xtheirs, do use different strategy you should of course go file by file.

I do not know if there is a way for checkout, but I do not honestly think it is terribly useful: selecting the strategy with the checkout command is useful if you want different solutions for different files, otherwise just go for the merge strategy approach.

How to compile and run C in sublime text 3?

{
 "cmd": ["gcc", "-Wall", "-ansi", "-pedantic-errors", "$file_name", "-o", 
 "${file_base_name}.exe", "&&", "start", "cmd", "/k" , "$file_base_name"],
 "selector": "source.c",
 "working_dir": "${file_path}",
 "shell": true
}

It takes input and show output on a command prompt.

using sql count in a case statement

ok. I solved it

SELECT `smart_projects`.project_id, `smart_projects`.business_id, `smart_projects`.title,
 `page_pages`.`funnel_id` as `funnel_id`, count(distinct(page_pages.page_id) )as page_count, count(distinct (CASE WHEN page_pages.funnel_id != 0 then  page_pages.funnel_id ELSE NULL END ) ) as funnel_count
FROM `smart_projects`
LEFT JOIN `page_pages` ON `smart_projects`.`project_id` = `page_pages`.`project_id`
WHERE  smart_projects.status !=  0 
AND `smart_projects`.`business_id` = 'cd9412774edb11e9'
GROUP BY `smart_projects`.`project_id`
ORDER BY `title` DESC

Django - makemigrations - No changes detected

In my case i forgot to insert the class arguments

Wrong:

class AccountInformation():

Correct

class AccountInformation(models.Model):

What are the differences between C, C# and C++ in terms of real-world applications?

My opinion is C# and ASP.NET would be the best of the three for development that is web biased.

I doubt anyone writes new web apps in C or C++ anymore. It was done 10 years ago, and there's likely a lot of legacy code still in use, but they're not particularly well suited, there doesn't appear to be as much (ongoing) tool support, and they probably have a small active community that does web development (except perhaps for web server development). I wrote many website C++ COM objects back in the day, but C# is far more productive that there's no compelling reason to code C or C++ (in this context) unless you need to.

I do still write C++ if necessary, but it's typically for a small problem domain. e.g. communicating from C# via P/Invoke to old C-style dll's - doing some things that are downright clumsy in C# were a breeze to create a C++ COM object as a bridge.

The nice thing with C# is that you can also easily transfer into writing Windows and Console apps and stay in C#. With Mono you're also not limited to Windows (although you may be limited to which libraries you use).

Anyways this is all from a web-biased perspective. If you asked about embedded devices I'd say C or C++. You could argue none of these are suited for web development, but C#/ASP.NET is pretty slick, it works well, there are heaps of online resources, a huge community, and free dev tools.

So from a real-world perspective, picking only one of C#, C++ and C as requested, as a general rule, you're better to stick with C#.

Error 500: Premature end of script headers

I bumped into this problem using PHP-FPM and Apache after increasing Apache's default LimitRequestFieldSize and LimitRequestLine values.

The only reason I did this (apache says don't mess) is because Yii2 has some pjax problems with POST requests. As a workaround, I decided to increase these limits and use gigantic GET headers.

php-fpm barfed up the 500 error though.

How to get Python requests to trust a self signed SSL certificate?

Incase anyone happens to land here (like I did) looking to add a CA (in my case Charles Proxy) for httplib2, it looks like you can append it to the cacerts.txt file included with the python package.

For example:

cat ~/Desktop/charles-ssl-proxying-certificate.pem >> /usr/local/google-cloud-sdk/lib/third_party/httplib2/cacerts.txt

The environment variables referenced in other solutions appear to be requests-specific and were not picked up by httplib2 in my testing.

Creating your own header file in C

#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here

#endif

MY_HEADER_H serves as a double-inclusion guard.

For the function declaration, you only need to define the signature, that is, without parameter names, like this:

int foo(char*);

If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.

This declares the function foo which accepts a char* and returns an int.

In your source file, you would have:

#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;
}

Deleting Objects in JavaScript

delete is not used for deleting an object in java Script.

delete used for removing an object key in your case

var obj = { helloText: "Hello World!" }; 
var foo = obj;
delete obj;

object is not deleted check obj still take same values delete usage:

delete obj.helloText

and then check obj, foo, both are empty object.

What are the most common font-sizes for H1-H6 tags

It would depend on the browser's default stylesheet. You can view an (unofficial) table of CSS2.1 User Agent stylesheet defaults here.

Based on the page listed above, the default sizes look something like this:

    IE7     IE8     FF2         FF3         Opera   Safari 3.1
H1  24pt    2em     32px        32px        32px    32px       
H2  18pt    1.5em   24px        24px        24px    24px
H3  13.55pt 1.17em  18.7333px   18.7167px   18px    19px
H4  n/a     n/a     n/a         n/a         n/a     n/a
H5  10pt    0.83em  13.2667px   13.2833px   13px    13px
H6  7.55pt  0.67em  10.7333px   10.7167px   10px    11px

Also worth taking a look at is the default stylesheet for HTML 4. The W3C recommends using these styles as the default. An abridged excerpt:

h1 { font-size: 2em; }
h2 { font-size: 1.5em; }
h3 { font-size: 1.17em; }
h4 { font-size: 1.12em; }
h5 { font-size: .83em; }
h6 { font-size: .75em; }

Hope this information is helpful.

How can I write to the console in PHP?

Try the following. It is working:

echo("<script>console.log('PHP: " . $data . "');</script>");

JFrame background image

The best way to load an image is through the ImageIO API

BufferedImage img = ImageIO.read(new File("/path/to/some/image"));

There are a number of ways you can render an image to the screen.

You could use a JLabel. This is the simplest method if you don't want to modify the image in anyway...

JLabel background = new JLabel(new ImageIcon(img));

Then simply add it to your window as you see fit. If you need to add components to it, then you can simply set the label's layout manager to whatever you need and add your components.

If, however, you need something more sophisticated, need to change the image somehow or want to apply additional effects, you may need to use custom painting.

First cavert: Don't ever paint directly to a top level container (like JFrame). Top level containers aren't double buffered, so you may end up with some flashing between repaints, other objects live on the window, so changing it's paint process is troublesome and can cause other issues and frames have borders which are rendered inside the viewable area of the window...

Instead, create a custom component, extending from something like JPanel. Override it's paintComponent method and render your output to it, for example...

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, this);
}

Take a look at Performing Custom Painting and 2D Graphics for more details

PIL image to array (numpy array to array) - Python

I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects

import Image
import numpy as np

im = Image.load('foo.jpg')
im = im.convert('L')

arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)

arr ^= 0xFF  # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()

curl usage to get header

google.com is not responding to HTTP HEAD requests, which is why you are seeing a hang for the first command.

It does respond to GET requests, which is why the third command works.

As for the second, curl just prints the headers from a standard request.

ORACLE convert number to string

Using the FM format model modifier to get close, as you won't get the trailing zeros after the decimal separator; but you will still get the separator itself, e.g. 50.. You can use rtrim to get rid of that:

select to_char(a, '99D90'),
    to_char(a, '90D90'),
    to_char(a, 'FM90D99'),
    rtrim(to_char(a, 'FM90D99'), to_char(0, 'D'))
from (
    select 50 a from dual
    union all select 50.57 from dual
    union all select 5.57 from dual
    union all select 0.35 from dual
    union all select 0.4 from dual
)
order by a;

TO_CHA TO_CHA TO_CHA RTRIM(
------ ------ ------ ------
   .35   0.35 0.35   0.35
   .40   0.40 0.4    0.4
  5.57   5.57 5.57   5.57
 50.00  50.00 50.    50
 50.57  50.57 50.57  50.57

Note that I'm using to_char(0, 'D') to generate the character to trim, to match the decimal separator - so it looks for the same character, , or ., as the first to_char adds.

The slight downside is that you lose the alignment. If this is being used elsewhere it might not matter, but it does then you can also wrap it in an lpad, which starts to make it look a bit complicated:

...
lpad(rtrim(to_char(a, 'FM90D99'), to_char(0, 'D')), 6)
...

TO_CHA TO_CHA TO_CHA RTRIM( LPAD(RTRIM(TO_CHAR(A,'FM
------ ------ ------ ------ ------------------------
   .35   0.35 0.35   0.35     0.35
   .40   0.40 0.4    0.4       0.4
  5.57   5.57 5.57   5.57     5.57
 50.00  50.00 50.    50         50
 50.57  50.57 50.57  50.57   50.57

Open the terminal in visual studio?

New in the most recent version of Visual Studio, there is View --> Terminal, which will open a PowerShell instance as a VS dockable window, rather than a floating PowerShell or cmd instance from the Developer Command Prompt.

View then Terminal

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

This is a bit late but I know it will help someone:

If you are using datetimepicker make sure you include the right CSS and JS files. datetimepicker uses(Take note of their names);

https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css

and

https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js

On the above question asked by @mindfreak,The main problem is due to the imported files.

How do I create a new column from the output of pandas groupby().sum()?

You want to use transform this will return a Series with the index aligned to the df so you can then add it as a new column:

In [74]:

df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
   Data2  Data3        Date   Sym  Data4
0     11      5  2015-05-08  aapl     55
1      8      8  2015-05-07  aapl    108
2     10      6  2015-05-06  aapl     66
3     15      1  2015-05-05  aapl    121
4    110     50  2015-05-08  aaww     55
5     60    100  2015-05-07  aaww    108
6    100     60  2015-05-06  aaww     66
7     40    120  2015-05-05  aaww    121

How to indent HTML tags in Notepad++

Building on Constantin's answer, here's the essence of what I learned while transitioning to Notepad++ as my primary HTML editor.

Install Notepad++ 32-bit

There's no 64-bit version of Tidy2 and some other popular plugins. The 32-bit version of NPP has few practical downsides, so axe the 64-bit version.

Install the Plugin Manager

Plugin Manager isn't strictly necessary for plugin usage. It does make things much easier, though.

Plugin Manager was eliminated from the core package apparently because the developer didn't like some included attribution linking.

You may notice that Plugin Manager plugin has been removed from the official distribution. The reason is Plugin Manager contains the advertising in its dialog. I hate Ads in applications, and I ensure you that there was no, and there will never be Ads in Notepad++.

It's a manual install, but it's not difficult.

  1. Download the UNI (32-bit) zip package and extract it. Inside you'll see folders called plugins and updater. Each contains one file.
  2. Drag those two files to the respective identically-named folders in your Notepad++ installation directory. Typically that's C:\Program Files (x86)\Notepad++.
  3. Restart Notepad++ and follow any install/update prompts.

Now you'll see a new entry under Plugins for Plugin Manager.

Install Tidy2 (or your preferred alternative)

In Plugin Manager, check the box for Tidy2. Click Install. Restart when prompted.

To use Tidy2, select one of the preconfigured profiles in its Plugins submenu item, or create your own.

using if else with eval in aspx page

You can try c#

public string ProcessMyDataItem(object myValue)
 {
  if (myValue == null)
   {
   return "0 %"";
  }
   else
  {
     if(Convert.ToInt32(myValue) < 50)
       return "0";
     else
      return myValue.ToString() + "%";
  }

 }

asp

 <div class="tooltip" style="display: none">                                                                  
      <div style="text-align: center; font-weight: normal">
   Value =<%# ProcessMyDataItem(Eval("Percentage")) %> </div>
 </div>

How do I save and restore multiple variables in python?

You could use klepto, which provides persistent caching to memory, disk, or database.

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('foo.txt')
>>> db['1'] = 1
>>> db['max'] = max
>>> squared = lambda x: x**2
>>> db['squared'] = squared
>>> def add(x,y):
...   return x+y
... 
>>> db['add'] = add
>>> class Foo(object):
...   y = 1
...   def bar(self, x):
...     return self.y + x
... 
>>> db['Foo'] = Foo
>>> f = Foo()
>>> db['f'] = f  
>>> db.dump()
>>> 

Then, after interpreter restart...

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('foo.txt')
>>> db
file_archive('foo.txt', {}, cached=True)
>>> db.load()
>>> db
file_archive('foo.txt', {'1': 1, 'add': <function add at 0x10610a0c8>, 'f': <__main__.Foo object at 0x10510ced0>, 'max': <built-in function max>, 'Foo': <class '__main__.Foo'>, 'squared': <function <lambda> at 0x10610a1b8>}, cached=True)
>>> db['add'](2,3)
5
>>> db['squared'](3)
9
>>> db['f'].bar(4)
5
>>> 

Get the code here: https://github.com/uqfoundation

How to select multiple rows filled with constants?

Try the connect by clause in oracle, something like this

select level,level+1,level+2 from dual connect by level <=3;

For more information on connect by clause follow this link : removed URL because oraclebin site is now malicious.

How to hide 'Back' button on navigation bar on iPhone?

It wasn't working for me in all cases when I set

self.navigationItem.hidesBackButton = YES;

in viewWillAppear or ViewDidLoad, but worked perfectly when I set it in init of the viewController.

Read from file or stdin

Just testing for end of file with feof would do, I think.

How to use external ".js" files

I hope this helps someone here: I encountered an issue where I needed to use JavaScript to manipulate some dynamically generated elements. After including the code to my external .js file which I had referenced to between the <script> </script> tags at the head section and it was working perfectly, nothing worked again from the script.Tried using developer tool on FF and it returned null value for the variable holding the new element. I decided to move my script tag to the bottom of the html file just before the </body> tag and bingo every part of the script started to respond fine again.

React passing parameter via onclick event using ES6 syntax

I am using React-Bootstrap. The onSelect trigger for dropdowns were not allowing me to pass data. Just the event. So remember you can just set any values as attributes and pick them up from the function using javascript. Picking up those attributes you set in that event target.

    let currentTarget = event.target;
    let currentId = currentTarget.getAttribute('data-id');
    let currentValue = currentTarget.getAttribute('data-value');

How would you make two <div>s overlap?

Just use negative margins, in the second div say:

<div style="margin-top: -25px;">

And make sure to set the z-index property to get the layering you want.

How to unzip a file in Powershell?

Use Expand-Archive cmdlet with one of parameter set:

Expand-Archive -LiteralPath C:\source\file.Zip -DestinationPath C:\destination
Expand-Archive -Path file.Zip -DestinationPath C:\destination

XPath to select multiple tags

You can avoid the repetition with an attribute test instead:

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

Contrary to Dimitre's antagonistic opinion, the above is not incorrect in a vacuum where the OP has not specified the interaction with namespaces. The self:: axis is namespace restrictive, local-name() is not. If the OP's intention is to capture c|d|e regardless of namespace (which I'd suggest is even a likely scenario given the OR nature of the problem) then it is "another answer that still has some positive votes" which is incorrect.

You can't be definitive without definition, though I'm quite happy to delete my answer as genuinely incorrect if the OP clarifies his question such that I am incorrect.

Difference between Groovy Binary and Source release?

The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.

Why do I keep getting Delete 'cr' [prettier/prettier]?

I am using git+vscode+windows+vue, and after read the eslint document: https://eslint.org/docs/rules/linebreak-style

Finally fix it by:

add *.js text eol=lf to .gitattributes

then run vue-cli-service lint --fix

ssl.SSLError: tlsv1 alert protocol version

For Mac OS X

1) Update to Python 3.6.5 using the native app installer downloaded from the official Python language website https://www.python.org/downloads/

I've found that the installer is taking care of updating the links and symlinks for the new Python a lot better than homebrew.

2) Install a new certificate using "./Install Certificates.command" which is in the refreshed Python 3.6 directory

> cd "/Applications/Python 3.6/"
> sudo "./Install Certificates.command"

Add IIS 7 AppPool Identities as SQL Server Logons

In my case the problem was that I started to create an MVC Alloy sample project from scratch in using Visual Studio/Episerver extension and it worked fine when executed using local Visual studio iis express. However by default it points the sql database to LocalDB and when I deployed the site to local IIS it started giving errors some of the initial errors I resolved by: 1.adding the local site url binding to C:/Windows/System32/drivers/etc/hosts 2. Then by editing the application.config found the file location by right clicking on IIS express in botton right corner of the screen when running site using Visual studio and added binding there for local iis url. 3. Finally I was stuck with "unable to access database errors" for which I created a blank new DB in Sql express and changed connection string in web config to point to my new DB and then in package manager console (using Visual Studio) executed Episerver DB commands like - 1. initialize-epidatabase 2. update-epidatabase 3. Convert-EPiDatabaseToUtc

Changing file extension in Python

Sadly, I experienced a case of multiple dots on file name that splittext does not worked well... my work around:

file = r'C:\Docs\file.2020.1.1.xls'
ext = '.'+ os.path.realpath(file).split('.')[-1:][0]
filefinal = file.replace(ext,'.zip')
os.rename(file ,filefinal)

How to Truncate a string in PHP to the word closest to a certain number of characters?

/*
Cut the string without breaking any words, UTF-8 aware 
* param string $str The text string to split
* param integer $start The start position, defaults to 0
* param integer $words The number of words to extract, defaults to 15
*/
function wordCutString($str, $start = 0, $words = 15 ) {
    $arr = preg_split("/[\s]+/",  $str, $words+1);
    $arr = array_slice($arr, $start, $words);
    return join(' ', $arr);
}

Usage:

$input = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna liqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.';
echo wordCutString($input, 0, 10); 

This will output first 10 words.

The preg_split function is used to split a string into substrings. The boundaries along which the string is to be split, are specified using a regular expressions pattern.

preg_split function takes 4 parameters, but only the first 3 are relevant to us right now.

First Parameter – Pattern The first parameter is the regular expressions pattern along which the string is to be split. In our case, we want to split the string across word boundaries. Therefore we use a predefined character class \s which matches white space characters such as space, tab, carriage return and line feed.

Second Parameter – Input String The second parameter is the long text string which we want to split.

Third Parameter – Limit The third parameter specifies the number of substrings which should be returned. If you set the limit to n, preg_split will return an array of n elements. The first n-1 elements will contain the substrings. The last (n th) element will contain the rest of the string.

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

Look at the commit message:

commit 0e1329e551a5700614a2a34d8101e92fd9f2cad6 (HEAD, master)
Merge: fc17405 ee2de56
Author: Tilman Vogel <email@email>
Date:   Tue Feb 22 00:27:17 2011 +0100

Merge branch 'testing' into master

notice the line:

Merge: fc17405 ee2de56

take those two commit ids and reverse them. so in order get the diff that you want, you would do:

git diff ee2de56..fc17405

to show just the names of the changed files:

git diff --name-only ee2de56..fc17405

and to extract them, you can add this to your gitconfig:

exportfiles = !sh -c 'git diff $0 --name-only | "while read files; do mkdir -p \"$1/$(dirname $files)\"; cp -vf $files $1/$(dirname $files); done"'

then use it by doing:

git exportfiles ee2de56..fc17405 /c/temp/myproject

CSS to hide INPUT BUTTON value text

well:

font-size: 0; line-height: 0;

work awesome for me!

Change some value inside the List<T>

I'd probably go with this (I know its not pure linq), keep a reference to the original list if you want to retain all items, and you should find the updated values are in there:

 foreach (var mc in list.Where(x => x.Name == "height"))  
     mc.Value = 30;

Interop type cannot be embedded

I had same problem in VB.NET 2013 with Office 2007, and this solved it:

VS 2013 VB.NET Project > Props > Refs > Microsoft Word 12.0 Object Lib > Embed Interop Types: change True to False

How do I enable the column selection mode in Eclipse?

On Windows and Linux, it's AltShiftA, as RichieHindle pointed out. On OSX it's OptionCommandA (??A). It's also worth noting that the two modes can have different font preferences, so if you've changed the default text font, it can be jarring to toggle block selection modes and see the font change.

Finally, the "search commands" (Ctrl3 or Command3) pop-up will find it for you if you type block. This is useful if you use the feature just frequently enough to forget the hotkey.

Assigning more than one class for one event

Have you tried this:

 function doSomething() {
     if ($(this).hasClass('clickedTag')){
         // code here
     } else {
         // and here
     }
 }

 $('.tag1, .tag2').click(doSomething);

Python time measure function

First and foremost, I highly suggest using a profiler or atleast use timeit.

However if you wanted to write your own timing method strictly to learn, here is somewhere to get started using a decorator.

Python 2:

def timing(f):
    def wrap(*args):
        time1 = time.time()
        ret = f(*args)
        time2 = time.time()
        print '%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0)
        return ret
    return wrap

And the usage is very simple, just use the @timing decorator:

@timing
def do_work():
  #code

Python 3:

def timing(f):
    def wrap(*args, **kwargs):
        time1 = time.time()
        ret = f(*args, **kwargs)
        time2 = time.time()
        print('{:s} function took {:.3f} ms'.format(f.__name__, (time2-time1)*1000.0))

        return ret
    return wrap

Note I'm calling f.func_name to get the function name as a string(in Python 2), or f.__name__ in Python 3.

Swift: Sort array of objects alphabetically

With Swift 3, you can choose one of the following ways to solve your problem.


1. Using sorted(by:?) with a Movie class that does not conform to Comparable protocol

If your Movie class does not conform to Comparable protocol, you must specify in your closure the property on which you wish to use Array's sorted(by:?) method.

Movie class declaration:

import Foundation

class Movie: CustomStringConvertible {

    let name: String
    var date: Date
    var description: String { return name }

    init(name: String, date: Date = Date()) {
        self.name = name
        self.date = date
    }

}

Usage:

let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")

let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0.name < $1.name })
// let sortedMovies = movies.sorted { $0.name < $1.name } // also works

print(sortedMovies)

/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/

2. Using sorted(by:?) with a Movie class that conforms to Comparable protocol

However, by making your Movie class conform to Comparable protocol, you can have a much concise code when you want to use Array's sorted(by:?) method.

Movie class declaration:

import Foundation

class Movie: CustomStringConvertible, Comparable {

    let name: String
    var date: Date
    var description: String { return name }

    init(name: String, date: Date = Date()) {
        self.name = name
        self.date = date
    }

    static func ==(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name == rhs.name
    }

    static func <(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name < rhs.name
    }

}

Usage:

let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")

let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0 < $1 })
// let sortedMovies = movies.sorted { $0 < $1 } // also works
// let sortedMovies = movies.sorted(by: <) // also works

print(sortedMovies)

/*
 prints: [Avatar, Piranha II: The Spawning, Titanic]
 */

3. Using sorted() with a Movie class that conforms to Comparable protocol

By making your Movie class conform to Comparable protocol, you can use Array's sorted() method as an alternative to sorted(by:?).

Movie class declaration:

import Foundation

class Movie: CustomStringConvertible, Comparable {

    let name: String
    var date: Date
    var description: String { return name }

    init(name: String, date: Date = Date()) {
        self.name = name
        self.date = date
    }

    static func ==(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name == rhs.name
    }

    static func <(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name < rhs.name
    }

}

Usage:

let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")

let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted()

print(sortedMovies)

/*
 prints: [Avatar, Piranha II: The Spawning, Titanic]
 */

Default port for SQL Server

The default, unnamed instance always gets port 1433 for TCP. UDP port 1434 is used by the SQL Browser service to allow named instances to be located. In SQL Server 2000 the first instance to be started took this role.

Non-default instances get their own dynamically-allocated port, by default. If necessary, for example to configure a firewall, you can set them explicitly. If you don't want to enable or allow access to SQL Browser, you have to either include the instance's port number in the connection string, or set it up with the Alias tab in cliconfg (SQL Server Client Network Utility) on each client machine.

For more information see SQL Server Browser Service on MSDN.

When to use 'npm start' and when to use 'ng serve'?

For a project that's using the CLI, you will usually use ng serve. In other cases you may want to use npm start. Here the detailed explanation:

ng serve

Will serve a project that is 'Angular CLI aware', i.e. a project that has been created using the Angular CLI, particularly using:

ng new app-name

So, if you've scaffolded a project using the CLI, you'll probably want to use ng serve

npm start

This can be used in the case of a project that is not Angular CLI aware (or it can simply be used to run 'ng serve' for a project that's Angular CLI aware)

As the other answers state, this is an npm command that will run the npm command(s) from the package.json that have the identifier 'start', and it doesn't just have to run 'ng serve'. It's possible to have something like the following in the package.json:

   "scripts": {
     "build:watch": "tsc -p src/ -w",
     "serve": "lite-server -c=bs-config.json",
     "start": "concurrently \"npm run build:watch\" \"npm run serve\""
     ...
   },
   "devDependencies": {
     "concurrently": "^3.2.0",
     "lite-server": "^2.2.2",

In this case, 'npm start' will result in the following commands to be run:

concurrently "npm run build:watch" "npm run serve"

This will concurrently run the TypeScript compiler (watching for code changes), and run the Node lite-server (which users BrowserSync)

Alter Table Add Column Syntax

The correct syntax for adding column into table is:

ALTER TABLE table_name
  ADD column_name column-definition;

In your case it will be:

ALTER TABLE Employees
  ADD EmployeeID int NOT NULL IDENTITY (1, 1)

To add multiple columns use brackets:

ALTER TABLE table_name
  ADD (column_1 column-definition,
       column_2 column-definition,
       ...
       column_n column_definition);

COLUMN keyword in SQL SERVER is used only for altering:

ALTER TABLE table_name
  ALTER COLUMN column_name column_type;

mysql - move rows from one table to another

A simple INSERT INTO SELECT statement:

INSERT INTO persons_table SELECT * FROM customer_table WHERE person_name = 'tom';

DELETE FROM customer_table WHERE person_name = 'tom';

session handling in jquery

Assuming you're referring to this plugin, your code should be:

// To Store
$(function() {
    $.session.set("myVar", "value");
});


// To Read
$(function() {
    alert($.session.get("myVar"));
});

Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown file, which is displayed on the project page.

Angular2: How to load data before rendering the component?

You can pre-fetch your data by using Resolvers in Angular2+, Resolvers process your data before your Component fully be loaded.

There are many cases that you want to load your component only if there is certain thing happening, for example navigate to Dashboard only if the person already logged in, in this case Resolvers are so handy.

Look at the simple diagram I created for you for one of the way you can use the resolver to send the data to your component.

enter image description here

Applying Resolver to your code is pretty simple, I created the snippets for you to see how the Resolver can be created:

import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { MyData, MyService } from './my.service';

@Injectable()
export class MyResolver implements Resolve<MyData> {
  constructor(private ms: MyService, private router: Router) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<MyData> {
    let id = route.params['id'];

    return this.ms.getId(id).then(data => {
      if (data) {
        return data;
      } else {
        this.router.navigate(['/login']);
        return;
      }
    });
  }
}

and in the module:

import { MyResolver } from './my-resolver.service';

@NgModule({
  imports: [
    RouterModule.forChild(myRoutes)
  ],
  exports: [
    RouterModule
  ],
  providers: [
    MyResolver
  ]
})
export class MyModule { }

and you can access it in your Component like this:

/////
 ngOnInit() {
    this.route.data
      .subscribe((data: { mydata: myData }) => {
        this.id = data.mydata.id;
      });
  }
/////

And in the Route something like this (usually in the app.routing.ts file):

////
{path: 'yourpath/:id', component: YourComponent, resolve: { myData: MyResolver}}
////

Is it possible to animate scrollTop with jQuery?

Nick's answer works great. Be careful when specifying a complete() function inside the animate() call because it will get executed twice since you have two selectors declared (html and body).

$("html, body").animate(
    { scrollTop: "300px" },
    {
        complete : function(){
            alert('this alert will popup twice');
        }
    }
);

Here's how you can avoid the double callback.

var completeCalled = false;
$("html, body").animate(
    { scrollTop: "300px" },
    {
        complete : function(){
            if(!completeCalled){
                completeCalled = true;
                alert('this alert will popup once');
            }
        }
    }
);

How to select all instances of a variable and edit variable name in Sublime

  1. Put the cursor in the variable.

    Note: the key is to start with an empty selection. Don't highlight; just put your cursor there.

text cursor on variable

  1. Press ?D as needed. Not on a Mac? Use CtrlD.

more instances of variable highlighted

Didn't work? Try again, making sure to start with nothing selected.

More commands:

Find All: Ctrl?G selects all occurences at once. Not on a Mac? AltF3

Undo Selection: ?U steps backwards. Not on a Mac? CtrlU

Quick Skip Next: ?K?D skips the next occurence. Not on a Mac? CtrlKCtrlD

Sublime Docs

pandas convert some columns into rows

I guess I found a simpler solution

temp1 = pd.melt(df1, id_vars=["location"], var_name='Date', value_name='Value')
temp2 = pd.melt(df1, id_vars=["name"], var_name='Date', value_name='Value')

Concat whole temp1 with temp2's column name

temp1['new_column'] = temp2['name']

You now have what you asked for.

How to open this .DB file?

You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.

However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.

If you are using Linux File is a command that will do a similar task.

The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db file.

How to iterate over a TreeMap?

Just to point out the generic way to iterate over any map:

 private <K, V> void iterateOverMap(Map<K, V> map) {
    for (Map.Entry<K, V> entry : map.entrySet()) {
        System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
    }
    }

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

You can't remove hidden without also removing system.

You want:

cd mydir
attrib -H -S /D /S

That will remove the hidden and system attributes from all the files/folders inside of your current directory.

Google Maps API v3: InfoWindow not sizing correctly

Funny enough, while the following code will correct the WIDTH scroll bar:

.gm-style-iw
{
    overflow: hidden !important;
    line-height: 1.35;

}

It took this to correct the HEIGHT scroll bar:

    .gm-style-iw div
    {
        overflow: hidden !important;
    }

EDIT: Adding white-space: nowrap; to either style might correct the spacing issue that seems to linger when the scroll bars are removed. Great point Nathan.

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

There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.

<script language="javascript" type="text/javascript">
 function _vals(target, value){
   form1.all("target").value=target;
   form1.all("value").value=value;
   form1.submit();
 }
</script>

Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.

I'm sure there's probably more methods which are better, but these are just a few that spring to mind.

EDIT: Building on this from what others have said using the above method you would have an anchor tag like

<a onclick="_vals('name', 'val')" href="#">My Link</a>

And then in your PHP you can get form data using

$val = $_POST['value'];

So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.

What is the difference between lower bound and tight bound?

Θ-notation (theta notation) is called tight-bound because it's more precise than O-notation and Ω-notation (omega notation).

If I were lazy, I could say that binary search on a sorted array is O(n2), O(n3), and O(2n), and I would be technically correct in every case. That's because O-notation only specifies an upper bound, and binary search is bounded on the high side by all of those functions, just not very closely. These lazy estimates would be useless.

Θ-notation solves this problem by combining O-notation and Ω-notation. If I say that binary search is Θ(log n), that gives you more precise information. It tells you that the algorithm is bounded on both sides by the given function, so it will never be significantly faster or slower than stated.

undefined reference to boost::system::system_category() when compiling

I got the same Problem:

g++ -mconsole -Wl,--export-all-symbols -LC:/Programme/CPP-Entwicklung/MinGW-4.5.2/lib  -LD:/bfs_ENTW_deb/lib   -static-libgcc -static-libstdc++ -LC:/Programme/CPP-Entwicklung/boost_1_47_0/stage/lib   \
 D:/bfs_ENTW_deb/obj/test/main_filesystem.obj \
 -o D:/bfs_ENTW_deb/bin/filesystem.exe -lboost_system-mgw45-mt-1_47 -lboost_filesystem-mgw45-mt-1_47

D:/bfs_ENTW_deb/obj/test/main_filesystem.obj:main_filesystem.cpp:(.text+0x54): undefined reference to `boost::system::generic_category()

Solution was to use the debug-version of the system-lib:

g++ -mconsole -Wl,--export-all-symbols -LC:/Programme/CPP-Entwicklung/MinGW-4.5.2/lib  -LD:/bfs_ENTW_deb/lib   -static-libgcc -static-libstdc++ -LC:/Programme/CPP-Entwicklung/boost_1_47_0/stage/lib   \
 D:/bfs_ENTW_deb/obj/test/main_filesystem.obj \
 -o D:/bfs_ENTW_deb/bin/filesystem.exe -lboost_system-mgw45-mt-d-1_47 -lboost_filesystem-mgw45-mt-1_47

But why?

How do I change column default value in PostgreSQL?

If you want to remove the default value constraint, you can do:

ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

Below format try if number is like

ex 1 suppose number like 10.1 if apply below format it will be come as 10.10

ex 2 suppose number like .02 if apply below format it will be come as 0.02

ex 3 suppose number like 0.2 if apply below format it will be come as 0.20

to_char(round(to_number(column_name)/10000000,2),'999999999990D99') as column_name

Is it better to return null or empty collection?

I like to give explain here, with suitable example.

Consider a case here..

int totalValue = MySession.ListCustomerAccounts()
                          .FindAll(ac => ac.AccountHead.AccountHeadID 
                                         == accountHead.AccountHeadID)
                          .Sum(account => account.AccountValue);

Here Consider the functions I am using ..

1. ListCustomerAccounts() // User Defined
2. FindAll()              // Pre-defined Library Function

I can easily use ListCustomerAccount and FindAll instead of.,

int totalValue = 0; 
List<CustomerAccounts> custAccounts = ListCustomerAccounts();
if(custAccounts !=null ){
  List<CustomerAccounts> custAccountsFiltered = 
        custAccounts.FindAll(ac => ac.AccountHead.AccountHeadID 
                                   == accountHead.AccountHeadID );
   if(custAccountsFiltered != null)
      totalValue = custAccountsFiltered.Sum(account => 
                                            account.AccountValue).ToString();
}

NOTE : Since AccountValue is not null, the Sum() function will not return null., Hence I can use it directly.

What is Java EE?

J(2)EE, strictly speaking, is a set of APIs (as the current top answer has it) which enable a programmer to build distributed, transactional systems. The idea was to abstract away the complicated distributed, transactional bits (which would be implemented by a Container such as WebSphere or Weblogic), leaving the programmer to develop business logic free from worries about storage mechanisms and synchronization.

In reality, it was a cobbled-together, design-by-committee mish-mash, which was pushed pretty much for the benefit of vendors like IBM, Oracle and BEA so they could sell ridicously over-complicated, over-engineered, over-useless products. Which didn't have the most basic features (such as scheduling)!

J2EE was a marketing construct.

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

Copy Pasting @Lichtamberg's comments to gotoalberto's answer

Works also for Java 1.8:

# in ~/.zshrc and ~/.bashrc

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home 
export PATH=$JAVA_HOME/bin:$PATH 

This fixed my issue on java 8.

Parsing JSON array into java.util.List with Gson

Definitely the easiest way to do that is using Gson's default parsing function fromJson().

There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType (e.g., any List), which is fromJson(JsonElement json, Type typeOfT).

In your case, you just need to get the Type of a List<String> and then parse the JSON array into that Type, like this:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();

List<String> yourList = new Gson().fromJson(yourJson, listType);

In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.

You may want to take a look at Gson API documentation.

Function to get yesterday's date in Javascript in format DD/MM/YYYY

Try this:

function getYesterdaysDate() {
    var date = new Date();
    date.setDate(date.getDate()-1);
    return date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
}

if statement checks for null but still throws a NullPointerException

The problem here is that in your code the program is calling 'null.length()' which is not defined if the argument passed to the function is null. That's why the exception is thrown.

Creating virtual directories in IIS express

@Be.St.'s aprroach is true, but incomplete. I'm just copying his explanation with correcting the incorrect part.

IIS express configuration is managed by applicationhost.config.
You can find it in

Users\<username>\Documents\IISExpress\config folder.

Inside you can find the sites section that hold a section for each IIS Express configured site.

Add (or modify) a site section like this:

<site name="WebSiteWithVirtualDirectory" id="20">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="c:\temp\website1" />
     <virtualDirectory path="/OffSiteStuff" physicalPath="d:\temp\SubFolderApp" />
   </application>
   <bindings>
      <binding protocol="http" bindingInformation="*:1132:localhost" />
   </bindings>
</site>

Instead of adding a new application block, you should just add a new virtualDirectory element to the application parent element.

Edit - Visual Studio 2015

If you're looking for the applicationHost.config file and you're using VS2015 you'll find it in:

[solution_directory]/.vs/config/applicationHost.config

How can I find the method that called the current method?

We can improve on Mr Assad's code (the current accepted answer) just a little bit by instantiating only the frame we actually need rather than the entire stack:

new StackFrame(1).GetMethod().Name;

This might perform a little better, though in all likelihood it still has to use the full stack to create that single frame. Also, it still has the same caveats that Alex Lyman pointed out (optimizer/native code might corrupt the results). Finally, you might want to check to be sure that new StackFrame(1) or .GetFrame(1) don't return null, as unlikely as that possibility might seem.

See this related question: Can you use reflection to find the name of the currently executing method?

hexadecimal string to byte array in python

There is a built-in function in bytearray that does what you intend.

bytearray.fromhex("de ad be ef 00")

It returns a bytearray and it reads hex strings with or without space separator.

How to change XAMPP apache server port?

If the XAMPP server is running for the moment, stop XAMPP server.

Follow these steps to change the port number.

Open the file in following location.

[XAMPP Installation Folder]/apache/conf/httpd.conf

Open the httpd.conf file and search for the String:

Listen 80

This is the port number used by XAMMP.

Then search for the string ServerName and update the Port Number which you entered earlier for Listen

Now save and re-start XAMPP server.

How do I create a file and write to it?

package fileoperations;
import java.io.File;
import java.io.IOException;

public class SimpleFile {
    public static void main(String[] args) throws IOException {
        File file =new File("text.txt");
        file.createNewFile();
        System.out.println("File is created");
        FileWriter writer = new FileWriter(file);

        // Writes the content to the file
        writer.write("Enter the text that you want to write"); 
        writer.flush();
        writer.close();
        System.out.println("Data is entered into file");
    }
}

Get the value of a dropdown in jQuery

$('#Crd').val() will give you the selected value of the drop down element. Use this to get the selected options text.

$('#Crd option:selected').text();

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

I resolve the problem. It's very simple . if do you checking care the problem may be because the auxiliar variable has whitespace. Why ? I don't know but yus must use the trim() method and will resolve the problem

How to add 10 days to current time in Rails

Use

Time.now + 10.days

or even

10.days.from_now

Both definitely work. Are you sure you're in Rails and not just Ruby?

If you definitely are in Rails, where are you trying to run this from? Note that Active Support has to be loaded.

Get GPS location via a service in Android

All these answers doesn't work from M - to - Android"O" - 8, Due to Dozer mode that restrict the service - whatever service or any background operation that requires discrete things in background would be no longer able to run.

So the approach would be listening to the system FusedLocationApiClient through BroadCastReciever that always listening the location and work even in Doze mode.

Posting the link would be pointless, please search FusedLocation with Broadcast receiver.

Thanks

Limiting number of displayed results when using ngRepeat

Slightly more "Angular way" would be to use the straightforward limitTo filter, as natively provided by Angular:

<ul class="phones">
  <li ng-repeat="phone in phones | filter:query | orderBy:orderProp | limitTo:quantity">
    {{phone.name}}
    <p>{{phone.snippet}}</p>
  </li>
</ul>
app.controller('PhoneListCtrl', function($scope, $http) {
    $http.get('phones.json').then(
      function(phones){
        $scope.phones = phones.data;
      }
    );
    $scope.orderProp = 'age';
    $scope.quantity = 5;
  }
);

PLUNKER

frequent issues arising in android view, Error parsing XML: unbound prefix

I'll throw in a little more for the newbies and for folks, like myself, that don't understand XML.

The answers above a pretty good, but the general answer is that you need a namespace for any namespace used in the config.xml file.

Translation: Any XML tag name that has is a tag with a namespace where blah is the namespace and fubar is the XML tag. The namespace lets you use many different tools to interpret the XML with their own tag names. For example, Intel XDK uses the namespace intelxdk and android uses android. Thus you need the following namespaces or the build throws up blood (i.e. Error parsing XML: unbound prefix) which is translated to: You used a namespace, but did not define it.

  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:intelxdk="http://xdk.intel.com/ns/v1"

Apply CSS style attribute dynamically in Angular JS

ngStyle directive allows you to set CSS style on an HTML element dynamically.

Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys. Since some CSS style names are not valid keys for an object, they must be quoted.

ng-style="{color: myColor}"

Your code will be:

<div ng-style="{'width':'20px', 'height':'20px', 'margin-top':'10px', 'border':'solid 1px black', 'background-color':'#ff0000'}"></div>

If you want to use scope variables:

<div ng-style="{'background-color': data.backgroundCol}"></div>

Here an example on fiddle that use ngStyle, and below the code with the running snippet:

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
.controller('MyCtrl', function($scope) {_x000D_
  $scope.items = [{_x000D_
      name: 'Misko',_x000D_
      title: 'Angular creator'_x000D_
    }, {_x000D_
      name: 'Igor',_x000D_
      title: 'Meetup master'_x000D_
    }, {_x000D_
      name: 'Vojta',_x000D_
      title: 'All-around superhero'_x000D_
    }_x000D_
_x000D_
  ];_x000D_
});
_x000D_
.pending-delete {_x000D_
  background-color: pink_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="myApp" ng-controller='MyCtrl' ng-style="{color: myColor}">_x000D_
_x000D_
  <input type="text" ng-model="myColor" placeholder="enter a color name">_x000D_
_x000D_
  <div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">_x000D_
    name: {{item.name}}, {{item.title}}_x000D_
    <input type="checkbox" ng-model="item.checked" />_x000D_
    <span ng-show="item.checked"/><span>(will be deleted)</span>_x000D_
  </div>_x000D_
  <p>_x000D_
    <div ng-hide="myColor== 'red'">I will hide if the color is set to 'red'.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

There was no endpoint listening at (url) that could accept the message

Another case I just had - when the request size is bigger than the request size set in IIS as a limit, then you can get that error too.

Check the IIS request limit and increase it if it's lower than you need. Here is how you can check and change the IIS request limit:

  1. Open the IIS
  2. Click your site and/or your mapped application
  3. Click on Feature view and click Request Filtering
  4. Click - Edit Feature Settings.

Edit Feature Settings

I just found also another thread in stack IIS 7.5 hosted WCF service throws EndpointNotFoundException with 404 only for large requests

plot with custom text for x axis points

This worked for me. Each month on X axis

str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

I have used the content from this site to create the following script which changes collation of all columns in all tables:

CREATE PROCEDURE [dbo].[sz_pipeline001_collation] 
    -- Add the parameters for the stored procedure here
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;


SELECT 'ALTER TABLE [' + SYSOBJECTS.Name + '] ALTER COLUMN [' + SYSCOLUMNS.Name + '] ' +
SYSTYPES.name + 
    CASE systypes.NAME
    WHEN 'text' THEN ' '
    ELSE
    '(' + RTRIM(CASE SYSCOLUMNS.length
    WHEN -1 THEN 'MAX'
    ELSE CONVERT(CHAR,SYSCOLUMNS.length)
    END) + ') ' 
    END

    + ' ' + ' COLLATE Latin1_General_CI_AS ' + CASE ISNULLABLE WHEN 0 THEN 'NOT NULL' ELSE 'NULL' END
    FROM SYSCOLUMNS , SYSOBJECTS , SYSTYPES
    WHERE SYSCOLUMNS.ID = SYSOBJECTS.ID
    AND SYSOBJECTS.TYPE = 'U'
    AND SYSTYPES.Xtype = SYSCOLUMNS.xtype
    AND SYSCOLUMNS.COLLATION IS NOT NULL
    AND NOT ( sysobjects.NAME LIKE 'sys%' )
    AND NOT ( SYSTYPES.name LIKE 'sys%' )

END

How to pass arguments and redirect stdin from a file to program run in gdb?

Pass the arguments to the run command from within gdb.

$ gdb ./a.out
(gdb) r < t
Starting program: /dir/a.out < t

How do I change the font size of a UILabel in Swift?

Swift 4.2

myLabel.font = UIFont.systemFont(ofSize: 12)

When to use setAttribute vs .attribute= in JavaScript?

You should always use the direct .attribute form (but see the quirksmode link below) if you want programmatic access in JavaScript. It should handle the different types of attributes (think "onload") correctly.

Use getAttribute/setAttribute when you wish to deal with the DOM as it is (e.g. literal text only). Different browsers confuse the two. See Quirks modes: attribute (in)compatibility.

RegExp in TypeScript

In typescript, the declaration is something like this:

const regex : RegExp = /.+\*.+/;

using RegExp constructor:

const regex = new RegExp('.+\\*.+');

How to pip install a package with min and max version range?

An elegant method would be to use the ~= compatible release operator according to PEP 440. In your case this would amount to:

package~=0.5.0

As an example, if the following versions exist, it would choose 0.5.9:

  • 0.5.0
  • 0.5.9
  • 0.6.0

For clarification, each pair is equivalent:

~= 0.5.0
>= 0.5.0, == 0.5.*

~= 0.5
>= 0.5, == 0.*

List file using ls command in Linux with full path

Print the full path (also called resolved path) with:

realpath README.md

In interactive mode you can use shell expansion to list all files in the directory with their full paths:

realpath *

If you're programming a bash script, I guess you'll have a variable for the individual file names.

Thanks to VIPIN KUMAR for pointing to the related readlink command.

get the latest fragment in backstack

Looks like something has changed for the better, because code below works perfectly for me, but I didn't find it in already provided answers.

Kotlin:

supportFragmentManager.fragments[supportFragmentManager.fragments.size - 1]

Java:

getSupportFragmentManager().getFragments()
.get(getSupportFragmentManager().getFragments().size() - 1)

How to use PHP's password_hash to hash and verify passwords

Never use md5() for securing your password, even with salt, it is always dangerous!!

Make your password secured with latest hashing algorithms as below.

<?php

// Your original Password
$password = '121@121';

//PASSWORD_BCRYPT or PASSWORD_DEFAULT use any in the 2nd parameter
/*
PASSWORD_BCRYPT always results 60 characters long string.
PASSWORD_DEFAULT capacity is beyond 60 characters
*/
$password_encrypted = password_hash($password, PASSWORD_BCRYPT);

For matching with database's encrypted password and user inputted password use the below function.

<?php 

if (password_verify($password_inputted_by_user, $password_encrypted)) {
    // Success!
    echo 'Password Matches';
}else {
    // Invalid credentials
    echo 'Password Mismatch';
}

If you want to use your own salt, use your custom generated function for the same, just follow below, but I not recommend this as It is found deprecated in latest versions of PHP.

Read about password_hash() before using below code.

<?php

$options = [
    'salt' => your_custom_function_for_salt(), 
    //write your own code to generate a suitable & secured salt
    'cost' => 12 // the default cost is 10
];

$hash = password_hash($your_password, PASSWORD_DEFAULT, $options);