Programs & Examples On #Spring el

The Spring Expression Language (SpEL for short) is a powerful expression language that supports querying and manipulating an object graph at runtime. The language syntax is similar to Unified EL but offers additional features, most notably method invocation and basic string templating functionality.

Thymeleaf using path variables to th:href

Your code looks syntactically correct, but I think your property doesn't exist to create the URL.

I just tested it, and it works fine for me.

Try using category.idCategory instead of category.id, for example…

  <tr th:each="category : ${categories}">
    <td th:text="${category.idCategory}"></td>
    <td th:text="${category.name}"></td>
    <td>
      <a th:href="@{'/category/edit/' + ${category.idCategory}}">view</a>
    </td>
  </tr>

Concatenate multiple node values in xpath

for $d in $doc/element2/element3 return fn:string-join(fn:data($d/element()), ".").
$doc stores the Xml.

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents

In my case when I browsed to site5.com I got the following error.

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.

Most likely causes: A default document is not configured for the requested URL, and directory browsing is not enabled on the server.

And then when I browsed to

site5.com/home/index

I was met with

HTTP Error 404.0 - Not Found The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

Most likely causes: The directory or file specified does not exist on the Web server. The URL contains a typographical error. A custom filter or module, such as URLScan, restricts access to the file.

All that I did is installed the feature in IIS ASP.NET 4.8 as shown below.

enter image description here

Reading PDF documents in .Net

iTextSharp is the best bet. Used it to make a spider for lucene.Net so that it could crawl PDF.

using System;
using System.IO;
using iTextSharp.text.pdf;
using System.Text.RegularExpressions;

namespace Spider.Utils
{
    /// <summary>
    /// Parses a PDF file and extracts the text from it.
    /// </summary>
    public class PDFParser
    {
        /// BT = Beginning of a text object operator 
        /// ET = End of a text object operator
        /// Td move to the start of next line
        ///  5 Ts = superscript
        /// -5 Ts = subscript

        #region Fields

        #region _numberOfCharsToKeep
        /// <summary>
        /// The number of characters to keep, when extracting text.
        /// </summary>
        private static int _numberOfCharsToKeep = 15;
        #endregion

        #endregion

