Programs & Examples On #Xml serialization

This tag refers to serialization technologies which use XML as a data format.

Serialize an object to XML

I have a simple way to serialize an object to XML using C#, it works great and it's highly reusable. I know this is an older thread, but I wanted to post this because someone may find this helpful to them.

Here is how I call the method:

var objectToSerialize = new MyObject();
var xmlString = objectToSerialize.ToXmlString();

Here is the class that does the work:

Note: Since these are extension methods they need to be in a static class.

using System.IO;
using System.Xml.Serialization;

public static class XmlTools
{
    public static string ToXmlString<T>(this T input)
    {
        using (var writer = new StringWriter())
        {
            input.ToXml(writer);
            return writer.ToString();
        }
    }

    private static void ToXml<T>(this T objectToSerialize, StringWriter writer)
    {
        new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
    }
}

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

XmlSerializer xs = new XmlSerializer(typeof(User), new XmlRootAttribute("yourRootName")); 

Serialize an object to string

Use a StringWriter instead of a StreamWriter:

public static string SerializeObject<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());

    using(StringWriter textWriter = new StringWriter())
    {
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

Note, it is important to use toSerialize.GetType() instead of typeof(T) in XmlSerializer constructor: if you use the first one the code covers all possible subclasses of T (which are valid for the method), while using the latter one will fail when passing a type derived from T.    Here is a link with some example code that motivate this statement, with XmlSerializer throwing an Exception when typeof(T) is used, because you pass an instance of a derived type to a method that calls SerializeObject that is defined in the derived type's base class: http://ideone.com/1Z5J1.

Also, Ideone uses Mono to execute code; the actual Exception you would get using the Microsoft .NET runtime has a different Message than the one shown on Ideone, but it fails just the same.

Using DataContractSerializer to serialize, but can't deserialize back

Other solution is:

public static T Deserialize<T>(string rawXml)
{
    using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
    {
        DataContractSerializer formatter0 = 
            new DataContractSerializer(typeof(T));
        return (T)formatter0.ReadObject(reader);
    }
}

One remark: sometimes it happens that raw xml contains e.g.:

<?xml version="1.0" encoding="utf-16"?>

then of course you can't use UTF8 encoding used in other examples..

Reading from memory stream to string

string result = Encoding.UTF8.GetString((stream as MemoryStream).ToArray());

Serialize Property as Xml Attribute in Element

Kind of, use the XmlAttribute instead of XmlElement, but it won't look like what you want. It will look like the following:

<SomeModel SomeStringElementName="testData"> 
</SomeModel> 

The only way I can think of to achieve what you want (natively) would be to have properties pointing to objects named SomeStringElementName and SomeInfoElementName where the class contained a single getter named "value". You could take this one step further and use DataContractSerializer so that the wrapper classes can be private. XmlSerializer won't read private properties.

// TODO: make the class generic so that an int or string can be used.
[Serializable]  
public class SerializationClass
{
    public SerializationClass(string value)
    {
        this.Value = value;
    }

    [XmlAttribute("value")]
    public string Value { get; }
}


[Serializable]                     
public class SomeModel                     
{                     
    [XmlIgnore]                     
    public string SomeString { get; set; }                     

    [XmlIgnore]                      
    public int SomeInfo { get; set; }  

    [XmlElement]
    public SerializationClass SomeStringElementName
    {
        get { return new SerializationClass(this.SomeString); }
    }               
}

XmlSerializer giving FileNotFoundException at constructor

This exception can also be trapped by a managed debugging assistant (MDA) called BindingFailure.

This MDA is useful if your application is designed to ship with pre-build serialization assemblies. We do this to increase performance for our application. It allows us to make sure that the pre-built serialization assemblies are being properly built by our build process, and loaded by the application without being re-built on the fly.

It's really not useful except in this scenario, because as other posters have said, when a binding error is trapped by the Serializer constructor, the serialization assembly is re-built at runtime. So you can usually turn it off.

Convert XML String to Object

Just in case anyone might find this useful:

public static class XmlConvert
{
    public static string SerializeObject<T>(T dataObject)
    {
        if (dataObject == null)
        {
            return string.Empty;
        }
        try
        {
            using (StringWriter stringWriter = new System.IO.StringWriter())
            {
                var serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(stringWriter, dataObject);
                return stringWriter.ToString();
            }
        }
        catch (Exception ex)
        {
            return string.Empty;
        }
    }

    public static T DeserializeObject<T>(string xml)
         where T : new()
    {
        if (string.IsNullOrEmpty(xml))
        {
            return new T();
        }
        try
        {
            using (var stringReader = new StringReader(xml))
            {
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(stringReader);
            }
        }
        catch (Exception ex)
        {
            return new T();
        }
    }
}

You can call it using:

MyCustomObject myObject = new MyCustomObject();
string xmlString = XmlConvert.SerializeObject(myObject)
myObject = XmlConvert.DeserializeObject<MyCustomObject>(xmlString);

Xml serialization - Hide null values

In my case the nullable variables/elements were all String type. So, I simply performed a check and assigned them string.Empty in case of NULL. This way I got rid of the unnecessary nil and xmlns attributes (p3:nil="true" xmlns:p3="http://www.w3.org/2001/XMLSchema-instance)

// Example:

myNullableStringElement = varCarryingValue ?? string.Empty

// OR

myNullableStringElement = myNullableStringElement ?? string.Empty

JAXB: How to ignore namespace during unmarshalling XML document?

This is just a modification of lunicon's answer (https://stackoverflow.com/a/24387115/3519572) if you want to replace one namespace for another during parsing. And if you want to see what exactly is going on, just uncomment the output lines and set a breakpoint.

public class XMLReaderWithNamespaceCorrection extends StreamReaderDelegate {

    private final String wrongNamespace;
    private final String correctNamespace;

    public XMLReaderWithNamespaceCorrection(XMLStreamReader reader, String wrongNamespace, String correctNamespace) {
        super(reader);

        this.wrongNamespace = wrongNamespace;
        this.correctNamespace = correctNamespace;
    }

    @Override
    public String getAttributeNamespace(int arg0) {
//        System.out.println("--------------------------\n");
//        System.out.println("arg0: " + arg0);
//        System.out.println("getAttributeName: " + getAttributeName(arg0));
//        System.out.println("super.getAttributeNamespace: " + super.getAttributeNamespace(arg0));
//        System.out.println("getAttributeLocalName: " + getAttributeLocalName(arg0));
//        System.out.println("getAttributeType: " + getAttributeType(arg0));
//        System.out.println("getAttributeValue: " + getAttributeValue(arg0));
//        System.out.println("getAttributeValue(correctNamespace, LN):"
//                + getAttributeValue(correctNamespace, getAttributeLocalName(arg0)));
//        System.out.println("getAttributeValue(wrongNamespace, LN):"
//                + getAttributeValue(wrongNamespace, getAttributeLocalName(arg0)));

        String origNamespace = super.getAttributeNamespace(arg0);

        boolean replace = (((wrongNamespace == null) && (origNamespace == null))
                || ((wrongNamespace != null) && wrongNamespace.equals(origNamespace)));
        return replace ? correctNamespace : origNamespace;
    }

    @Override
    public String getNamespaceURI() {
//        System.out.println("getNamespaceCount(): " + getNamespaceCount());
//        for (int i = 0; i < getNamespaceCount(); i++) {
//            System.out.println(i + ": " + getNamespacePrefix(i));
//        }
//
//        System.out.println("super.getNamespaceURI: " + super.getNamespaceURI());

        String origNamespace = super.getNamespaceURI();

        boolean replace = (((wrongNamespace == null) && (origNamespace == null))
                || ((wrongNamespace != null) && wrongNamespace.equals(origNamespace)));
        return replace ? correctNamespace : origNamespace;
    }
}

usage:

InputStream is = new FileInputStream(xmlFile);
XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);
XMLReaderWithNamespaceCorrection xr =
    new XMLReaderWithNamespaceCorrection(xsr, "http://wrong.namespace.uri", "http://correct.namespace.uri");
rootJaxbElem = (JAXBElement<SqgRootType>) um.unmarshal(xr);
handleSchemaError(rootJaxbElem, pmRes);

Is it possible to deserialize XML into List<T>?

Yes, it will serialize and deserialize a List<>. Just make sure you use the [XmlArray] attribute if in doubt.

[Serializable]
public class A
{
    [XmlArray]
    public List<string> strings;
}

This works with both Serialize() and Deserialize().

There is an error in XML document (1, 41)

First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....

Why XML-Serializable class need a parameterless constructor

This is a limitation of XmlSerializer. Note that BinaryFormatter and DataContractSerializer do not require this - they can create an uninitialized object out of the ether and initialize it during deserialization.

Since you are using xml, you might consider using DataContractSerializer and marking your class with [DataContract]/[DataMember], but note that this changes the schema (for example, there is no equivalent of [XmlAttribute] - everything becomes elements).

Update: if you really want to know, BinaryFormatter et al use FormatterServices.GetUninitializedObject() to create the object without invoking the constructor. Probably dangerous; I don't recommend using it too often ;-p See also the remarks on MSDN:

Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object. The current method should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.

I have my own serialization engine, but I don't intend making it use FormatterServices; I quite like knowing that a constructor (any constructor) has actually executed.

Serializing an object as UTF-8 XML in .NET

Your code doesn't get the UTF-8 into memory as you read it back into a string again, so its no longer in UTF-8, but back in UTF-16 (though ideally its best to consider strings at a higher level than any encoding, except when forced to do so).

To get the actual UTF-8 octets you could use:

var serializer = new XmlSerializer(typeof(SomeSerializableObject));

var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);

serializer.Serialize(streamWriter, entry);

byte[] utf8EncodedXml = memoryStream.ToArray();

I've left out the same disposal you've left. I slightly favour the following (with normal disposal left in):

var serializer = new XmlSerializer(typeof(SomeSerializableObject));
using(var memStm = new MemoryStream())
using(var  xw = XmlWriter.Create(memStm))
{
  serializer.Serialize(xw, entry);
  var utf8 = memStm.ToArray();
}

Which is much the same amount of complexity, but does show that at every stage there is a reasonable choice to do something else, the most pressing of which is to serialise to somewhere other than to memory, such as to a file, TCP/IP stream, database, etc. All in all, it's not really that verbose.

Checking if an object is a number in C#

You will simply need to do a type check for each of the basic numeric types.

Here's an extension method that should do the job:

public static bool IsNumber(this object value)
{
    return value is sbyte
            || value is byte
            || value is short
            || value is ushort
            || value is int
            || value is uint
            || value is long
            || value is ulong
            || value is float
            || value is double
            || value is decimal;
}

This should cover all numeric types.

Update

It seems you do actually want to parse the number from a string during deserialisation. In this case, it would probably just be best to use double.TryParse.

string value = "123.3";
double num;
if (!double.TryParse(value, out num))
    throw new InvalidOperationException("Value is not a number.");

Of course, this wouldn't handle very large integers/long decimals, but if that is the case you just need to add additional calls to long.TryParse / decimal.TryParse / whatever else.

How to serialize an object to XML without getting xmlns="..."?

If you want to remove the namespace you may also want to remove the version, to save you searching I've added that functionality so the below code will do both.

I've also wrapped it in a generic method as I'm creating very large xml files which are too large to serialize in memory so I've broken my output file down and serialize it in smaller "chunks":

    public static string XmlSerialize<T>(T entity) where T : class
    {
        // removes version
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;

        XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
        using (StringWriter sw = new StringWriter())
        using (XmlWriter writer = XmlWriter.Create(sw, settings))
        {
            // removes namespace
            var xmlns = new XmlSerializerNamespaces();
            xmlns.Add(string.Empty, string.Empty);

            xsSubmit.Serialize(writer, entity, xmlns);
            return sw.ToString(); // Your XML
        }
    }

XML Serialize generic list of serializable objects

The easiest way to do it, that I have found.. Apply the System.Xml.Serialization.XmlArray attribute to it.

[System.Xml.Serialization.XmlArray] //This is the part that makes it work
List<object> serializableList = new List<object>();

XmlSerializer xmlSerializer = new XmlSerializer(serializableList.GetType());

serializableList.Add(PersonList);

using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
    xmlSerializer.Serialize(streamWriter, serializableList);
}

The serializer will pick up on it being an array and serialize the list's items as child nodes.

Omitting all xsi and xsd namespaces when serializing an object in .NET?

After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer and custom XML serialization via IXmlSerialiazble.

To wit, I'll use the same MyTypeWithNamespaces XML sample that's been used in the answers to this question so far.

[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
    // As noted below, per Microsoft's documentation, if the class exposes a public
    // member of type XmlSerializerNamespaces decorated with the 
    // XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
    // namespaces during serialization.
    public MyTypeWithNamespaces( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            // Don't do this!! Microsoft's documentation explicitly says it's not supported.
            // It doesn't throw any exceptions, but in my testing, it didn't always work.

            // new XmlQualifiedName(string.Empty, string.Empty),  // And don't do this:
            // new XmlQualifiedName("", "")

            // DO THIS:
            new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
            // Add any other namespaces, with prefixes, here.
        });
    }

    // If you have other constructors, make sure to call the default constructor.
    public MyTypeWithNamespaces(string label, int epoch) : this( )
    {
        this._label = label;
        this._epoch = epoch;
    }

    // An element with a declared namespace different than the namespace
    // of the enclosing type.
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        get { return this._label; }
        set { this._label = value; }
    }
    private string _label;

    // An element whose tag will be the same name as the property name.
    // Also, this element will inherit the namespace of the enclosing type.
    public int Epoch
    {
        get { return this._epoch; }
        set { this._epoch = value; }
    }
    private int _epoch;

    // Per Microsoft's documentation, you can add some public member that
    // returns a XmlSerializerNamespaces object. They use a public field,
    // but that's sloppy. So I'll use a private backed-field with a public
    // getter property. Also, per the documentation, for this to work with
    // the XmlSerializer, decorate it with the XmlNamespaceDeclarations
    // attribute.
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

That's all to this class. Now, some objected to having an XmlSerializerNamespaces object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.

Now, when it comes time to serialize the class, you would use the following code:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