        #region ExtractText
        /// <summary>
        /// Extracts a text from a PDF file.
        /// </summary>
        /// <param name="inFileName">the full path to the pdf file.</param>
        /// <param name="outFileName">the output file name.</param>
        /// <returns>the extracted text</returns>
        public bool ExtractText(string inFileName, string outFileName)
        {
            StreamWriter outFile = null;
            try
            {
                // Create a reader for the given PDF file
                PdfReader reader = new PdfReader(inFileName);
                //outFile = File.CreateText(outFileName);
                outFile = new StreamWriter(outFileName, false, System.Text.Encoding.UTF8);

                Console.Write("Processing: ");

                int totalLen = 68;
                float charUnit = ((float)totalLen) / (float)reader.NumberOfPages;
                int totalWritten = 0;
                float curUnit = 0;

                for (int page = 1; page <= reader.NumberOfPages; page++)
                {
                    outFile.Write(ExtractTextFromPDFBytes(reader.GetPageContent(page)) + " ");

                    // Write the progress.
                    if (charUnit >= 1.0f)
                    {
                        for (int i = 0; i < (int)charUnit; i++)
                        {
                            Console.Write("#");
                            totalWritten++;
                        }
                    }
                    else
                    {
                        curUnit += charUnit;
                        if (curUnit >= 1.0f)
                        {
                            for (int i = 0; i < (int)curUnit; i++)
                            {
                                Console.Write("#");
                                totalWritten++;
                            }
                            curUnit = 0;
                        }

                    }
                }

                if (totalWritten < totalLen)
                {
                    for (int i = 0; i < (totalLen - totalWritten); i++)
                    {
                        Console.Write("#");
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (outFile != null) outFile.Close();
            }
        }
        #endregion

        #region ExtractTextFromPDFBytes
        /// <summary>
        /// This method processes an uncompressed Adobe (text) object 
        /// and extracts text.
        /// </summary>
        /// <param name="input">uncompressed</param>
        /// <returns></returns>
        public string ExtractTextFromPDFBytes(byte[] input)
        {
            if (input == null || input.Length == 0) return "";

            try
            {
                string resultString = "";

                // Flag showing if we are we currently inside a text object
                bool inTextObject = false;

                // Flag showing if the next character is literal 
                // e.g. '\\' to get a '\' character or '\(' to get '('
                bool nextLiteral = false;

                // () Bracket nesting level. Text appears inside ()
                int bracketDepth = 0;

                // Keep previous chars to get extract numbers etc.:
                char[] previousCharacters = new char[_numberOfCharsToKeep];
                for (int j = 0; j < _numberOfCharsToKeep; j++) previousCharacters[j] = ' ';


                for (int i = 0; i < input.Length; i++)
                {
                    char c = (char)input[i];
                    if (input[i] == 213)
                        c = "'".ToCharArray()[0];

                    if (inTextObject)
                    {
                        // Position the text
                        if (bracketDepth == 0)
                        {
                            if (CheckToken(new string[] { "TD", "Td" }, previousCharacters))
                            {
                                resultString += "\n\r";
                            }
                            else
                            {
                                if (CheckToken(new string[] { "'", "T*", "\"" }, previousCharacters))
                                {
                                    resultString += "\n";
                                }
                                else
                                {
                                    if (CheckToken(new string[] { "Tj" }, previousCharacters))
                                    {
                                        resultString += " ";
                                    }
                                }
                            }
                        }

                        // End of a text object, also go to a new line.
                        if (bracketDepth == 0 &&
                            CheckToken(new string[] { "ET" }, previousCharacters))
                        {

                            inTextObject = false;
                            resultString += " ";
                        }
                        else
                        {
                            // Start outputting text
                            if ((c == '(') && (bracketDepth == 0) && (!nextLiteral))
                            {
                                bracketDepth = 1;
                            }
                            else
                            {
                                // Stop outputting text
                                if ((c == ')') && (bracketDepth == 1) && (!nextLiteral))
                                {
                                    bracketDepth = 0;
                                }
                                else
                                {
                                    // Just a normal text character:
                                    if (bracketDepth == 1)
                                    {
                                        // Only print out next character no matter what. 
                                        // Do not interpret.
                                        if (c == '\\' && !nextLiteral)
                                        {
                                            resultString += c.ToString();
                                            nextLiteral = true;
                                        }
                                        else
                                        {
                                            if (((c >= ' ') && (c <= '~')) ||
                                                ((c >= 128) && (c < 255)))
                                            {
                                                resultString += c.ToString();
                                            }

                                            nextLiteral = false;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Store the recent characters for 
                    // when we have to go back for a checking
                    for (int j = 0; j < _numberOfCharsToKeep - 1; j++)
                    {
                        previousCharacters[j] = previousCharacters[j + 1];
                    }
                    previousCharacters[_numberOfCharsToKeep - 1] = c;

                    // Start of a text object
                    if (!inTextObject && CheckToken(new string[] { "BT" }, previousCharacters))
                    {
                        inTextObject = true;
                    }
                }

                return CleanupContent(resultString);
            }
            catch
            {
                return "";
            }
        }

        private string CleanupContent(string text)
        {
            string[] patterns = { @"\\\(", @"\\\)", @"\\226", @"\\222", @"\\223", @"\\224", @"\\340", @"\\342", @"\\344", @"\\300", @"\\302", @"\\304", @"\\351", @"\\350", @"\\352", @"\\353", @"\\311", @"\\310", @"\\312", @"\\313", @"\\362", @"\\364", @"\\366", @"\\322", @"\\324", @"\\326", @"\\354", @"\\356", @"\\357", @"\\314", @"\\316", @"\\317", @"\\347", @"\\307", @"\\371", @"\\373", @"\\374", @"\\331", @"\\333", @"\\334", @"\\256", @"\\231", @"\\253", @"\\273", @"\\251", @"\\221"};
            string[] replace = {   "(",     ")",      "-",     "'",      "\"",      "\"",    "à",      "â",      "ä",      "À",      "Â",      "Ä",      "é",      "è",      "ê",      "ë",      "É",      "È",      "Ê",      "Ë",      "ò",      "ô",      "ö",      "Ò",      "Ô",      "Ö",      "ì",      "î",      "ï",      "Ì",      "Î",      "Ï",      "ç",      "Ç",      "ù",      "û",      "ü",      "Ù",      "Û",      "Ü",      "®",      "™",      "«",      "»",      "©",      "'" };

            for (int i = 0; i < patterns.Length; i++)
            {
                string regExPattern = patterns[i];
                Regex regex = new Regex(regExPattern, RegexOptions.IgnoreCase);
                text = regex.Replace(text, replace[i]);
            }

            return text;
        }

        #endregion

        #region CheckToken
        /// <summary>
        /// Check if a certain 2 character token just came along (e.g. BT)
        /// </summary>
        /// <param name="tokens">the searched token</param>
        /// <param name="recent">the recent character array</param>
        /// <returns></returns>
        private bool CheckToken(string[] tokens, char[] recent)
        {
            foreach (string token in tokens)
            {
                if ((recent[_numberOfCharsToKeep - 3] == token[0]) &&
                    (recent[_numberOfCharsToKeep - 2] == token[1]) &&
                    ((recent[_numberOfCharsToKeep - 1] == ' ') ||
                    (recent[_numberOfCharsToKeep - 1] == 0x0d) ||
                    (recent[_numberOfCharsToKeep - 1] == 0x0a)) &&
                    ((recent[_numberOfCharsToKeep - 4] == ' ') ||
                    (recent[_numberOfCharsToKeep - 4] == 0x0d) ||
                    (recent[_numberOfCharsToKeep - 4] == 0x0a))
                    )
                {
                    return true;
                }
            }
            return false;
        }
        #endregion
    }
}

What's the simplest way to extend a numpy array in 2 dimensions?

A useful alternative answer to the first question, using the examples from tomeedee’s answer, would be to use numpy’s vstack and column_stack methods:

Given a matrix p,

>>> import numpy as np
>>> p = np.array([ [1,2] , [3,4] ])

an augmented matrix can be generated by:

>>> p = np.vstack( [ p , [5 , 6] ] )
>>> p = np.column_stack( [ p , [ 7 , 8 , 9 ] ] )
>>> p
array([[1, 2, 7],
       [3, 4, 8],
       [5, 6, 9]])

These methods may be convenient in practice than np.append() as they allow 1D arrays to be appended to a matrix without any modification, in contrast to the following scenario:

>>> p = np.array([ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ] )
>>> p = np.append( p , [ 7 , 8 , 9 ] , 1 )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/dist-packages/numpy/lib/function_base.py", line 3234, in append
    return concatenate((arr, values), axis=axis)
ValueError: arrays must have same number of dimensions

In answer to the second question, a nice way to remove rows and columns is to use logical array indexing as follows:

Given a matrix p,

>>> p = np.arange( 20 ).reshape( ( 4 , 5 ) )

suppose we want to remove row 1 and column 2:

>>> r , c = 1 , 2
>>> p = p [ np.arange( p.shape[0] ) != r , : ] 
>>> p = p [ : , np.arange( p.shape[1] ) != c ]
>>> p
array([[ 0,  1,  3,  4],
       [10, 11, 13, 14],
       [15, 16, 18, 19]])

Note - for reformed Matlab users - if you wanted to do these in a one-liner you need to index twice:

>>> p = np.arange( 20 ).reshape( ( 4 , 5 ) )    
>>> p = p [ np.arange( p.shape[0] ) != r , : ] [ : , np.arange( p.shape[1] ) != c ]

This technique can also be extended to remove sets of rows and columns, so if we wanted to remove rows 0 & 2 and columns 1, 2 & 3 we could use numpy's setdiff1d function to generate the desired logical index:

>>> p = np.arange( 20 ).reshape( ( 4 , 5 ) )
>>> r = [ 0 , 2 ]
>>> c = [ 1 , 2 , 3 ]
>>> p = p [ np.setdiff1d( np.arange( p.shape[0] ), r ) , : ] 
>>> p = p [ : , np.setdiff1d( np.arange( p.shape[1] ) , c ) ]
>>> p
array([[ 5,  9],
       [15, 19]])

C# find highest array value and index

Just another perspective using DataTable. Declare a DataTable with 2 columns called index and val. Add an AutoIncrement option and both AutoIncrementSeed and AutoIncrementStep values 1 to the index column. Then use a foreach loop and insert each array item into the datatable as a row. Then by using Select method, select the row having the maximum value.

Code

int[] anArray = { 1, 5, 2, 7 };
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("index"), new DataColumn("val")});
dt.Columns["index"].AutoIncrement = true;
dt.Columns["index"].AutoIncrementSeed = 1;
dt.Columns["index"].AutoIncrementStep = 1;
foreach(int i in anArray)
    dt.Rows.Add(null, i);

DataRow[] dr = dt.Select("[val] = MAX([val])");
Console.WriteLine("Max Value = {0}, Index = {1}", dr[0][1], dr[0][0]);

Output

Max Value = 7, Index = 4

Find a demo here

How to use onResume()?

Re-review the Android Activity Lifecycle reference. There is a nice picture, and the table showing what methods get called. reference Link google

https://developer.android.com/reference/android/app/Activity.html

Closing a Userform with Unload Me doesn't work

As specified by the top answer, I used the following in the code behind the button control.

Private Sub btnClose_Click()
    Unload Me
End Sub

In doing so, it will not attempt to unload a control, but rather will unload the user form where the button control resides. The "Me" keyword refers to the user form object even when called from a control on the user form. If you are getting errors with this technique, there are a couple of possible reasons.

  1. You could be entering the code in the wrong place (such as a separate module)

  2. You might be using an older version of Office. I'm using Office 2013. I've noticed that VBA changes over time.

From my experience, the use of the the DoCmd.... method is more specific to the macro features in MS Access, but not commonly used in Excel VBA.

Under normal (out of the box) conditions, the code above should work just fine.

How do you dynamically allocate a matrix?

I have this grid class that can be used as a simple matrix if you don't need any mathematical operators.

/**
 * Represents a grid of values.
 * Indices are zero-based.
 */
template<class T>
class GenericGrid
{
    public:
        GenericGrid(size_t numRows, size_t numColumns);

        GenericGrid(size_t numRows, size_t numColumns, const T & inInitialValue);

        const T & get(size_t row, size_t col) const;

        T & get(size_t row, size_t col);

        void set(size_t row, size_t col, const T & inT);

        size_t numRows() const;

        size_t numColumns() const;

    private:
        size_t mNumRows;
        size_t mNumColumns;
        std::vector<T> mData;
};


template<class T>
GenericGrid<T>::GenericGrid(size_t numRows, size_t numColumns):
    mNumRows(numRows),
    mNumColumns(numColumns)
{
    mData.resize(numRows*numColumns);
}


template<class T>
GenericGrid<T>::GenericGrid(size_t numRows, size_t numColumns, const T & inInitialValue):
    mNumRows(numRows),
    mNumColumns(numColumns)
{
    mData.resize(numRows*numColumns, inInitialValue);
}


template<class T>
const T & GenericGrid<T>::get(size_t rowIdx, size_t colIdx) const
{
    return mData[rowIdx*mNumColumns + colIdx];
}


template<class T>
T & GenericGrid<T>::get(size_t rowIdx, size_t colIdx)
{
    return mData[rowIdx*mNumColumns + colIdx];
}


template<class T>
void GenericGrid<T>::set(size_t rowIdx, size_t colIdx, const T & inT)
{
    mData[rowIdx*mNumColumns + colIdx] = inT;
}


template<class T>
size_t GenericGrid<T>::numRows() const
{
    return mNumRows;
}


template<class T>
size_t GenericGrid<T>::numColumns() const
{
    return mNumColumns;
}

sqlite database default time value 'now'

i believe you can use

CREATE TABLE test (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  t TIMESTAMP
  DEFAULT CURRENT_TIMESTAMP
);

as of version 3.1 (source)

Typescript ReferenceError: exports is not defined

Simply add libraryTarget: 'umd', like so

const webpackConfig = {
  output: {
    libraryTarget: 'umd' // Fix: "Uncaught ReferenceError: exports is not defined".
  }
};

module.exports = webpackConfig; // Export all custom Webpack configs.

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

You can trigger a file input element by sending it a Javascript click event, e.g.

<input type="file" ... id="file-input">

$("#file-input").click();

You could put this in a click event handler for the image, for instance, then hide the file input with CSS. It'll still work even if it's invisible.

Once you've got that part working, you can set a change event handler on the input element to see when the user puts a file into it. This event handler can create a temporary "blob" URL for the image by using window.URL.createObjectURL, e.g.:

var file = document.getElementById("file-input").files[0];
var blob_url = window.URL.createObjectURL(file);

That URL can be set as the src for an image on the page. (It only works on that page, though. Don't try to save it anywhere.)

Note that not all browsers currently support camera capture. (In fact, most desktop browsers don't.) Make sure your interface still makes sense if the user gets asked to pick a file.

Mockito: List Matchers with generics

In addition to anyListOf above, you can always specify generics explicitly using this syntax:

when(mock.process(Matchers.<List<Bar>>any(List.class)));

Java 8 newly allows type inference based on parameters, so if you're using Java 8, this may work as well:

when(mock.process(Matchers.any()));

Remember that neither any() nor anyList() will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class) was changed to mean "any instanceof Foo", but any() still means "any value including null".

NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers. Older versions of Mockito will need to keep using org.mockito.Matchers as above.

Converting a sentence string to a string array of words in Java

Use string.replace(".", "").replace(",", "").replace("?", "").replace("!","").split(' ') to split your code into an array with no periods, commas, question marks, or exclamation marks. You can add/remove as many replace calls as you want.

Insert multiple rows with one query MySQL

If you would like to insert multiple values lets say from multiple inputs that have different post values but the same table to insert into then simply use:

mysql_query("INSERT INTO `table` (a,b,c,d,e,f,g) VALUES 
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g')")
or die (mysql_error()); // Inserts 3 times in 3 different rows

How to copy text from a div to clipboard

<div id='myInputF2'> YES ITS DIV TEXT TO COPY  </div>

<script>

    function myFunctionF2()  {
        str = document.getElementById('myInputF2').innerHTML;
        const el = document.createElement('textarea');
        el.value = str;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        alert('Copied the text:' + el.value);
    };
</script>

more info: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

How to get tf.exe (TFS command line client)?

The tf.exe command line is included in the VSTS agent package in folder externals\vstsom.

Adding system header search path to Xcode

To use quotes just for completeness.

"/Users/my/work/a project with space"/**

If not recursive, remove the /**

ldap query for group members

Active Directory does not store the group membership on user objects. It only stores the Member list on the group. The tools show the group membership on user objects by doing queries for it.

How about:

(&(objectClass=group)(member=cn=my,ou=full,dc=domain))

(You forgot the (& ) bit in your example in the question as well).

UILabel with text of two different colors

Here you go

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:lblTemp.text];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
lblTemp.attributedText = string;

Importing variables from another file?

Best to import x1 and x2 explicitly:

from file1 import x1, x2

This allows you to avoid unnecessary namespace conflicts with variables and functions from file1 while working in file2.

But if you really want, you can import all the variables:

from file1 import * 

syntax error: unexpected token <

This error can also arise from a JSON AJAX call to a PHP script that has an error in its code. Servers are often set up to return PHP error information formatted with html markup. This response is interpreted as invalid JSON, resulting in the "unexpected token <" AJAX error.

To view the PHP error using Chrome, go to the Network panel in the web inspector, click the PHP file listed on the left side, and click on the Response tab.

Update query with PDO and MySQL

Your update syntax is incorrect. Please check Update Syntax for the correct syntax.

$sql = "UPDATE `access_users` set `contact_first_name` = :firstname,  `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

  • If you want to find the webapp folder, it may be over here:

/var/lib/tomcat7/webapps/

  • But you also can type this to find it:

find / -name 'tomcat_version' -type d

How to remove all numbers from string?

Use some regex like [0-9] or \d:

$words = preg_replace('/\d+/', '', $words );

You might want to read the preg_replace() documentation as this is directly shown there.

CSS file not refreshing in browser

A good way to force your CSS to reload is to:

<link href='styles.css?version=1' rel='stylesheet'></link>

And then just increment the version number as you change your CSS. The browser will then obey. I believe StackOverflow uses this technique.

How to get current html page title with javascript

Like this :

jQuery(document).ready(function () {
    var title = jQuery(this).attr('title');
});

works for IE, Firefox and Chrome.

HTML form with side by side input fields

For the sake of bandwidth saving, we shouldn't include <div> for each of <label> and <input> pair

This solution may serve you better and may increase readability

<div class="form">
            <label for="product_name">Name</label>
            <input id="product_name" name="product[name]" size="30" type="text" value="4">
            <label for="product_stock">Stock</label>
            <input id="product_stock" name="product[stock]" size="30" type="text" value="-1">
            <label for="price_amount">Amount</label>
            <input id="price_amount" name="price[amount]" size="30" type="text" value="6.0">
</div>

The css for above form would be

.form > label
{
  float: left;
  clear: right;
}

.form > input
{
  float: right;
}

I believe the output would be as following:

Demo

Save file to specific folder with curl command

curl doesn't have an option to that (without also specifying the filename), but wget does. The directory can be relative or absolute. Also, the directory will automatically be created if it doesn't exist.

wget -P relative/dir "$url"

wget -P /absolute/dir "$url"

Android Studio update -Error:Could not run build action using Gradle distribution

I have run into a similar problem on Mac.

Looking at the log under Help -> Show logs in Finder I found the following entry.

You have JVM property "https.proxyHost" set to "127.0.0.1".
This may lead to incorrect behaviour. Proxy should be set in Settings | HTTP Proxy
This JVM property is old and its usage is not recommended by Oracle.
(Note: It could have been assigned by some code dynamically.)

and it turned out I had Charles as a network proxy running. Shutting down Charles solved the problem.

Flutter - The method was called on null

You have a CryptoListPresenter _presenter but you are never initializing it. You should either be doing that when you declare it or in your initState() (or another appropriate but called-before-you-need-it method).

One thing I find that helps is that if I know a member is functionally 'final', to actually set it to final as that way the analyzer complains that it hasn't been initialized.

EDIT:

I see diegoveloper beat me to answering this, and that the OP asked a follow up.

@Jake - it's hard for us to tell without knowing exactly what CryptoListPresenter is, but depending on what exactly CryptoListPresenter actually is, generally you'd do final CryptoListPresenter _presenter = new CryptoListPresenter(...);, or

CryptoListPresenter _presenter;

@override
void initState() {
  _presenter = new CryptoListPresenter(...);
}

How to generate graphs and charts from mysql database in php

I use highcharts. They are very interactive (and very fancy I might add). You do have to get a little creative to access data from MySQL database, but if you have a general understanding of JavaScript and PHP, you should have no problems.

How to get back to most recent version in Git?

This did the trick for me (I still was on the master branch):

git reset --hard origin/master

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

Short answer (asked version): (format 3.33.20150710.182906)

Please, simple use a makefile with:

MAJOR = 3
MINOR = 33
BUILD = $(shell date +"%Y%m%d.%H%M%S")
VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
CPPFLAGS = -DVERSION=$(VERSION)

program.x : source.c
       gcc $(CPPFLAGS) source.c -o program.x

and if you don't want a makefile, shorter yet, just compile with:

gcc source.c -o program.x -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"

Short answer (suggested version): (format 150710.182906)

Use a double for version number:

MakeFile:

VERSION = $(shell date +"%g%m%d.%H%M%S")
CPPFLAGS = -DVERSION=$(VERSION)
program.x : source.c
      gcc $(CPPFLAGS) source.c -o program.x

Or a simple bash command:

$ gcc source.c -o program.x -DVERSION=$(date +"%g%m%d.%H%M%S")

Tip: Still don't like makefile or is it just for a not-so-small test program? Add this line:

 export CPPFLAGS='-DVERSION='$(date +"%g%m%d.%H%M%S")

to your ~/.profile, and remember compile with gcc $CPPFLAGS ...


Long answer:

I know this question is older, but I have a small contribution to make. Best practice is always automatize what otherwise can became a source of error (or oblivion).

I was used to a function that created the version number for me. But I prefer this function to return a float. My version number can be printed by: printf("%13.6f\n", version()); which issues something like: 150710.150411 (being Year (2 digits) month day DOT hour minute seconds).

But, well, the question is yours. If you prefer "major.minor.date.time", it will have to be a string. (Trust me, double is better. If you insist in a major, you can still use double if you set the major and let the decimals to be date+time, like: major.datetime = 1.150710150411

Lets get to business. The example bellow will work if you compile as usual, forgetting to set it, or use -DVERSION to set the version directly from shell, but better of all, I recommend the third option: use a makefile.


Three forms of compiling and the results:

Using make:

beco> make program.x
gcc -Wall -Wextra -g -O0 -ansi -pedantic-errors -c -DVERSION="\"3.33.20150710.045829\"" program.c -o program.o
gcc  program.o -o program.x

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:29'
VERSION: '3.33.20150710.045829'

Using -DVERSION:

beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:37'
VERSION: '2.22.20150710.045837'

Using the build-in function:

beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:43'
VERSION(): '1.11.20150710.045843'

Source code

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 
  5 #define FUNC_VERSION (0)
  6 #ifndef VERSION
  7   #define MAJOR 1
  8   #define MINOR 11
  9   #define VERSION version()
 10   #undef FUNC_VERSION
 11   #define FUNC_VERSION (1)
 12   char sversion[]="9999.9999.20150710.045535";
 13 #endif
 14 
 15 #if(FUNC_VERSION)
 16 char *version(void);
 17 #endif
 18 
 19 int main(void)
 20 {
 21 
 22   printf("__DATE__: '%s'\n", __DATE__);
 23   printf("__TIME__: '%s'\n", __TIME__);
 24 
 25   printf("VERSION%s: '%s'\n", (FUNC_VERSION?"()":""), VERSION);
 26   return 0;
 27 }
 28 
 29 /* String format: */
 30 /* __DATE__="Oct  8 2013" */
 31 /*  __TIME__="00:13:39" */
 32
 33 /* Version Function: returns the version string */
 34 #if(FUNC_VERSION)
 35 char *version(void)
 36 {
 37   const char data[]=__DATE__;
 38   const char tempo[]=__TIME__;
 39   const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
 40   char omes[4];
 41   int ano, mes, dia, hora, min, seg;
 42 
 43   if(strcmp(sversion,"9999.9999.20150710.045535"))
 44     return sversion;
 45 
 46   if(strlen(data)!=11||strlen(tempo)!=8)
 47     return NULL;
 48 
 49   sscanf(data, "%s %d %d", omes, &dia, &ano);
 50   sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
 51   mes=(strstr(nomes, omes)-nomes)/3+1;
 52   sprintf(sversion,"%d.%d.%04d%02d%02d.%02d%02d%02d", MAJOR, MINOR, ano, mes, dia, hora, min, seg);
 53 
 54   return sversion;
 55 }
 56 #endif

Please note that the string is limited by MAJOR<=9999 and MINOR<=9999. Of course, I set this high value that will hopefully never overflow. But using double is still better (plus, it's completely automatic, no need to set MAJOR and MINOR by hand).

Now, the program above is a bit too much. Better is to remove the function completely, and guarantee that the macro VERSION is defined, either by -DVERSION directly into GCC command line (or an alias that automatically add it so you can't forget), or the recommended solution, to include this process into a makefile.

Here it is the makefile I use:


MakeFile source:

  1   MAJOR = 3
  2   MINOR = 33
  3   BUILD = $(shell date +"%Y%m%d.%H%M%S")
  4   VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
  5   CC = gcc
  6   CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors
  7   CPPFLAGS = -DVERSION=$(VERSION)
  8   LDLIBS =
  9   
 10    %.x : %.c
 11          $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@

A better version with DOUBLE

Now that I presented you "your" preferred solution, here it is my solution:

Compile with (a) makefile or (b) gcc directly:

(a) MakeFile:

   VERSION = $(shell date +"%g%m%d.%H%M%S")
   CC = gcc
   CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors 
   CPPFLAGS = -DVERSION=$(VERSION)
   LDLIBS =
   %.x : %.c
         $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@

(b) Or a simple bash command:

 $ gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=$(date +"%g%m%d.%H%M%S")

Source code (double version):

#ifndef VERSION
  #define VERSION version()
#endif

double version(void);

int main(void)
{
  printf("VERSION%s: '%13.6f'\n", (FUNC_VERSION?"()":""), VERSION);
  return 0;
}

double version(void)
{
  const char data[]=__DATE__;
  const char tempo[]=__TIME__;
  const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  char omes[4];
  int ano, mes, dia, hora, min, seg;
  char sversion[]="130910.001339";
  double fv;

  if(strlen(data)!=11||strlen(tempo)!=8)
    return -1.0;

  sscanf(data, "%s %d %d", omes, &dia, &ano);
  sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
  mes=(strstr(nomes, omes)-nomes)/3+1;
  sprintf(sversion,"%04d%02d%02d.%02d%02d%02d", ano, mes, dia, hora, min, seg);
  fv=atof(sversion);

  return fv;
}

Note: this double function is there only in case you forget to define macro VERSION. If you use a makefile or set an alias gcc gcc -DVERSION=$(date +"%g%m%d.%H%M%S"), you can safely delete this function completely.


Well, that's it. A very neat and easy way to setup your version control and never worry about it again!

How do you make a LinearLayout scrollable?

 <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <---------Content Here --------------->
            </LinearLayout>
       </ScrollView>
    </LinearLayout>

Which concurrent Queue implementation should I use in Java?

ConcurrentLinkedQueue means no locks are taken (i.e. no synchronized(this) or Lock.lock calls). It will use a CAS - Compare and Swap operation during modifications to see if the head/tail node is still the same as when it started. If so, the operation succeeds. If the head/tail node is different, it will spin around and try again.

LinkedBlockingQueue will take a lock before any modification. So your offer calls would block until they get the lock. You can use the offer overload that takes a TimeUnit to say you are only willing to wait X amount of time before abandoning the add (usually good for message type queues where the message is stale after X number of milliseconds).

Fairness means that the Lock implementation will keep the threads ordered. Meaning if Thread A enters and then Thread B enters, Thread A will get the lock first. With no fairness, it is undefined really what happens. It will most likely be the next thread that gets scheduled.

As for which one to use, it depends. I tend to use ConcurrentLinkedQueue because the time it takes my producers to get work to put onto the queue is diverse. I don't have a lot of producers producing at the exact same moment. But the consumer side is more complicated because poll won't go into a nice sleep state. You have to handle that yourself.

Get current language in CultureInfo

To get the 2 chars ISO 639-1 language identifier use:

System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

Decode JSON with unknown structure

You really just need a single struct, and as mentioned in the comments the correct annotations on the field will yield the desired results. JSON is not some extremely variant data format, it is well defined and any piece of json, no matter how complicated and confusing it might be to you can be represented fairly easily and with 100% accuracy both by a schema and in objects in Go and most other OO programming languages. Here's an example;

package main

import (
    "fmt"
    "encoding/json"
)

type Data struct {
    Votes *Votes `json:"votes"`
    Count string `json:"count,omitempty"`
}

type Votes struct {
    OptionA string `json:"option_A"`
}

func main() {
    s := `{ "votes": { "option_A": "3" } }`
    data := &Data{
        Votes: &Votes{},
    }
    err := json.Unmarshal([]byte(s), data)
    fmt.Println(err)
    fmt.Println(data.Votes)
    s2, _ := json.Marshal(data)
    fmt.Println(string(s2))
    data.Count = "2"
    s3, _ := json.Marshal(data)
    fmt.Println(string(s3))
}

https://play.golang.org/p/ScuxESTW5i

Based on your most recent comment you could address that by using an interface{} to represent data besides the count, making the count a string and having the rest of the blob shoved into the interface{} which will accept essentially anything. That being said, Go is a statically typed language with a fairly strict type system and to reiterate, your comments stating 'it can be anything' are not true. JSON cannot be anything. For any piece of JSON there is schema and a single schema can define many many variations of JSON. I advise you take the time to understand the structure of your data rather than hacking something together under the notion that it cannot be defined when it absolutely can and is probably quite easy for someone who knows what they're doing.

Change background color of iframe issue

Put the Iframe between aside tags

<aside style="background-color:#FFF"> your IFRAME </aside>

Best way to track onchange as-you-type in input type="text"?

Use oninput instead of onchange.

index.html

<html>
  <head>
    <title>title here</title>
    <script src="index.js"></script>
  </head>
  <body>
    <input oninput="onclickhandler(this)"></input>
  </body>
</html>

script.js

function onclickhandler(e) {
  console.log(e.value);
}

How to Read and Write from the Serial Port

SerialPort (RS-232 Serial COM Port) in C# .NET
This article explains how to use the SerialPort class in .NET to read and write data, determine what serial ports are available on your machine, and how to send files. It even covers the pin assignments on the port itself.

Example Code:

using System;
using System.IO.Ports;
using System.Windows.Forms;

namespace SerialPortExample
{
  class SerialPortProgram
  {
    // Create the serial port with basic settings
    private SerialPort port = new SerialPort("COM1",
      9600, Parity.None, 8, StopBits.One);

    [STAThread]
    static void Main(string[] args)
    { 
      // Instatiate this class
      new SerialPortProgram();
    }

    private SerialPortProgram()
    {
      Console.WriteLine("Incoming Data:");

      // Attach a method to be called when there
      // is data waiting in the port's buffer
      port.DataReceived += new 
        SerialDataReceivedEventHandler(port_DataReceived);

      // Begin communications
      port.Open();

      // Enter an application loop to keep this thread alive
      Application.Run();
    }

    private void port_DataReceived(object sender,
      SerialDataReceivedEventArgs e)
    {
      // Show all the incoming data in the port's buffer
      Console.WriteLine(port.ReadExisting());
    }
  }
}

Structs data type in php?

A public class is one option, if you want something more encapsulated you can use an abstract/anonymous class combination. My favorite part is that autocomplete still works (for PhpStorm) for this but I don't have a public class sitting around.

<?php

final class MyParentClass
{
    /**
     * @return MyStruct[]
     */
    public function getData(): array
    {
        return array(
            $this->createMyObject("One", 1.0, new DateTime("now")),
            $this->createMyObject("Two", 2.0, new DateTime("tommorow"))
        );
    }

    private function createMyObject(string $description, float $magnitude, DateTime $timeStamp): MyStruct
    {
        return new class(func_get_args()) extends MyStruct {
            protected function __construct(array $args)
            {
                $this->description = $args[0];
                $this->magnitude = $args[1];
                $this->timeStamp = $args[2];
            }
        };
    }
}

abstract class MyStruct
{
    public string $description;
    public float $magnitude;
    public DateTime $timeStamp;
}

Java creating .jar file

Put all the 6 classes to 6 different projects. Then create jar files of all the 6 projects. In this manner you will get 6 executable jar files.

When to use LinkedList over ArrayList in Java?

In addition to the other good arguments above, you should notice ArrayList implements RandomAccess interface, while LinkedList implements Queue.

So, somehow they address slightly different problems, with difference of efficiency and behavior (see their list of methods).

How to get the selected row values of DevExpress XtraGrid?

Which one of their Grids are you using? XtraGrid or AspXGrid? Here is a piece taken from one of my app using XtraGrid.

private void grdContactsView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
    _selectedContact = GetSelectedRow((DevExpress.XtraGrid.Views.Grid.GridView)sender);
}

private Contact GetSelectedRow(DevExpress.XtraGrid.Views.Grid.GridView view)
{
    return (Contact)view.GetRow(view.FocusedRowHandle);
}

My Grid have a list of Contact objects bound to it. Every time a row is clicked I load the selected row into _selectedContact. Hope this helps. You will find lots of information on using their controls buy visiting their support and documentation sites.

Is it possible to start a shell session in a running container (without ssh)

Keep an eye on this pull request: https://github.com/docker/docker/pull/7409

Which implements the forthcoming docker exec <container_id> <command> utility. When this is available it should be possible to e.g. start and stop the ssh service inside a running container.

There is also nsinit to do this: "nsinit provides a handy way to access a shell inside a running container's namespace", but it looks difficult to get running. https://gist.github.com/ubergarm/ed42ebbea293350c30a6

Is Python interpreted, or compiled, or both?

According to the official Python site, it's interpreted.

https://www.python.org/doc/essays/blurb/

Python is an interpreted, object-oriented, high-level programming language...

...

Since there is no compilation step ...

...

The Python interpreter and the extensive standard library are available...

...

Instead, when the interpreter discovers an error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack trace.

How do I set Java's min and max heap size through environment variables?

A couple of notes:

  1. Apache ant doesn't know anything about JAVA_OPTS, while Tomcat's startup scripts do. For Apache ant, use ANT_OPTS to affect the environment for the JVM that runs /ant/, but not for the things that ant might launch.

  2. The maximum heap size you can set depends entirely on the environment: for most 32-bit systems, the maximum amount of heap space you can request, regardless of available memory, is in the 2GiB range. The largest heap on a 64-bit system is "really big". Also, you are practically limited by physical memory as well, since the heap is managed by the JVM and you don't want a lot of swapping going on to the disk.

  3. For server environments, you typically want to set -Xms and -Xmx to the same value: this will fix the size of the heap at a certain size and the garbage collector has less work to do because the heap will never have to be re-sized.

How to prevent form from submitting multiple times from client side?

You can try safeform jquery plugin.

$('#example').safeform({
    timeout: 5000, // disable form on 5 sec. after submit
    submit: function(event) {
        // put here validation and ajax stuff...

        // no need to wait for timeout, re-enable the form ASAP
        $(this).safeform('complete');
        return false;
    }
})

Can I create a One-Time-Use Function in a Script or Stored Procedure?

Common Table Expressions let you define what are essentially views that last only within the scope of your select, insert, update and delete statements. Depending on what you need to do they can be terribly useful.

How to change the text on the action bar

The easiest way is to call this.setTitle("...") if you are in the activity. And if you are in a fragment, just call getActivity().setTitle("...");

This way will let you change the title anytime, no need to call it before setContentView(R.layout.activity_test);

How can I convert a string to boolean in JavaScript?

Wood-eye be careful. After seeing the consequences after applying the top answer with 500+ upvotes, I feel obligated to post something that is actually useful:

Let's start with the shortest, but very strict way:

var str = "true";
var mybool = JSON.parse(str);

And end with a proper, more tolerant way:

var parseBool = function(str) 
{
    // console.log(typeof str);
    // strict: JSON.parse(str)
    
    if(str == null)
        return false;
    
    if (typeof str === 'boolean')
    {
        return (str === true);
    } 
    
    if(typeof str === 'string')
    {
        if(str == "")
            return false;
            
        str = str.replace(/^\s+|\s+$/g, '');
        if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
            return true;
        
        str = str.replace(/,/g, '.');
        str = str.replace(/^\s*\-\s*/g, '-');
    }
    
    // var isNum = string.match(/^[0-9]+$/) != null;
    // var isNum = /^\d+$/.test(str);
    if(!isNaN(str))
        return (parseFloat(str) != 0);
        
    return false;
}

Testing:

var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", "  true  ", "  TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");

var array_2 = new Array(null, "", false, "false", "   false   ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");


for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}

for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}

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

How can I disable mod_security in .htaccess file?

For anyone that simply are looking to bypass the ERROR page to display the content on shared hosting. You might wanna try and use redirect in .htaccess file. If it is say 406 error, on UnoEuro it didn't seem to work simply deactivating the security. So I used this instead:

ErrorDocument 406 /

Then you can always change the error status using PHP. But be aware that in my case doing so means I am opening a door to SQL injections as I am bypassing WAF. So you will need to make sure that you either have your own security measures or enable the security again asap.

How should I validate an e-mail address?

I have used follwing code.This works grate.I hope this will help you.

if (validMail(yourEmailString)){
   //do your stuf
 }else{
 //email is not valid.
}

and use follwing method.This returns true if email is valid.

    private boolean validMail(String yourEmailString) {
    Pattern emailPattern = Pattern.compile(".+@.+\\.[a-z]+");
    Matcher emailMatcher = emailPattern.matcher(emailstring);
    return emailMatcher.matches();
}

Stratified Train/Test-split in scikit-learn

[update for 0.17]

See the docs of sklearn.model_selection.train_test_split:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    stratify=y, 
                                                    test_size=0.25)

[/update for 0.17]

There is a pull request here. But you can simply do train, test = next(iter(StratifiedKFold(...))) and use the train and test indices if you want.

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

I was getting the same error when trying to copy a file. Closing a channel associated with the target file solved the problem.

Path destFile = Paths.get("dest file");
SeekableByteChannel destFileChannel = Files.newByteChannel(destFile);
//...
destFileChannel.close();  //removing this will throw java.nio.file.AccessDeniedException:
Files.copy(Paths.get("source file"), destFile);

How can I render a list select box (dropdown) with bootstrap?

Ben's code requires the parent div to have the form-group class (I was using btn-group), this is a slightly different version which just searches for the closest div and may even be a bit faster.

$(".dropdown-menu li a").click(function(){
    var selText = $(this).text();
    $(this).closest('div').find('button[data-toggle="dropdown"]').html(selText + ' <span class="caret"></span>');
});

No Multiline Lambda in Python: Why not?

Here's a more interesting implementation of multi line lambdas. It's not possible to achieve because of how python use indents as a way to structure code.

But luckily for us, indent formatting can be disabled using arrays and parenthesis.

As some already pointed out, you can write your code as such:

lambda args: (expr1, expr2,... exprN)

In theory if you're guaranteed to have evaluation from left to right it would work but you still lose values being passed from one expression to an other.

One way to achieve that which is a bit more verbose is to have

lambda args: [lambda1, lambda2, ..., lambdaN]

Where each lambda receives arguments from the previous one.

def let(*funcs):
    def wrap(args):
        result = args                                                                                                                                                                                                                         
        for func in funcs:
            if not isinstance(result, tuple):
                result = (result,)
            result = func(*result)
        return result
    return wrap

This method let you write something that is a bit lisp/scheme like.

So you can write things like this:

let(lambda x, y: x+y)((1, 2))

A more complex method could be use to compute the hypotenuse

lst = [(1,2), (2,3)]
result = map(let(
  lambda x, y: (x**2, y**2),
  lambda x, y: (x + y) ** (1/2)
), lst)

This will return a list of scalar numbers so it can be used to reduce multiple values to one.

Having that many lambda is certainly not going to be very efficient but if you're constrained it can be a good way to get something done quickly then rewrite it as an actual function later.

How to perform grep operation on all files in a directory?

grep $PATTERN * would be sufficient. By default, grep would skip all subdirectories. However, if you want to grep through them, grep -r $PATTERN * is the case.

OS X Terminal shortcut: Jump to beginning/end of line

This worked for me Option + left-arrow or Option + right-arrow for moving the cursor to the start or end of the line.

Mac Os Version: Catalina

Simplest two-way encryption using PHP

Edited:

You should really be using openssl_encrypt() & openssl_decrypt()

As Scott says, Mcrypt is not a good idea as it has not been updated since 2007.

There is even an RFC to remove Mcrypt from PHP - https://wiki.php.net/rfc/mcrypt-viking-funeral

How to set image in circle in swift

First you need to set equal width and height for getting Circular ImageView.Below I set width and height as 100,100.If you want to set equal width and height according to your required size,set here.

 var imageCircle = UIImageView(frame: CGRectMake(0, 0, 100, 100))

Then you need to set height/2 for corner radius

 imageCircle.layer.cornerRadius = imageCircle.frame.size.height/2
 imageCircle.layer.borderWidth = 1
 imageCircle.layer.borderColor = UIColor.blueColor().CGColor
 imageCircle.clipsToBounds = true
 self.view.addSubview(imageCircle)

PHP substring extraction. Get the string before the first '/' or the whole string

You can also use this one line solution

list($substring) = explode("/", $string);

jquery loop on Json data using $.each

getJSON will evaluate the data to JSON for you, as long as the correct content-type is used. Make sure that the server is returning the data as application/json.

Table and Index size in SQL Server

To see a single table's (and its indexes) storage data:

exec sp_spaceused MyTable

TypeError: 'str' object is not callable (Python)

I had the same error. In my case wasn't because of a variable named str. But because I named a function with a str parameter and the variable the same.

same_name = same_name(var_name: str)

I run it in a loop. The first time it run ok. The second time I got this error. Renaming the variable to a name different from the function name fixed this. So I think it's because Python once associate a function name in a scope, the second time tries to associate the left part (same_name =) as a call to the function and detects that the str parameter is not present, so it's missing, then it throws that error.

How to add RSA key to authorized_keys file?

Make sure when executing Michael Krelin's solution you do the following

cat <your_public_key_file> >> ~/.ssh/authorized_keys

Note the double > without the double > the existing contents of authorized_keys will be over-written (nuked!) and that may not be desirable

How to split comma separated string using JavaScript?

Use

YourCommaSeparatedString.split(',');

How can I break up this long line in Python?

You can use textwrap module to break it in multiple lines

import textwrap
str="ABCDEFGHIJKLIMNO"
print("\n".join(textwrap.wrap(str,8)))

ABCDEFGH
IJKLIMNO

From the documentation:

textwrap.wrap(text[, width[, ...]])
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.

Optional keyword arguments correspond to the instance attributes of TextWrapper, documented below. width defaults to 70.

See the TextWrapper.wrap() method for additional details on how wrap() behaves.

Node.js Error: Cannot find module express

create one folder in your harddisk e.g sample1 and go to command prompt type :cd and gives the path of sample1 folder and then install all modules...

npm install express

npm install jade

npm install socket.io

and then whatever you are creating application save in sample1 folder

try it...

avrdude: stk500v2_ReceiveMessage(): timeout

I was running this code from Arduino setup , got same error resolve after changing
serial port to COM13
GO TO Option
tool>> serial port>> COM132

How to set alignment center in TextBox in ASP.NET?

Add the css styling text-align: center to the control.

Ideally you would do this through a css class assigned to the control, but if you must do it directly, here is an example:

<asp:TextBox ID="myTextBox" runat="server" style="text-align: center"></asp:TextBox>

Read a HTML file into a string variable in memory

Use File.ReadAllText(path_to_file) to read

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

onActivityCreated() - Deprecated

onActivityCreated() is now deprecated as Fragments Version 1.3.0-alpha02

The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.

Detailed information can be found here

Elegant way to report missing values in a data.frame

summary(airquality)

already gives you this information

The VIM packages also offers some nice missing data plot for data.frame

library("VIM")
aggr(airquality)

enter image description here

WCF service maxReceivedMessageSize basicHttpBinding issue

Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:

<services>
  <service name="Service.IService">
    <clear />
    <endpoint binding="basicHttpBinding" contract="Service.IService" />
  </service>
</services>
<bindings>
  <basicHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
        maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    </binding>
  </basicHttpBinding>
  <webHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
  </webHttpBinding>
</bindings>

Also note that I removed the bindingConfiguration attribute from the endpoint node. Otherwise you would get an exception.

This same solution was found here : Problem with large requests in WCF

JSON to pandas DataFrame

Rumble supports JSON natively with JSONiq and runs on Spark, managing DataFrames internally so you don't need to -- even if the data isn't fully structured:

let $coords := "42.974049,-81.205203%7C42.974298,-81.195755"
let $request := json-doc("http://maps.googleapis.com/maps/api/elevation/json?locations="||$coords||"&sensor=false")
for $obj in $request.results[]
return {
  "latitude" : $obj.location.lat,
  "longitude" : $obj.location.lng,
  "elevation" : $obj.elevation
}

The results can be exported to CSV and then reopened in any other host language as a DataFrame.

How do I make a Mac Terminal pop-up/alert? Applescript?

Use osascript. For example:

osascript -e 'tell app "Finder" to display dialog "Hello World"' 

Replacing “Finder” with whatever app you desire. Note if that app is backgrounded, the dialog will appear in the background too. To always show in the foreground, use “System Events” as the app:

osascript -e 'tell app "System Events" to display dialog "Hello World"'

Read more on Mac OS X Hints.

Split string in JavaScript and detect line break

This is what I used to print text to a canvas. The input is not coming from a textarea, but from input and I'm only splitting by space. Definitely not perfect, but works for my case. It returns the lines in an array:

splitTextToLines: function (text) {
        var idealSplit = 7,
            maxSplit = 20,
            lineCounter = 0,
            lineIndex = 0,
            lines = [""],
            ch, i;

        for (i = 0; i < text.length; i++) {
            ch = text[i];
            if ((lineCounter >= idealSplit && ch === " ") || lineCounter >= maxSplit) {
                ch = "";
                lineCounter = -1;
                lineIndex++;
                lines.push("");
            }
            lines[lineIndex] += ch;
            lineCounter++;
        }

        return lines;
    }

Generate a dummy-variable

Using dummies::dummy():

library(dummies)

# example data
df1 <- data.frame(id = 1:4, year = 1991:1994)

df1 <- cbind(df1, dummy(df1$year, sep = "_"))

df1
#   id year df1_1991 df1_1992 df1_1993 df1_1994
# 1  1 1991        1        0        0        0
# 2  2 1992        0        1        0        0
# 3  3 1993        0        0        1        0
# 4  4 1994        0        0        0        1

How to validate phone numbers using regex

Working example for Turkey, just change the

d{9}

according to your needs and start using it.

function validateMobile($phone)
{
    $pattern = "/^(05)\d{9}$/";
    if (!preg_match($pattern, $phone))
    {
        return false;
    }
    return true;
}

$phone = "0532486061";

if(!validateMobile($phone))
{
    echo 'Incorrect Mobile Number!';
}

$phone = "05324860614";
if(validateMobile($phone))
{
    echo 'Correct Mobile Number!';
}

caching JavaScript files

I just finished my weekend project cached-webpgr.js which uses the localStorage / web storage to cache JavaScript files. This approach is very fast. My small test showed

  • Loading jQuery from CDN: Chrome 268ms, FireFox: 200ms
  • Loading jQuery from localStorage: Chrome 47ms, FireFox 14ms

The code to achieve that is tiny, you can check it out at my Github project https://github.com/webpgr/cached-webpgr.js

Here is a full example how to use it.

The complete library:

function _cacheScript(c,d,e){var a=new XMLHttpRequest;a.onreadystatechange=function(){4==a.readyState&&(200==a.status?localStorage.setItem(c,JSON.stringify({content:a.responseText,version:d})):console.warn("error loading "+e))};a.open("GET",e,!0);a.send()}function _loadScript(c,d,e,a){var b=document.createElement("script");b.readyState?b.onreadystatechange=function(){if("loaded"==b.readyState||"complete"==b.readyState)b.onreadystatechange=null,_cacheScript(d,e,c),a&&a()}:b.onload=function(){_cacheScript(d,e,c);a&&a()};b.setAttribute("src",c);document.getElementsByTagName("head")[0].appendChild(b)}function _injectScript(c,d,e,a){var b=document.createElement("script");b.type="text/javascript";c=JSON.parse(c);var f=document.createTextNode(c.content);b.appendChild(f);document.getElementsByTagName("head")[0].appendChild(b);c.version!=e&&localStorage.removeItem(d);a&&a()}function requireScript(c,d,e,a){var b=localStorage.getItem(c);null==b?_loadScript(e,c,d,a):_injectScript(b,c,d,a)};

Calling the library

requireScript('jquery', '1.11.2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function(){
    requireScript('examplejs', '0.0.3', 'example.js');
});

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

If you don't have httpd.conf in folder /etc/apache2, you should have apache2.conf - simply add:

ServerName localhost

Then restart the apache2 service.

How can I get the current PowerShell executing file?

I've tried to summarize the various answers here, updated for PowerShell 5:

  • If you're only using PowerShell 3 or higher, use $PSCommandPath

  • If want compatibility with older versions, insert the shim:

    if ($PSCommandPath -eq $null) { function GetPSCommandPath() { return $MyInvocation.PSCommandPath; } $PSCommandPath = GetPSCommandPath; }

    This adds $PSCommandPath if it doesn't already exist.

    The shim code can be executed anywhere (top-level or inside a function), though $PSCommandPath variable is subject to normal scoping rules (eg, if you put the shim in a function, the variable is scoped to that function only).

Details

There's 4 different methods used in various answers, so I wrote this script to demonstrate each (plus $PSCommandPath):

function PSCommandPath() { return $PSCommandPath; }
function ScriptName() { return $MyInvocation.ScriptName; }
function MyCommandName() { return $MyInvocation.MyCommand.Name; }
function MyCommandDefinition() {
    # Begin of MyCommandDefinition()
    # Note: ouput of this script shows the contents of this function, not the execution result
    return $MyInvocation.MyCommand.Definition;
    # End of MyCommandDefinition()
}
function MyInvocationPSCommandPath() { return $MyInvocation.PSCommandPath; }

Write-Host "";
Write-Host "PSVersion: $($PSVersionTable.PSVersion)";
Write-Host "";
Write-Host "`$PSCommandPath:";
Write-Host " *   Direct: $PSCommandPath";
Write-Host " * Function: $(PSCommandPath)";
Write-Host "";
Write-Host "`$MyInvocation.ScriptName:";
Write-Host " *   Direct: $($MyInvocation.ScriptName)";
Write-Host " * Function: $(ScriptName)";
Write-Host "";
Write-Host "`$MyInvocation.MyCommand.Name:";
Write-Host " *   Direct: $($MyInvocation.MyCommand.Name)";
Write-Host " * Function: $(MyCommandName)";
Write-Host "";
Write-Host "`$MyInvocation.MyCommand.Definition:";
Write-Host " *   Direct: $($MyInvocation.MyCommand.Definition)";
Write-Host " * Function: $(MyCommandDefinition)";
Write-Host "";
Write-Host "`$MyInvocation.PSCommandPath:";
Write-Host " *   Direct: $($MyInvocation.PSCommandPath)";
Write-Host " * Function: $(MyInvocationPSCommandPath)";
Write-Host "";

Output:

PS C:\> .\Test\test.ps1

PSVersion: 5.1.19035.1

$PSCommandPath:
 *   Direct: C:\Test\test.ps1
 * Function: C:\Test\test.ps1

$MyInvocation.ScriptName:
 *   Direct:
 * Function: C:\Test\test.ps1

$MyInvocation.MyCommand.Name:
 *   Direct: test.ps1
 * Function: MyCommandName

$MyInvocation.MyCommand.Definition:
 *   Direct: C:\Test\test.ps1
 * Function:
    # Begin of MyCommandDefinition()
    # Note this is the contents of the MyCommandDefinition() function, not the execution results
    return $MyInvocation.MyCommand.Definition;
    # End of MyCommandDefinition()


$MyInvocation.PSCommandPath:
 *   Direct:
 * Function: C:\Test\test.ps1

Notes:

  • Executed from C:\, but actual script is C:\Test\test.ps1.
  • No method tells you the passed invocation path (.\Test\test.ps1)
  • $PSCommandPath is the only reliable way, but was introduced in PowerShell 3
  • For versions prior to 3, no single method works both inside and outside of a function

how to add key value pair in the JSON object already declared

possible duplicate , best way to achieve same as stated below:

function getKey(key) {
  return `${key}`;
}

var obj = {key1: "value1", key2: "value2", [getKey('key3')]: "value3"};

https://stackoverflow.com/a/47405116/3510511

What does it mean by select 1 from table?

This means that You want a value "1" as output or Most of the time used as Inner Queries because for some reason you want to calculate the outer queries based on the result of inner queries.. not all the time you use 1 but you have some specific values...

This will statically gives you output as value 1.

Executing <script> injected by innerHTML after AJAX call

JavaScript inserted as DOM text will not execute. However, you can use the dynamic script pattern to accomplish your goal. The basic idea is to move the script that you want to execute into an external file and create a script tag when you get your Ajax response. You then set the src attribute of your script tag and voila, it loads and executes the external script.

This other StackOverflow post may also be helpful to you: Can scripts be inserted with innerHTML?.

What is the list of valid @SuppressWarnings warning names in Java?

JSL 1.7

The Oracle documentation mentions:

  • unchecked: Unchecked warnings are identified by the string "unchecked".
  • deprecation: A Java compiler must produce a deprecation warning when a type, method, field, or constructor whose declaration is annotated with the annotation @Deprecated is used (i.e. overridden, invoked, or referenced by name), unless: [...] The use is within an entity that is annotated to suppress the warning with the annotation @SuppressWarnings("deprecation"); or

It then explains that implementations can add and document their own:

Compiler vendors should document the warning names they support in conjunction with this annotation type. Vendors are encouraged to cooperate to ensure that the same names work across multiple compilers.

How do I enable NuGet Package Restore in Visual Studio?

Microsoft has dropped support for the 'Enable NuGet Package Restore' in VS2015 and you need to do some manual changes to either migrate old solutions or add the feature to new solutions. The new feature is described pretty well in NuGet Package Restore.

There is also a migration guide for existing projects (as previously mentioned) here: NuGet Migration Guide

When upgrading:

  1. do not delete the .nuget directory.
  2. Delete the nuget.exe and nuget.targets files.
  3. Leave the nuget.config.
  4. Purge each of the project files of any reference to the NuGet targets by hand. The Powershell script mentioned seemed to do more damage than good.

When creating a new project:

  1. In your Visual Studio 2015 solution, create a Solution Directory called .nuget.

  2. Create an actual directory of the solution directory (where the .sln file lives) and call it .nuget (note that the solution directory is not the same as the actual file system directory even though they have the same name).

  3. Create a file in the .nuget directory called nuget.config.

  4. Add the 'nuget.config' to the solution directory created in step #2.

  5. Place the following text in the nuget.config file:

    <?xml version="1.0" encoding="utf-8"?>
     <configuration>
      <config>
        <add key="repositorypath" value="$\..\..\..\..\Packages" />
      </config>
      <solution>
        <add key="disableSourceControlIntegration" value="true" />
      </solution>
    </configuration>
    

This configuration file will allow you to consolidate all your packages in a single place so you don't have 20 different copies of the same package floating around on your file system. The relative path will change depending on your solution directory architecture but it should point to a directory common to all your solutions.

You need to restart visual studio after doing step 5. Nuget won't recognize the changes until you do so.

Finally, you may have to use the 'Nuget Package Manager for Solutions' to uninstall and then re-install the packages. I don't know if this was a side-effect of the Powershell script I ran or just a method to kick NuGet back into gear. Once I did all these steps, my complicated build architecture worked flawlessly at bringing down new packages when I checked projects out of TFVC.

How to check if element has any children in Javascript?

A reusable isEmpty( <selector> ) function.
You can also run it toward a collection of elements (see example)

_x000D_
_x000D_
const isEmpty = sel =>_x000D_
    ![... document.querySelectorAll(sel)].some(el => el.innerHTML.trim() !== "");_x000D_
_x000D_
console.log(_x000D_
  isEmpty("#one"), // false_x000D_
  isEmpty("#two"), // true_x000D_
  isEmpty(".foo"), // false_x000D_
  isEmpty(".bar")  // true_x000D_
);
_x000D_
<div id="one">_x000D_
 foo_x000D_
</div>_x000D_
_x000D_
<div id="two">_x000D_
 _x000D_
</div>_x000D_
_x000D_
<div class="foo"></div>_x000D_
<div class="foo"><p>foo</p></div>_x000D_
<div class="foo"></div>_x000D_
_x000D_
<div class="bar"></div>_x000D_
<div class="bar"></div>_x000D_
<div class="bar"></div>
_x000D_
_x000D_
_x000D_

returns true (and exits loop) as soon one element has any kind of content beside spaces or newlines.

How to export all collections in MongoDB?

If you want to dump all collections in all databases (which is an expansive interpretation of the original questioner's intent) then use

mongodump

All the databases and collections will be created in a directory called 'dump' in the 'current' location

How to check if variable's type matches Type stored in a variable

You need to see if the Type of your instance is equal to the Type of the class. To get the type of the instance you use the GetType() method:

 u.GetType().Equals(t);

or

 u.GetType.Equals(typeof(User));

should do it. Obviously you could use '==' to do your comparison if you prefer.

T-SQL split string based on delimiter

May be this will help you.

SELECT SUBSTRING(myColumn, 1, CASE CHARINDEX('/', myColumn)
            WHEN 0
                THEN LEN(myColumn)
            ELSE CHARINDEX('/', myColumn) - 1
            END) AS FirstName
    ,SUBSTRING(myColumn, CASE CHARINDEX('/', myColumn)
            WHEN 0
                THEN LEN(myColumn) + 1
            ELSE CHARINDEX('/', myColumn) + 1
            END, 1000) AS LastName
FROM MyTable

How to prevent gcc optimizing some statements in C?

Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile type qualifier.

// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];

The volatile type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.

This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma or __attribute__ syntax.

how can I enable PHP Extension intl?

All you need to do is go to php.ini in your xampp folder (xampp\php\php.ini) and remove ; from ;extension=php_intl.dll

;extension=php_intl.dll

TO

extension=php_intl.dll

Nginx: stat() failed (13: permission denied)

Nginx need to have +x access on all directories leading to the site's root directory.

Ensure you have +x on all of the directories in the path leading to the site's root. For example, if the site root is /home/username/siteroot:

chmod +x /home/
chmod +x /home/username
chmod +x /home/username/siteroot

Sql connection-string for localhost server

In .Net configuration I would use something like:

"Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=..."

This information is from https://www.connectionstrings.com/sql-server-2016/

How to send Request payload to REST API in java?

The following code works for me.

//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);

method implementation:

public static String sendPostRequest(String requestUrl, String payload) {
    try {
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writer.write(payload);
        writer.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer jsonString = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
                jsonString.append(line);
        }
        br.close();
        connection.disconnect();
        return jsonString.toString();
    } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
    }

}

Best way to overlay an ESRI shapefile on google maps?

Free "Export to KML" script for ArcGIS 9

Here is a list of available methods that someone found.

Also, it seems to me that the most efficient representation of a polygon layer is by using Google Maps API's polyline encoding, which significantly compresses lat-lng data. But getting into that format takes work: use ArcMap to export Shape as lat/lng coordinates, then convert into polylines using Google Maps API.

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

Like the previous comment mention, the message "It looks like you are trying to access MongoDB over HTTP on the native driver port." its a warning because you are missunderstanding this line: mongoose.connect('mongodb://localhost/info'); and browsing this url: http://localhost:28017/

However, if you want to see the mongo's admin web page, you could do it, with this command:

mongod --rest --httpinterface

browsing this url: http://localhost:28017/

the parameter httpinterface activate the admin web page, and the parameter rest its needed for activate the rest services the page require

Looking for simple Java in-memory cache

Since this question was originally asked, Google's Guava library now includes a powerful and flexible cache. I would recommend using this.

How to provide password to a command that prompts for one in bash?

Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.

If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.

Some applications will actually open up /dev/tty to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty (creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.

Can HTML be embedded inside PHP "if" statement?

<?php if ($my_name == 'aboutme') { ?>
    HTML_GOES_HERE
<?php } ?>

How to set a transparent background of JPanel?

(Feature Panel).setOpaque(false);

Hope this helps.

Plotting two variables as lines using ggplot2 on the same graph

I am also new to R but trying to understand how ggplot works I think I get another way to do it. I just share probably not as a complete perfect solution but to add some different points of view.

I know ggplot is made to work with dataframes better but maybe it can be also sometimes useful to know that you can directly plot two vectors without using a dataframe.

Loading data. Original date vector length is 100 while var0 and var1 have length 50 so I only plot the available data (first 50 dates).

var0 <- 100 + c(0, cumsum(runif(49, -20, 20)))
var1 <- 150 + c(0, cumsum(runif(49, -10, 10)))
date <- seq(as.Date("2002-01-01"), by="1 month", length.out=50)    

Plotting

ggplot() + geom_line(aes(x=date,y=var0),color='red') + 
           geom_line(aes(x=date,y=var1),color='blue') + 
           ylab('Values')+xlab('date')

enter image description here

However I was not able to add a correct legend using this format. Does anyone know how?

Testing whether a value is odd or even

_x000D_
_x000D_
for(var a=0; a<=20;a++){
   if(a%2!==0){
       console.log("Odd number "+a);
   }
}

for(var b=0; b<=20;a++){
    if(b%2===0){
        console.log("Even number "+b);  
    }     
 }
_x000D_
_x000D_
_x000D_

Rename a dictionary key

A few people before me mentioned the .pop trick to delete and create a key in a one-liner.

I personally find the more explicit implementation more readable:

d = {'a': 1, 'b': 2}
v = d['b']
del d['b']
d['c'] = v

The code above returns {'a': 1, 'c': 2}

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

If you're using Radiant CMS, simply add

require 'thread'

to the top of config/boot.rb.

(Kudos to Aaron's and nathanvda's responses.)

How to get status code from webclient?

You can try this code to get HTTP status code from WebException or from OpenReadCompletedEventArgs.Error. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

HttpStatusCode GetHttpStatusCode(System.Exception err)
{
    if (err is WebException)
    {
        WebException we = (WebException)err;
        if (we.Response is HttpWebResponse)
        {
            HttpWebResponse response = (HttpWebResponse)we.Response;
            return response.StatusCode;
        }
    }
    return 0;
}

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

Is it possible the INSERT is valid, but that a separate UPDATE is done afterwards that is invalid but wouldn't fire the trigger?

How to re-render flatlist?

In react-native-flatlist, they are a property called as extraData. add the below line to your flatlist.

 <FlatList
          data={data }
          style={FlatListstyles}
          extraData={this.state}
          renderItem={this._renderItem}
       />

Java - Convert String to valid URI object

I'm going to add one suggestion here aimed at Android users. You can do this which avoids having to get any external libraries. Also, all the search/replace characters solutions suggested in some of the answers above are perilous and should be avoided.

Give this a try:

String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();

You can see that in this particular URL, I need to have those spaces encoded so that I can use it for a request.

This takes advantage of a couple features available to you in Android classes. First, the URL class can break a url into its proper components so there is no need for you to do any string search/replace work. Secondly, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.

The beauty of this approach is that you can take any valid url string and have it work without needing any special knowledge of it yourself.

Javascript Thousand Separator / string format

Update (7 years later)

The reference cited in the original answer below was wrong. There is a built in function for this, which is exactly what kaiser suggests below: toLocaleString

So you can do:

(1234567.89).toLocaleString('en')              // for numeric input
parseFloat("1234567.89").toLocaleString('en')  // for string input

The function implemented below works, too, but simply isn't necessary.

(I thought perhaps I'd get lucky and find out that it was necessary back in 2010, but no. According to this more reliable reference, toLocaleString has been part of the standard since ECMAScript 3rd Edition [1999], which I believe means it would have been supported as far back as IE 5.5.)


Original Answer

According to this reference there isn't a built in function for adding commas to a number. But that page includes an example of how to code it yourself:

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Edit: To go the other way (convert string with commas to number), you could do something like this:

parseFloat("1,234,567.89".replace(/,/g,''))

Configure Apache .conf for Alias

Sorry not sure what was going on this worked in the end:

<VirtualHost *> 
    ServerName example.com
    DocumentRoot /var/www/html/mjp

    Alias /ncn "/var/www/html/ncn"

    <Directory "/var/www/html/ncn">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

What is the best way to extract the first word from a string in Java?

String anotherPalindrome = "Niagara. O roar again!"; 
String roar = anotherPalindrome.substring(11, 15); 

You can also do like these

Get Selected Item Using Checkbox in Listview

Assuming you want to get items of row whose check boxes are checked at the click of a button. Assumption based on your title "Get Selected Item Using Checkbox in Listview when I click a Button".

Try the below. Make only changes as below. Keep the rest the same.

Explanation and discussion on the topic @

https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M

MainActivity.java

public class MainActivity extends Activity {
     AppInfoAdapter adapter ;
     AppInfo app_info[] ;
        @Override
        protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


            final ListView listApplication = (ListView)findViewById(R.id.listApplication);
            Button b= (Button) findViewById(R.id.button1);
            b.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    StringBuilder result = new StringBuilder();
                    for(int i=0;i<adapter.mCheckStates.size();i++)
                    {
                        if(adapter.mCheckStates.get(i)==true)
                        {

                                           result.append(app_info[i].applicationName);
                            result.append("\n");
                        }

                    }
                    Toast.makeText(MainActivity.this, result, 1000).show();
                }

            });

            ApplicationInfo applicationInfo = getApplicationInfo();
            PackageManager pm = getPackageManager();
            List<PackageInfo> pInfo = new ArrayList<PackageInfo>();
            pInfo.addAll(pm.getInstalledPackages(0));
            app_info = new AppInfo[pInfo.size()];

            int counter = 0;
            for(PackageInfo item: pInfo){
                try{

                    applicationInfo = pm.getApplicationInfo(item.packageName, 1);

                    app_info[counter] = new AppInfo(pm.getApplicationIcon(applicationInfo), 
                            String.valueOf(pm.getApplicationLabel(applicationInfo)));

                    System.out.println(counter);

                }
                catch(Exception e){
                     System.out.println(e.getMessage());
                }

                counter++;
            }

           adapter = new AppInfoAdapter(this, R.layout.listview_item_row, app_info);
            listApplication.setAdapter(adapter);

        }
}

activity_main.xml ListView with button at the buton

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:layout_width="fill_parent"
        android:id="@+id/listApplication"
        android:layout_height="fill_parent"
        android:layout_above="@+id/button1"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Button" />

</RelativeLayout>

AppInfoAdapter

public class AppInfoAdapter extends ArrayAdapter<AppInfo> implements CompoundButton.OnCheckedChangeListener
{  SparseBooleanArray mCheckStates; 

    Context context;
    int layoutResourceId;
    AppInfo  data[] = null;

    public AppInfoAdapter(Context context, int layoutResourceId, AppInfo[] data){
        super(context, layoutResourceId,data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
        mCheckStates = new SparseBooleanArray(data.length);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){

        View row = convertView;
        AppInfoHolder holder= null;

        if (row == null){

            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new AppInfoHolder();

            holder.imgIcon = (ImageView) row.findViewById(R.id.imageView1);
            holder.txtTitle = (TextView) row.findViewById(R.id.textView1);
            holder.chkSelect = (CheckBox) row.findViewById(R.id.checkBox1);

            row.setTag(holder);

        }
        else{
            holder = (AppInfoHolder)row.getTag();
        }


        AppInfo appinfo = data[position];
        holder.txtTitle.setText(appinfo.applicationName);
        holder.imgIcon.setImageDrawable(appinfo.icon);
       // holder.chkSelect.setChecked(true);
        holder.chkSelect.setTag(position);
        holder.chkSelect.setChecked(mCheckStates.get(position, false));
        holder.chkSelect.setOnCheckedChangeListener(this);
        return row;

    }
    public boolean isChecked(int position) {
        return mCheckStates.get(position, false);
    }

    public void setChecked(int position, boolean isChecked) {
        mCheckStates.put(position, isChecked);

    }

    public void toggle(int position) {
        setChecked(position, !isChecked(position));

    }
@Override
public void onCheckedChanged(CompoundButton buttonView,
        boolean isChecked) {

     mCheckStates.put((Integer) buttonView.getTag(), isChecked);    

}
static class AppInfoHolder
{
    ImageView imgIcon;
    TextView txtTitle;
    CheckBox chkSelect;

}
}

Here's the snap shot

enter image description here

Detect end of ScrollView

scrollView = (ScrollView) findViewById(R.id.scrollView);