/******
   OK, I just figured I could do this to make the code shorter, so I commented out the
   below and replaced it with what follows:

// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
    new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");

******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();

// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.

// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

Once you have done this, you should get the following output:

<MyTypeWithNamespaces>
    <Label xmlns="urn:Whoohoo">myLabel</Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable.

It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi and xsd namespaces generated by the XmlSerializer.

UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra and Whoohoo. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra is the defalt namespace. I could inside my MyTypeWithNamespaces class add a namespace prefix for the Whoohoo namespace like so:

public MyTypeWithNamespaces
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
        new XmlQualifiedName("w", "urn:Whoohoo")
    });
}

Now, in my class definition, I indicated that the <Label/> element is in the namespace "urn:Whoohoo", so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:

<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
    <w:Label>myLabel</w:Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Because <Label> is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi and xsd namespaces.

Using StringWriter for XML Serialization

First of all, beware of finding old examples. You've found one that uses XmlTextWriter, which is deprecated as of .NET 2.0. XmlWriter.Create should be used instead.

Here's an example of serializing an object into an XML column:

public void SerializeToXmlColumn(object obj)
{
    using (var outputStream = new MemoryStream())
    {
        using (var writer = XmlWriter.Create(outputStream))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj);
        }

        outputStream.Position = 0;
        using (var conn = new SqlConnection(Settings.Default.ConnectionString))
        {
            conn.Open();

            const string INSERT_COMMAND = @"INSERT INTO XmlStore (Data) VALUES (@Data)";
            using (var cmd = new SqlCommand(INSERT_COMMAND, conn))
            {
                using (var reader = XmlReader.Create(outputStream))
                {
                    var xml = new SqlXml(reader);

                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@Data", xml);
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}

XmlSerializer: remove unnecessary xsi and xsd namespaces

Since Dave asked for me to repeat my answer to Omitting all xsi and xsd namespaces when serializing an object in .NET, I have updated this post and repeated my answer here from the afore-mentioned link. The example used in this answer is the same example used for the other question. What follows is copied, verbatim.


After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer and custom XML serialization via IXmlSerialiazble.

To whit, I'll use the same MyTypeWithNamespaces XML sample that's been used in the answers to this question so far.

[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
    // As noted below, per Microsoft's documentation, if the class exposes a public
    // member of type XmlSerializerNamespaces decorated with the 
    // XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
    // namespaces during serialization.
    public MyTypeWithNamespaces( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            // Don't do this!! Microsoft's documentation explicitly says it's not supported.
            // It doesn't throw any exceptions, but in my testing, it didn't always work.

            // new XmlQualifiedName(string.Empty, string.Empty),  // And don't do this:
            // new XmlQualifiedName("", "")

            // DO THIS:
            new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
            // Add any other namespaces, with prefixes, here.
        });
    }

    // If you have other constructors, make sure to call the default constructor.
    public MyTypeWithNamespaces(string label, int epoch) : this( )
    {
        this._label = label;
        this._epoch = epoch;
    }

    // An element with a declared namespace different than the namespace
    // of the enclosing type.
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        get { return this._label; }
        set { this._label = value; }
    }
    private string _label;

    // An element whose tag will be the same name as the property name.
    // Also, this element will inherit the namespace of the enclosing type.
    public int Epoch
    {
        get { return this._epoch; }
        set { this._epoch = value; }
    }
    private int _epoch;

    // Per Microsoft's documentation, you can add some public member that
    // returns a XmlSerializerNamespaces object. They use a public field,
    // but that's sloppy. So I'll use a private backed-field with a public
    // getter property. Also, per the documentation, for this to work with
    // the XmlSerializer, decorate it with the XmlNamespaceDeclarations
    // attribute.
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

That's all to this class. Now, some objected to having an XmlSerializerNamespaces object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.

Now, when it comes time to serialize the class, you would use the following code:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

/******
   OK, I just figured I could do this to make the code shorter, so I commented out the
   below and replaced it with what follows:

// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
    new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");

******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();

// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.

// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

Once you have done this, you should get the following output:

<MyTypeWithNamespaces>
    <Label xmlns="urn:Whoohoo">myLabel</Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable.

It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi and xsd namespaces generated by the XmlSerializer.

UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra and Whoohoo. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra is the default namespace. I could inside my MyTypeWithNamespaces class add a namespace prefix for the Whoohoo namespace like so:

public MyTypeWithNamespaces
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
        new XmlQualifiedName("w", "urn:Whoohoo")
    });
}

Now, in my class definition, I indicated that the <Label/> element is in the namespace "urn:Whoohoo", so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:

<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
    <w:Label>myLabel</w:Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Because <Label> is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi and xsd namespaces.


This ends my answer to the other question. But I wanted to make sure I answered the OP's question about using no namespaces, as I feel I didn't really address it yet. Assume that <Label> is part of the same namespace as the rest of the document, in this case urn:Abracadabra:

<MyTypeWithNamespaces>
    <Label>myLabel<Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Your constructor would look as it would in my very first code example, along with the public property to retrieve the default namespace:

// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the 
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
    });
}

[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
    get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;

Then, later, in your code that uses the MyTypeWithNamespaces object to serialize it, you would call it as I did above:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

...

// Above, you'd setup your XmlTextWriter.

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

And the XmlSerializer would spit back out the same XML as shown immediately above with no additional namespaces in the output:

<MyTypeWithNamespaces>
    <Label>myLabel<Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

jquery $(window).height() is returning the document height

Its really working if we use Doctype on our web page jquery(window) will return the viewport height else it will return the complete document height.

Define the following tag on the top of your web page: <!DOCTYPE html>

TypeError: 'float' object not iterable

for i in count: means for i in 7:, which won't work. The bit after the in should be of an iterable type, not a number. Try this:

for i in range(count):

datetime dtypes in pandas read_csv

You might try passing actual types instead of strings.

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime, datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

But it's going to be really hard to diagnose this without any of your data to tinker with.

And really, you probably want pandas to parse the the dates into TimeStamps, so that might be:

pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=True)

How to dismiss keyboard for UITextView with return key?

Simular to other answers using the UITextViewDelegate but a newer swift interface isNewline would be:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if let character = text.first, character.isNewline {
        textView.resignFirstResponder()
        return false
    }
    return true
}

Google Maps API v2: How to make markers clickable?

Here is my whole code of a map activity with 4 clickable markers. Click on a marker shows an info window, and after click on info window you are going to another activity: English, German, Spanish or Italian. If you want to use OnMarkerClickListener in spite of OnInfoWindowClickListener, you just have to swap this line:

mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener()

to this:

mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()

this line:

public void onInfoWindowClick(Marker arg0)

to this:

public boolean onMarkerClick(Marker arg0)

and at the end of the method "onMarkerClick":

return true;

I think it may be helpful for someone ;)

package pl.pollub.translator;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

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

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        Toast.makeText(this, "Choose a language.", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener()
        {

            @Override
            public void onInfoWindowClick(Marker arg0) {
                if(arg0 != null && arg0.getTitle().equals("English")){
                Intent intent1 = new Intent(MapsActivity.this, English.class);
                startActivity(intent1);}

                if(arg0 != null && arg0.getTitle().equals("German")){
                Intent intent2 = new Intent(MapsActivity.this, German.class);
                startActivity(intent2);} 

                if(arg0 != null && arg0.getTitle().equals("Italian")){
                Intent intent3 = new Intent(MapsActivity.this, Italian.class);
                startActivity(intent3);}

                if(arg0 != null && arg0.getTitle().equals("Spanish")){
                Intent intent4 = new Intent(MapsActivity.this, Spanish.class);
                startActivity(intent4);}
            }
        });
        LatLng greatBritain = new LatLng(51.30, -0.07);
        LatLng germany = new LatLng(52.3107, 13.2430);
        LatLng italy = new LatLng(41.53, 12.29);
        LatLng spain = new LatLng(40.25, -3.41);
        mMap.addMarker(new MarkerOptions()
                .position(greatBritain)
                .title("English")
                .snippet("Click on me:)"));
        mMap.addMarker(new MarkerOptions()
                .position(germany)
                .title("German")
                .snippet("Click on me:)"));
        mMap.addMarker(new MarkerOptions()
                .position(italy)
                .title("Italian")
                .snippet("Click on me:)"));
        mMap.addMarker(new MarkerOptions()
                .position(spain)
                .title("Spanish")
                .snippet("Click on me:)"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(greatBritain));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(germany));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(italy));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(spain));
    }
}

Printing all properties in a Javascript Object

What about this:

var txt="";
var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

for (var x in nyc){
    txt += nyc[x];
}

How to use jquery $.post() method to submit form values

Yor $.post has no data. You need to pass the form data. You can use serialize() to post the form data. Try this

$("#post-btn").click(function(){
    $.post("process.php", $('#reg-form').serialize() ,function(data){
        alert(data);
    });
});

Escape @ character in razor view engine

You can use @@ for this purpose. Like var email = firstName + '\@@' + domain;

Change default global installation directory for node.js modules in Windows?

Building on the installation concept of chocolatey and the idea suggested by @Tracker, what worked for me was to do the following and all users on windows were then happy working with nodejs and npm.

Choose C:\ProgramData\nodejs as installation directory for nodejs and install nodejs with any user that is a member of the administrator group.

This can be done with chocolatey as: choco install nodejs.install -ia "'INSTALLDIR=C:\ProgramData\nodejs'"

Then create a folder called npm-cache at the root of the installation directory, which after following above would be C:\ProgramData\nodejs\npm-cache.

Create a folder called etc at the root of the installation directory, which after following above would be C:\ProgramData\nodejs\etc.

Set NODE environment variable as C:\ProgramData\nodejs.

Set NODE_PATH environment variable as C:\ProgramData\nodejs\node_modules.

Ensure %NODE% environment variable previously created above is added (or its path) is added to %PATH% environment variable.

Edit %NODE_PATH%\npm\npmrc with the following content prefix=C:\ProgramData\nodejs

From command prompt, set the global config like so...

npm config --global set prefix "C:\ProgramData\nodejs"

npm config --global set cache "C:\ProgramData\nodejs\npm-cache"

It is important the steps above are carried out preferably in sequence and before updating npm (npm -g install npm@latest) or attempting to install any npm module.

Performing the above steps helped us running nodejs as system wide installation, easily available to all users with proper permissions. Each user can then run node and npm as required.

Combine two arrays

To do this, you can loop through one and append to the other:

<?php

$test1 = array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);

$test2 = array( 
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);


function combineWithKeys($array1, $array2)
{
    foreach($array1 as $key=>$value) $array2[$key] = $value;
    asort($array2);
    return $array2;
} 

print_r(combineWithKeys($test1, $test2));

?>

UPDATE: KingCrunch came up with the best solution: print_r($array1+$array2);

Get the client's IP address in socket.io

This works for the 2.3.0 version:

io.on('connection', socket => {
   const ip = socket.handshake.headers['x-forwarded-for'] || socket.conn.remoteAddress.split(":")[3];
   console.log(ip);
});

Verify ImageMagick installation

Try this one-shot solution that should figure out where ImageMagick is, if you have access to it...

This found all versions on my Godaddy hosting.

Upload this file to your server and call it ImageMagick.php or something then run it. You will get all the info you need... hopefully...

Good luck.

<?
/*
// This file will run a test on your server to determine the location and versions of ImageMagick. 
//It will look in the most commonly found locations. The last two are where most popular hosts (including "Godaddy") install ImageMagick.
//
// Upload this script to your server and run it for a breakdown of where ImageMagick is.
//
*/
echo '<h2>Test for versions and locations of ImageMagick</h2>';
echo '<b>Path: </b> convert<br>';

function alist ($array) {  //This function prints a text array as an html list.
    $alist = "<ul>";
    for ($i = 0; $i < sizeof($array); $i++) {
        $alist .= "<li>$array[$i]";
    }
    $alist .= "</ul>";
    return $alist;
}