    scrollView.getViewTreeObserver()
            .addOnScrollChangedListener(new 
            ViewTreeObserver.OnScrollChangedListener() {
                @Override
                public void onScrollChanged() {

                    if (!scrollView.canScrollVertically(1)) {
                        // bottom of scroll view
                    }
                    if (!scrollView.canScrollVertically(-1)) {
                        // top of scroll view


                    }
                }
            });

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

Comparing to Apple's UINavigationController and UIViewController, Google does not do well in Android software architecture. And Android's document about Fragment does not help much.

When you enter FragmentB from FragmentA, the existing FragmentA instance is not destroyed. When you press Back in FragmentB and return to FragmentA, we don't create a new FragmentA instance. The existing FragmentA instance's onCreateView() will be called.

The key thing is we should not inflate view again in FragmentA's onCreateView(), because we are using the existing FragmentA's instance. We need to save and reuse the rootView.

The following code works well. It does not only keep fragment state, but also reduces the RAM and CPU load (because we only inflate layout if necessary). I can't believe Google's sample code and document never mention it but always inflate layout.

Version 1(Don't use version 1. Use version 2)

public class FragmentA extends Fragment {
    View _rootView;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (_rootView == null) {
            // Inflate the layout for this fragment
            _rootView = inflater.inflate(R.layout.fragment_a, container, false);
            // Find and setup subviews
            _listView = (ListView)_rootView.findViewById(R.id.listView);
            ...
        } else {
            // Do not inflate the layout again.
            // The returned View of onCreateView will be added into the fragment.
            // However it is not allowed to be added twice even if the parent is same.
            // So we must remove _rootView from the existing parent view group
            // (it will be added back).
            ((ViewGroup)_rootView.getParent()).removeView(_rootView);
        }
        return _rootView;
    }
}

------Update on May 3 2005:-------

As the comments mentioned, sometimes _rootView.getParent() is null in onCreateView, which causes the crash. Version 2 removes _rootView in onDestroyView(), as dell116 suggested. Tested on Android 4.0.3, 4.4.4, 5.1.0.

Version 2

public class FragmentA extends Fragment {
    View _rootView;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (_rootView == null) {
            // Inflate the layout for this fragment
            _rootView = inflater.inflate(R.layout.fragment_a, container, false);
            // Find and setup subviews
            _listView = (ListView)_rootView.findViewById(R.id.listView);
            ...
        } else {
            // Do not inflate the layout again.
            // The returned View of onCreateView will be added into the fragment.
            // However it is not allowed to be added twice even if the parent is same.
            // So we must remove _rootView from the existing parent view group
            // in onDestroyView() (it will be added back).
        }
        return _rootView;
    }

    @Override
    public void onDestroyView() {
        if (_rootView.getParent() != null) {
            ((ViewGroup)_rootView.getParent()).removeView(_rootView);
        }
        super.onDestroyView();
    }
}

WARNING!!!

This is a HACK! Though I am using it in my app, you need to test and read comments carefully.

What is the reason for a red exclamation mark next to my project in Eclipse?

Go to Project -> right click -> properties -> Java Build Path -> Libraries

Delete all the JARs which have red cross symbol on the icon.

Resolved.

Passing parameters to a JQuery function

Using POST

function DoAction( id, name )
{
    $.ajax({
         type: "POST",
         url: "someurl.php",
         data: "id=" + id + "&name=" + name,
         success: function(msg){
                     alert( "Data Saved: " + msg );
                  }
    });
}

Using GET

function DoAction( id, name )
{
     $.ajax({
          type: "GET",
          url: "someurl.php",
          data: "id=" + id + "&name=" + name,
          success: function(msg){
                     alert( "Data Saved: " + msg );
                   }
     });
}

EDIT:

A, perhaps, better way to do this that would work (using GET) if javascript were not enabled would be to generate the URL for the href, then use a click handler to call that URL via ajax instead.

<a href="/someurl.php?id=1&name=Jose" class="ajax-link"> Click </a>
<a href="/someurl.php?id=2&name=Juan" class="ajax-link"> Click </a>
<a href="/someurl.php?id=3&name=Pedro" class="ajax-link"> Click </a>
...
<a href="/someurl.php?id=n&name=xxx" class="ajax-link"> Click </a>

<script type="text/javascript">
$(function() {
   $('.ajax-link').click( function() {
         $.get( $(this).attr('href'), function(msg) {
              alert( "Data Saved: " + msg );
         });
         return false; // don't follow the link!
   });
});
</script>

Regular expression to extract text between square brackets

In R, try:

x <- 'foo[bar]baz'
str_replace(x, ".*?\\[(.*?)\\].*", "\\1")
[1] "bar"

How is Pythons glob.glob ordered?

At least in Python3 you also can do this:

import os, re, glob

path = '/home/my/path'
files = glob.glob(os.path.join(path, '*.png'))
files.sort(key=lambda x:[int(c) if c.isdigit() else c for c in re.split(r'(\d+)', x)])
for infile in files:
    print(infile)

This should lexicographically order your input array of strings (e.g. respect numbers in strings while ordering).

Error ITMS-90717: "Invalid App Store Icon"

I had this problem and it was because my app store icon wasn't explicitly listed in my config.xml. Once I added the line

<icon height="1024" src="www/res/icon/ios/icon-1024.png" width="1024" />,

cordova copied it over correctly without adding an alpha channel.

Looping through a hash, or using an array in PowerShell

Here is another quick way, just using the key as an index into the hash table to get the value:

$hash = @{
    'a' = 1;
    'b' = 2;
    'c' = 3
};

foreach($key in $hash.keys) {
    Write-Host ("Key = " + $key + " and Value = " + $hash[$key]);
}

Add ripple effect to my button with button background color?

Adding foreground and clickable attributes worked for me.

<Button
    ... 
    android:background="@color/your_color"
    android:foreground="?attr/selectableItemBackgroundBorderless"
    android:clickable="true" />

PermissionError: [Errno 13] in python

I encountered this problem when I accidentally tried running my python module through the command prompt while my working directory was C:\Windows\System32 instead of the usual directory from which I run my python module

Check if a value is within a range of numbers

You're asking a question about numeric comparisons, so regular expressions really have nothing to do with the issue. You don't need "multiple if" statements to do it, either:

if (x >= 0.001 && x <= 0.009) {
  // something
}

You could write yourself a "between()" function:

function between(x, min, max) {
  return x >= min && x <= max;
}
// ...
if (between(x, 0.001, 0.009)) {
  // something
}

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

I realize this is an old post, but it ranks high in Google, so I'm adding what I figured out for MY problem. If you have a mix of table types (e.g. MyISAM and InnoDB), you will get this error as well. In this case, InnoDB is the default table type, but one table needed fulltext searching so it was migrated to MyISAM. In this situation, you cannot create a foreign key in the InnoDB table that references the MyISAM table.

Fetch: POST json data

Had the same issue - no body was sent from a client to a server.

Adding Content-Type header solved it for me:

var headers = new Headers();

headers.append('Accept', 'application/json'); // This one is enough for GET requests
headers.append('Content-Type', 'application/json'); // This one sends body

return fetch('/some/endpoint', {
    method: 'POST',
    mode: 'same-origin',
    credentials: 'include',
    redirect: 'follow',
    headers: headers,
    body: JSON.stringify({
        name: 'John',
        surname: 'Doe'
    }),
}).then(resp => {
    ...
}).catch(err => {
   ...
})

The type or namespace name 'System' could not be found

i had to upgrade from visual studio 2017 to 2019. no other proposed solution here helped me, i installed and configured, rebooted every one here plus many other options from ms site.

my root cause was probably due to the fact the git repository developer used 2019 and i tried to clone the original git repo into ma 2017.

How to deselect a selected UITableView cell?

swift 3.0