exec("convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version"
echo '<br>';
echo '<b>This should test for ImageMagick version 5.x</b><br>';
echo '<b>Path: </b> /usr/bin/convert<br>';

exec("/usr/bin/convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version"

echo '<br>';
echo '<b>This should test for ImageMagick version 6.x</b><br>';
echo '<b>Path: </b> /usr/local/bin/convert<br>';

exec("/usr/local/bin/convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version";

?>

Linq to Sql: Multiple left outer joins

I think you should be able to follow the method used in this post. It looks really ugly, but I would think you could do it twice and get the result you want.

I wonder if this is actually a case where you'd be better off using DataContext.ExecuteCommand(...) instead of converting to linq.

Generate signed apk android studio

Use Keytool binary or exe to generate a private keystore. Instructions here. You can then sign your app using this keystore. Keytool gets installed when you install Java.

NOTE: Save/backup this keystore because once you publish an app on play by signing it with this keystore, you will have to use the same keystore for any future updates. So, it's important that you back it up.

HTH.

Char to int conversion in C

Normally, if there's no guarantee that your input is in the '0'..'9' range, you'd have to perform a check like this:

if (c >= '0' && c <= '9') {
    int v = c - '0';
    // safely use v
}

An alternative is to use a lookup table. You get simple range checking and conversion with less (and possibly faster) code:

// one-time setup of an array of 256 integers;
// all slots set to -1 except for ones corresponding
// to the numeric characters
static const int CHAR_TO_NUMBER[] = {
    -1, -1, -1, ...,
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, // '0'..'9'
    -1, -1, -1, ...
};

// Now, all you need is:

int v = CHAR_TO_NUMBER[c];

if (v != -1) {
    // safely use v
}

P.S. I know that this is an overkill. I just wanted to present it as an alternative solution that may not be immediately evident.

Difference between 'struct' and 'typedef struct' in C++?

In C++, there is only a subtle difference. It's a holdover from C, in which it makes a difference.

The C language standard (C89 §3.1.2.3, C99 §6.2.3, and C11 §6.2.3) mandates separate namespaces for different categories of identifiers, including tag identifiers (for struct/union/enum) and ordinary identifiers (for typedef and other identifiers).

If you just said:

struct Foo { ... };
Foo x;

you would get a compiler error, because Foo is only defined in the tag namespace.

You'd have to declare it as:

struct Foo x;

Any time you want to refer to a Foo, you'd always have to call it a struct Foo. This gets annoying fast, so you can add a typedef:

struct Foo { ... };
typedef struct Foo Foo;

Now struct Foo (in the tag namespace) and just plain Foo (in the ordinary identifier namespace) both refer to the same thing, and you can freely declare objects of type Foo without the struct keyword.


The construct:

typedef struct Foo { ... } Foo;

is just an abbreviation for the declaration and typedef.


Finally,

typedef struct { ... } Foo;

declares an anonymous structure and creates a typedef for it. Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. This means it also cannot be forward-declared. If you want to make a forward declaration, you have to give it a name in the tag namespace.


In C++, all struct/union/enum/class declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name. See Michael Burr's answer for the full details.

Type safety: Unchecked cast

A warning is just that. A warning. Sometimes warnings are irrelevant, sometimes they're not. They're used to call your attention to something that the compiler thinks could be a problem, but may not be.

In the case of casts, it's always going to give a warning in this case. If you are absolutely certain that a particular cast will be safe, then you should consider adding an annotation like this (I'm not sure of the syntax) just before the line:

@SuppressWarnings (value="unchecked")

Conditional WHERE clause in SQL Server

The problem with your query is that in CASE expressions, the THEN and ELSE parts have to have an expression that evaluates to a number or a varchar or any other datatype but not to a boolean value.

You just need to use boolean logic (or rather the ternary logic that SQL uses) and rewrite it:

WHERE 
    DateDropped = 0
AND ( @JobsOnHold = 1 AND DateAppr >= 0 
   OR (@JobsOnHold <> 1 OR @JobsOnHold IS NULL) AND DateAppr <> 0
    )

Undefined symbols for architecture armv7

If you're building from Unity3D 5 and also using a Prime31 plugin and you're getting this error it's probably due to a duplicate .dll. If you look through your warnings in Unity's editor one of them will tell you this and warn that it could cause build errors. To see if this is the case, type P31 in your project search field and it should pop right up, maybe even more than one. The duplicate's will have a ' 1' at the end of the file name. This is probably caused from updating the plugin in editor via the store or the Prime31 menu tab.

JavaFX and OpenJDK

For me this worked.

$ sudo apt-get install openjfx

How to create temp table using Create statement in SQL Server?

A temporary table can have 3 kinds, the # is the most used. This is a temp table that only exists in the current session. An equivalent of this is @, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session. The ## is one that is the same as the #, however, the scope is wider, so you can use it within the same session, within other stored procedures.

You can create a temp table in various ways:

declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz

Spring - applicationContext.xml cannot be opened because it does not exist

The ClassPathXmlApplicationContext isn't going to find the applicationContext.xml in your WEB-INF folder, it's not on the classpath. You could copy the application context into your classpath (could put it under src/test/resources and let Maven copy it over) when running the tests.

What is the Record type in typescript?

  1. Can someone give a simple definition of what Record is?

A Record<K, T> is an object type whose property keys are K and whose property values are T. That is, keyof Record<K, T> is equivalent to K, and Record<K, T>[K] is (basically) equivalent to T.

  1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

As you note, K has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.

  1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:

declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'

and it would treat them as excess properties which are sometimes rejected:

declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties

and sometimes accepted:

const y = {a: "hey", b: "you"};
acceptR(y); // okay
  1. With the given example:

    type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
    

    Is it exactly the same as this?:

    type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
    

Yes!

Hope that helps. Good luck!

How to get selected option using Selenium WebDriver with Java

In Selenium Python it is:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select

def get_selected_value_from_drop_down(self):
    try:
        select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, 'data_configuration_edit_data_object_tab_details_lb_use_for_match'))))
        return select.first_selected_option.get_attribute("value")
    except NoSuchElementException, e:
        print "Element not found "
        print e

What is the minimum I have to do to create an RPM file?

For quick RPM building, check out Togo:

https://github.com/genereese/togo-rpm

The project has a Quick-Start guide and I was able to create a basic RPM in less than 3 minutes.

Example using the data provided in the original question:

1) Create the project directory using the script:

$ togo project create foobar; cd foobar

2) Make your desired directory structure under ./root and copy your files into it:

$ mkdir -p root/etc; cp /path/to/foobar.conf root/etc/
$ mkdir -p root/usr/bin; cp /path/to/foobar root/usr/bin/

3) Exclude system-owned directories from your RPM's ownership:

$ togo file exclude root/etc root/usr/bin

4) (OPTIONAL) Modify the generated spec to change your package description/dependencies/version/whatever, etc.:

$ vi spec/header

5) Build the RPM:

$ togo build package

-and your RPM is spit out into the ./rpms directory.

Android Device not recognized by adb

I recently had this issue (but before that debug over wifi was working fine) and since none of the above answers helped me let me share what I did.

  1. Go to developer options
  2. Find Select USB configurations and click it
  3. Choose MTP (Media Transfer Protocol)

Note: If it's set to this option chose another option such as PTP first then set it to MTP again.

UPDATE:

PTP stands for “Picture Transfer Protocol.” When Android uses this protocol, it appears to the computer as a digital camera.

MTP is actually based on PTP, but adds more features, or “extensions.” PTP works similarly to MTP and is commonly used by digital cameras.

How do I convert a list of ascii values to a string in python?

Same basic solution as others, but I personally prefer to use map instead of the list comprehension:


>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'

SQL to find the number of distinct values in a column

**

Using following SQL we can get the distinct column value count in Oracle 11g.

**

Select count(distinct(Column_Name)) from TableName

What does FETCH_HEAD in Git mean?

git pull is combination of a fetch followed by a merge. When git fetch happens it notes the head commit of what it fetched in FETCH_HEAD (just a file by that name in .git) And these commits are then merged into your working directory.

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

The proper way is to use Hibernate Transformers:

public class StudentDTO {
private String studentName;
private String courseDescription;

public StudentDTO() { }  
...
} 

.

List resultWithAliasedBean = s.createSQLQuery(
"SELECT st.name as studentName, co.description as courseDescription " +
"FROM Enrolment e " +
"INNER JOIN Student st on e.studentId=st.studentId " +
"INNER JOIN Course co on e.courseCode=co.courseCode")
.setResultTransformer( Transformers.aliasToBean(StudentDTO.class))
.list();

StudentDTO dto =(StudentDTO) resultWithAliasedBean.get(0);

Iterating througth Object[] is redundant and would have some performance penalty. Detailed information about transofrmers usage you will find here: Transformers for HQL and SQL

If you are looking for even more simple solution you can use out-of-the-box-map-transformer:

List iter = s.createQuery(
"select e.student.name as studentName," +
"       e.course.description as courseDescription" +
"from   Enrolment as e")
.setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP )
.iterate();

String name = (Map)(iter.next()).get("studentName");

await is only valid in async function

Yes, await / async was a great concept, but the implementation is completely broken.

For whatever reason, the await keyword has been implemented such that it can only be used within an async method. This is in fact a bug, though you will not see it referred to as such anywhere but right here. The fix for this bug would be to implement the await keyword such that it can only be used TO CALL an async function, regardless of whether the calling function is itself synchronous or asynchronous.

Due to this bug, if you use await to call a real asynchronous function somewhere in your code, then ALL of your functions must be marked as async and ALL of your function calls must use await.

This essentially means that you must add the overhead of promises to all of the functions in your entire application, most of which are not and never will be asynchronous.

If you actually think about it, using await in a function should require the function containing the await keyword TO NOT BE ASYNC - this is because the await keyword is going to pause processing in the function where the await keyword is found. If processing in that function is paused, then it is definitely NOT asynchronous.

So, to the developers of javascript and ECMAScript - please fix the await/async implementation as follows...

  • await can only be used to CALL async functions.
  • await can appear in any kind of function, synchronous or asynchronous.
  • Change the error message from "await is only valid in async function" to "await can only be used to call async functions".

Powershell command to hide user from exchange address lists

"WARNING: The command completed successfully but no settings of '[user id here]' have been modified."

This warning means the setting was already set like what you want it to be. So it didn't change anything for that object.

Detect when input has a 'readonly' attribute

Since JQuery 1.6, always use .prop() Read why here: http://api.jquery.com/prop/

if($('input').prop('readonly')){ }

.prop() can also be used to set the property

$('input').prop('readonly',true);

$('input').prop('readonly',false);

YAML equivalent of array of objects in JSON

TL;DR

You want this:

AAPL:
  - shares: -75.088
    date: 11/27/2015
  - shares: 75.088
    date: 11/26/2015

Mappings

The YAML equivalent of a JSON object is a mapping, which looks like these:

# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2

Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:

# OK
   foo: 1
   bar: 2
# Parse error
   foo: 1
    bar: 2

Sequences

The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):

# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz

In a block sequence the -s must be in the same column.

JSON to YAML

Let's turn your JSON into YAML. Here's your JSON:

{"AAPL": [
  {
    "shares": -75.088,
    "date": "11/27/2015"
  },
  {
    "shares": 75.088,
    "date": "11/26/2015"
  },
]}

As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.

Starting from the inside out, we have objects that look like this:

{
  "shares": -75.088,
  "date": "11/27/2015"
}

The equivalent YAML mapping is:

shares: -75.088
date: 11/27/2015

We have two of these in an array (sequence):

- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

Note how the -s line up and the first characters of the mapping keys line up.

Finally, this sequence is itself a value in a mapping with the key AAPL:

AAPL:
  - shares: -75.088
    date: 11/27/2015
  - shares: 75.088
    date: 11/26/2015

Parsing this and converting it back to JSON yields the expected result:

{
  "AAPL": [
    {
      "date": "11/27/2015", 
      "shares": -75.088
    }, 
    {
      "date": "11/26/2015", 
      "shares": 75.088
    }
  ]
}

You can see it (and edit it interactively) here.

Define global variable with webpack

I solved this issue by setting the global variables as a static properties on the classes to which they are most relevant. In ES5 it looks like this:

var Foo = function(){...};
Foo.globalVar = {};

Bootstrap change carousel height

From Bootstrap 4

.carousel-item{
    height: 200px;
} 
.carousel-item img{
    height: 200px;
}

Hive Alter table change Column Name

In the comments @libjack mentioned a point which is really important. I would like to illustrate more into it. First, we can check what are the columns of our table by describe <table_name>; command. enter image description here

there is a double-column called _c1 and such columns are created by the hive itself when we moving data from one table to another. To address these columns we need to write it inside backticks

`_c1`

Finally, the ALTER command will be,

ALTER TABLE <table_namr> CHANGE `<system_genarated_column_name>` <new_column_name> <data_type>;

Equivalent of LIMIT for DB2

Developed this method:

You NEED a table that has an unique value that can be ordered.

If you want rows 10,000 to 25,000 and your Table has 40,000 rows, first you need to get the starting point and total rows:

int start = 40000 - 10000;

int total = 25000 - 10000;

And then pass these by code to the query:

SELECT * FROM 
(SELECT * FROM schema.mytable 
ORDER BY userId DESC fetch first {start} rows only ) AS mini 
ORDER BY mini.userId ASC fetch first {total} rows only

exception in initializer error in java when using Netbeans

Retrofit have recently updated to 2.7.1 version. After that Android 4.x clients have crashed. See https://stackoverflow.com/a/60071876/2914140.

Downgrade Retrofit to 2.6.4.

How do I center floated elements?

Set your container's width in px and add:

margin: 0 auto;

Reference.

ES6 export all values from object

Why not just do a named export of the object:

let values = { a: 1, b: 2, c: 3 }
export { values }

or

export let values = { a: 1, b: 2, c: 3 }

and then a named import where you need it:

import { values } from './my-module'

let foo = values.a
let { a, b, c } = values

or

import { values as myModule } from './my-module'

let foo = myModule.a
let { a, b, c } = myModule

can do default export as well:

let values = { a: 1, b: 2, c: 3 }
export default values 

or

export default { a: 1, b: 2, c: 3 }

and then consume it:

import whateverIcallIt from './my-Module'

let foo = whateverIcallIt.a
let {a, b, c } = whateverIcallIt

If you want to export a bunch of individual values, say a bunch of constants, you can:

export const a = 1
export const b = 2
//...

or even

export const a = 1,
             b = 2,
             c = 3,
//...

and then import them individually:

import { a, b, c } from './my-module'

Visual Studio Code - Convert spaces to tabs

{
  "editor.insertSpaces": true
}

True works for me.

How to add (vertical) divider to a horizontal LinearLayout?

If the answer of Kapil Vats is not working try something like this:

drawable/divider_horizontal_green_22.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <size android:width="22dip"/>
    <solid android:color="#00ff00"/>

</shape>

layout/your_layout.xml

LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/llTopBar"
            android:orientation="horizontal"
            android:divider="@drawable/divider_horizontal_green_22"
            android:showDividers="middle"
           >

I encountered an issue where the padding attribute wasn't working, thus I had to set the height of the divider directly in the divider.

Note:

If you want to use it in vertical LinearLayout, make a new one, like this: drawable/divider_vertical_green_22.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <size android:height="22dip"/>
    <solid android:color="#00ff00"/>

</shape>

Better techniques for trimming leading zeros in SQL Server?

This makes a nice Function....

DROP FUNCTION [dbo].[FN_StripLeading]
GO
CREATE FUNCTION [dbo].[FN_StripLeading] (@string VarChar(128), @stripChar VarChar(1))
RETURNS VarChar(128)
AS
BEGIN
-- http://stackoverflow.com/questions/662383/better-techniques-for-trimming-leading-zeros-in-sql-server
    DECLARE @retVal VarChar(128),
            @pattern varChar(10)
    SELECT @pattern = '%[^'+@stripChar+']%'
    SELECT @retVal = CASE WHEN SUBSTRING(@string, PATINDEX(@pattern, @string+'.'), LEN(@string)) = '' THEN @stripChar ELSE SUBSTRING(@string, PATINDEX(@pattern, @string+'.'), LEN(@string)) END
    RETURN (@retVal)
END
GO
GRANT EXECUTE ON [dbo].[FN_StripLeading] TO PUBLIC

Unable to merge dex

Deleting .gradle as suggested by Suragch wasn't enough for me. Additionally, I had to perform a Build > Clean Project.

Note that, in order to see .gradle, you need to switch to the "Project" view in the navigator on the top left:

Switch to project view

How do I prevent DIV tag starting a new line?

I am not an expert but try white-space:nowrap;

The white-space property is supported in all major browsers.

Note: The value "inherit" is not supported in IE7 and earlier. IE8 requires a !DOCTYPE. IE9 supports "inherit".

SQL string value spanning multiple lines in query

I prefer to use the @ symbol so I see the query exactly as I can copy and paste into a query file:

string name = "Joe";
string gender = "M";
string query = String.Format(@"
SELECT
   *
FROM
   tableA
WHERE
   Name = '{0}' AND
   Gender = '{1}'", name, gender);

It's really great with long complex queries. Nice thing is it keeps tabs and line feeds so pasting into a query browser retains the nice formatting

Multiple submit buttons in the same form calling different Servlets

In addition to the previous response, the best option to submit a form with different buttons without language problems is actually using a button tag.

<form>
    ...
    <button type="submit" name="submit" value="servlet1">Go to 1st Servlet</button>
    <button type="submit" name="submit" value="servlet2">Go to 2nd Servlet</button>
</form>

How to change the locale in chrome browser

The easiest way I found, summarized in a few pictures:

Adding Language

Changing Language

Relaunch

You could skip a few steps (up to step 4) by simply navigating to chrome://settings/languages right away.

SQL - IF EXISTS UPDATE ELSE INSERT INTO

  1. Create a UNIQUE constraint on your subs_email column, if one does not already exist:

    ALTER TABLE subs ADD UNIQUE (subs_email)
    
  2. Use INSERT ... ON DUPLICATE KEY UPDATE:

    INSERT INTO subs
      (subs_name, subs_email, subs_birthday)
    VALUES
      (?, ?, ?)
    ON DUPLICATE KEY UPDATE
      subs_name     = VALUES(subs_name),
      subs_birthday = VALUES(subs_birthday)
    

You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com

  1. Note that I have used parameter placeholders in the place of string literals, as one really should be using parameterised statements to defend against SQL injection attacks.

What is the Swift equivalent of respondsToSelector?

Functions are first-class types in Swift, so you can check whether an optional function defined in a protocol has been implemented by comparing it to nil:

if (someObject.someMethod != nil) {
    someObject.someMethod!(someArgument)
} else {
    // do something else
}

how to declare global variable in SQL Server..?

Try to use ; instead of GO. It worked for me for 2008 R2 version

DECLARE @GLOBAL_VAR_1 INT = Value_1;

DECLARE @GLOBAL_VAR_2 INT = Value_2;

USE "DB_1";
SELECT * FROM "TABLE" WHERE "COL_!" = @GLOBAL_VAR_1 

AND "COL_2" = @GLOBAL_VAR_2;

USE "DB_2";

SELECT * FROM "TABLE" WHERE "COL_!" = @GLOBAL_VAR_2;

How do I start a program with arguments when debugging?

My suggestion would be to use Unit Tests.

In your application do the following switches in Program.cs:

#if DEBUG
    public class Program
#else
    class Program
#endif

and the same for static Main(string[] args).

Or alternatively use Friend Assemblies by adding

[assembly: InternalsVisibleTo("TestAssembly")]

to your AssemblyInfo.cs.

Then create a unit test project and a test that looks a bit like so:

[TestClass]
public class TestApplication
{
    [TestMethod]
    public void TestMyArgument()
    {
        using (var sw = new StringWriter())
        {
            Console.SetOut(sw); // this makes any Console.Writes etc go to sw

            Program.Main(new[] { "argument" });

            var result = sw.ToString();

            Assert.AreEqual("expected", result);
        }
    }
}

This way you can, in an automated way, test multiple inputs of arguments without having to edit your code or change a menu setting every time you want to check something different.

Transition color fade on hover?

For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:

_x000D_
_x000D_
.field-error {_x000D_
    color: #f44336;_x000D_
    padding: 2px 5px;_x000D_
    position: absolute;_x000D_
    font-size: small;_x000D_
    background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
    animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
    -moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
    -webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
    -o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
    from { background-color: lightgreen; } /** from color **/_x000D_
    to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
_x000D_
_x000D_

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

What is "stdafx.h" used for in Visual Studio?

It's a "precompiled header file" -- any headers you include in stdafx.h are pre-processed to save time during subsequent compilations. You can read more about it here on MSDN.

If you're building a cross-platform application, check "Empty project" when creating your project and Visual Studio won't put any files at all in your project.

Custom Listview Adapter with filter Android

One thing I've noticed is that whenever you are editing the list (adding items for example) as well as filtering for it, then inside the @Override getView method, you shouldn't use filteredData.get(position), as it throws an IndexOutOfBounds exception.

Instead, what worked for me, was using the getItem(position) method, which belongs to the ArrayAdapter class.

How to share my Docker-Image without using the Docker-Hub?

Docker images are stored as filesystem layers. Every command in the Dockerfile creates a layer. You can also create layers by using docker commit from the command line after making some changes (via docker run probably).

These layers are stored by default under /var/lib/docker. While you could (theoretically) cherry pick files from there and install it in a different docker server, is probably a bad idea to play with the internal representation used by Docker.

When you push your image, these layers are sent to the registry (the docker hub registry, by default… unless you tag your image with another registry prefix) and stored there. When pushing, the layer id is used to check if you already have the layer locally or it needs to be downloaded. You can use docker history to peek at which layers (other images) are used (and, to some extent, which command created the layer).

As for options to share an image without pushing to the docker hub registry, your best options are:

  • docker save an image or docker export a container. This will output a tar file to standard output, so you will like to do something like docker save 'dockerizeit/agent' > dk.agent.latest.tar. Then you can use docker load or docker import in a different host.

  • Host your own private registry. - Outdated, see comments See the docker registry image. We have built an s3 backed registry which you can start and stop as needed (all state is kept on the s3 bucket of your choice) which is trivial to setup. This is also an interesting way of watching what happens when pushing to a registry

  • Use another registry like quay.io (I haven't personally tried it), although whatever concerns you have with the docker hub will probably apply here too.

PHP include relative path

You could always include it using __DIR__:

include(dirname(__DIR__).'/config.php');

__DIR__ is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__. In this case, as we need to ascend a directory we use PHP's dirname which ascends the file tree, and from here we can access config.php.

You could set the root path in this method too:

define('ROOT_PATH', dirname(__DIR__) . '/');

in test.php would set your root to be at the /root/ level.

include(ROOT_PATH.'config.php');

Should then work to include the config file from where you want.

Generating random numbers in Objective-C

For game dev use random() to generate randoms. Probably at least 5x faster than using arc4random(). Modulo bias is not an issue, especially for games, when generating randoms using the full range of random(). Be sure to seed first. Call srandomdev() in AppDelegate. Here's some helper functions:

static inline int random_range(int low, int high){ return (random()%(high-low+1))+low;}
static inline CGFloat frandom(){ return (CGFloat)random()/UINT32_C(0x7FFFFFFF);}
static inline CGFloat frandom_range(CGFloat low, CGFloat high){ return (high-low)*frandom()+low;}

Generate GUID in MySQL for existing Data?

I'm not sure if it's the easiest way, but it works. The idea is to create a trigger that does all work for you, then, to execute a query that updates your table, and finally to drop this trigger:

delimiter //
create trigger beforeYourTableUpdate  BEFORE UPDATE on YourTable
FOR EACH ROW
BEGIN
  SET new.guid_column := (SELECT UUID());
END
//

Then execute

UPDATE YourTable set guid_column = (SELECT UUID());

And DROP TRIGGER beforeYourTableUpdate;

UPDATE Another solution that doesn't use triggers, but requires primary key or unique index :

UPDATE YourTable,
INNER JOIN (SELECT unique_col, UUID() as new_id FROM YourTable) new_data 
ON (new_data.unique_col = YourTable.unique_col)
SET guid_column = new_data.new_id

UPDATE once again: It seems that your original query should also work (maybe you don't need WHERE columnID is not null, so all my fancy code is not needed.

Delete everything in a MongoDB database

For Meteor developers.

  1. Open a second terminal window while running your app in localhost:3000.

  2. In your project's folder run, meteor mongo.

    coolName = new Mongo.Collection('yourCollectionName');

  3. Then simply enter db.yourCollectionName.drop();

  4. You'll automatically see the changes in your local server.

For everybody else.

db.yourCollectionName.drop();

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

For mac users, this is the best way to solve, Download the chromedriver and then paste that chromedriver in this directory

/usr/local/bin

If this directory is not found to you then from finder click on go then select computer then press command+shift+. (this shows the hidden files in mac) then definitely you will see these directory easily

What size do you use for varchar(MAX) in your parameter declaration?

For those of us who did not see -1 by Michal Chaniewski, the complete line of code:

cmd.Parameters.Add("@blah",SqlDbType.VarChar,-1).Value = "some large text";

Is it possible to log all HTTP request headers with Apache?

If you're interested in seeing which specific headers a remote client is sending to your server, and you can cause the request to run a CGI script, then the simplest solution is to have your server script dump the environment variables into a file somewhere.

e.g. run the shell command "env > /tmp/headers" from within your script

Then, look for the environment variables that start with HTTP_...

You will see lines like:

HTTP_ACCEPT=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_ENCODING=gzip, deflate
HTTP_ACCEPT_LANGUAGE=en-US,en;q=0.5
HTTP_CACHE_CONTROL=max-age=0

Each of those represents a request header.

Note that the header names are modified from the actual request. For example, "Accept-Language" becomes "HTTP_ACCEPT_LANGUAGE", and so on.

Reporting Services permissions on SQL Server R2 SSRS

This did the trick for me. http://thecodeattic.wordpress.com/category/ssrs/. Go down to step 35 to see the error you are getting. Paraphrasing:

Once you're able to log in to YourServer/Reports as an administrator, click Home in the top-right corner, then Folder Settings and New Role Assignment. Enter your user name and check a box for each role you want to grant yourself. Finally, click OK. You should now be able to browse folders without launching your browser with elevated privileges.

Don't forget to set the security at the site level **AND ** at the folder level. I hope that helps.

Rick

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

If you are using Facebook SDK, you don't need to bother yourself to enter anything for redirect URI on the app management page of facebook. Just setup a URL scheme for your iOS app. The URL scheme of your app should be a value "fbxxxxxxxxxxx" where xxxxxxxxxxx is your app id as identified on facebook. To setup URL scheme for your iOS app, go to info tab of your app settings and add URL Type.

How to get error information when HttpWebRequest.GetResponse() fails

HttpWebRequest myHttprequest = null;
HttpWebResponse myHttpresponse = null;
myHttpRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpRequest.Method = "POST";
myHttpRequest.ContentType = "application/x-www-form-urlencoded";
myHttpRequest.ContentLength = urinfo.Length;
StreamWriter writer = new StreamWriter(myHttprequest.GetRequestStream());
writer.Write(urinfo);
writer.Close();
myHttpresponse = (HttpWebResponse)myHttpRequest.GetResponse();
if (myHttpresponse.StatusCode == HttpStatusCode.OK)
 {
   //Perform necessary action based on response
 }
myHttpresponse.Close(); 

How get an apostrophe in a string in javascript

You can put an apostrophe in a single quoted JavaScript string by escaping it with a backslash, like so:

theAnchorText = 'I\'m home';

How to test if list element exists?

The best way to check for named elements is to use exist(), however the above answers are not using the function properly. You need to use the where argument to check for the variable within the list.

foo <- list(a=42, b=NULL)

exists('a', where=foo) #TRUE
exists('b', where=foo) #TRUE
exists('c', where=foo) #FALSE

How to import JsonConvert in C# application?

right click on the project and select Manage NuGet Packages.. In that select Json.NET and install

After installation,

use the following namespace

using Newtonsoft.Json;

then use the following to deserialize

JsonConvert.DeserializeObject

How does += (plus equal) work?

+= in JavaScript (as well as in many other languages) adds the right hand side to the variable on the left hand side, storing the result in that variable. Your example of 1 +=2 therefore does not make sense. Here is an example:

var x = 5;
x += 4; // x now equals 9, same as writing x = x + 4;
x -= 3; // x now equals 6, same as writing x = x - 3;
x *= 2; // x now equals 12, same as writing x = x * 2;
x /= 3; // x now equals 4, same as writing x = x / 3;

In your specific example the loop is summing the numbers in the array data.

jQuery datepicker to prevent past date

I am using following code to format date and show 2 months in calendar...

<script>
$(function() {

    var dates = $( "#from, #to" ).datepicker({

        showOn: "button",
        buttonImage: "imgs/calendar-month.png",
        buttonImageOnly: true,                           
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 2,

        onSelect: function( selectedDate ) {




            $( ".selector" ).datepicker({ defaultDate: +7 });
            var option = this.id == "from" ? "minDate" : "maxDate",


                instance = $( this ).data( "datepicker" ),
                date = $.datepicker.parseDate(
                    instance.settings.dateFormat ||
                    $.datepicker._defaults.dateFormat,
                    selectedDate, instance.settings );

            dates.not( this ).datepicker( "option", "dateFormat", 'yy-mm-dd' );


        }
    });
});

</script>

The problem is I am not sure how to restrict previous dates selection.

Eclipse Error: "Failed to connect to remote VM"

I am using jboss so solution to your problem was restart.

service jboss-portal restart

Jenkins returned status code 128 with github

This error:

stderr: Permission denied (publickey). fatal: The remote end hung up unexpectedly

indicates that Jenkins is trying to connect to github with the wrong ssh key.

You should:

  1. Determine the user that jenkins runs as, eg. 'build' or 'jenkins'
  2. Login on the jenkins host that is trying to do the clone - that is, do not login to the master if a node is actually doing the build.
  3. Try you ssh to github - if it fails, then you need to add the proper key to /.ssh

How to set a ripple effect on textview or imageview on Android?

addition to above answers is adding focusable to avoid UI editor's warning

android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:focusable="true"

How do I convert a byte array to Base64 in Java?

Java 8+

Encode or decode byte arrays:

byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded));   // Outputs "SGVsbG8="

byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded)    // Outputs "Hello"

For more info, see Base64.

Java < 8

Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.

For direct byte arrays:

Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded));   // Outputs "SGVsbG8="

byte[] decoded = codec.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(codec.decodeBase64(encoded));
println(decoded)    // Outputs "Hello"

Spring

If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils class more ergonomic:

For direct byte arrays:

byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded))    // Outputs "SGVsbG8="

byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = Base64Utils.decodeFromString(encoded);
println(new String(decoded))    // Outputs "Hello"

Android (with Java < 8)

If you are using the Android SDK before Java 8 then your best option is to use the bundled android.util.Base64.

For direct byte arrays:

byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded))    // Outputs "SGVsbG8="

byte [] decoded = Base64.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(Base64.decode(encoded));
println(decoded)    // Outputs "Hello"

How do I include a newline character in a string in Delphi?

On the side, a trick that can be useful:
If you hold your multiple strings in a TStrings, you just have to use the Text property of the TStrings like in the following example.

Label1.Caption := Memo1.Lines.Text;

And you'll get your multi-line label...

Best way to require all files from a directory in ruby?

Dir[File.dirname(__FILE__) + '/../lib/*.rb'].each do |file| 
  require File.basename(file, File.extname(file))
end

If you don't strip the extension then you may end up requiring the same file twice (ruby won't realize that "foo" and "foo.rb" are the same file). Requiring the same file twice can lead to spurious warnings (e.g. "warning: already initialized constant").

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