    tableView.deselectRow(at: indexPath, animated: true)

How to find whether or not a variable is empty in Bash?

if [ ${foo:+1} ]
then
    echo "yes"
fi

prints yes if the variable is set. ${foo:+1} will return 1 when the variable is set, otherwise it will return empty string.

AngularJS ng-repeat handle empty list case

You might want to check out the angular-ui directive ui-if if you just want to remove the ul from the DOM when the list is empty:

<ul ui-if="!!events.length">
    <li ng-repeat="event in events">{{event.title}}</li>
</ul>

Hadoop: «ERROR : JAVA_HOME is not set»

Here we provide simple steps to setup JAVA_HOME while installing of Hadoop

Step1: Goto Java library path /lib jvm

Then set the JAVA_HOME & PATH in .bashrc file

Source : http://commandstech.com/hadoop-error-java_home-is-not-set-and-could-not-be-found-in-hadoop-installation/

Step 2 : Once it is done then go with Hadoop env file then update it.

After once it is done then stop the daemons and start daemons once again.

How can I style the border and title bar of a window in WPF?

You need to set

WindowStyle="None", AllowsTransparency="True" and optionally ResizeMode="NoResize"
and then set the Style property of the window to your custom window style, where you design the appearance of the window (title bar, buttons, border) to anything you want and display the window contents in a ContentPresenter.

This seems to be a good article on how you can achieve this, but there are many other articles on the internet.

Apache2: 'AH01630: client denied by server configuration'

I actually solved this one by adding the directory access to the :80 entry.

 <Directory "c:/whatever-directory-you-use/">
    AllowOverride All
    Require all granted
</Directory>

Before everyone gets all 'security' on me, under my specific circumstances this is not a security issue.

If you are using a remote resource, I'd recommend instead make sure your CURL request goes via HTTPS / TLS, then this directory entry goes on the 443 port.

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

Seems like answered here: https://public-inbox.org/git/[email protected]/

So in a similar way, running

$ git diff --cc $M $M^1 $M^2 $(git merge-base $M^1 $M^2)

should show a combined patch that explains the state at $M relative to the states recorded in its parents and the merge base.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

It appears that IntelliJ 11 has changed the method, and the checked answer no longer works for me. In case anyone else arrives here via a search engine, here's how I solved it in IntelliJ 11:

  1. Go to the Project Structure, click on Modules, and click on your Module
  2. Choose the "Dependencies" tab
  3. Click the "+" button on the right-hand side and select "Jars or directories..."
  4. Add the directory(ies) you want (note you can multi-select) and click OK
  5. In the dialog that comes up, select "classes" and NOT "jar directory"
  6. Make sure you're using that Module in your run target

Note that step 5 seems to be the key difference. If you select "jar directory" it will look exactly the same in the IDE but won't include the path at runtime. There appears to be no way to determine whether you've previously selected "classes" or "jar directory" after the fact.

NULL value for int in Update statement

If this is nullable int field then yes.

update TableName
set FiledName = null
where Id = SomeId

How To Auto-Format / Indent XML/HTML in Notepad++

Since I upgraded to 6.3.2, I use XML Tools.

  • install XML Tools via the Plugin Admin (Plugins ? Plugins Admin... Then search for "XML Tools", check its box and click the "Install" button).
  • use the shortcut Ctrl+Alt+Shift+B (or menu ? Plugins ? XML Tools ? Pretty Print)

enter image description here

enter image description here

In older versions: menu ? TextFX ? HTML Tidy ? Tidy: Reindent XML.

SQLite - getting number of rows in a database

You can query the actual number of rows with

SELECT Count(*) FROM tblName
see https://www.w3schools.com/sql/sql_count_avg_sum.asp

reading from app.config file

This:

Console.WriteLine( "StartingMonthColumn is {0}", ConfigurationManager.AppSettings["StartingMonthColumn"]);

works fine for me.

Note that ConfigurationManager is in the System.Configuration namespace (so you'll likely want a using System.Configuration; statement), and that since what you read in has a string type you'll need to parse what you read in to use it as a number.

Also, be sure you set system.configuration.dll as a reference in your project or build script.

How to get .app file of a xcode application

You can find the .app file here:

~/Library/Developer/Xcode/DerivedData/{app name}/Build/Products/Deployment/ 

credit for path goes to this answer

SIDENOTE: I had a lot of fun trying to get this into my iPad after that. It worked however. Using Snow Leopard + Xcode 4.2 + iPad with IOS 5.1.1 :) - I used the iPhone configuration utility to get the app into the ipad (you have to add the app, then click on the device, then click "install" behind the app you just added in the "application library" of iphone configuration utility) and had to create a Distribution Provisioning Profile and get the WWDR certificate and finally change the build settings in Xcode after all the certificates were in place. See here

But after much fun I am now looking at my first app on my iPad :) - btw, for getting apps into the app store you need to create a app store Distribution Provisioning Profile, while for ad hoc installs like these you create an ad hoc one. There is a bit more to it, but I think these are the most important and tricky steps. Enjoy.

PS. Just remembered that you also have to set the build type (top left of Xcode) to "iOS device", otherwise it will never sign your application. So the path name above only has limited value: yes, it will have the .app file in it, but no you can't upload it (at least not using the iPhone configuration utility) since it is not code signed - you will get an "Could not copy validate signature" error. So change it to "iOS device" and build (remember to select the right certificates in the build section of Xcode as per the url info above). In that same build section, you can also set the "Installation Build Products Location" to a different path, so that you can determine where the .app (the one that is properly code signed) ends up.

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

JavaScriptSerializer.Deserialize - how to change field names

For those who don't want to go for Newtonsoft Json.Net or DataContractJsonSerializer for some reason (I can't think of any :) ), here is an implementation of JavaScriptConverter that supports DataContract and enum to string conversion -

    public class DataContractJavaScriptConverter : JavaScriptConverter
    {
        private static readonly List<Type> _supportedTypes = new List<Type>();

        static DataContractJavaScriptConverter()
        {
            foreach (Type type in Assembly.GetExecutingAssembly().DefinedTypes)
            {
                if (Attribute.IsDefined(type, typeof(DataContractAttribute)))
                {
                    _supportedTypes.Add(type);
                }
            }
        }

        private bool ConvertEnumToString = false;

        public DataContractJavaScriptConverter() : this(false)
        {
        }

        public DataContractJavaScriptConverter(bool convertEnumToString)
        {
            ConvertEnumToString = convertEnumToString;
        }

        public override IEnumerable<Type> SupportedTypes
        {
            get { return _supportedTypes; }
        }

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (Attribute.IsDefined(type, typeof(DataContractAttribute)))
            {
                try
                {
                    object instance = Activator.CreateInstance(type);

                    IEnumerable<MemberInfo> members = ((IEnumerable<MemberInfo>)type.GetFields())
                        .Concat(type.GetProperties().Where(property => property.CanWrite && property.GetIndexParameters().Length == 0))
                        .Where((member) => Attribute.IsDefined(member, typeof(DataMemberAttribute)));
                    foreach (MemberInfo member in members)
                    {
                        DataMemberAttribute attribute = (DataMemberAttribute)Attribute.GetCustomAttribute(member, typeof(DataMemberAttribute));
                        object value;
                        if (dictionary.TryGetValue(attribute.Name, out value) == false)
                        {
                            if (attribute.IsRequired)
                            {
                                throw new SerializationException(String.Format("Required DataMember with name {0} not found", attribute.Name));
                            }
                            continue;
                        }
                        if (member.MemberType == MemberTypes.Field)
                        {
                            FieldInfo field = (FieldInfo)member;
                            object fieldValue;
                            if (ConvertEnumToString && field.FieldType.IsEnum)
                            {
                                fieldValue = Enum.Parse(field.FieldType, value.ToString());
                            }
                            else
                            {
                                fieldValue = serializer.ConvertToType(value, field.FieldType);
                            }
                            field.SetValue(instance, fieldValue);
                        }
                        else if (member.MemberType == MemberTypes.Property)
                        {
                            PropertyInfo property = (PropertyInfo)member;
                            object propertyValue;
                            if (ConvertEnumToString && property.PropertyType.IsEnum)
                            {
                                propertyValue = Enum.Parse(property.PropertyType, value.ToString());
                            }
                            else
                            {
                                propertyValue = serializer.ConvertToType(value, property.PropertyType);
                            }
                            property.SetValue(instance, propertyValue);
                        }
                    }
                    return instance;
                }
                catch (Exception)
                {
                    return null;
                }
            }
            return null;
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            if (obj != null && Attribute.IsDefined(obj.GetType(), typeof(DataContractAttribute)))
            {
                Type type = obj.GetType();
                IEnumerable<MemberInfo> members = ((IEnumerable<MemberInfo>)type.GetFields())
                    .Concat(type.GetProperties().Where(property => property.CanRead && property.GetIndexParameters().Length == 0))
                    .Where((member) => Attribute.IsDefined(member, typeof(DataMemberAttribute)));
                foreach (MemberInfo member in members)
                {
                    DataMemberAttribute attribute = (DataMemberAttribute)Attribute.GetCustomAttribute(member, typeof(DataMemberAttribute));
                    object value;
                    if (member.MemberType == MemberTypes.Field)
                    {
                        FieldInfo field = (FieldInfo)member;
                        if (ConvertEnumToString && field.FieldType.IsEnum)
                        {
                            value = field.GetValue(obj).ToString();
                        }
                        else
                        {
                            value = field.GetValue(obj);
                        }
                    }
                    else if (member.MemberType == MemberTypes.Property)
                    {
                        PropertyInfo property = (PropertyInfo)member;
                        if (ConvertEnumToString && property.PropertyType.IsEnum)
                        {
                            value = property.GetValue(obj).ToString();
                        }
                        else
                        {
                            value = property.GetValue(obj);
                        }
                    }
                    else
                    {
                        continue;
                    }
                    if (dictionary.ContainsKey(attribute.Name))
                    {
                        throw new SerializationException(String.Format("More than one DataMember found with name {0}", attribute.Name));
                    }
                    dictionary[attribute.Name] = value;
                }
            }
            return dictionary;
        }
    }

Note: This DataContractJavaScriptConverter will only handle DataContract classes defined in the assembly where it is placed. If you want classes from separate assemblies, modify the _supportedTypes list accordingly in the static constructror.

This can be used as follows -

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    serializer.RegisterConverters(new JavaScriptConverter[] { new DataContractJavaScriptConverter(true) });
    DataObject dataObject = serializer.Deserialize<DataObject>(JsonData);

The DataObject class would look like this -

    using System.Runtime.Serialization;

    [DataContract]
    public class DataObject
    {
        [DataMember(Name = "user_id")]
        public int UserId { get; set; }

        [DataMember(Name = "detail_level")]
        public string DetailLevel { get; set; }
    }

Please note that this solution doesn't handle EmitDefaultValue and Order properties supported by DataMember attribute.

PHP foreach with Nested Array?

If you know the number of levels in nested arrays you can simply do nested loops. Like so:

//  Scan through outer loop
foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

if you do not know the depth of array you need to use recursion. See example below:

//  Multi-dementional Source Array
$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(
            7,
            8,
            array("four", 9, 10)
    ))
);

//  Output array
displayArrayRecursively($tmpArray);

/**
 * Recursive function to display members of array with indentation
 *
 * @param array $arr Array to process
 * @param string $indent indentation string
 */
function displayArrayRecursively($arr, $indent='') {
    if ($arr) {
        foreach ($arr as $value) {
            if (is_array($value)) {
                //
                displayArrayRecursively($value, $indent . '--');
            } else {
                //  Output
                echo "$indent $value \n";
            }
        }
    }
}

The code below with display only nested array with values for your specific case (3rd level only)

$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(7, 8, 9))
);

//  Scan through outer loop
foreach ($tmpArray as $inner) {

    //  Check type
    if (is_array($inner)) {
        //  Scan through inner loop
        foreach ($inner[1] as $value) {
           echo "$value \n";
        }
    }
}

Java 8 Lambda function that throws exception?

I use an overloaded utility function called unchecked() which handles multiple use-cases.


SOME EAMPLE USAGES

unchecked(() -> new File("hello.txt").createNewFile());

boolean fileWasCreated = unchecked(() -> new File("hello.txt").createNewFile());

myFiles.forEach(unchecked(file -> new File(file.path).createNewFile()));