I made a little test (Perl v5.20.1 under FreeBSD in VM) calling the following blocks 1.000.000 times each:

A

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
my $now = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $year+1900, $mon+1, $mday, $hour, $min, $sec);

B

my $now = strftime('%Y%m%d%H%M%S',localtime);

C

my $now = Time::Piece::localtime->strftime('%Y%m%d%H%M%S');

with the following results:

A: 2 seconds

B: 11 seconds

C: 19 seconds

This is of course not a thorough test or benchmark, but at least it is reproducable for me, so even though it is more complicated, I'd prefer the first method if generating a datetimestamp is required very often.

Calling (eg. under FreeBSD 10.1)

my $now = `date "+%Y%m%d%H%M%S" | tr -d "\n"`;

might not be such a good idea because it is not OS-independent and takes quite some time.

Best regards, Holger

Choosing a file in Python with simple Dialog

Another option to consider is Zenity: http://freecode.com/projects/zenity.

I had a situation where I was developing a Python server application (no GUI component) and hence didn't want to introduce a dependency on any python GUI toolkits, but I wanted some of my debug scripts to be parameterized by input files and wanted to visually prompt the user for a file if they didn't specify one on the command line. Zenity was a perfect fit. To achieve this, invoke "zenity --file-selection" using the subprocess module and capture the stdout. Of course this solution isn't Python-specific.

Zenity supports multiple platforms and happened to already be installed on our dev servers so it facilitated our debugging/development without introducing an unwanted dependency.

Split String into an array of String

You need a regular expression like "\\s+", which means: split whenever at least one whitespace is encountered. The full Java code is:

try {
    String[] splitArray = input.split("\\s+");
} catch (PatternSyntaxException ex) {
    // 
}

Environment Specific application.properties file in Spring Boot application

Yes you can. Since you are using spring, check out @PropertySource anotation.

Anotate your configuration with

@PropertySource("application-${spring.profiles.active}.properties")

You can call it what ever you like, and add inn multiple property files if you like too. Can be nice if you have more sets and/or defaults that belongs to all environments (can be written with @PropertySource{...,...,...} as well).

@PropertySources({
  @PropertySource("application-${spring.profiles.active}.properties"),
  @PropertySource("my-special-${spring.profiles.active}.properties"),
  @PropertySource("overridden.properties")})

Then you can start the application with environment

-Dspring.active.profiles=test

In this example, name will be replaced with application-test-properties and so on.

Check if a String contains numbers Java

As I was redirected here searching for a method to find digits in string in Kotlin language, I'll leave my findings here for other folks wanting a solution specific to Kotlin.

Finding out if a string contains digit:

val hasDigits = sampleString.any { it.isDigit() }

Finding out if a string contains only digits:

val hasOnlyDigits = sampleString.all { it.isDigit() }

Extract digits from string:

val onlyNumberString = sampleString.filter { it.isDigit() }

plot a circle with pyplot

You need to add it to an axes. A Circle is a subclass of an Patch, and an axes has an add_patch method. (You can also use add_artist but it's not recommended.)

Here's an example of doing this:

import matplotlib.pyplot as plt

circle1 = plt.Circle((0, 0), 0.2, color='r')
circle2 = plt.Circle((0.5, 0.5), 0.2, color='blue')
circle3 = plt.Circle((1, 1), 0.2, color='g', clip_on=False)

fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot
# (or if you have an existing figure)
# fig = plt.gcf()
# ax = fig.gca()

ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)

fig.savefig('plotcircles.png')

This results in the following figure:

The first circle is at the origin, but by default clip_on is True, so the circle is clipped when ever it extends beyond the axes. The third (green) circle shows what happens when you don't clip the Artist. It extends beyond the axes (but not beyond the figure, ie the figure size is not automatically adjusted to plot all of your artists).

The units for x, y and radius correspond to data units by default. In this case, I didn't plot anything on my axes (fig.gca() returns the current axes), and since the limits have never been set, they defaults to an x and y range from 0 to 1.

Here's a continuation of the example, showing how units matter:

circle1 = plt.Circle((0, 0), 2, color='r')
# now make a circle with no fill, which is good for hi-lighting key results
circle2 = plt.Circle((5, 5), 0.5, color='b', fill=False)
circle3 = plt.Circle((10, 10), 2, color='g', clip_on=False)
    
ax = plt.gca()
ax.cla() # clear things for fresh plot

# change default range so that new circles will work
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
# some data
ax.plot(range(11), 'o', color='black')
# key data point that we are encircling
ax.plot((5), (5), 'o', color='y')
    
ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)
fig.savefig('plotcircles2.png')

which results in:

You can see how I set the fill of the 2nd circle to False, which is useful for encircling key results (like my yellow data point).

How to reset AUTO_INCREMENT in MySQL?

I googled and found this question, but the answer I am really looking for fulfils two criteria:

  1. using purely MySQL queries
  2. reset an existing table auto-increment to max(id) + 1

Since I couldn't find exactly what I want here, I have cobbled the answer from various answers and sharing it here.

Few things to note:

  1. the table in question is InnoDB
  2. the table uses the field id with type as int as primary key
  3. the only way to do this purely in MySQL is to use stored procedure
  4. my images below are using SequelPro as the GUI. You should be able to adapt it based on your preferred MySQL editor
  5. I have tested this on MySQL Ver 14.14 Distrib 5.5.61, for debian-linux-gnu

Step 1: Create Stored Procedure

create a stored procedure like this:

DELIMITER //
CREATE PROCEDURE reset_autoincrement(IN tablename varchar(200))
BEGIN

      SET @get_next_inc = CONCAT('SELECT @next_inc := max(id) + 1 FROM ',tablename,';');
      PREPARE stmt FROM @get_next_inc; 
      EXECUTE stmt; 
      SELECT @next_inc AS result;
      DEALLOCATE PREPARE stmt; 

      set @alter_statement = concat('ALTER TABLE ', tablename, ' AUTO_INCREMENT = ', @next_inc, ';');
      PREPARE stmt FROM @alter_statement;
      EXECUTE stmt;
      DEALLOCATE PREPARE stmt;
END //
DELIMITER ;

Then run it.

Before run, it looks like this when you look under Stored Procedures in your database.

enter image description here

When I run, I simply select the stored procedure and press Run Selection

enter image description here

Note: the delimiters part are crucial. Hence if you copy and paste from the top selected answers in this question, they tend not to work for this reason.

After I run, I should see the stored procedure

enter image description here

If you need to change the stored procedure, you need to delete the stored procedure, then select to run again.

Step 2: Call the stored procedure

This time you can simply use normal MySQL queries.

call reset_autoincrement('products');

Originally from my own SQL queries notes in https://simkimsia.com/library/sql-queries/#mysql-reset-autoinc and adapted for StackOverflow

Paste a multi-line Java String in Eclipse

The EclipsePasteAsJavaString plug-in allows you to insert text as a Java string by Ctrl + Shift + V

Example

Paste as usual via Ctrl+V:

some text with tabs and new lines

Paste as Java string via Ctrl+Shift+V

"some text\twith tabs\r\n" + "and new \r\n" + "lines"

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Another option is to get a ".pem" (public key) file for that particular server, and install it locally into the heart of your JRE's "cacerts" file (use the keytool helper application), then it will be able to download from that server without complaint, without compromising the entire SSL structure of your running JVM and enabling download from other unknown cert servers...

jQuery - Add active class and remove active from other element on click

Try this one:

$(document).ready(function() {
    $(".tab").click(function () {
        $("this").addClass("active").siblings().removeClass("active");   
    });
});

Send FormData with other field in AngularJS

Using $resource in AngularJS you can do:

task.service.js

$ngTask.factory("$taskService", [
    "$resource",
    function ($resource) {
        var taskModelUrl = 'api/task/';
        return {
            rest: {
                taskUpload: $resource(taskModelUrl, {
                    id: '@id'
                }, {
                    save: {
                        method: "POST",
                        isArray: false,
                        headers: {"Content-Type": undefined},
                        transformRequest: angular.identity
                    }
                })
            }
        };
    }
]);

And then use it in a module:

task.module.js

$ngModelTask.controller("taskController", [
    "$scope",
    "$taskService",
    function (
        $scope,
        $taskService,
    ) {
    $scope.saveTask = function (name, file) {
        var newTask,
            payload = new FormData();
        payload.append("name", name);
        payload.append("file", file);
        newTask = $taskService.rest.taskUpload.save(payload);
        // check if exists
    }
}

Use querystring variables in MVC controller

I had this problem while inheriting from ApiController instead of the regular Controller class. I solved it by using var container = Request.GetQueryNameValuePairs().ToLookup(x => x.Key, x => x.Value);

I followed this thread How to get Request Querystring values?

EDIT: After trying to filter through the container I was getting odd error messages. After going to my project properties and I unchecked the Optimize Code checkbox which changed so that all of a sudden the parameters in my controller where filled up from the url as I wanted.

Hopefully this will help someone with the same problem..

Log4net rolling daily filename with date in the file name

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
  <file value="logs\" />
  <datePattern value="dd.MM.yyyy'.log'" />
  <staticLogFileName value="false" />
  <appendToFile value="true" />
  <rollingStyle value="Composite" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="5MB" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  </layout>
</appender>

Detecting when user scrolls to bottom of div with jQuery

this worked for me though

$(window).scroll(function() {
  if ($(window).scrollTop() >= (($(document).height() - $(window).height()) - $('#divID').innerHeight())) {
    console.log('div reached');
  }
});

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

sudo apt-get install putty

This will automatically install the puttygen tool.

Now to convert the PPK file to be used with SSH command execute the following in terminal

puttygen mykey.ppk -O private-openssh -o my-openssh-key

Then, you can connect via SSH with:

ssh -v [email protected] -i my-openssh-key

http://www.graphicmist.in/use-your-putty-ppk-file-to-ssh-remote-server-in-ubuntu/#comment-28603

What is the benefit of zerofill in MySQL?

One example in order to understand, where the usage of ZEROFILL might be interesting:

In Germany, we have 5 digit zipcodes. However, those Codes may start with a Zero, so 80337 is a valid zipcode for munic, 01067 is a zipcode of Berlin.

As you see, any German citizen expects the zipcodes to be displayed as a 5 digit code, so 1067 looks strange.

In order to store those data, you could use a VARCHAR(5) or INT(5) ZEROFILL whereas the zerofilled integer has two big advantages:

  1. Lot lesser storage space on hard disk
  2. If you insert 1067, you still get 01067 back

Maybe this example helps understanding the use of ZEROFILL.

Add one year in current date PYTHON

You can use Python-dateutil's relativedelta to increment a datetime object while remaining sensitive to things like leap years and month lengths. Python-dateutil comes packaged with matplotlib if you already have that. You can do the following:

from dateutil.relativedelta import relativedelta

new_date = old_date + relativedelta(years=1)

(This answer was given by @Max to a similar question).

But if your date is a string (i.e. not already a datetime object) you can convert it using datetime:

from datetime import datetime
from dateutil.relativedelta import relativedelta

your_date_string = "April 1, 2012"
format_string = "%B %d, %Y"

datetime_object = datetime.strptime(your_date_string, format_string).date()
new_date = datetime_object + relativedelta(years=1)
new_date_string = datetime.strftime(new_date, format_string).replace(' 0', ' ')

new_date_string will contain "April 1, 2013".

NB: Unfortunately, datetime only outputs day values as "decimal numbers" - i.e. with leading zeros if they're single digit numbers. The .replace() at the end is a workaround to deal with this issue copied from @Alex Martelli (see this question for his and other approaches to this problem).

CSS media queries for screen sizes

For all smartphones and large screens use this format of media query

/* Smartphones (portrait and landscape) ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */

@media only screen and (min-width : 321px) {
/* Styles */
}



/* Smartphones (portrait) ----------- */

@media only screen and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}

/**********
iPad 3
**********/

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* Desktops and laptops ----------- */

@media only screen  and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* iPhone 5 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6 ----------- */

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6+ ----------- */

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S3 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

/* Samsung Galaxy S5 ----------- */

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

oracle.jdbc.driver.OracleDriver ClassNotFoundException

1.Right click on your java project.

2.Select "RUN AS".

3.Select "RUN CONFIGURATIOS...".

4.Here select your server at left side of the page and then u would see "CLASS PATH" tab at riht side,just click on it.

5.Here clilck on "USER ENTRIES" and select "ADD EXTERNAL JARS".

6.Select "ojdbc14.jar" file.

7.Click on Apply.

8.Click on Run.

9.Finally Restart your server then it would be execute.

Change the icon of the exe file generated from Visual Studio 2010

To specify an application icon

  1. In Solution Explorer, choose a project node (not the Solution node).
  2. On the menu bar, choose Project, Properties.
  3. When the Project Designer appears, choose the Application tab.
  4. In the Icon list, choose an icon (.ico) file.

To specify an application icon and add it to your project

  1. In Solution Explorer, choose a project node (not the Solution node).
  2. On the menu bar, choose Project, Properties.
  3. When the Project Designer appears, choose the Application tab.
  4. Near the Icon list, choose the button, and then browse to the location of the icon file that you want.

The icon file is added to your project as a content file.

reference : for details see here

Deserializing a JSON into a JavaScript object

I think this should help:

Also documentations also prove that you can use require() for json files: https://www.bennadel.com/blog/2908-you-can-use-require-to-load-json-javascript-object-notation-files-in-node-js.htm

var jsonfile = require("./path/to/jsonfile.json");
node = jsonfile.adjacencies.nodeTo;
node2 = jsonfile.adjacencies.nodeFrom;
node3 = jsonfile.adjacencies.data.$color;
//other things.

Using C++ base class constructors?

Yes, Since C++11:

struct B2 {
    B2(int = 13, int = 42);
};
struct D2 : B2 {
    using B2::B2;
// The set of inherited constructors is
// 1. B2(const B2&)
// 2. B2(B2&&)
// 3. B2(int = 13, int = 42)
// 4. B2(int = 13)
// 5. B2()

// D2 has the following constructors:
// 1. D2()
// 2. D2(const D2&)
// 3. D2(D2&&)
// 4. D2(int, int) <- inherited
// 5. D2(int) <- inherited
};

For additional information see http://en.cppreference.com/w/cpp/language/using_declaration

ASP.NET: Session.SessionID changes between requests

My issue was with a Microsoft MediaRoom IPTV application. It turns out that MPF MRML applications don't support cookies; changing to use cookieless sessions in the web.config solved my issue

<sessionState cookieless="true"  />

Here's a REALLY old article about it: Cookieless ASP.NET

Android Studio: Application Installation Failed

Some solutions:

1 Build -> Clean Project

2 Build -> Rebuild Project

3 Built -> Make Project

4 Remove your application from device and try install again

5 Mb you have some problems with actual version of yours app(try to pull actual branch). Also you can check on your emmulator, if yours app is running.

6 Try to use 1,2,3,4 solutions.

How to get a resource id with a known resource name?

in addition to @lonkly solution

  1. see reflections and field accessibility
  2. unnecessary variables

method:

/**
 * lookup a resource id by field name in static R.class 
 * 
 * @author - ceph3us
 * @param variableName - name of drawable, e.g R.drawable.<b>image</b>
 * @param ?            - class of resource, e.g R.drawable.class or R.raw.class
 * @return integer id of resource
 */
public static int getResId(String variableName, Class<?> ?)
                     throws android.content.res.Resources.NotFoundException {
    try {
        // lookup field in class 
        java.lang.reflect.Field field = ?.getField(variableName);
        // always set access when using reflections  
        // preventing IllegalAccessException   
        field.setAccessible(true);
        // we can use here also Field.get() and do a cast 
        // receiver reference is null as it's static field 
        return field.getInt(null);
    } catch (Exception e) {
        // rethrow as not found ex
        throw new Resources.NotFoundException(e.getMessage());
    }
}

How to copy a file to a remote server in Python using SCP or SSH?

Kind of hacky, but the following should work :)

import os
filePath = "/foo/bar/baz.py"
serverPath = "/blah/boo/boom.py"
os.system("scp "+filePath+" [email protected]:"+serverPath)

SQL update fields of one table from fields of another one

I have been working with IBM DB2 database for more then decade and now trying to learn PostgreSQL.

It works on PostgreSQL 9.3.4, but does not work on DB2 10.5:

UPDATE B SET
     COLUMN1 = A.COLUMN1,
     COLUMN2 = A.COLUMN2,
     COLUMN3 = A.COLUMN3
FROM A
WHERE A.ID = B.ID

Note: Main problem is FROM cause that is not supported in DB2 and also not in ANSI SQL.

It works on DB2 10.5, but does NOT work on PostgreSQL 9.3.4:

UPDATE B SET
    (COLUMN1, COLUMN2, COLUMN3) =
               (SELECT COLUMN1, COLUMN2, COLUMN3 FROM A WHERE ID = B.ID)

FINALLY! It works on both PostgreSQL 9.3.4 and DB2 10.5:

UPDATE B SET
     COLUMN1 = (SELECT COLUMN1 FROM A WHERE ID = B.ID),
     COLUMN2 = (SELECT COLUMN2 FROM A WHERE ID = B.ID),
     COLUMN3 = (SELECT COLUMN3 FROM A WHERE ID = B.ID)

How to find the last day of the month from date?

An other way using mktime and not date('t') :

$dateStart= date("Y-m-d", mktime(0, 0, 0, 10, 1, 2016)); //2016-10-01
$dateEnd = date("Y-m-d", mktime(0, 0, 0, 11, 0, 2016)); //This will return the last day of october, 2016-10-31 :)

So this way it calculates either if it is 31,30 or 29

Vertical align middle with Bootstrap responsive grid

Add !important rule to display: table of your .v-center class.

.v-center {
    display:table !important;
    border:2px solid gray;
    height:300px;
}

Your display property is being overridden by bootstrap to display: block.

Example

Regular expression for excluding special characters

I would just white list the characters.

^[a-zA-Z0-9äöüÄÖÜ]*$

Building a black list is equally simple with regex but you might need to add much more characters - there are a lot of Chinese symbols in unicode ... ;)

^[^<>%$]*$

The expression [^(many characters here)] just matches any character that is not listed.

How do I read a text file of about 2 GB?

There are quite number of tools available for viewing large files. http://download.cnet.com/Large-Text-File-Viewer/3000-2379_4-90541.html This for instance. However, I was successful with larger files viewing in Visual studio. Thought it took some time to load, it worked.

Can you explain the HttpURLConnection connection process?

On which point does HTTPURLConnection try to establish a connection to the given URL?

It's worth clarifying, there's the 'UrlConnection' instance and then there's the underlying Tcp/Ip/SSL socket connection, 2 different concepts. The 'UrlConnection' or 'HttpUrlConnection' instance is synonymous with a single HTTP page request, and is created when you call url.openConnection(). But if you do multiple url.openConnection()'s from the one 'url' instance then if you're lucky, they'll reuse the same Tcp/Ip socket and SSL handshaking stuff...which is good if you're doing lots of page requests to the same server, especially good if you're using SSL where the overhead of establishing the socket is very high.

See: HttpURLConnection implementation

Full width image with fixed height

<div id="container">
    <img style="width: 100%; height: 40%;" id="image" src="...">
</div>

I hope this will serve your purpose.

how to modify an existing check constraint?

NO, you can't do it other way than so.

Why does the jquery change event not trigger when I set the value of a select using val()?

As far as I can read in API's. The event is only fired when the user clicks on an option.

http://api.jquery.com/change/

For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

ALTER table - adding AUTOINCREMENT in MySQL

CREATE TABLE ALLITEMS(
    itemid INT(10)UNSIGNED,
    itemname VARCHAR(50)
);

ALTER TABLE ALLITEMS CHANGE itemid itemid INT(10)AUTO_INCREMENT PRIMARY KEY;

DESC ALLITEMS;

INSERT INTO ALLITEMS(itemname)
VALUES
    ('Apple'),
    ('Orange'),
    ('Banana');

SELECT
    *
FROM
    ALLITEMS;

I was confused with CHANGE and MODIFY keywords before too:

ALTER TABLE ALLITEMS CHANGE itemid itemid INT(10)AUTO_INCREMENT PRIMARY KEY;

ALTER TABLE ALLITEMS MODIFY itemid INT(5);

While we are there, also note that AUTO_INCREMENT can also start with a predefined number:

ALTER TABLE tbl AUTO_INCREMENT = 100;

iOS: present view controller programmatically

If you're using a storyboard, you probably shouldn't be using alloc and init to create a new view controller. Instead, look at your storyboard and find the segue that you want to perform; it should have a unique identifier (and if not, you can set one in the right sidebar).

Once you've found the identifier for that segue, send your current view controller a -performSegueWithIdentifier:sender message:

[self performSegueWithIdentifier:@"mySegueIdentifier" sender:self];

This will cause the storyboard to instantiate an AddTaskViewController and present it in the way that you've defined for that segue.


If, on the other hand, you're not using a storyboard at all, then you need to give your AddTaskViewController some kind of user interface. The most common way of doing so is to initialize the controller with a nib: instead of just calling init, you'll call -initWithNibName:bundle: and provide the name of a .xib file that contains your add-task UI:

AddTaskViewController *add = [[AddTaskViewController alloc]
                              initWithNibName:@"AddTaskView" bundle:nil];
[self presentViewController:add animated:YES completion:nil];

(There are other (less common) ways of getting a view associated with your new view controller, but this will probably present you the least trouble to get working.)

Shuffle DataFrame rows

TL;DR: np.random.shuffle(ndarray) can do the job.
So, in your case

np.random.shuffle(DataFrame.values)

DataFrame, under the hood, uses NumPy ndarray as data holder. (You can check from DataFrame source code)

So if you use np.random.shuffle(), it would shuffles the array along the first axis of a multi-dimensional array. But index of the DataFrame remains unshuffled.

Though, there are some points to consider.

  • function returns none. In case you want to keep a copy of the original object, you have to do so before you pass to the function.
  • sklearn.utils.shuffle(), as user tj89 suggested, can designate random_state along with another option to control output. You may want that for dev purpose.
  • sklearn.utils.shuffle() is faster. But WILL SHUFFLE the axis info(index, column) of the DataFrame along with the ndarray it contains.

Benchmark result

between sklearn.utils.shuffle() and np.random.shuffle().

ndarray

nd = sklearn.utils.shuffle(nd)

0.10793248389381915 sec. 8x faster

np.random.shuffle(nd)

0.8897626010002568 sec

DataFrame

df = sklearn.utils.shuffle(df)

0.3183923360193148 sec. 3x faster

np.random.shuffle(df.values)

0.9357550159329548 sec

Conclusion: If it is okay to axis info(index, column) to be shuffled along with ndarray, use sklearn.utils.shuffle(). Otherwise, use np.random.shuffle()

used code

import timeit
setup = '''
import numpy as np
import pandas as pd
import sklearn
nd = np.random.random((1000, 100))
df = pd.DataFrame(nd)
'''

timeit.timeit('nd = sklearn.utils.shuffle(nd)', setup=setup, number=1000)
timeit.timeit('np.random.shuffle(nd)', setup=setup, number=1000)
timeit.timeit('df = sklearn.utils.shuffle(df)', setup=setup, number=1000)
timeit.timeit('np.random.shuffle(df.values)', setup=setup, number=1000)

What do .c and .h file extensions mean to C?

The .c files are source files which will be compiled. The .h files are used to expose the API of a program to either other part of that program or other program is you are creating a library.

For example, the program PizzaDelivery could have 1 .c file with the main program, and 1 .c file with utility functions. Now, for the main part of the program to be able to use the utility functions, you need to expose the API, via function prototype, into a .h file, this .h file being included by the main .c file.

Curl error: Operation timed out