SUPPORTING UTILITIES

public class UncheckedUtils {

    @FunctionalInterface
    public interface ThrowingConsumer<T> {
        void accept(T t) throws Exception;
    }

    @FunctionalInterface
    public interface ThrowingSupplier<T> {
        T get() throws Exception;
    }

    @FunctionalInterface
    public interface ThrowingRunnable {
        void run() throws Exception;
    }

    public static <T> Consumer<T> unchecked(
            ThrowingConsumer<T> throwingConsumer
    ) {
        return i -> {
            try {
                throwingConsumer.accept(i);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        };
    }

    public static <T> T unchecked(
            ThrowingSupplier<T> throwingSupplier
    ) {
        try {
            return throwingSupplier.get();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static void unchecked(
            ThrowingRunnable throwing
    ) {
        try {
            throwing.run();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}

error: ‘NULL’ was not declared in this scope

NULL is not a keyword. It's an identifier defined in some standard headers. You can include

#include <cstddef>

To have it in scope, including some other basics, like std::size_t.

Convert Dictionary to JSON in Swift

Swift 5:

let dic = ["2": "B", "1": "A", "3": "C"]
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(dic) {
    if let jsonString = String(data: jsonData, encoding: .utf8) {
        print(jsonString)
    }
}

Note that keys and values must implement Codable. Strings, Ints, and Doubles (and more) are already Codable. See Encoding and Decoding Custom Types.

Copy entire contents of a directory to another using php

With Symfony this is very easy to accomplish:

$fileSystem = new Symfony\Component\Filesystem\Filesystem();
$fileSystem->mirror($from, $to);

See https://symfony.com/doc/current/components/filesystem.html

What is the difference between bottom-up and top-down?

Following is the DP based solution for Edit Distance problem which is top down. I hope it will also help in understanding the world of Dynamic Programming:

public int minDistance(String word1, String word2) {//Standard dynamic programming puzzle.
         int m = word2.length();
            int n = word1.length();


     if(m == 0) // Cannot miss the corner cases !
                return n;
        if(n == 0)
            return m;
        int[][] DP = new int[n + 1][m + 1];

        for(int j =1 ; j <= m; j++) {
            DP[0][j] = j;
        }
        for(int i =1 ; i <= n; i++) {
            DP[i][0] = i;
        }

        for(int i =1 ; i <= n; i++) {
            for(int j =1 ; j <= m; j++) {
                if(word1.charAt(i - 1) == word2.charAt(j - 1))
                    DP[i][j] = DP[i-1][j-1];
                else
                DP[i][j] = Math.min(Math.min(DP[i-1][j], DP[i][j-1]), DP[i-1][j-1]) + 1; // Main idea is this.
            }
        }

        return DP[n][m];
}

You can think of its recursive implementation at your home. It's quite good and challenging if you haven't solved something like this before.

How do I correctly detect orientation change using Phonegap on iOS?

Although the question refers to only PhoneGap and iOS usage, and although it was already answered, I can add a few points to the broader question of detecting screen orientation with JS in 2019:

  1. window.orientation property is deprecated and not supported by Android browsers.There is a newer property that provides more information about the orientation - screen.orientation. But it is still experimental and not supported by iOS Safari. So to achieve the best result you probably need to use the combination of the two: const angle = screen.orientation ? screen.orientation.angle : window.orientation.

  2. As @benallansmith mentioned in his comment, window.onorientationchange event is fired before window.onresize, so you won't get the actual dimensions of the screen unless you add some delay after the orientationchange event.

  3. There is a Cordova Screen Orientation Plugin for supporting older mobile browsers, but I believe there is no need in using it nowadays.

  4. There was also a screen.onorientationchange event, but it is deprecated and should not be used. Added just for completeness of the answer.

In my use-case, I didn't care much about the actual orientation, but rather about the actual width and height of the window, which obviously changes with orientation. So I used resize event to avoid dealing with delays between orientationchange event and actualizing window dimensions:

window.addEventListener('resize', () => {
  console.log(`Actual dimensions: ${window.innerWidth}x${window.innerHeight}`);
  console.log(`Actual orientation: ${screen.orientation ? screen.orientation.angle : window.orientation}`);
});

Note 1: I used EcmaScript 6 syntax here, make sure to compile it to ES5 if needed.

Note 2: window.onresize event is also fired when virtual keyboard is toggled, not only when orientation changes.

Convert canvas to PDF

You can achieve this by utilizing the jsPDF library and the toDataURL function.

I made a little demonstration:

_x000D_
_x000D_
var canvas = document.getElementById('myCanvas');_x000D_
var context = canvas.getContext('2d');_x000D_
_x000D_
// draw a blue cloud_x000D_
context.beginPath();_x000D_
context.moveTo(170, 80);_x000D_
context.bezierCurveTo(130, 100, 130, 150, 230, 150);_x000D_
context.bezierCurveTo(250, 180, 320, 180, 340, 150);_x000D_
context.bezierCurveTo(420, 150, 420, 120, 390, 100);_x000D_
context.bezierCurveTo(430, 40, 370, 30, 340, 50);_x000D_
context.bezierCurveTo(320, 5, 250, 20, 250, 50);_x000D_
context.bezierCurveTo(200, 5, 150, 20, 170, 80);_x000D_
context.closePath();_x000D_
context.lineWidth = 5;_x000D_
context.fillStyle = '#8ED6FF';_x000D_
context.fill();_x000D_
context.strokeStyle = '#0000ff';_x000D_
context.stroke();_x000D_
_x000D_
download.addEventListener("click", function() {_x000D_
  // only jpeg is supported by jsPDF_x000D_
  var imgData = canvas.toDataURL("image/jpeg", 1.0);_x000D_
  var pdf = new jsPDF();_x000D_
_x000D_
  pdf.addImage(imgData, 'JPEG', 0, 0);_x000D_
  pdf.save("download.pdf");_x000D_
}, false);
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>_x000D_
_x000D_
_x000D_
<canvas id="myCanvas" width="578" height="200"></canvas>_x000D_
<button id="download">download</button>
_x000D_
_x000D_
_x000D_

How can I add a hint text to WPF textbox?

I once got into the same situation, I solved it following way. I've only fulfilled the requirements of a hint box, you can make it more interactive by adding effects and other things on other events like on focus etc.

WPF CODE (I've removed styling to make it readable)

<Grid Margin="0,0,0,0"  Background="White">
    <Label Name="adminEmailHint" Foreground="LightGray" Padding="6"  FontSize="14">Admin Email</Label>
    <TextBox Padding="4,7,4,8" Background="Transparent" TextChanged="adminEmail_TextChanged" Height="31" x:Name="adminEmail" Width="180" />
</Grid>
<Grid Margin="10,0,10,0" Background="White" >
    <Label Name="adminPasswordHint" Foreground="LightGray" Padding="6"  FontSize="14">Admin Password</Label>
    <PasswordBox Padding="4,6,4,8" Background="Transparent" PasswordChanged="adminPassword_PasswordChanged" Height="31" x:Name="adminPassword" VerticalContentAlignment="Center" VerticalAlignment="Center" Width="180" FontFamily="Helvetica" FontWeight="Light" FontSize="14" Controls:TextBoxHelper.Watermark="Admin Password"  FontStyle="Normal" />
</Grid>

C# Code

private void adminEmail_TextChanged(object sender, TextChangedEventArgs e)
    {
        if(adminEmail.Text.Length == 0)
        {
            adminEmailHint.Visibility = Visibility.Visible;
        }
        else
        {
            adminEmailHint.Visibility = Visibility.Hidden;
        }
    }

private void adminPassword_PasswordChanged(object sender, RoutedEventArgs e)
    {
        if (adminPassword.Password.Length == 0)
        {
            adminPasswordHint.Visibility = Visibility.Visible;
        }
        else
        {
            adminPasswordHint.Visibility = Visibility.Hidden;
        }
    }

how to use Spring Boot profiles

I'm not sure I fully understand the question but I'll attempt to answer by providing a few details about profiles in Spring Boot.

For your #1 example, according to the docs you can select the profile using the Spring Boot Maven plugin using -Drun.profiles.

Edit: For Spring Boot 2.0+ run has been renamed to spring-boot.run and run.profiles has been renamed to spring-boot.run.profiles

mvn spring-boot:run -Dspring-boot.run.profiles=dev

https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/maven-plugin/examples/run-profiles.html

From your #2 example, you are defining the active profile after the name of the jar. You need to provide the JVM argument before the name of the jar you are running.

java -jar -Dspring.profiles.active=dev XXX.jar

General info:

You mention that you have both an application.yml and a application-dev.yml. Running with the dev profile will actually load both config files. Values from application-dev.yml will override the same values provided by application.yml but values from both yml files will be loaded.

There are also multiple ways to define the active profile.

You can define them as you did, using -Dspring.profiles.active when running your jar. You can also set the profile using a SPRING_PROFILES_ACTIVE environment variable or a spring.profiles.active system property.

More info can be found here: https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-set-active-spring-profiles

In Excel, sum all values in one column in each row where another column is a specific value

You should be able to use the IF function for that. the syntax is =IF(condition, value_if_true, value_if_false). To add an extra column with only the non-reimbursed amounts, you would use something like:

=IF(B1="No", A1, 0)

and sum that. There's probably a way to include it in a single cell below the column as well, but off the top of my head I can't think of anything simple.

firefox proxy settings via command line

Just wanted to post the code in a cleaner format... originally posted by sam3344920

cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
cd *.default
set ffile=%cd%
echo user_pref("network.proxy.http", "148.233.229.235 ");>>"%ffile%\prefs.js"
echo user_pref("network.proxy.http_port", 3128);>>"%ffile%\prefs.js"
echo user_pref("network.proxy.type", 1);>>"%ffile%\prefs.js"
set ffile=
cd %windir%

If someone wants to remove the proxy settings, here is some code that will do that for you.

cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
cd *.default
set ffile=%cd%
type "%ffile%\prefs.js" | findstr /v "user_pref("network.proxy.type", 1);" >"%ffile%\prefs_.js"
rename "%ffile%\prefs.js" "prefs__.js"
rename "%ffile%\prefs_.js" "prefs.js"
del "%ffile%\prefs__.js"
set ffile=
cd %windir%

Explanation: The code goes and finds the perfs.js file. Then looks within it to find the line "user_pref("network.proxy.type", 1);". If it finds it, it deletes the file with the /v parameter. The reason I added the rename and delete lines is because I couldn't find a way to overwrite the file once I had removed the proxy line. I'm sure there is a more efficient/safer way of doing this...

What is the technology behind wechat, whatsapp and other messenger apps?

WhatsApp has chosen Erlang a language built for writing scalable applications that are designed to withstand errors. Erlang uses an abstraction called the Actor model for it's concurrency - http://en.wikipedia.org/wiki/Actor_(programming_language) Instead of the more traditional shared memory approach, actors communicate by sending each other messages. Actors unlike threads are designed to be lightweight. Actors could be on the same machine or on different machines and the message passing abstractions works for both. A simple implementation of WhatsApp could be: Each user/device is represented as an actor. This actor is responsible for handling the inbox of the user, how it gets serialized to disk, the messages that the user sends and the messages that the user receives. Let's assume that Alice and Bob are friends on WhatsApp. So there is an an Alice actor and a Bob actor.

Let's trace a series of messages flowing back and forth:

Alice decides to message Bob. Alice's phone establishes a connection to the WhatsApp server and it is established that this connection is definitely from Alice's phone. Alice now sends via TCP the following message: "For Bob: A giant monster is attacking the Golden Gate Bridge". One of the WhatsApp front end server deserializes this message and delivers this message to the actor called Alice.

Alice the actor decides to serialize this and store it in a file called "Alice's Sent Messages", stored on a replicated file system to prevent data loss due to unpredictable monster rampage. Alice the actor then decides to forward this message to Bob the actor by passing it a message "Msg1 from Alice: A giant monster is attacking the Golden Gate Bridge". Alice the actor can retry with exponential back-off till Bob the actor acknowledges receiving the message.

Bob the actor eventually receives the message from (2) and decides to store this message in a file called "Bob's Inbox". Once it has stored this message durably Bob the actor will acknowledge receiving the message by sending Alice the actor a message of it's own saying "I received Msg1". Alice the actor can now stop it's retry efforts. Bob the actor then checks to see if Bob's phone has an active connection to the server. It does and so Bob the actor streams this message to the device via TCP.

Bob sees this message and replies with "For Alice: Let's create giant robots to fight them". This is now received by Bob the actor as outlined in Step 1. Bob the actor then repeats Step 2 and 3 to make sure Alice eventually receives the idea that will save mankind.

WhatsApp actually uses the XMPP protocol instead of the vastly superior protocol that I outlined above, but you get the point.

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

My problem was; None admin users were getting "the http request is unauthorized with client authentication scheme 'negotiate' asmx" on my asmx services.

I gived read/execute folder permissions for the none admin users and my problem was solved.

How to embed a SWF file in an HTML page?

If you are using one of those js libraries to insert Flash, I suggest adding plain object embed tag inside of <noscript/>.

How to check that a string is parseable to a double?

Apache, as usual, has a good answer from Apache Commons-Lang in the form of NumberUtils.isCreatable(String).

Handles nulls, no try/catch block required.

RegEx for matching UK Postcodes

There is no such thing as a comprehensive UK postcode regular expression that is capable of validating a postcode. You can check that a postcode is in the correct format using a regular expression; not that it actually exists.

Postcodes are arbitrarily complex and constantly changing. For instance, the outcode W1 does not, and may never, have every number between 1 and 99, for every postcode area.

You can't expect what is there currently to be true forever. As an example, in 1990, the Post Office decided that Aberdeen was getting a bit crowded. They added a 0 to the end of AB1-5 making it AB10-50 and then created a number of postcodes in between these.

Whenever a new street is build a new postcode is created. It's part of the process for obtaining permission to build; local authorities are obliged to keep this updated with the Post Office (not that they all do).

Furthermore, as noted by a number of other users, there's the special postcodes such as Girobank, GIR 0AA, and the one for letters to Santa, SAN TA1 - you probably don't want to post anything there but it doesn't appear to be covered by any other answer.

Then, there's the BFPO postcodes, which are now changing to a more standard format. Both formats are going to be valid. Lastly, there's the overseas territories source Wikipedia.

+----------+----------------------------------------------+
| Postcode |                   Location                   |
+----------+----------------------------------------------+
| AI-2640  | Anguilla                                     |
| ASCN 1ZZ | Ascension Island                             |
| STHL 1ZZ | Saint Helena                                 |
| TDCU 1ZZ | Tristan da Cunha                             |
| BBND 1ZZ | British Indian Ocean Territory               |
| BIQQ 1ZZ | British Antarctic Territory                  |
| FIQQ 1ZZ | Falkland Islands                             |
| GX11 1AA | Gibraltar                                    |
| PCRN 1ZZ | Pitcairn Islands                             |
| SIQQ 1ZZ | South Georgia and the South Sandwich Islands |
| TKCA 1ZZ | Turks and Caicos Islands                     |
+----------+----------------------------------------------+

Next, you have to take into account that the UK "exported" its postcode system to many places in the world. Anything that validates a "UK" postcode will also validate the postcodes of a number of other countries.

If you want to validate a UK postcode the safest way to do it is to use a look-up of current postcodes. There are a number of options:

  • Ordnance Survey releases Code-Point Open under an open data licence. It'll be very slightly behind the times but it's free. This will (probably - I can't remember) not include Northern Irish data as the Ordnance Survey has no remit there. Mapping in Northern Ireland is conducted by the Ordnance Survey of Northern Ireland and they have their, separate, paid-for, Pointer product. You could use this and append the few that aren't covered fairly easily.

  • Royal Mail releases the Postcode Address File (PAF), this includes BFPO which I'm not sure Code-Point Open does. It's updated regularly but costs money (and they can be downright mean about it sometimes). PAF includes the full address rather than just postcodes and comes with its own Programmers Guide. The Open Data User Group (ODUG) is currently lobbying to have PAF released for free, here's a description of their position.

  • Lastly, there's AddressBase. This is a collaboration between Ordnance Survey, Local Authorities, Royal Mail and a matching company to create a definitive directory of all information about all UK addresses (they've been fairly successful as well). It's paid-for but if you're working with a Local Authority, government department, or government service it's free for them to use. There's a lot more information than just postcodes included.

Where does Java's String constant pool live, the heap or the stack?

As other answers explain Memory in Java is divided into two portions

1. Stack: One stack is created per thread and it stores stack frames which again stores local variables and if a variable is a reference type then that variable refers to a memory location in heap for the actual object.

2. Heap: All kinds of objects will be created in heap only.

Heap memory is again divided into 3 portions

1. Young Generation: Stores objects which have a short life, Young Generation itself can be divided into two categories Eden Space and Survivor Space.

2. Old Generation: Store objects which have survived many garbage collection cycles and still being referenced.

3. Permanent Generation: Stores metadata about the program e.g. runtime constant pool.

String constant pool belongs to the permanent generation area of Heap memory.

We can see the runtime constant pool for our code in the bytecode by using javap -verbose class_name which will show us method references (#Methodref), Class objects ( #Class ), string literals ( #String )

runtime-constant-pool

You can read more about it on my article How Does JVM Handle Method Overloading and Overriding Internally.

How to Customize the time format for Python logging?

From the official documentation regarding the Formatter class:

The constructor takes two optional arguments: a message format string and a date format string.

So change

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

to

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")

What is the correct wget command syntax for HTTPS with username and password?

By specifying the option --user and --ask-password wget will ask for the credentials. Below is an example. Change the username and download link to your needs.

wget --user=username --ask-password https://xyz.com/changelog-6.40.txt

Access multiple elements of list knowing their index

Alternatives:

>>> map(a.__getitem__, b)
[1, 5, 5]

>>> import operator
>>> operator.itemgetter(*b)(a)
(1, 5, 5)

Using iText to convert HTML to PDF

When I needed HTML to PDF conversion earlier this year, I tried the trial of Winnovative HTML to PDF converter (I think ExpertPDF is the same product, too). It worked great so we bought a license at that company. I don't go into it too in depth after that.

Wrapping long text without white space inside of a div

white-space: pre-wrap

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

How can I insert into a BLOB column from an insert statement in sqldeveloper?

To insert a VARCHAR2 into a BLOB column you can rely on the function utl_raw.cast_to_raw as next:

insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));

It will cast your input VARCHAR2 into RAW datatype without modifying its content, then it will insert the result into your BLOB column.

More details about the function utl_raw.cast_to_raw

Apply a function to every row of a matrix or a data frame

Here is a short example of applying a function to each row of a matrix. (Here, the function applied normalizes every row to 1.)

Note: The result from the apply() had to be transposed using t() to get the same layout as the input matrix A.

A <- matrix(c(
  0, 1, 1, 2,
  0, 0, 1, 3,
  0, 0, 1, 3
), nrow = 3, byrow = TRUE)

t(apply(A, 1, function(x) x / sum(x) ))

Result:

     [,1] [,2] [,3] [,4]
[1,]    0 0.25 0.25 0.50
[2,]    0 0.00 0.25 0.75
[3,]    0 0.00 0.25 0.75

Wait .5 seconds before continuing code VB.net

In web application a timer will be the best approach.

Just fyi, in desktop application I use this instead, inside an async method.

... 
Await Task.Run(Sub()
    System.Threading.Thread.Sleep(5000)
End Sub)
...

It work for me, importantly it doesn't freeze entire screen. But again this is on desktop, i try in web application it does freeze.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

I had this same issue and a couple others being reported for a existing maven project.

I had the proper dependencies in place and I could see the jar under maven dependencies, however the project was improperly brought into eclipse.

I ended up having to delete the project, clone from git again then do an import of the project as an existing maven project.

This solved the issue in this thread and several others issues I was having. More details on solution can be found here: Maven Project in Eclipse `org.springframework cannot be resolved to a type` from target path

How to trim white space from all elements in array?

String val = "hi hello prince";
String arr[] = val.split(" ");

for (int i = 0; i < arr.length; i++)
{   
     System.out.print(arr[i]);
}

How to list files in an android directory?

I just discovered that:

new File("/sdcard/").listFiles() returns null if you do not have:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

set in your AndroidManifest.xml file.

SQL - Update multiple records in one query

instead of this

UPDATE staff SET salary = 1200 WHERE name = 'Bob';
UPDATE staff SET salary = 1200 WHERE name = 'Jane';
UPDATE staff SET salary = 1200 WHERE name = 'Frank';
UPDATE staff SET salary = 1200 WHERE name = 'Susan';
UPDATE staff SET salary = 1200 WHERE name = 'John';

you can use

UPDATE staff SET salary = 1200 WHERE name IN ('Bob', 'Frank', 'John');

Reading Excel files from C#

I want to show a simple method to read xls/xlsx file with .NET. I hope that the following will be helpful for you.

 private DataTable ReadExcelToTable(string path)    
 {

     //Connection String

     string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";  
     //the same name 
     //string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + //";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; 

     using(OleDbConnection conn = new OleDbConnection(connstring))
     {
        conn.Open();
        //Get All Sheets Name
        DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"});  

        //Get the First Sheet Name
        string firstSheetName = sheetsName.Rows[0][2].ToString(); 

        //Query String 
        string sql = string.Format("SELECT * FROM [{0}]",firstSheetName); 
        OleDbDataAdapter ada =new OleDbDataAdapter(sql,connstring);
        DataSet set = new DataSet();
        ada.Fill(set);
        return set.Tables[0];   
   }
 }

Code is from article: http://www.c-sharpcorner.com/uploadfile/d2dcfc/read-excel-file-with-net/. You can get more details from it.

Pythonically add header to a csv file

The DictWriter() class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer() and pass in a simple row for the header:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.writer(outcsv)
    writer.writerow(["Date", "temperature 1", "Temperature 2"])

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

The alternative would be to generate dictionaries when copying across your data:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
    writer.writeheader()

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)

PostgreSQL: days/months/years between two dates

One more solution, version for the 'years' difference:

SELECT count(*) - 1 FROM (SELECT distinct(date_trunc('year', generate_series('2010-04-01'::timestamp, '2012-03-05', '1 week')))) x

    2

(1 row)

And the same trick for the months:

SELECT count(*) - 1 FROM (SELECT distinct(date_trunc('month', generate_series('2010-04-01'::timestamp, '2012-03-05', '1 week')))) x

   23

(1 row)

In real life query there can be some timestamp sequences grouped by hour/day/week/etc instead of generate_series.

This 'count(distinct(date_trunc('month', ts)))' can be used right in the 'left' side of the select:

SELECT sum(a - b)/count(distinct(date_trunc('month', c))) FROM d

I used generate_series() here just for the brevity.

Is there a php echo/print equivalent in javascript

// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

Using window.log will allow you to perform the same action as console.log, but it checks if the browser you are using has the ability to use console.log first, so as not to error out for compatibility reasons (IE 6, etc.).

Current timestamp as filename in Java

You can get the current timestamp appended with a file extension in the following way:

String fileName = new Date().getTime() + ".txt";

Removing a list of characters in string

Why not a simple loop?

for i in replace_list:
    string = string.replace(i, '')

Also, avoid naming lists 'list'. It overrides the built-in function list.

How can I convert ticks to a date format?

A DateTime object can be constructed with a specific value of ticks. Once you have determined the ticks value, you can do the following:

DateTime myDate = new DateTime(numberOfTicks);
String test = myDate.ToString("MMMM dd, yyyy");

Iterating over every property of an object in javascript using Prototype?

There's no need for Prototype here: JavaScript has for..in loops. If you're not sure that no one messed with Object.prototype, check hasOwnProperty() as well, ie

for(var prop in obj) {
    if(obj.hasOwnProperty(prop))
        doSomethingWith(obj[prop]);
}

How to check if a column is empty or null using SQL query select statement?

Here's a slightly different way:

SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
  AND (LEN(ISNULL(PropertyValue,'')) = 0)

What's the difference between VARCHAR and CHAR?

CHAR is a fixed length field; VARCHAR is a variable length field. If you are storing strings with a wildly variable length such as names, then use a VARCHAR, if the length is always the same, then use a CHAR because it is slightly more size-efficient, and also slightly faster.

jquery fill dropdown with json data

If your data is already in array form, it's really simple using jQuery:

 $(data.msg).each(function()
 {
     alert(this.value);
     alert(this.label);

     //this refers to the current item being iterated over

     var option = $('<option />');
     option.attr('value', this.value).text(this.label);

     $('#myDropDown').append(option);
 });

.ajax() is more flexible than .getJSON() - for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().

CSS 100% height with padding/margin

A solution with flexbox (working on IE11): (or view on jsfiddle)

<html>
  <style>
    html, body {
      height: 100%; /* fix for IE11, not needed for chrome/ff */
      margin: 0; /* CSS-reset for chrome */
    }
  </style>
  <body style="display: flex;">
    <div style="background-color: black; flex: 1; margin: 25px;"></div>
  </body>
</html>

(The CSS-reset is not necessarily important for the actual problem.)

The important part is flex: 1 (In combination with display: flex at the parent). Funnily enough, the most plausible explanation I know for how the Flex property works comes from a react-native documentation, so I refer to it anyway:

(...) flex: 1, which tells a component to fill all available space, shared evenly amongst other components with the same parent

java.io.InvalidClassException: local class incompatible:

If you are using the Eclipse IDE, check your Debug/Run configuration. At Classpath tab, select the runner project and click Edit button. Only include exported entries must be checked.

how to enable sqlite3 for php?

Only use:

sudo apt-get install php5-sqlite

and later

sudo service apache2 restart

Can I change the scroll speed using css or jQuery?

The scroll speed CAN be changed, adjusted, reversed, all of the above - via javascript (or a js library such as jQuery).

WHY would you want to do this? Parallax is just one of the reasons. I have no idea why anyone would argue against doing so -- the same negative arguments can be made against hiding DIVs, sliding elements up/down, etc. Websites are always a combination of technical functionality and UX design -- a good designer can use almost any technical capability to improve UX. That is what makes him/her good.

Toni Almeida of Portugal created a brilliant demo, reproduced below:

jsFiddle Demo

HTML:

<div id="myDiv">
    Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. <span class="boldit">Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. </span>
</div>

javascript/jQuery:

  function wheel(event) {
      var delta = 0;
      if (event.wheelDelta) {(delta = event.wheelDelta / 120);}
      else if (event.detail) {(delta = -event.detail / 3);}

      handle(delta);
      if (event.preventDefault) {(event.preventDefault());}
      event.returnValue = false;
  }

  function handle(delta) {
      var time = 1000;
      var distance = 300;

      $('html, body').stop().animate({
          scrollTop: $(window).scrollTop() - (distance * delta)
      }, time );
  }

  if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);}
    window.onmousewheel = document.onmousewheel = wheel;

Source:

How to change default scrollspeed,scrollamount,scrollinertia of a webpage

How to use particular CSS styles based on screen size / device

Detection is automatic. You must specify what css can be used for each screen resolution:

/* for all screens, use 14px font size */
body {  
    font-size: 14px;    
}
/* responsive, form small screens, use 13px font size */
@media (max-width: 479px) {
    body {
        font-size: 13px;
    }
}

visual c++: #include files from other projects in the same solution

Expanding on @Benav's answer, my preferred approach is to:

  1. Add the solution directory to your include paths:
    • right click on your project in the Solution Explorer
    • select Properties
    • select All Configurations and All Platforms from the drop-downs
    • select C/C++ > General
    • add $(SolutionDir) to the Additional Include Directories
  2. Add references to each project you want to use:
    • right click on your project's References in the Solution Explorer
    • select Add Reference...
    • select the project(s) you want to refer to

Now you can include headers from your referenced projects like so:

#include "OtherProject/Header.h"

Notes:

  • This assumes that your solution file is stored one folder up from each of your projects, which is the default organization when creating projects with Visual Studio.
  • You could now include any file from a path relative to the solution folder, which may not be desirable but for the simplicity of the approach I'm ok with this.
  • Step 2 isn't necessary for #includes, but it sets the correct build dependencies, which you probably want.

Import file size limit in PHPMyAdmin

I had the same problem, My upload limit was 2 MB, I edited my php.ini, and I set it to 5 MB but still it was showing 2 MB even after restarting server. Than I compressed my .sql file to zip by keeping its name as xyz.sql.zip so it became 451 kb from 3.5 mb. Then I uploaded it again. It worked for me.

Get operating system info

If you want very few info like a class in your html for common browsers for instance, you could use:

function get_browser()
{
    $browser = '';
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
    elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];

    return $browser;
}

which will return 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.

kubectl apply vs kubectl create?

Those are two different approaches:

Imperative Management

kubectl create is what we call Imperative Management. On this approach you tell the Kubernetes API what you want to create, replace or delete, not how you want your K8s cluster world to look like.

Declarative Management

kubectl apply is part of the Declarative Management approach, where changes that you may have applied to a live object (i.e. through scale) are "maintained" even if you apply other changes to the object.

You can read more about imperative and declarative management in the Kubernetes Object Management documentation.

PHP memcached Fatal error: Class 'Memcache' not found

There are two extensions for memcached in PHP, "memcache" and "memcached".

It looks like you're trying to use one ("memcache"), but the other is installed ("memcached").

How to randomly select an item from a list?

Random item selection:

import random

my_list = [1, 2, 3, 4, 5]
num_selections = 2

new_list = random.sample(my_list, num_selections)

To preserve the order of the list, you could do:

randIndex = random.sample(range(len(my_list)), n_selections)
randIndex.sort()
new_list = [my_list[i] for i in randIndex]

Duplicate of https://stackoverflow.com/a/49682832/4383027

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

You will get this error when you call any of the setXxx() methods on PreparedStatement, while the SQL query string does not have any placeholders ? for this.

For example this is wrong:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

You need to fix the SQL query string accordingly to specify the placeholders.

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

Note the parameter index starts with 1 and that you do not need to quote those placeholders like so:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";

Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.

See also:

How can I simulate a print statement in MySQL?

If you do not want to the text twice as column heading as well as value, use the following stmt!

SELECT 'some text' as '';

Example:

mysql>SELECT 'some text' as ''; +-----------+ | | +-----------+ | some text | +-----------+ 1 row in set (0.00 sec)

Getting the difference between two sets

If you use Guava (former Google Collections) library there is a solution:

SetView<Number> difference = com.google.common.collect.Sets.difference(test2, test1);

The returned SetView is a Set, it is a live representation you can either make immutable or copy to another set. test1 and test2 are left intact.