$curl = curl_init();

  curl_setopt_array($curl, array(
  CURLOPT_URL => "", // Server Path
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 3000, // increase this
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"email\":\"[email protected]\",\"password\":\"markus William\",\"username\":\"Daryl Brown\",\"mobile\":\"013132131112\","msg":"No more SSRIs." }",
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/json",
    "Postman-Token: 4867c7a3-2b3d-4e9a-9791-ed6dedb046b1",
    "cache-control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

initialize array index "CURLOPT_TIMEOUT" with a value in seconds according to time required for response .

Get GMT Time in Java

To get the time in millis at GMT all you need is

long millis = System.currentTimeMillis();

You can also do

long millis = new Date().getTime();

and

long millis = 
    Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis();

but these are inefficient ways of making the same call.

How to overlay density plots in R?

Adding base graphics version that takes care of y-axis limits, add colors and works for any number of columns:

If we have a data set:

myData <- data.frame(std.nromal=rnorm(1000, m=0, sd=1),
                     wide.normal=rnorm(1000, m=0, sd=2),
                     exponent=rexp(1000, rate=1),
                     uniform=runif(1000, min=-3, max=3)
                     )

Then to plot the densities:

dens <- apply(myData, 2, density)

plot(NA, xlim=range(sapply(dens, "[", "x")), ylim=range(sapply(dens, "[", "y")))
mapply(lines, dens, col=1:length(dens))

legend("topright", legend=names(dens), fill=1:length(dens))

Which gives:

enter image description here

What is the purpose of willSet and didSet in Swift?

NOTE

willSet and didSet observers are not called when a property is set in an initializer before delegation takes place

Check if URL has certain string with PHP

worked for me with php

if(strpos($_SERVER['REQUEST_URI'], 'shop.php') !== false){
echo 'url contains shop';
}

Git credential helper - update password

None of these answers ended up working for my Git credential issue. Here is what did work if anyone needs it (I'm using Git 1.9 on Windows 8.1).

To update your credentials, go to Control PanelCredential ManagerGeneric Credentials. Find the credentials related to your Git account and edit them to use the updated password.

Reference: How to update your Git credentials on Windows

Note that to use the Windows Credential Manager for Git you need to configure the credential helper like so:

git config --global credential.helper wincred

If you have multiple GitHub accounts that you use for different repositories, then you should configure credentials to use the full repository path (rather than just the domain, which is the default):

git config --global credential.useHttpPath true

Step-by-step debugging with IPython

What about ipdb.set_trace() ? In your code :

import ipdb; ipdb.set_trace()

update: now in Python 3.7, we can write breakpoint(). It works the same, but it also obeys to the PYTHONBREAKPOINT environment variable. This feature comes from this PEP.

This allows for full inspection of your code, and you have access to commands such as c (continue), n (execute next line), s (step into the method at point) and so on.

See the ipdb repo and a list of commands. IPython is now called (edit: part of) Jupyter.


ps: note that an ipdb command takes precedence over python code. So in order to write list(foo) you'd need print(list(foo)), or !list(foo) .

Also, if you like the ipython prompt (its emacs and vim modes, history, completions,…) it's easy to get the same for your project since it's based on the python prompt toolkit.

How to count the number of occurrences of a character in an Oracle varchar value?

SELECT {FN LENGTH('123-345-566')} - {FN LENGTH({FN REPLACE('123-345-566', '#', '')})} FROM DUAL

How can I zoom an HTML element in Firefox and Opera?

For me this works well with IE10, Chrome, Firefox and Safari:

   #MyDiv>*
   {
        zoom: 50%;
        -moz-transform: scale(0.5);
        -webkit-transform: scale(1.0);
   }

This zooms all content in to 50%.

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

I've tried both these and still get failure due to conflicts. At the end of my patience, I cloned master in another location, copied everything into the other branch and committed it. which let me continue. The "-X theirs" option should have done this for me, but it did not.

git merge -s recursive -X theirs master

error: 'merge' is not possible because you have unmerged files. hint: Fix them up in the work tree, hint: and then use 'git add/rm ' as hint: appropriate to mark resolution and make a commit, hint: or use 'git commit -a'. fatal: Exiting because of an unresolved conflict.

Why am I getting the error "connection refused" in Python? (Sockets)

I was being able to ping my connection but was STILL getting the 'connection refused' error. Turns out I was pinging myself! That's what the problem was.

How to redirect on another page and pass parameter in url from table?

Here is a general solution that doesn't rely on JQuery. Simply modify the definition of window.location.

<html>
   <head>
      <script>
         function loadNewDoc(){ 
            var loc = window.location;
            window.location = loc.hostname + loc.port + loc.pathname + loc.search; 
         };
      </script>
   </head>
   <body onLoad="loadNewDoc()">
   </body>  
</html>

Resource files not found from JUnit test cases

The test Resource files(src/test/resources) are loaded to target/test-classes sub folder. So we can use the below code to load the test resource files.

String resource = "sample.txt";
File file = new File(getClass().getClassLoader().getResource(resource).getFile());

System.out.println(file.getAbsolutePath());

Note : Here the sample.txt file should be placed under src/test/resources folder.

For more details refer options_to_load_test_resources

Getting all file names from a folder using C#

http://msdn.microsoft.com/en-us/library/system.io.directory.getfiles.aspx

The System.IO namespace has loads of methods to help you with file operations. The

Directory.GetFiles() 

method returns an array of strings which represent the files in the target directory.

Handling very large numbers in Python

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate. In Python 3.0+, the int type has been dropped completely.

That's just an implementation detail, though — as long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.

You can find all the gory details in PEP 0237.

When should I use the new keyword in C++?

Method 1 (using new)

  • Allocates memory for the object on the free store (This is frequently the same thing as the heap)
  • Requires you to explicitly delete your object later. (If you don't delete it, you could create a memory leak)
  • Memory stays allocated until you delete it. (i.e. you could return an object that you created using new)
  • The example in the question will leak memory unless the pointer is deleted; and it should always be deleted, regardless of which control path is taken, or if exceptions are thrown.

Method 2 (not using new)

  • Allocates memory for the object on the stack (where all local variables go) There is generally less memory available for the stack; if you allocate too many objects, you risk stack overflow.
  • You won't need to delete it later.
  • Memory is no longer allocated when it goes out of scope. (i.e. you shouldn't return a pointer to an object on the stack)

As far as which one to use; you choose the method that works best for you, given the above constraints.

Some easy cases:

  • If you don't want to worry about calling delete, (and the potential to cause memory leaks) you shouldn't use new.
  • If you'd like to return a pointer to your object from a function, you must use new

Is there a simple way to remove unused dependencies from a maven pom.xml?

You can use dependency:analyze -DignoreNonCompile

This will print a list of used undeclared and unused declared dependencies (while ignoring runtime/provided/test/system scopes for unused dependency analysis.)

** Be careful while using this, some libraries used at runtime are considered as unused **

For more details refer this link

Simple way to change the position of UIView?

UIView's also have a center property. If you just want to move the position rather than resize, you can just change that - eg:

aView.center = CGPointMake(50, 200);

Otherwise you would do it the way you posted.

Logical operators ("and", "or") in DOS batch

Try the negation operand - 'not'!

Well, if you can perform 'AND' operation on an if statement using nested 'if's (refer previous answers), then you can do the same thing with 'if not' to perform an 'or' operation.

If you haven't got the idea quite as yet, read on. Otherwise, just don't waste your time and get back to programming.

Just as nested 'if's are satisfied only when all conditions are true, nested 'if not's are satisfied only when all conditions are false. This is similar to what you want to do with an 'or' operand, isn't it?

Even when any one of the conditions in the nested 'if not' is true, the whole statement remains non-satisfied. Hence, you can use negated 'if's in succession by remembering that the body of the condition statement should be what you wanna do if all your nested conditions are false. The body that you actually wanted to give should come under the else statement.

And if you still didn't get the jist of the thing, sorry, I'm 16 and that's the best I can do to explain.

How can I maintain fragment state when added to the back stack?

Here, since onSaveInstanceState in fragment does not call when you add fragment into backstack. The fragment lifecycle in backstack when restored start onCreateView and end onDestroyView while onSaveInstanceState is called between onDestroyView and onDestroy. My solution is create instance variable and init in onCreate. Sample code:

private boolean isDataLoading = true;
private ArrayList<String> listData;
public void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     isDataLoading = false;
     // init list at once when create fragment
     listData = new ArrayList();
}

And check it in onActivityCreated:

public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if(isDataLoading){
         fetchData();
    }else{
         //get saved instance variable listData()
    }
}

private void fetchData(){
     // do fetch data into listData
}

return error message with actionResult

IN your view insert

@Html.ValidationMessage("Error")

then in the controller after you use new in your model

var model = new yourmodel();
try{
[...]
}catch(Exception ex){
ModelState.AddModelError("Error", ex.Message);
return View(model);
}

React Js conditionally applying class attributes

2019:

React is lake a lot of utilities. But you don't need any npm package for that . just create somewhere the function classnames and call it when you need;

function classnames(obj){
  return Object.entries(obj).filter( e => e[1] ).map( e=>e[0] ).join(' ');
}

or

function classnames(obj){
 return Object.entries(obj).map( ([k,v]) => v?k:'' ).join(' ');
}

example

  stateClass= {
    foo:true,
    bar:false,
    pony:2
  }
  classnames(stateClass) // return 'foo pony'


 <div className="foo bar {classnames(stateClass)}"> some content </div>

Just For Inspiration

declare helper element and used it toggle method

(DOMToken?List)classList.toggle(class,condition)

example:

const classes = document.createElement('span').classList; 

function classstate(obj){
  for( let n in obj) classes.toggle(n,obj[n]);
 return classes; 
}

Set icon for Android application

In AndroidManifest change these :

android:icon="@drawable/icon_name"
android:roundIcon="@drawable/icon_name"

How to create an object property from a variable value in JavaScript?

You cannot use a variable to access a property via dot notation, instead use the array notation.

var obj= {
     'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'

How to change link color (Bootstrap)

You can use .text-reset class to reset the color from default blue to anything you want. Hopefully this is helpful.

Source: https://getbootstrap.com/docs/4.5/utilities/text/#reset-color

Bootstrap 3 Multi-column within a single ul not floating properly

you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]

http://www.bootply.com/118886

css

.even{background: red; color:white;}
.odd{background: darkred; color:white;}

html

<div class="container">
  <ul class="list-unstyled">
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
  </ul>
</div>

Which command do I use to generate the build of a Vue app?

in your terminal

npm run build

and you host the dist folder. for more see this video

How do you change library location in R?

I've used this successfully inside R script:

library("reshape2",lib.loc="/path/to/R-packages/")

useful if for whatever reason libraries are in more than one place.

How to calculate probability in a normal distribution given mean & standard deviation?

You can just use the error function that's built in to the math library, as stated on their website.

Alter table add multiple columns ms sql

Take out the parentheses and the curly braces, neither are required when adding columns.

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

No, you should run mysql -u root -p in bash, not at the MySQL command-line. If you are in mysql, you can exit by typing exit.

Unsupported operation :not writeable python

You open the variable "file" as a read only then attempt to write to it:

file = open('ValidEmails.txt','r')

Instead, use the 'w' flag.

file = open('ValidEmails.txt','w')
...
file.write(email)

Pass Multiple Parameters to jQuery ajax call

Don't use string concatenation to pass parameters, just use a data hash:

$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',
    contentType: 'application/json; charset=utf-8',
    data: { jewellerId: filter, locale: 'en-US' },
    dataType: 'json',
    success: AjaxSucceeded,
    error: AjaxFailed
});

UPDATE:

As suggested by @Alex in the comments section, an ASP.NET PageMethod expects parameters to be JSON encoded in the request, so JSON.stringify should be applied on the data hash:

$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ jewellerId: filter, locale: 'en-US' }),
    dataType: 'json',
    success: AjaxSucceeded,
    error: AjaxFailed
});

How to change a <select> value from JavaScript

 <script language="javascript" type="text/javascript">
        function selectFunction() {
             var printStr = document.getElementById("select").options[0].value
            alert(printStr);
            document.getElementById("select").selectedIndex = 0;
        }
    </script>

List an Array of Strings in alphabetical order

 public static String[] textSort(String[] words) {
    for (int i = 0; i < words.length; i++) {
        for (int j = i + 1; j < words.length; j++) {
            if (words[i].compareTo(words[j]) > 0) {
                String temp = words[i];
                words[i] = words[j];
                words[j] = temp;
            }
        }
    }

    return words;
}

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Download Microsoft Drivers for PHP for SQL Server. Extract the files and use one of:

File                             Thread Safe         VC Bulid
php_sqlsrv_53_nts_vc6.dll           No                  VC6
php_sqlsrv_53_nts_vc9.dll           No                  VC9
php_sqlsrv_53_ts_vc6.dll            Yes                 VC6
php_sqlsrv_53_ts_vc9.dll            Yes                 VC9

You can see the Thread Safety status in phpinfo().

Add the correct file to your ext directory and the following line to your php.ini:

extension=php_sqlsrv_53_*_vc*.dll

Use the filename of the file you used.

As Gordon already posted this is the new Extension from Microsoft and uses the sqlsrv_* API instead of mssql_*

Update:
On Linux you do not have the requisite drivers and neither the SQLSERV Extension.
Look at Connect to MS SQL Server from PHP on Linux? for a discussion on this.

In short you need to install FreeTDS and YES you need to use mssql_* functions on linux. see update 2

To simplify things in the long run I would recommend creating a wrapper class with requisite functions which use the appropriate API (sqlsrv_* or mssql_*) based on which extension is loaded.

Update 2: You do not need to use mssql_* functions on linux. You can connect to an ms sql server using PDO + ODBC + FreeTDS. On windows, the best performing method to connect is via PDO + ODBC + SQL Native Client since the PDO + SQLSRV driver can be incredibly slow.

How to log Apache CXF Soap Request and Soap Response using Log4j?

Another easy way is to set the logger like this- ensure that you do it before you load the cxf web service related classes. You can use it in some static blocks.

YourClientConstructor() {

  LogUtils.setLoggerClass(org.apache.cxf.common.logging.Log4jLogger.class);

  URL wsdlURL = YOurURL;//

  //create the service
  YourService = new YourService(wsdlURL, SERVICE_NAME);
  port = yourService.getServicePort(); 

  Client client = ClientProxy.getClient(port);
  client.getInInterceptors().add(new LoggingInInterceptor());
  client.getOutInterceptors().add(new LoggingOutInterceptor());
}

Then the inbound and outbound messages will be printed to Log4j file instead of the console. Make sure your log4j is configured properly

Execute PowerShell Script from C# with Commandline Arguments

Here is a way to add Parameters to the script if you used

pipeline.Commands.AddScript(Script);

This is with using an HashMap as paramaters the key being the name of the variable in the script and the value is the value of the variable.

pipeline.Commands.AddScript(script));
FillVariables(pipeline, scriptParameter);
Collection<PSObject> results = pipeline.Invoke();

And the fill variable method is:

private static void FillVariables(Pipeline pipeline, Hashtable scriptParameters)
{
  // Add additional variables to PowerShell
  if (scriptParameters != null)
  {
    foreach (DictionaryEntry entry in scriptParameters)
    {
      CommandParameter Param = new CommandParameter(entry.Key as String, entry.Value);
      pipeline.Commands[0].Parameters.Add(Param);
    }
  }
}

this way you can easily add multiple parameters to a script. I've also noticed that if you want to get a value from a variable in you script like so:

Object resultcollection = runspace.SessionStateProxy.GetVariable("results");

//results being the name of the v

you'll have to do it the way I showed because for some reason if you do it the way Kosi2801 suggests the script variables list doesn't get filled with your own variables.

How can I remove an entry in global configuration with git config?

You can edit the ~/.gitconfig file in your home folder. This is where all --global settings are saved.

Using routes in Express-js

Seems that only index.js get loaded when you require("./routes") . I used the following code in index.js to load the rest of the routes:

var fs = require('fs')
  , path = require('path');

fs.readdirSync(__dirname).forEach(function(file){
  var route_fname = __dirname + '/' + file;
  var route_name = path.basename(route_fname, '.js');
  if(route_name !== 'index' && route_name[0] !== "."){ 
    exports[route_name] = require(route_fname)[route_name];
  }
});

Set a persistent environment variable from cmd.exe

The MSDN documentation for environment variables tells you what to do:

To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.

You will of course need admin rights to do this. I know of no way to broadcast a windows message from Windows batch so you'll need to write a small program to do this.

Use sudo with password as parameter

echo -e "YOURPASSWORD\n" | sudo -S yourcommand

Overlaying a DIV On Top Of HTML 5 Video

Here's an example that will center the content within the parent div. This also makes sure the overlay starts at the edge of the video, even when centered.

<div class="outer-container">
    <div class="inner-container">
        <div class="video-overlay">Bug Buck Bunny - Trailer</div>
        <video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" controls autoplay loop></video>
    </div>
</div>

with css as

.outer-container {
    border: 1px dotted black;
    width: 100%;
    height: 100%;
    text-align: center;
}
.inner-container {
    border: 1px solid black;
    display: inline-block;
    position: relative;
}
.video-overlay {
    position: absolute;
    left: 0px;
    top: 0px;
    margin: 10px;
    padding: 5px 5px;
    font-size: 20px;
    font-family: Helvetica;
    color: #FFF;
    background-color: rgba(50, 50, 50, 0.3);
}
video {
    width: 100%;
    height: 100%;
}

here's the jsfiddle https://jsfiddle.net/dyrepk2x/2/

Hope that helps :)

Pandas - replacing column values

Can try this too!
Create a dictionary of replacement values.

import pandas as pd
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

enter image description here

replace_dict= {0:'Female',1:'Male'}
print(replace_dict)

enter image description here

Use the map function for replacing values

data['sex']=data['sex'].map(replace_dict)

Output after replacing
enter image description here

Convert SVG to image (JPEG, PNG, etc.) in the browser

Svg to png can be converted depending on conditions:

  1. If svg is in format SVG (string) paths:
  • create canvas
  • create new Path2D() and set svg as parameter
  • draw path on canvas
  • create image and use canvas.toDataURL() as src.

example:

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let svgText = 'M10 10 h 80 v 80 h -80 Z';
let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
ctx.stroke(p);
let url = canvas.toDataURL();
const img = new Image();
img.src = url;

Note that Path2D not supported in ie and partially supported in edge. Polyfill solves that: https://github.com/nilzona/path2d-polyfill

  1. Create svg blob and draw on canvas using .drawImage():
  • make canvas element
  • make a svgBlob object from the svg xml
  • make a url object from domUrl.createObjectURL(svgBlob);
  • create an Image object and assign url to image src
  • draw image into canvas
  • get png data string from canvas: canvas.toDataURL();

Nice description: https://web.archive.org/web/20200125162931/http://ramblings.mcpher.com:80/Home/excelquirks/gassnips/svgtopng

Note that in ie you will get exception on stage of canvas.toDataURL(); It is because IE has too high security restriction and treats canvas as readonly after drawing image there. All other browsers restrict only if image is cross origin.

  1. Use canvg JavaScript library. It is separate library but has useful functions.

Like:

ctx.drawSvg(rawSvg);
var dataURL = canvas.toDataURL();

Text on image mouseover?

And if you come from even further in the future you can use the title property on div tags now to provide tooltips:

<div title="Tooltip text">Hover over me</div>

Let's just hope you're not using a browser from the past.

_x000D_
_x000D_
<div title="Tooltip text">Hover over me</div>
_x000D_
_x000D_
_x000D_

Linq select to new object

This is a great article for syntax needed to create new objects from a LINQ query.

But, if the assignments to fill in the fields of the object are anything more than simple assignments, for example, parsing strings to integers, and one of them fails, it is not possible to debug this. You can not create a breakpoint on any of the individual assignments.

And if you move all the assignments to a subroutine, and return a new object from there, and attempt to set a breakpoint in that routine, you can set a breakpoint in that routine, but the breakpoint will never be triggered.

So instead of:

var query2 = from c in doc.Descendants("SuggestionItem")
                select new SuggestionItem
                       { Phrase = c.Element("Phrase").Value
                         Blocked = bool.Parse(c.Element("Blocked").Value),
                         SeenCount = int.Parse(c.Element("SeenCount").Value)
                       };

Or

var query2 = from c in doc.Descendants("SuggestionItem")
                         select new SuggestionItem(c);

I instead did this:

List<SuggestionItem> retList = new List<SuggestionItem>();

var query = from c in doc.Descendants("SuggestionItem") select c;

foreach (XElement item in query)
{
    SuggestionItem anItem = new SuggestionItem(item);
    retList.Add(anItem);
}

This allowed me to easily debug and figure out which assignment was failing. In this case, the XElement was missing a field I was parsing for to set in the SuggestionItem.

I ran into these gotchas with Visual Studio 2017 while writing unit tests for a new library routine.

Proper use of mutexes in Python

You have to unlock your Mutex at sometime...

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

TL;DR

.col-X-Y means on screen size X and up, stretch this element to fill Y columns.

Bootstrap provides a grid of 12 columns per .row, so Y=3 means width=25%.

xs, sm, md, lg are the sizes for smartphone, tablet, laptop, desktop respectively.

The point of specifying different widths on different screen sizes is to let you make things larger on smaller screens.

Example

<div class="col-lg-6 col-xs-12">

Meaning: 50% width on Desktops, 100% width on Mobile, Tablet, and Laptop.

How do I return multiple values from a function?

I prefer:

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

It seems everything else is just extra code to do the same thing.

Java regex capturing groups indexes

Capturing and grouping

Capturing group (pattern) creates a group that has capturing property.

A related one that you might often see (and use) is (?:pattern), which creates a group without capturing property, hence named non-capturing group.

A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$ (^, then 0*1 or 1*0, then $) versus ^0*1|1*0$ (^0*1 or 1*0$).

A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern). Using your example, (.*):, .* matches ABC and : matches :, and since .* is inside capturing group (.*), the text ABC is recorded for the capturing group 1.

Group number

The whole pattern is defined to be group number 0.

Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:

(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
|     |                       |          | |      |      ||       |     |
1-----1                       |          | 4------4      |5-------5     |
                              |          3---------------3              |
                              2-----------------------------------------2

The group numbers are used in back-reference \n in pattern and $n in replacement string.

In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.

You can access the text matched by certain group with Matcher.group(int group). The group numbers can be identified with the rule stated above.

In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.

Group name

From Java 7, you can define a named capturing group (?<name>pattern), and you can access the content matched with Matcher.group(String name). The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.

The group names are used in back-reference \k<name> in pattern and ${name} in replacement string.

Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group).

Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.

Add resources, config files to your jar using gradle

By default any files you add to src/main/resources will be included in the jar.

If you need to change that behavior for whatever reason, you can do so by configuring sourceSets.

This part of the documentation has all the details

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

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

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

How to run shell script file using nodejs?

you can go:

var cp = require('child_process');

and then:

cp.exec('./myScript.sh', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a command in your $SHELL.
Or go

cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a file WITHOUT a shell.
Or go

cp.execFile();

which is the same as cp.exec() but doesn't look in the $PATH.

You can also go

cp.fork('myJS.js', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a javascript file with node.js, but in a child process (for big programs).

EDIT

You might also have to access stdin and stdout with event listeners. e.g.:

var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
  // handle stdout as `data`
});

How can I INSERT data into two tables simultaneously in SQL Server?

BEGIN TRANSACTION;

DECLARE @tblMapping table(sourceid int, destid int)

INSERT INTO [table1] ([data]) 
OUTPUT source.id, new.id
Select [data] from [external_table] source;

INSERT INTO [table2] ([table1_id], [data])
Select map.destid, source.[more data] 
from [external_table] source
    inner join @tblMapping map on source.id=map.sourceid;

COMMIT TRANSACTION;

unsigned int vs. size_t

Type size_t must be big enough to store the size of any possible object. Unsigned int doesn't have to satisfy that condition.

For example in 64 bit systems int and unsigned int may be 32 bit wide, but size_t must be big enough to store numbers bigger than 4G

Measuring code execution time

You can use this Stopwatch wrapper:

public class Benchmark : IDisposable 
{
    private readonly Stopwatch timer = new Stopwatch();
    private readonly string benchmarkName;

    public Benchmark(string benchmarkName)
    {
        this.benchmarkName = benchmarkName;
        timer.Start();
    }

    public void Dispose() 
    {
        timer.Stop();
        Console.WriteLine($"{benchmarkName} {timer.Elapsed}");
    }
}

Usage:

using (var bench = new Benchmark($"Insert {n} records:"))
{
    ... your code here
}

Output:

Insert 10 records: 00:00:00.0617594

For advanced scenarios, you can use BenchmarkDotNet or Benchmark.It or NBench

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Note that there's a weird problem if you're using Bootstrap's JS buttons and the 'loading' state. I don't know why this happens, but here's how to fix it.

Say you have a button and you set it to the loading state:

var myButton = $('#myBootstrapButton');
myButton.button('loading');

Now you want to take it out of the loading state, but also disable it (e.g. the button was a Save button, the loading state indicated an ongoing validation and the validation failed). This looks like reasonable Bootstrap JS:

myButton.button('reset').prop('disabled', true); // DOES NOT WORK

Unfortunately, that will reset the button, but not disable it. Apparently, button() performs some delayed task. So you'll also have to postpone your disabling:

myButton.button('reset');
setTimeout(function() { myButton.prop('disabled', true); }, 0);

A bit annoying, but it's a pattern I'm using a lot.

The Android emulator is not starting, showing "invalid command-line parameter"

emulator-arm.exe error, couldn't run. Problem was that my laptop has 2 graphic cards and was selected only one (the performance one) from Nvidia 555M. By selecting the other graphic card from Nvidia mediu,(selected base Intel card) the emulator started!

Find and replace with sed in directory and sub directories

I think we can do this with one line simple command

for i in `grep -rl eth0 . 2> /dev/null`; do sed -i ‘s/eth0/eth1/’ $i; done

Refer to this page.

PHP combine two associative arrays into one array

I stumbled upon this question trying to identify a clean way to join two assoc arrays.

I was trying to join two different tables that didn't have relationships to each other.

This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge() +1 to him.

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM ".databaseTbl_Residential_Prospects."";
        $ResidentialData = $pdo->prepare($sql);
        $ResidentialData->execute(array($lapi));
        $ResidentialProspects = $ResidentialData->fetchAll(PDO::FETCH_ASSOC);

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM ".databaseTbl_Commercial_Prospects."";
        $CommercialData = $pdo->prepare($sql);
        $CommercialData->execute(array($lapi));
        $CommercialProspects = $CommercialData->fetchAll(PDO::FETCH_ASSOC);

        $Prospects = array_merge($ResidentialProspects,$CommercialProspects);
        echo '<pre>';
        var_dump($Prospects);
        echo '</pre>';

Maybe this will help someone else out.

SQL query to make all data in a column UPPER CASE?

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

UPDATE MyTable
SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

How to make a Bootstrap accordion collapse when clicking the header div?

Actually my panel had this collapse state arrow icon and I tried other answers in this post , but icon position changed, so here is the solution with collapse state arrow icon.

Add this Custom CSS

 .panel-heading 
  {
   cursor: pointer;
   padding: 0;
  }

 a.accordion-toggle 
 {
  display: block;
  padding: 10px  15px;
 }

Credit's goes to this post answerer.

Hope helps.

How to send a simple email from a Windows batch file?

It works for me, by using double quotes around variables.

I am using batch script to call powershell Send-MailMessage

Batch Script:send_email.bat

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  -command 'E:\path\send_email.ps1

Pwershell Script send_email.ps1

Send-MailMessage -From "noreply@$env:computername" -To '<[email protected]>' -Subject 'Blah Blah' -SmtpServer  'smtp.domain.com'  -Attachments 'E:\path\file.log' -BODY "Blah Blah on Host: $env:computername "

Autonumber value of last inserted row - MS Access / VBA

This is an adaptation from my code for you. I was inspired from developpez.com (Look in the page for : "Pour insérer des données, vaut-il mieux passer par un RecordSet ou par une requête de type INSERT ?"). They explain (with a little French). This way is much faster than the one upper. In the example, this way was 37 times faster. Try it.

Const tableName As String = "InvoiceNumbers"
Const columnIdName As String = "??"
Const columnDateName As String = "date"

Dim rsTable As DAO.recordSet
Dim recordId as long

Set rsTable = CurrentDb.OpenRecordset(tableName)
Call rsTable .AddNew
recordId = CLng(rsTable (columnIdName)) ' Save your Id in a variable
rsTable (columnDateName) = Now()        ' Store your data
rsTable .Update

recordSet.Close

LeCygne

Remove json element

I recommend splice method to remove an object from JSON objects array.

jQuery(json).each(function (index){
        if(json[index].FirstName == "Test1"){
            json.splice(index,1); // This will remove the object that first name equals to Test1
            return false; // This will stop the execution of jQuery each loop.
        }
});

I use this because when I use delete method, I get null object after I do JSON.stringify(json)

How can I get a list of locally installed Python modules?

Since pip version 1.3, you've got access to:

pip list

Which seems to be syntactic sugar for "pip freeze". It will list all of the modules particular to your installation or virtualenv, along with their version numbers. Unfortunately it does not display the current version number of any module, nor does it wash your dishes or shine your shoes.

git replace local version with remote version

This is the safest solution:

git stash

Now you can do whatever you want without fear of conflicts.

For instance:

git checkout origin/master

If you want to include the remote changes in the master branch you can do:

git reset --hard origin/master

This will make you branch "master" to point to "origin/master".

How to subtract/add days from/to a date?

Just subtract a number:

> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"

Since the Date class only has days, you can just do basic arithmetic on it.

If you want to use POSIXlt for some reason, then you can use it's slots:

> a <- as.POSIXlt("2009-10-04")
> names(unclass(as.POSIXlt("2009-10-04")))
[1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"
> a$mday <- a$mday - 6
> a
[1] "2009-09-28 EDT"

postgres: upgrade a user to be a superuser?

ALTER USER myuser WITH SUPERUSER;

You can read more at the Documentation

How to check if a string contains an element from a list in Python

Use a generator together with any, which short-circuits on the first True:

if any(ext in url_string for ext in extensionsToCheck):
    print(url_string)

EDIT: I see this answer has been accepted by OP. Though my solution may be "good enough" solution to his particular problem, and is a good general way to check if any strings in a list are found in another string, keep in mind that this is all that this solution does. It does not care WHERE the string is found e.g. in the ending of the string. If this is important, as is often the case with urls, you should look to the answer of @Wladimir Palant, or you risk getting false positives.

Download File Using Javascript/jQuery

I'm surprised not a lot of people know about the download attribute for a elements. Please help spread the word about it! You can have a hidden html link, and fake a click on it. If the html link has the download attribute it downloads the file, not views it, no matter what. Here's the code. It will download a cat picture if it can find it.

_x000D_
_x000D_
document.getElementById('download').click();
_x000D_
<a href="https://docs.google.com/uc?id=0B0jH18Lft7ypSmRjdWg1c082Y2M" download id="download" hidden></a>
_x000D_
_x000D_
_x000D_

Note: This is not supported on all browsers: http://www.w3schools.com/tags/att_a_download.asp

PHP append one array to another (not array_push or +)

Since PHP 7.4 you can use the ... operator. This is also known as the splat operator in other languages, including Ruby.

$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);

Output

array(5) {
    [0]=>
    string(6) "banana"
    [1]=>
    string(6) "orange"
    [2]=>
    string(5) "apple"
    [3]=>
    string(4) "pear"
    [4]=>
    string(10) "watermelon"
}

Splat operator should have better performance than array_merge. That’s not only because the splat operator is a language structure while array_merge is a function, but also because compile time optimization can be performant for constant arrays.

Moreover, we can use the splat operator syntax everywhere in the array, as normal elements can be added before or after the splat operator.

$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$arr3 = [...$arr1, ...$arr2];
$arr4 = [...$arr1, ...$arr3, 7, 8, 9];

Comparing two integer arrays in Java

None of the existing answers involve using a comparator, and therefore cannot be used in binary trees or for sorting. So I'm just gonna leave this here:

public static int compareIntArrays(int[] a, int[] b) {
    if (a == null) {
        return b == null ? 0 : -1;
    }
    if (b == null) {
        return 1;
    }
    int cmp = a.length - b.length;
    if (cmp != 0) {
        return cmp;
    }
    for (int i = 0; i < a.length; i++) {
        cmp = Integer.compare(a[i], b[i]);
        if (cmp != 0) {
            return cmp;
        }
    }
    return 0;
}

How to insert a value that contains an apostrophe (single quote)?

The apostrophe character can be inserted by calling the CHAR function with the apostrophe's ASCII table lookup value, 39. The string values can then be concatenated together with a concatenate operator.

Insert into Person
  (First, Last)
Values
  'Joe',
  concat('O',char(39),'Brien')

How to display alt text for an image in chrome

You can use the title attribute.

<img height="90" width="90"
src="http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif"
alt="Google Images" title="Google Images" />

How to convert a Map to List in Java?

If you want to ensure the values in the resultant List<Value> are in the key-ordering of the input Map<Key, Value>, you need to "go via" SortedMap somehow.

Either start with a concrete SortedMap implementation (Such as TreeMap) or insert your input Map into a SortedMap before converting that to List. e.g.:

Map<Key,Value> map;
List<Value> list = new ArrayList<Value>( new TreeMap<Key Value>( map ));

Otherwise you'll get whatever native ordering the Map implementation provides, which can often be something other than the natural key ordering (Try Hashtable or ConcurrentHashMap, for variety).

react button onClick redirect page

I was trying to find a way with Redirect but failed. Redirecting onClick is simpler than we think. Just place the following basic JavaScript within your onClick function, no monkey business:

window.location.href="pagelink"