Programs & Examples On #Fgets

Anything related to C or C++ standard library functions `fgets` (C) or `std::fgets` (C++). These functions are used to read a sequence of characters from an input stream and to write it into a character buffer as a string.

Read each line of txt file to new array element

Just use this:

$array = explode("\n", file_get_contents('file.txt'));

Why is the gets function so dangerous that it should not be used?

Because gets doesn't do any kind of check while getting bytes from stdin and putting them somewhere. A simple example:

char array1[] = "12345";
char array2[] = "67890";

gets(array1);

Now, first of all you are allowed to input how many characters you want, gets won't care about it. Secondly the bytes over the size of the array in which you put them (in this case array1) will overwrite whatever they find in memory because gets will write them. In the previous example this means that if you input "abcdefghijklmnopqrts" maybe, unpredictably, it will overwrite also array2 or whatever.

The function is unsafe because it assumes consistent input. NEVER USE IT!

How to read from stdin with fgets()?

Assuming that you only want to read a single line, then use LINE_MAX, which is defined in <limits.h>:

#include <stdio.h>
#include <limits.h>
...
char line[LINE_MAX];
...
if (fgets(line, LINE_MAX, stdin) != NULL) {
...
}
...

Removing trailing newline character from fgets() input

The elegant way:

Name[strcspn(Name, "\n")] = 0;

The slightly ugly way:

char *pos;
if ((pos=strchr(Name, '\n')) != NULL)
    *pos = '\0';
else
    /* input too long for buffer, flag error */

The slightly strange way:

strtok(Name, "\n");

Note that the strtok function doesn't work as expected if the user enters an empty string (i.e. presses only Enter). It leaves the \n character intact.

There are others as well, of course.

Apply Calibri (Body) font to text

There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).

So use just font-family: Calibri or, better, font-family: Calibri, sans-serif. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)

How to prevent Browser cache for php site

I had problem with caching my css files. Setting headers in PHP didn't help me (perhaps because the headers would need to be set in the stylesheet file instead of the page linking to it?).

I found the solution on this page: https://css-tricks.com/can-we-prevent-css-caching/

The solution:

Append timestamp as the query part of the URI for the linked file.
(Can be used for css, js, images etc.)

For development:

<link rel="stylesheet" href="style.css?<?php echo date('Y-m-d_H:i:s'); ?>">

For production (where caching is mostly a good thing):

<link rel="stylesheet" type="text/css" href="style.css?version=3.2">
(and rewrite manually when it is required)

Or combination of these two:

<?php
    define( "DEBUGGING", true ); // or false in production enviroment
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo (DEBUGGING) ? date('_Y-m-d_H:i:s') : ""; ?>">

EDIT:

Or prettier combination of those two:

<?php
    // Init
    define( "DEBUGGING", true ); // or false in production enviroment
    // Functions
    function get_cache_prevent_string( $always = false ) {
        return (DEBUGGING || $always) ? date('_Y-m-d_H:i:s') : "";
    }
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo get_cache_prevent_string(); ?>">

How to convert an NSTimeInterval (seconds) into minutes

All of these look more complicated than they need to be! Here is a short and sweet way to convert a time interval into hours, minutes and seconds:

NSTimeInterval timeInterval = 326.4;
long seconds = lroundf(timeInterval); // Since modulo operator (%) below needs int or long

int hour = seconds / 3600;
int mins = (seconds % 3600) / 60;
int secs = seconds % 60;

Note when you put a float into an int, you get floor() automatically, but you can add it to the first two if if makes you feel better :-)

Relative Paths in Javascript in an external file

get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:

var jsFileLocation = $('script[src*=example]').attr('src');  // the js file path
jsFileLocation = jsFileLocation.replace('example.js', '');   // the js folder path

(assuming your javascript file is named 'example.js')

Parsing JSON in Excel VBA

Lots of good answers here - just chipping in my own.

I had a requirement to parse a very specific JSON string, representing the results of making a web-API call. The JSON described a list of objects, and looked something like this:

[
   {
     "property1": "foo",
     "property2": "bar",
     "timeOfDay": "2019-09-30T00:00:00",
     "numberOfHits": 98,
     "isSpecial": false,
     "comment": "just to be awkward, this contains a comma"
   },
   {
     "property1": "fool",
     "property2": "barrel",
     "timeOfDay": "2019-10-31T00:00:00",
     "numberOfHits": 11,
     "isSpecial": false,
     "comment": null
   },
   ...
]

There are a few things to note about this:

  1. The JSON should always describe a list (even if empty), which should only contain objects.
  2. The objects in the list should only contain properties with simple types (string / date / number / boolean or null).
  3. The value of a property may contain a comma - which makes parsing the JSON somewhat harder - but may not contain any quotes (because I'm too lazy to deal with that).

The ParseListOfObjects function in the code below takes the JSON string as input, and returns a Collection representing the items in the list. Each item is represented as a Dictionary, where the keys of the dictionary correspond to the names of the object's properties. The values are automatically converted to the appropriate type (String, Date, Double, Boolean - or Empty if the value is null).

Your VBA project will need a reference to the Microsoft Scripting Runtime library to use the Dictionary object - though it would not be difficult to remove this dependency if you use a different way of encoding the results.

Here's my JSON.bas:

Option Explicit

' NOTE: a fully-featured JSON parser in VBA would be a beast.
' This simple parser only supports VERY simple JSON (which is all we need).
' Specifically, it supports JSON comprising a list of objects, each of which has only simple properties.

Private Const strSTART_OF_LIST As String = "["
Private Const strEND_OF_LIST As String = "]"

Private Const strLIST_DELIMITER As String = ","

Private Const strSTART_OF_OBJECT As String = "{"
Private Const strEND_OF_OBJECT As String = "}"

Private Const strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR As String = ":"

Private Const strQUOTE As String = """"

Private Const strNULL_VALUE As String = "null"
Private Const strTRUE_VALUE As String = "true"
Private Const strFALSE_VALUE As String = "false"


Public Function ParseListOfObjects(ByVal strJson As String) As Collection

    ' Takes a JSON string that represents a list of objects (where each object has only simple value properties), and
    ' returns a collection of dictionary objects, where the keys and values of each dictionary represent the names and
    ' values of the JSON object properties.

    Set ParseListOfObjects = New Collection

    Dim strList As String: strList = Trim(strJson)

    ' Check we have a list
    If Left(strList, Len(strSTART_OF_LIST)) <> strSTART_OF_LIST _
    Or Right(strList, Len(strEND_OF_LIST)) <> strEND_OF_LIST Then
        Err.Raise vbObjectError, Description:="The provided JSON does not appear to be a list (it does not start with '" & strSTART_OF_LIST & "' and end with '" & strEND_OF_LIST & "')"
    End If

    ' Get the list item text (between the [ and ])
    Dim strBody As String: strBody = Trim(Mid(strList, 1 + Len(strSTART_OF_LIST), Len(strList) - Len(strSTART_OF_LIST) - Len(strEND_OF_LIST)))

    If strBody = "" Then
        Exit Function
    End If

    ' Check we have a list of objects
    If Left(strBody, Len(strSTART_OF_OBJECT)) <> strSTART_OF_OBJECT Then
        Err.Raise vbObjectError, Description:="The provided JSON does not appear to be a list of objects (the content of the list does not start with '" & strSTART_OF_OBJECT & "')"
    End If

    ' We now have something like:
    '    {"property":"value", "property":"value"}, {"property":"value", "property":"value"}, ...
    ' so we can't just split on a comma to get the various items (because the items themselves have commas in them).
    ' HOWEVER, since we know we're dealing with very simple JSON that has no nested objects, we can split on "}," because
    ' that should only appear between items. That'll mean that all but the last item will be missing it's closing brace.
    Dim astrItems() As String: astrItems = Split(strBody, strEND_OF_OBJECT & strLIST_DELIMITER)

    Dim ixItem As Long
    For ixItem = LBound(astrItems) To UBound(astrItems)

        Dim strItem As String: strItem = Trim(astrItems(ixItem))

        If Left(strItem, Len(strSTART_OF_OBJECT)) <> strSTART_OF_OBJECT Then
            Err.Raise vbObjectError, Description:="Mal-formed list item (does not start with '" & strSTART_OF_OBJECT & "')"
        End If

        ' Only the last item will have a closing brace (see comment above)
        Dim bIsLastItem As Boolean: bIsLastItem = ixItem = UBound(astrItems)

        If bIsLastItem Then
            If Right(strItem, Len(strEND_OF_OBJECT)) <> strEND_OF_OBJECT Then
                Err.Raise vbObjectError, Description:="Mal-formed list item (does not end with '" & strEND_OF_OBJECT & "')"
            End If
        End If

        Dim strContent: strContent = Mid(strItem, 1 + Len(strSTART_OF_OBJECT), Len(strItem) - Len(strSTART_OF_OBJECT) - IIf(bIsLastItem, Len(strEND_OF_OBJECT), 0))

        ParseListOfObjects.Add ParseObjectContent(strContent)

    Next ixItem

End Function

Private Function ParseObjectContent(ByVal strContent As String) As Scripting.Dictionary

    Set ParseObjectContent = New Scripting.Dictionary
    ParseObjectContent.CompareMode = TextCompare

    ' The object content will look something like:
    '    "property":"value", "property":"value", ...
    ' ... although the value may not be in quotes, since numbers are not quoted.
    ' We can't assume that the property value won't contain a comma, so we can't just split the
    ' string on the commas, but it's reasonably safe to assume that the value won't contain further quotes
    ' (and we're already assuming no sub-structure).
    ' We'll need to scan for commas while taking quoted strings into account.

    Dim ixPos As Long: ixPos = 1
    Do While ixPos <= Len(strContent)

        Dim strRemainder As String

        ' Find the opening quote for the name (names should always be quoted)
        Dim ixOpeningQuote As Long: ixOpeningQuote = InStr(ixPos, strContent, strQUOTE)

        If ixOpeningQuote <= 0 Then
            ' The only valid reason for not finding a quote is if we're at the end (though white space is permitted)
            strRemainder = Trim(Mid(strContent, ixPos))
            If Len(strRemainder) = 0 Then
                Exit Do
            End If
            Err.Raise vbObjectError, Description:="Mal-formed object (the object name does not start with a quote)"
        End If

        ' Now find the closing quote for the name, which we assume is the very next quote
        Dim ixClosingQuote As Long: ixClosingQuote = InStr(ixOpeningQuote + 1, strContent, strQUOTE)
        If ixClosingQuote <= 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (the object name does not end with a quote)"
        End If

        If ixClosingQuote - ixOpeningQuote - Len(strQUOTE) = 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (the object name is blank)"
        End If

        Dim strName: strName = Mid(strContent, ixOpeningQuote + Len(strQUOTE), ixClosingQuote - ixOpeningQuote - Len(strQUOTE))

        ' The next thing after the quote should be the colon

        Dim ixNameValueSeparator As Long: ixNameValueSeparator = InStr(ixClosingQuote + Len(strQUOTE), strContent, strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)

        If ixNameValueSeparator <= 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (missing '" & strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR & "')"
        End If

        ' Check that there was nothing between the closing quote and the colon

        strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE), ixNameValueSeparator - ixClosingQuote - Len(strQUOTE)))
        If Len(strRemainder) > 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (unexpected content between name and '" & strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR & "')"
        End If

        ' What comes after the colon is the value, which may or may not be quoted (e.g. numbers are not quoted).
        ' If the very next thing we see is a quote, then it's a quoted value, and we need to find the matching
        ' closing quote while ignoring any commas inside the quoted value.
        ' If the next thing we see is NOT a quote, then it must be an unquoted value, and we can scan directly
        ' for the next comma.
        ' Either way, we're looking for a quote or a comma, whichever comes first (or neither, in which case we
        ' have the last - unquoted - value).

        ixOpeningQuote = InStr(ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), strContent, strQUOTE)
        Dim ixPropertySeparator As Long: ixPropertySeparator = InStr(ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), strContent, strLIST_DELIMITER)

        If ixOpeningQuote > 0 And ixPropertySeparator > 0 Then
            ' Only use whichever came first
            If ixOpeningQuote < ixPropertySeparator Then
                ixPropertySeparator = 0
            Else
                ixOpeningQuote = 0
            End If
        End If

        Dim strValue As String
        Dim vValue As Variant

        If ixOpeningQuote <= 0 Then ' it's not a quoted value

            If ixPropertySeparator <= 0 Then ' there's no next value; this is the last one
                strValue = Trim(Mid(strContent, ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)))
                ixPos = Len(strContent) + 1
            Else ' this is not the last value
                strValue = Trim(Mid(strContent, ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), ixPropertySeparator - ixNameValueSeparator - Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)))
                ixPos = ixPropertySeparator + Len(strLIST_DELIMITER)
            End If

            vValue = ParseUnquotedValue(strValue)

        Else ' It is a quoted value

            ' Find the corresponding closing quote, which should be the very next one

            ixClosingQuote = InStr(ixOpeningQuote + Len(strQUOTE), strContent, strQUOTE)

            If ixClosingQuote <= 0 Then
                Err.Raise vbObjectError, Description:="Mal-formed object (the value does not end with a quote)"
            End If

            strValue = Mid(strContent, ixOpeningQuote + Len(strQUOTE), ixClosingQuote - ixOpeningQuote - Len(strQUOTE))
            vValue = ParseQuotedValue(strValue)

            ' Re-scan for the property separator, in case we hit one that was part of the quoted value
            ixPropertySeparator = InStr(ixClosingQuote + Len(strQUOTE), strContent, strLIST_DELIMITER)

            If ixPropertySeparator <= 0 Then ' this was the last value

                ' Check that there's nothing between the closing quote and the end of the text
                strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE)))
                If Len(strRemainder) > 0 Then
                    Err.Raise vbObjectError, Description:="Mal-formed object (there is content after the last value)"
                End If

                ixPos = Len(strContent) + 1

            Else ' this is not the last value

                ' Check that there's nothing between the closing quote and the property separator
                strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE), ixPropertySeparator - ixClosingQuote - Len(strQUOTE)))
                If Len(strRemainder) > 0 Then
                    Err.Raise vbObjectError, Description:="Mal-formed object (there is content after the last value)"
                End If

                ixPos = ixPropertySeparator + Len(strLIST_DELIMITER)

            End If

        End If

        ParseObjectContent.Add strName, vValue

    Loop

End Function

Private Function ParseUnquotedValue(ByVal strValue As String) As Variant

    If StrComp(strValue, strNULL_VALUE, vbTextCompare) = 0 Then
        ParseUnquotedValue = Empty
    ElseIf StrComp(strValue, strTRUE_VALUE, vbTextCompare) = 0 Then
        ParseUnquotedValue = True
    ElseIf StrComp(strValue, strFALSE_VALUE, vbTextCompare) = 0 Then
        ParseUnquotedValue = False
    ElseIf IsNumeric(strValue) Then
        ParseUnquotedValue = CDbl(strValue)
    Else
        Err.Raise vbObjectError, Description:="Mal-formed value (not null, true, false or a number)"
    End If

End Function

Private Function ParseQuotedValue(ByVal strValue As String) As Variant

    ' Both dates and strings are quoted; we'll treat it as a date if it has the expected date format.
    ' Dates are in the form:
    '    2019-09-30T00:00:00
    If strValue Like "####-##-##T##:00:00" Then
        ' NOTE: we just want the date part
        ParseQuotedValue = CDate(Left(strValue, Len("####-##-##")))
    Else
        ParseQuotedValue = strValue
    End If

End Function

A simple test:

Const strJSON As String = "[{""property1"":""foo""}]"
Dim oObjects As Collection: Set oObjects = Json.ParseListOfObjects(strJSON)

MsgBox oObjects(1)("property1") ' shows "foo"

System.Net.WebException: The operation has timed out

It means what it says. The operation took too long to complete.

BTW, look at WebRequest.Timeout and you'll see that you've set your timeout for 1/5 second.

Getting key with maximum value in dictionary?

With collections.Counter you could do

>>> import collections
>>> stats = {'a':1000, 'b':3000, 'c': 100}
>>> stats = collections.Counter(stats)
>>> stats.most_common(1)
[('b', 3000)]

If appropriate, you could simply start with an empty collections.Counter and add to it

>>> stats = collections.Counter()
>>> stats['a'] += 1
:
etc. 

Have log4net use application config file for configuration data

Add a line to your app.config in the configSections element

<configSections>
 <section name="log4net" 
   type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, 
         Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>

Then later add the log4Net section, but delegate to the actual log4Net config file elsewhere...

<log4net configSource="Config\Log4Net.config" />

In your application code, when you create the log, write

private static ILog GetLog(string logName)
{
    ILog log = LogManager.GetLogger(logName);
    return log;
}

Change link color of the current page with CSS

JavaScript will get the job done.

Get all links in the document and compare their reference URLs to the document's URL. If there is a match, add a class to that link.

JavaScript

<script>
    currentLinks = document.querySelectorAll('a[href="'+document.URL+'"]')
    currentLinks.forE??ach(function(link) {
        link.className += ' current-link')
    });
</script>

One Liner Version of Above

document.querySelectorAll('a[href="'+document.URL+'"]').forE??ach(function(elem){e??lem.className += ' current-link')});

CSS

.current-link {
    color:#baada7;
}

Other Notes

Taraman's jQuery answer above only searches on [href] which will return link tags and tags other than a which rely on the href attribute. Searching on a[href='*https://urlofcurrentpage.com*'] captures only those links which meets the criteria and therefore runs faster.

In addtion, if you don't need to rely on the jQuery library, a vanilla JavaScript solution is definitely the way to go.

How to redirect all HTTP requests to HTTPS

This is the html redirect approach it works but not the best.

 <meta http-equiv="Refresh" content="0;URL=https://www.example.com" />

PHP approach

<?php
function redirectTohttps() {
    if ($_SERVER['HTTPS']!="on") {
        $redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        header("Location:$redirect"); 
    } 
}
?>

.htaccess approch

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

copied from: www.letuslook.org

error C2220: warning treated as error - no 'object' file generated

This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):

warning C4101: 'i': unreferenced local variable

After I commented this unused i, and compiled it, the other error went away.

How do I spool to a CSV formatted file using SQLPLUS?

With newer versions of client tools, there are multiple options to format the query output. The rest is to spool it to a file or save the output as a file depending on the client tool. Here are few of the ways:

  • SQL*Plus

Using the SQL*Plus commands you could format to get your desired output. Use SPOOL to spool the output to a file.

For example,

SQL> SET colsep ,
SQL> SET pagesize 20
SQL> SET trimspool ON
SQL> SET linesize 200
SQL> SELECT * FROM scott.emp;

     EMPNO,ENAME     ,JOB      ,       MGR,HIREDATE ,       SAL,      COMM,    DEPTNO
----------,----------,---------,----------,---------,----------,----------,----------
      7369,SMITH     ,CLERK    ,      7902,17-DEC-80,       800,          ,        20
      7499,ALLEN     ,SALESMAN ,      7698,20-FEB-81,      1600,       300,        30
      7521,WARD      ,SALESMAN ,      7698,22-FEB-81,      1250,       500,        30
      7566,JONES     ,MANAGER  ,      7839,02-APR-81,      2975,          ,        20
      7654,MARTIN    ,SALESMAN ,      7698,28-SEP-81,      1250,      1400,        30
      7698,BLAKE     ,MANAGER  ,      7839,01-MAY-81,      2850,          ,        30
      7782,CLARK     ,MANAGER  ,      7839,09-JUN-81,      2450,          ,        10
      7788,SCOTT     ,ANALYST  ,      7566,09-DEC-82,      3000,          ,        20
      7839,KING      ,PRESIDENT,          ,17-NOV-81,      5000,          ,        10
      7844,TURNER    ,SALESMAN ,      7698,08-SEP-81,      1500,          ,        30
      7876,ADAMS     ,CLERK    ,      7788,12-JAN-83,      1100,          ,        20
      7900,JAMES     ,CLERK    ,      7698,03-DEC-81,       950,          ,        30
      7902,FORD      ,ANALYST  ,      7566,03-DEC-81,      3000,          ,        20
      7934,MILLER    ,CLERK    ,      7782,23-JAN-82,      1300,          ,        10

14 rows selected.

SQL>
  • SQL Developer Version pre 4.1

Alternatively, you could use the new /*csv*/ hint in SQL Developer.

/*csv*/

For example, in my SQL Developer Version 3.2.20.10:

enter image description here

Now you could save the output into a file.

  • SQL Developer Version 4.1

New in SQL Developer version 4.1, use the following just like sqlplus command and run as script. No need of the hint in the query.

SET SQLFORMAT csv

Now you could save the output into a file.

START_STICKY and START_NOT_STICKY

Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY tells the OS to recreate the service after it has enough memory and call onStartCommand() again with a null intent. START_NOT_STICKY tells the OS to not bother recreating the service again. There is also a third code START_REDELIVER_INTENT that tells the OS to recreate the service and redeliver the same intent to onStartCommand().

This article by Dianne Hackborn explained the background of this a lot better than the official documentation.

Source: http://android-developers.blogspot.com.au/2010/02/service-api-changes-starting-with.html

The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:

START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.

START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.

START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.

How to download files using axios

        axios.get(
            '/app/export'
        ).then(response => {    
            const url = window.URL.createObjectURL(new Blob([response]));
            const link = document.createElement('a');
            link.href = url;
            const fileName = `${+ new Date()}.csv`// whatever your file name .
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
            link.remove();// you need to remove that elelment which is created before.
})

Disable browser cache for entire ASP.NET website

You may want to disable browser caching for all pages rendered by controllers (i.e. HTML pages), but keep caching in place for resources such as scripts, style sheets, and images. If you're using MVC4+ bundling and minification, you'll want to keep the default cache durations for scripts and stylesheets (very long durations, since the cache gets invalidated based on a change to a unique URL, not based on time).

In MVC4+, to disable browser caching across all controllers, but retain it for anything not served by a controller, add this to FilterConfig.RegisterGlobalFilters:

filters.Add(new DisableCache());

Define DisableCache as follows:

class DisableCache : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }
}

Tesseract OCR simple example

I was able to get it to work by following these instructions.

  • Download the sample code Tesseract sample code

  • Unzip it to a new location

  • Open ~\tesseract-samples-master\src\Tesseract.Samples.sln (I used Visual Studio 2017)

  • Install the Tesseract NuGet package for that project (or uninstall/reinstall as I had to) NuGet Tesseract

  • Uncomment the last two meaningful lines in Tesseract.Samples.Program.cs: Console.Write("Press any key to continue . . . "); Console.ReadKey(true);

  • Run (hit F5)

  • You should get this windows console output enter image description here

Get table name by constraint name

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

will give you what you need

MS Access: how to compact current database in VBA

I did this many years back on 2003 or possibly 97, yikes!

If I recall you need to use one of the subcommands above tied to a timer. You cannot operate on the db with any connections or forms open.

So you do something about closing all forms, and kick off the timer as the last running method. (which will in turn call the compact operation once everything closes)

If you haven't figured this out I could dig through my archives and pull it up.

Change class on mouseover in directive

This is my solution for my scenario:

<div class="btn-group btn-group-justified">
    <a class="btn btn-default" ng-class="{'btn-success': hover.left, 'btn-danger': hover.right}" ng-click="setMatch(-1)" role="button" ng-mouseenter="hover.left = true;" ng-mouseleave="hover.left = false;">
        <i class="fa fa-thumbs-o-up fa-5x pull-left" ng-class="{'fa-rotate-90': !hover.left && !hover.right, 'fa-flip-vertical': hover.right}"></i>
        {{ song.name }}
    </a>
    <a class="btn btn-default" ng-class="{'btn-success': hover.right, 'btn-danger': hover.left}" ng-click="setMatch(1)" role="button" ng-mouseenter="hover.right = true;" ng-mouseleave="hover.right = false;">
        <i class="fa fa-thumbs-o-up fa-5x pull-right" ng-class="{'fa-rotate-270': !hover.left && !hover.right, 'fa-flip-vertical': hover.left}"></i>
        {{ match.name }}
    </a>
</div>

default state: enter image description here

on hover: enter image description here

Does Android support near real time push notification?

As GTalk is gone from the SDK, it might be a good idea to make a 'standard' push messaging system. That way, only one service has to run, only one extra tcp connection needs to be open. Applications should talk to this service using Intents and should first request permission to send and receive notification from the service. The service should then notify the user a new application wants to send and receive messages. The user will then grant or deny permission, so he stays in control. The application will then register an action + category to the service, so the service knows how to deliver the pushed message.

Would the a good idea or not?

cat, grep and cut - translated to python

For Translating the command to python refer below:-

1)Alternative of cat command is open refer this. Below is the sample

>>> f = open('workfile', 'r')
>>> print f

2)Alternative of grep command refer this

3)Alternative of Cut command refer this

PHP Warning: PHP Startup: ????????: Unable to initialize module

This is an old thread, but I stumbled across it when trying to solve a similar problem.

For me, I got this particular error relating to the php_wincache.dll. I was in the process of updating PHP from 5.5.38 to 5.6.31 on a Windows server. For some reason, not all of the DLL files updated with the newest versions. Most did, but some didn't.

So, if you get an error similar to this, make sure all the extensions are in place and updated.

Cause of No suitable driver found for

It might be that

hsql://localhost

can't be resolved to a file. Look at the sample program here:

Sample HSQLDB program

See if you can get that working first, and then see if you can take that configuration information and use it in the Spring bean configuration.

Good luck!

How do you develop Java Servlets using Eclipse?

You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.

You can get the Java EE Edition of eclipse with has it pre-installed.

To create and run your first servlet:

  1. New... Project... Dynamic Web Project.
  2. Right click the project... New Servlet.
  3. Write some code in the doGet() method.
  4. Find the servers view in the Java EE perspective, it's usually one of the tabs at the bottom.
  5. Right click in there and select new Server.
  6. Select Tomcat X.X and a wizard will point you to finding the installation.
  7. Right click the server you just created and select Add and Remove... and add your created web project.
  8. Right click your servlet and select Run > Run on Server...

That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.

How can I change Eclipse theme?

In the eclipse Version: 2019-09 R (4.13.0) on windows Go to Window > preferences > Appearance Select the required theme for dark theme to choose Dark and click on Ok. enter image description here

How can I expose more than 1 port with Docker?

if you use docker-compose.ymlfile:

services:
    varnish:
        ports:
            - 80
            - 6081

You can also specify the host/network port as HOST/NETWORK_PORT:CONTAINER_PORT

varnish:
    ports:
        - 81:80
        - 6081:6081

Convert image from PIL to openCV format

The code commented works as well, just choose which do you prefer

import numpy as np
from PIL import Image


def convert_from_cv2_to_image(img: np.ndarray) -> Image:
    # return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    return Image.fromarray(img)


def convert_from_image_to_cv2(img: Image) -> np.ndarray:
    # return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
    return np.asarray(img)

MySQL Trigger: Delete From Table AFTER DELETE

Why not set ON CASCADE DELETE on Foreign Key patron_info.pid?

What are the differences between a multidimensional array and an array of arrays in C#?

I am parsing .il files generated by ildasm to build a database of assemnblies, classes, methods, and stored procedures for use doing a conversion. I came across the following, which broke my parsing.

.method private hidebysig instance uint32[0...,0...] 
        GenerateWorkingKey(uint8[] key,
                           bool forEncryption) cil managed

The book Expert .NET 2.0 IL Assembler, by Serge Lidin, Apress, published 2006, Chapter 8, Primitive Types and Signatures, pp. 149-150 explains.

<type>[] is termed a Vector of <type>,

<type>[<bounds> [<bounds>**] ] is termed an array of <type>

** means may be repeated, [ ] means optional.

Examples: Let <type> = int32.

1) int32[...,...] is a two-dimensional array of undefined lower bounds and sizes

2) int32[2...5] is a one-dimensional array of lower bound 2 and size 4.

3) int32[0...,0...] is a two-dimensional array of lower bounds 0 and undefined size.

Tom

How could I create a function with a completion handler in Swift?

In addition to above : Trailing closure can be used .

downloadFileFromURL(NSURL(string: "url_str")!)  { (success) -> Void in

  // When download completes,control flow goes here.
  if success {
      // download success
  } else {
    // download fail
  }
}

'uint32_t' does not name a type

You need to include stdint.h

 #include <stdint.h>

Turn a number into star rating display using jQuery and CSS

Here's a solution for you, using only one very tiny and simple image and one automatically generated span element:

CSS

span.stars, span.stars span {
    display: block;
    background: url(stars.png) 0 -16px repeat-x;
    width: 80px;
    height: 16px;
}

span.stars span {
    background-position: 0 0;
}

Image

alt text
(source: ulmanen.fi)

Note: do NOT hotlink to the above image! Copy the file to your own server and use it from there.

jQuery

$.fn.stars = function() {
    return $(this).each(function() {
        // Get the value
        var val = parseFloat($(this).html());
        // Make sure that the value is in 0 - 5 range, multiply to get width
        var size = Math.max(0, (Math.min(5, val))) * 16;
        // Create stars holder
        var $span = $('<span />').width(size);
        // Replace the numerical value with stars
        $(this).html($span);
    });
}

If you want to restrict the stars to only half or quarter star sizes, add one of these rows before the var size row:

val = Math.round(val * 4) / 4; /* To round to nearest quarter */
val = Math.round(val * 2) / 2; /* To round to nearest half */

HTML

<span class="stars">4.8618164</span>
<span class="stars">2.6545344</span>
<span class="stars">0.5355</span>
<span class="stars">8</span>

Usage

$(function() {
    $('span.stars').stars();
});

Output

Image from fugue icon set (www.pinvoke.com)
(source: ulmanen.fi)

Demo

http://www.ulmanen.fi/stuff/stars.php

This will probably suit your needs. With this method you don't have to calculate any three quarter or whatnot star widths, just give it a float and it'll give you your stars.


A small explanation on how the stars are presented might be in order.

The script creates two block level span elements. Both of the spans initally get a size of 80px * 16px and a background image stars.png. The spans are nested, so that the structure of the spans looks like this:

<span class="stars">
    <span></span>
</span>

The outer span gets a background-position of 0 -16px. That makes the gray stars in the outer span visible. As the outer span has height of 16px and repeat-x, it will only show 5 gray stars.

The inner span on the other hand has a background-position of 0 0 which makes only the yellow stars visible.

This would of course work with two separate imagefiles, star_yellow.png and star_gray.png. But as the stars have a fixed height, we can easily combine them into one image. This utilizes the CSS sprite technique.

Now, as the spans are nested, they are automatically overlayed over each other. In the default case, when the width of both spans is 80px, the yellow stars completely obscure the grey stars.

But when we adjust the width of the inner span, the width of the yellow stars decreases, revealing the gray stars.

Accessibility-wise, it would have been wiser to leave the float number inside the inner span and hide it with text-indent: -9999px, so that people with CSS turned off would at least see the floating point number instead of the stars.

Hopefully that made some sense.


Updated 2010/10/22

Now even more compact and harder to understand! Can also be squeezed down to a one liner:

$.fn.stars = function() {
    return $(this).each(function() {
        $(this).html($('<span />').width(Math.max(0, (Math.min(5, parseFloat($(this).html())))) * 16));
    });
}

Specifying Font and Size in HTML table

This worked for me and also worked with bootstrap tables

<style>
    .table td, .table th {
        font-size: 10px;
    }
</style>

How to access Session variables and set them in javascript?

You can't access Session directly in JavaScript.

You can make a hidden field and pass it to your page and then use JavaScript to retrieve the object via document.getElementById

TensorFlow not found using pip

Python 3.7 works for me, I uninstalled python 3.8.1 and reinstalled 3.7.6. After that, I executed:

pip3 install --user --upgrade tensorflow

and it works

string decode utf-8

Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?

ssh script returns 255 error

It can very much be an ssh-agent issue. Check whether there is an ssh-agent PID currently running with eval "$(ssh-agent -s)"

Check whether your identity is added with ssh-add -l and if not, add it with ssh-add <pathToYourRSAKey>.

Then try again your ssh command (or any other command that spawns ssh daemons, like autossh for example) that returned 255.

How do I determine if my python shell is executing in 32bit or 64bit?

platform.architecture() is problematic (and expensive).

Conveniently test for sys.maxsize > 2**32 since Py2.6 .

This is a reliable test for the actual (default) pointer size and compatible at least since Py2.3: struct.calcsize('P') == 8. Also: ctypes.sizeof(ctypes.c_void_p) == 8.

Notes: There can be builds with gcc option -mx32 or so, which are 64bit architecture applications, but use 32bit pointers as default (saving memory and speed). 'sys.maxsize = ssize_t' may not strictly represent the C pointer size (its usually 2**31 - 1 anyway). And there were/are systems which have different pointer sizes for code and data and it needs to be clarified what exactly is the purpose of discerning "32bit or 64bit mode?"

How to insert a newline in front of a pattern?

echo one,two,three | sed 's/,/\
/g'

Why use HttpClient for Synchronous Connection

If you're building a class library, then perhaps the users of your library would like to use your library asynchronously. I think that's the biggest reason right there.

You also don't know how your library is going to be used. Perhaps the users will be processing lots and lots of requests, and doing so asynchronously will help it perform faster and more efficient.

If you can do so simply, try not to put the burden on the users of your library trying to make the flow asynchronous when you can take care of it for them.

The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support.

Java SecurityException: signer information does not match

This happens when classes belonging to the same package are loaded from different JAR files, and those JAR files have signatures signed with different certificates - or, perhaps more often, at least one is signed and one or more others are not (which includes classes loaded from directories since those AFAIK cannot be signed).

So either make sure all JARs (or at least those which contain classes from the same packages) are signed using the same certificate, or remove the signatures from the manifest of JAR files with overlapping packages.

How to get 30 days prior to current date?

Try this

var today = new Date()
var priorDate = new Date().setDate(today.getDate()-30)

As noted by @Neel, this method returns in Javascript Timestamp format. To convert it back to date object, you need to pass the above to a new Date object; new Date(priorDate).

Key hash for Android-Facebook app

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.os.Bundle;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.text.Editable;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

    Button btn;
    EditText et;
    PackageInfo info;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn=(Button)findViewById(R.id.button1);
        et=(EditText)findViewById(R.id.editText1);
        btn.setOnClickListener(new OnClickListener() {

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

                try {
                    info = getPackageManager().getPackageInfo("com.example.id", PackageManager.GET_SIGNATURES);
                    for (Signature signature : info.signatures) {
                        MessageDigest md;
                        md = MessageDigest.getInstance("SHA");
                        md.update(signature.toByteArray());
                        String something = new String(Base64.encode(md.digest(), 0));
                        //String something = new String(Base64.encodeBytes(md.digest()));
                        et.setText("" + something);
                        Log.e("hash key", something);
                    }
                } catch (NameNotFoundException e1) {
                    Log.e("name not found", e1.toString());
                } catch (NoSuchAlgorithmException e) {
                    Log.e("no such an algorithm", e.toString());
                } catch (Exception e) {
                    Log.e("exception", e.toString());
                }
            }
        });
    }



}

How to get a list of all files that changed between two Git commits?

When I have added/modified/deleted many files (since the last commit), I like to look at those modifications in chronological order.

For that I use:

  • To list all non-staged files:

    git ls-files --other --modified --exclude-standard
    
  • To get the last modified date for each file:

    while read filename; do  echo -n "$(stat -c%y -- $filename 2> /dev/null) "; echo $filename;  done
    

Although ruvim suggests in the comments:

xargs -0 stat -c '%y %n' -- 
  • To sort them from oldest to more recent:

    sort
    

An alias makes it easier to use:

alias gstlast='git ls-files --other --modified --exclude-standard|while read filename; do  echo -n "$(stat -c%y -- $filename 2> /dev/null) "; echo $filename;  done|sort'

Or (shorter and more efficient, thanks to ruvim)

alias gstlast='git ls-files --other --modified --exclude-standard|xargs -0 stat -c '%y %n' --|sort'

For example:

username@hostname:~> gstlast
2015-01-20 11:40:05.000000000 +0000 .cpl/params/libelf
2015-01-21 09:02:58.435823000 +0000 .cpl/params/glib
2015-01-21 09:07:32.744336000 +0000 .cpl/params/libsecret
2015-01-21 09:10:01.294778000 +0000 .cpl/_deps
2015-01-21 09:17:42.846372000 +0000 .cpl/params/npth
2015-01-21 12:12:19.002718000 +0000 sbin/git-rcd

I now can review my modifications, from oldest to more recent.

Python: CSV write by column rather than row

As an alternate streaming approach:

  • dump each col into a file
  • use python or unix paste command to rejoin on tab, csv, whatever.

Both steps should handle steaming just fine.

Pitfalls:

  • if you have 1000s of columns, you might run into the unix file handle limit!

Query to get all rows from previous month

Even though the answer for this question has been selected already, however, I believe the simplest query will be

SELECT * 
FROM table 
WHERE 
date_created BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH) AND CURRENT_DATE();

How to view DLL functions?

Use dotPeek by JetBrains.

https://www.jetbrains.com/decompiler/

dotPeek is a free tool based on ReSharper. It can reliably decompile any .NET assembly into C# or IL code.

Is there functionality to generate a random character in Java?

In following 97 ascii value of small "a".

public static char randomSeriesForThreeCharacter() {
Random r = new Random();
char random_3_Char = (char) (97 + r.nextInt(3));
return random_3_Char;
}

in above 3 number for a , b , c or d and if u want all character like a to z then you replace 3 number to 25.

How to clear text area with a button in html using javascript?

<input type="button" value="Clear" onclick="javascript: functionName();" >

you just need to set the onclick event, call your desired function on this onclick event.

function functionName()
{
    $("#output").val("");
}

Above function will set the value of text area to empty string.

Is there a way to make text unselectable on an HTML page?

For Firefox you can apply the CSS declaration "-moz-user-select" to "none". Check out their documentation, user-select.

It's a "preview" of the future "user-select" as they say, so maybe Opera or WebKit-based browsers will support that. I also recall finding something for Internet Explorer, but I don't remember what :).

Anyway, unless it's a specific situation where text-selecting makes some dynamic functionality fail, you shouldn't really override what users are expecting from a webpage, and that is being able to select any text they want.

How to correctly link php-fpm and Nginx Docker containers?

As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).

Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from.

Using compose (1.6.2 in my machine), the docker-compose.yml file would read:

version: "2"
services:
  nginx:
    build:
      context: .
      dockerfile: nginx/Dockerfile
    ports:
      - "80:80"
    links:
      - fpm
    volumes_from:
      - data
  fpm:
    image: php:fpm
    volumes_from:
      - data
  data:
    build:
      context: .
      dockerfile: data/Dockerfile
    volumes:
      - /var/www/html

Note that data publishes a volume that is linked to the nginx and fpm services. Then the Dockerfile for the data service, that contains your source code:

FROM busybox

# content
ADD path/to/source /var/www/html

And the Dockerfile for nginx, that just replaces the default config:

FROM nginx

# config
ADD config/default.conf /etc/nginx/conf.d

For the sake of completion, here's the config file required for the example to work:

server {
    listen 0.0.0.0:80;

    root /var/www/html;

    location / {
        index index.php index.html;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass fpm:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
    }
}

which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT, which is fpm:9000 thanks to the hostnames defined by compose, and the SCRIPT_FILENAME).

SQL Server Output Clause into a scalar variable

Over a year later... if what you need is get the auto generated id of a table, you can just

SELECT @ReportOptionId = SCOPE_IDENTITY()

Otherwise, it seems like you are stuck with using a table.

Which @NotNull Java annotation should I use?

Unfortunately, JSR 308 will not add more values than this project local Not Null suggestion here

Java 8 will not come with a single default annotation or its own Checker framework. Similar to Find-bugs or JSR 305, this JSR is poorly maintained by a small bunch of mostly academic teams.

No commercial power behind it, thus JSR 308 launches EDR 3 (Early Draft Review at JCP) NOW, while Java 8 is supposed to ship in less than 6 months:-O Similar to 310 btw. but unlike 308 Oracle has taken charge of that now away from its founders to minimize harm it'll do to the Java Platform.

Every project, vendor and academic class like the ones behind the Checker Framework and JSR 308 will create its own proprietary checker annotation.

Making source code incompatible for years to come, until a few popular compromises could be found and maybe added to Java 9 or 10, or via frameworks like Apache Commons or Google Guava;-)

How do I pre-populate a jQuery Datepicker textbox with today's date?

You've got 2 options:

OPTION A) Marks as "active" in your calendar, only when you click in the input.

Js:

$('input.datepicker').datepicker(
                        {   
                            changeMonth: false,
                            changeYear: false,
                            beforeShow: function(input, instance) { 
                                $(input).datepicker('setDate', new Date());
                            }
                        }                         
                     );

Css:

div.ui-datepicker table.ui-datepicker-calendar .ui-state-active,
        div.ui-datepicker table.ui-datepicker-calendar .ui-widget-content .ui-state-active  {
            background: #1ABC9C;
            border-radius: 50%;
            color: #fff;
            cursor: pointer;
            display: inline-block;
            width: 24px; height: 24px;
        }?

OPTION B) Input by default with today. You've to populate first the datepicker .

$("input.datepicker").datepicker().datepicker("setDate", new Date());

In android how to set navigation drawer header image and name programmatically in class file?

First you need to access the navigation drawer in your MainActivity(or the calling activity) like this:

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

Then you need to remove the header layout from the activity_main.xml because the layout will be inflated programatically in the MainActivity. Your activity_main.xml should look like this:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout            

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:menu="@menu/activity_main_drawer" />

    </android.support.v4.widget.DrawerLayout>

Then in your MainActivity, we inflate the nav_header_main layout and get access to its views, in this case the ImageView and TextView

//inflate header layout
View navView =  navigationView.inflateHeaderView(R.layout.nav_header_main);
//reference to views
ImageView imgvw = (ImageView)navView.findViewById(R.id.imageView);
TextView tv = (TextView)navView.findViewById(R.id.textview);
//set views
imgvw.setImageResource(R.drawable.your_image);
tv.setText("new text");

navigationView.setNavigationItemSelectedListener(this);

You can read more here

Uploading a file in Rails

Sept 2018

For anyone checking this question recently, Rails 5.2+ now has ActiveStorage by default & I highly recommend checking it out.

Since it is part of the core Rails 5.2+ now, it is very well integrated & has excellent capabilities out of the box (still all other well-known gems like Carrierwave, Shrine, paperclip,... are great but this one offers very good features that we can consider for any new Rails project)

Paperclip team deprecated the gem in favor of the Rails ActiveStorage.

Here is the github page for the ActiveStorage & plenty of resources are available everywhere

Also I found this video to be very helpful to understand the features of Activestorage

how to set radio button checked in edit mode in MVC razor view

Here is how I do it and works both for create and edit:

//How to do it with enums
<div class="editor-field">
   @Html.RadioButtonFor(x => x.gender, (int)Gender.Male) Male
   @Html.RadioButtonFor(x => x.gender, (int)Gender.Female) Female
</div>

//And with Booleans
<div class="editor-field">
   @Html.RadioButtonFor(x => x.IsMale, true) Male
   @Html.RadioButtonFor(x => x.IsMale, false) Female
</div>

the provided values (true and false) are the values that the engine will render as the values for the html element i.e.:

<input id="IsMale" type="radio" name="IsMale" value="True">
<input id="IsMale" type="radio" name="IsMale" value="False">

And the checked property is dependent on the Model.IsMale value.

Razor engine seems to internally match the set radio button value to your model value, if a proper from and to string convert exists for it. So there is no need to add it as an html attribute in the helper method.

How to get 'System.Web.Http, Version=5.2.3.0?

In Package Manager Console

Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

Pyspark: display a spark data frame in a table format

The show method does what you're looking for.

For example, given the following dataframe of 3 rows, I can print just the first two rows like this:

df = sqlContext.createDataFrame([("foo", 1), ("bar", 2), ("baz", 3)], ('k', 'v'))
df.show(n=2)

which yields:

+---+---+
|  k|  v|
+---+---+
|foo|  1|
|bar|  2|
+---+---+
only showing top 2 rows

How can I install MacVim on OS X?

  1. Download the latest build from https://github.com/macvim-dev/macvim/releases

  2. Expand the archive.

  3. Put MacVim.app into /Applications/.

Done.

How to convert an array to object in PHP?

You could also use an ArrayObject, for example:

<?php
    $arr = array("test",
                 array("one"=>1,"two"=>2,"three"=>3), 
                 array("one"=>1,"two"=>2,"three"=>3)
           );
    $o = new ArrayObject($arr);
    echo $o->offsetGet(2)["two"],"\n";
    foreach ($o as $key=>$val){
        if (is_array($val)) {
            foreach($val as $k => $v) {
               echo $k . ' => ' . $v,"\n";
            }
        }
        else
        {
               echo $val,"\n";
        }
    }
?>

//Output:
  2
  test
  one => 1
  two => 2
  three => 3
  one => 1
  two => 2
  three => 3

How do I `jsonify` a list in Flask?

jsonify prevents you from doing this in Flask 0.10 and lower for security reasons.

To do it anyway, just use json.dumps in the Python standard library.

http://docs.python.org/library/json.html#json.dumps

Pandas/Python: Set value of one column based on value in another column

Try out df.apply() if you've a small/medium dataframe,

df['c2'] = df.apply(lambda x: 10 if x['c1'] == 'Value' else x['c1'], axis = 1)

Else, follow the slicing techniques mentioned in the above comments if you've got a big dataframe.

How do I compare a value to a backslash?

When you only need to check for equality, you can also simply use the in operator to do a membership test in a sequence of accepted elements:

if message.value[0] in ('/', '\\'):
    do_stuff()

How to sort an object array by date property?

I personally use following approach to sort dates.

let array = ["July 11, 1960", "February 1, 1974", "July 11, 1615", "October 18, 1851", "November 12, 1995"];

array.sort(function(date1, date2) {
   date1 = new Date(date1);
   date2 = new Date(date2);
   if (date1 > date2) return 1;
   if (date1 < date2) return -1;
})

How to find the users list in oracle 11g db?

The command select username from all_users; requires less privileges

Update row with data from another row in the same table

If you just need to insert a new row with a data from another row,

    insert into ORDER_ITEM select * from ORDER_ITEM where ITEM_NUMBER =123;

Generate a random number in the range 1 - 10

This stored procedure inserts a rand number into a table. Look out, it inserts an endless numbers. Stop executing it when u get enough numbers.

create a table for the cursor:

CREATE TABLE [dbo].[SearchIndex](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Cursor] [nvarchar](255) NULL) 

GO

Create a table to contain your numbers:

CREATE TABLE [dbo].[ID](
[IDN] [int] IDENTITY(1,1) NOT NULL,
[ID] [int] NULL)

INSERTING THE SCRIPT :

INSERT INTO [SearchIndex]([Cursor])  SELECT N'INSERT INTO ID  SELECT   FLOOR(rand() * 9 + 1)  SELECT COUNT (ID) FROM ID

CREATING AND EXECUTING THE PROCEDURE:

CREATE PROCEDURE [dbo].[RandNumbers] AS
BEGIN
Declare  CURSE  CURSOR  FOR (SELECT  [Cursor] FROM [dbo].[SearchIndex]  WHERE [Cursor] IS NOT NULL)
DECLARE @RandNoSscript NVARCHAR (250)
OPEN CURSE
FETCH NEXT FROM CURSE
INTO @RandNoSscript 
WHILE @@FETCH_STATUS IS NOT NULL 
BEGIN
Print @RandNoSscript
EXEC SP_EXECUTESQL @RandNoSscript;  
 END
 END
GO

Fill your table:

EXEC RandNumbers

How do you cache an image in Javascript

Even though your question says "using javascript", you can use the prefetch attribute of a link tag to preload any asset. As of this writing (Aug 10, 2016) it isn't supported in Safari, but is pretty much everywhere else:

<link rel="prefetch" href="(url)">

More info on support here: http://caniuse.com/#search=prefetch

Note that IE 9,10 aren't listed in the caniuse matrix because Microsoft has discontinued support for them.

So if you were really stuck on using javascript, you could use jquery to dynamically add these elements to your page as well ;-)

How to check permissions of a specific directory?

In addition to the above posts, i'd like to point out that "man ls" will give you a nice manual about the "ls" ( List " command.

Also, using ls -la myFile will list & show all the facts about that file.

Understanding The Modulus Operator %

(This explanation is only for positive numbers since it depends on the language otherwise)

Definition

The Modulus is the remainder of the euclidean division of one number by another. % is called the modulo operation.

For instance, 9 divided by 4 equals 2 but it remains 1. Here, 9 / 4 = 2 and 9 % 4 = 1.

Euclidean Division

In your example: 5 divided by 7 gives 0 but it remains 5 (5 % 7 == 5).

Calculation

The modulo operation can be calculated using this equation:

a % b = a - floor(a / b) * b
  • floor(a / b) represents the number of times you can divide a by b
  • floor(a / b) * b is the amount that was successfully shared entirely
  • The total (a) minus what was shared equals the remainder of the division

Applied to the last example, this gives:

5 % 7 = 5 - floor(5 / 7) * 7 = 5

Modular Arithmetic

That said, your intuition was that it could be -2 and not 5. Actually, in modular arithmetic, -2 = 5 (mod 7) because it exists k in Z such that 7k - 2 = 5.

You may not have learned modular arithmetic, but you have probably used angles and know that -90° is the same as 270° because it is modulo 360. It's similar, it wraps! So take a circle, and say that it's perimeter is 7. Then you read where is 5. And if you try with 10, it should be at 3 because 10 % 7 is 3.

Is it possible to get all arguments of a function as single object inside that function?

In ES6 you can do something like this:

_x000D_
_x000D_
function foo(...args) _x000D_
{_x000D_
   let [a,b,...c] = args;_x000D_
_x000D_
   console.log(a,b,c);_x000D_
}_x000D_
_x000D_
_x000D_
foo(1, null,"x",true, undefined);
_x000D_
_x000D_
_x000D_

How do I search for an object by its ObjectId in the mongo console?

In MongoDB Stitch functions it can be done using BSON like below:

Use the ObjectId helper in the BSON utility package for this purpose like in the follwing example:

var id = "5bb9e9f84186b222c8901149";  
BSON.ObjectId(id);

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Unless there is some other requirement not specified, I would simply convert your color image to grayscale and work with that only (no need to work on the 3 channels, the contrast present is too high already). Also, unless there is some specific problem regarding resizing, I would work with a downscaled version of your images, since they are relatively large and the size adds nothing to the problem being solved. Then, finally, your problem is solved with a median filter, some basic morphological tools, and statistics (mostly for the Otsu thresholding, which is already done for you).

Here is what I obtain with your sample image and some other image with a sheet of paper I found around:

enter image description here enter image description here

The median filter is used to remove minor details from the, now grayscale, image. It will possibly remove thin lines inside the whitish paper, which is good because then you will end with tiny connected components which are easy to discard. After the median, apply a morphological gradient (simply dilation - erosion) and binarize the result by Otsu. The morphological gradient is a good method to keep strong edges, it should be used more. Then, since this gradient will increase the contour width, apply a morphological thinning. Now you can discard small components.

At this point, here is what we have with the right image above (before drawing the blue polygon), the left one is not shown because the only remaining component is the one describing the paper:

enter image description here

Given the examples, now the only issue left is distinguishing between components that look like rectangles and others that do not. This is a matter of determining a ratio between the area of the convex hull containing the shape and the area of its bounding box; the ratio 0.7 works fine for these examples. It might be the case that you also need to discard components that are inside the paper, but not in these examples by using this method (nevertheless, doing this step should be very easy especially because it can be done through OpenCV directly).

For reference, here is a sample code in Mathematica:

f = Import["http://thwartedglamour.files.wordpress.com/2010/06/my-coffee-table-1-sa.jpg"]
f = ImageResize[f, ImageDimensions[f][[1]]/4]
g = MedianFilter[ColorConvert[f, "Grayscale"], 2]
h = DeleteSmallComponents[Thinning[
     Binarize[ImageSubtract[Dilation[g, 1], Erosion[g, 1]]]]]
convexvert = ComponentMeasurements[SelectComponents[
     h, {"ConvexArea", "BoundingBoxArea"}, #1 / #2 > 0.7 &], 
     "ConvexVertices"][[All, 2]]
(* To visualize the blue polygons above: *)
Show[f, Graphics[{EdgeForm[{Blue, Thick}], RGBColor[0, 0, 1, 0.5], 
     Polygon @@ convexvert}]]

If there are more varied situations where the paper's rectangle is not so well defined, or the approach confuses it with other shapes -- these situations could happen due to various reasons, but a common cause is bad image acquisition -- then try combining the pre-processing steps with the work described in the paper "Rectangle Detection based on a Windowed Hough Transform".

Location of GlassFish Server Logs

tail -f /path/to/glassfish/domains/YOURDOMAIN/logs/server.log

You can also upload log from admin console : http://yoururl:4848

enter image description here

What does the "+" (plus sign) CSS selector mean?

"+" is the adjacent sibling selector. It will select any p DIRECTLY AFTER a p (not a child or parent though, a sibling).

Dynamically access object property using variable

Whenever you need to access property dynamically you have to use square bracket for accessing property not "." operator
Syntax: object[propery}

_x000D_
_x000D_
const something = { bar: "Foobar!" };_x000D_
const foo = 'bar';_x000D_
// something.foo; -- not correct way at it is expecting foo as proprty in  something={ foo: "value"};_x000D_
// correct way is  something[foo]_x000D_
alert( something[foo])
_x000D_
_x000D_
_x000D_

How to make a .NET Windows Service start right after the installation?

You need to add a Custom Action to the end of the 'ExecuteImmediate' sequence in the MSI, using the component name of the EXE or a batch (sc start) as the source. I don't think this can be done with Visual Studio, you may have to use a real MSI authoring tool for that.

How can I align all elements to the left in JPanel?

My favorite method to use would be the BorderLayout method. Here are the five examples with each position the component could go in. The example is for if the component were a button. We will add it to a JPanel, p. The button will be called b.

//To align it to the left
p.add(b, BorderLayout.WEST);

//To align it to the right
p.add(b, BorderLayout.EAST);

//To align it at the top
p.add(b, BorderLayout.NORTH);

//To align it to the bottom
p.add(b, BorderLayout.SOUTH);

//To align it to the center
p.add(b, BorderLayout.CENTER);

Don't forget to import it as well by typing:

import java.awt.BorderLayout;

There are also other methods in the BorderLayout class involving things like orientation, but you can do your own research on that if you curious about that. I hope this helped!

How to use the unsigned Integer in Java 8 and Java 9?

    // Java 8
    int vInt = Integer.parseUnsignedInt("4294967295");
    System.out.println(vInt); // -1
    String sInt = Integer.toUnsignedString(vInt);
    System.out.println(sInt); // 4294967295

    long vLong = Long.parseUnsignedLong("18446744073709551615");
    System.out.println(vLong); // -1
    String sLong = Long.toUnsignedString(vLong);
    System.out.println(sLong); // 18446744073709551615

    // Guava 18.0
    int vIntGu = UnsignedInts.parseUnsignedInt(UnsignedInteger.MAX_VALUE.toString());
    System.out.println(vIntGu); // -1
    String sIntGu = UnsignedInts.toString(vIntGu);
    System.out.println(sIntGu); // 4294967295

    long vLongGu = UnsignedLongs.parseUnsignedLong("18446744073709551615");
    System.out.println(vLongGu); // -1
    String sLongGu = UnsignedLongs.toString(vLongGu);
    System.out.println(sLongGu); // 18446744073709551615

    /**
     Integer - Max range
     Signed: From -2,147,483,648 to 2,147,483,647, from -(2^31) to 2^31 – 1
     Unsigned: From 0 to 4,294,967,295 which equals 2^32 - 1

     Long - Max range
     Signed: From -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, from -(2^63) to 2^63 - 1
     Unsigned: From 0 to 18,446,744,073,709,551,615 which equals 2^64 – 1
     */

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.

Type definition in object literal in TypeScript

You're pretty close, you just need to replace the = with a :. You can use an object type literal (see spec section 3.5.3) or an interface. Using an object type literal is close to what you have:

var obj: { property: string; } = { property: "foo" };

But you can also use an interface

interface MyObjLayout {
    property: string;
}

var obj: MyObjLayout = { property: "foo" };

How to use comparison operators like >, =, < on BigDecimal

Use the compareTo method of BigDecimal :

public int compareTo(BigDecimal val) Compares this BigDecimal with the specified BigDecimal.

Returns:
-1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

java.lang.OutOfMemoryError: GC overhead limit exceeded

For this use below code in your app gradle file under android closure.

dexOptions { javaMaxHeapSize "4g" }

How to create a HTTP server in Android?

You can try Restlet edition for android:

The source can be downloaded from Restlet website:

How to query for Xml values and attributes from table in SQL Server?

Actually you're close to your goal, you just need to use nodes() method to split your rows and then get values:

select
    s.SqmId,
    m.c.value('@id', 'varchar(max)') as id,
    m.c.value('@type', 'varchar(max)') as type,
    m.c.value('@unit', 'varchar(max)') as unit,
    m.c.value('@sum', 'varchar(max)') as [sum],
    m.c.value('@count', 'varchar(max)') as [count],
    m.c.value('@minValue', 'varchar(max)') as minValue,
    m.c.value('@maxValue', 'varchar(max)') as maxValue,
    m.c.value('.', 'nvarchar(max)') as Value,
    m.c.value('(text())[1]', 'nvarchar(max)') as Value2
from sqm as s
    outer apply s.data.nodes('Sqm/Metrics/Metric') as m(c)

sql fiddle demo

Html.RenderPartial() syntax with Razor

Html.RenderPartial() is a void method - you can check whether a method is a void method by placing your mouse over the call to RenderPartial in your code and you will see the text (extension) void HtmlHelper.RenderPartial...

Void methods require a semicolon at the end of the calling code.

In the Webforms view engine you would have encased your Html.RenderPartial() call within the bee stings <% %>

like so

<% Html.RenderPartial("Path/to/my/partial/view"); %>

when you are using the Razor view engine the equivalent is

@{Html.RenderPartial("Path/to/my/partial/view");}

Check if selected dropdown value is empty using jQuery

You can try this also-

if( !$('#EventStartTimeMin').val() ) {
// do something
}

How to input a string from user into environment variable from batch file

You can use set with the /p argument:

SET /P variable=[promptString]

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

So, simply use something like

set /p Input=Enter some text: 

Later you can use that variable as argument to a command:

myCommand %Input%

Be careful though, that if your input might contain spaces it's probably a good idea to quote it:

myCommand "%Input%"

Strip last two characters of a column in MySQL

You can use a LENGTH(that_string) minus the number of characters you want to remove in the SUBSTRING() select perhaps or use the TRIM() function.

How to Merge Two Eloquent Collections?

All do not work for me on eloquent collections, laravel eloquent collections use the key from the items I think which causes merging issues, you need to get the first collection back as an array, put that into a fresh collection and then push the others into the new collection;

public function getFixturesAttribute()
{
    $fixtures = collect( $this->homeFixtures->all() );
    $this->awayFixtures->each( function( $fixture ) use ( $fixtures ) {
        $fixtures->push( $fixture );
    });
    return $fixtures;
}

What's the main difference between Java SE and Java EE?

http://www.dreamincode.net/forums/topic/99678-j2se-vs-j2ee-what-are-main-differences/

As far as the language goes it is not as though java changes. Java EE has access to all of the SE libraries. However EE adds a set of libraries for dealing with enterprise applications.

Java EE is more like a "platform" or an general area of development.

In Java SE you write applications that run as standalone java programs or as Applets. In JavaEE you can still do this, but you can also write applications that run inside of a Java EE container. The container can do a great amount of management for you such as scaling an application across threads, providing resource pools, and management features.

Java EE has a web framework based upon Servlets. It has JSP (Java Server Pages) which is a templating language that compiles from JSP to a Java servlet where it can be run by the container.

So Java EE is more or less Java SE + Enterprise platform technologies.

Java EE is far more than just a couple of extra libraries (that is what I thought when I first looked at it) since there are a ton of frameworks and technologies built upon the Java EE specifications.

But it all boils down to just plain old java.

How to allow download of .json file with ASP.NET

Just had this issue but had to find the config for IIS Express so I could add the mime types. For me, it was located at C:\Users\<username>\Documents\IISExpress\config\applicationhost.config and I was able to add in the correct "mime map" there.

Can I convert a boolean to Yes/No in a ASP.NET GridView

Nope - but you could use a template column:

<script runat="server">
  TResult Eval<T, TResult>(string field, Func<T, TResult> converter) {
     object o = DataBinder.Eval(Container.DataItem, field);
     if (converter == null) {
        return (TResult)o;
     }
     return converter((T)o);
  }
</script>

<asp:TemplateField>
  <ItemTemplate>
     <%# Eval<bool, string>("Active", b => b ? "Yes" : "No") %>
  </ItemTemplate>
</asp:TemplateField>

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

MySQL selecting yesterday's date

I adapted one of the above answers from cdhowie as I could not get it to work. This seems to work for me. I suspect it's also possible to do this with the UNIX_TIMESTAMP function been used.

SELECT * FROM your_table

WHERE UNIX_TIMESTAMP(DateVisited) >= UNIX_TIMESTAMP(CAST(NOW() - INTERVAL 1 DAY AS DATE))
  AND UNIX_TIMESTAMP(DateVisited) <= UNIX_TIMESTAMP(CAST(NOW() AS DATE));

For files in directory, only echo filename (no path)

if you want filename only :

for file in /home/user/*; do       
  f=$(echo "${file##*/}");
  filename=$(echo $f| cut  -d'.' -f 1); #file has extension, it return only filename
  echo $filename
done

for more information about cut command see here.

TortoiseSVN icons not showing up under Windows 7

Windows can only show a limited number of Overlay Icons (15 total, 11 after what Windows uses). Programs like Office Groove, Dropbox, Mozy, Carbonite, etc, will hijack a bunch of the 11 possible overlay icons (boy would it be nice if Microsoft upped the number of these as the number of applications that use them seem to increase and increase)...

You can see what overlays are set up, and change them (at your own risk) in the registry here:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\ShellIconOverlayIdentifiers

If you are using TortoiseCVS (and have nothing else using overlay icons), you will get a couple of TortoiseSVN Icons, and all of your TortoiseCVS icons. This is because the overlay icons are used in alphabetical order. Again, at your own risk (editing the registry may blow up your computer, yada, yada, yada -- and if you are reading Stack Overflow and using Windows and haven't edited the registry, you are a rare beast indeed), feel free to rename them (I suggest putting numbers in front of the ones you want to use and "z_"'s prefixed to the ones you don't need). The TortoiseSVN Shell extensions are nicely named so you know what they do, the TortoiseCVS extensions are not. After looking through the source code, I found the pertinent information:

  • TortoiseCVS0 - In CVS
  • TortoiseCVS1 - Not in CVS
  • TortoiseCVS3 - Conflicted
  • TortoiseCVS4 - In CVS readonly
  • TortoiseCVS5 - Ignored
  • TortoiseCVS6 - Added
  • TortoiseCVS7 - Deleted
  • TortoiseCVS8 - Locked

What are Java command line options to set to allow JVM to be remotely debugged?

-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=PORT_NUMBER

Here we just use a Socket Attaching Connector, which is enabled by default when the dt_socket transport is configured and the VM is running in the server debugging mode.

For more details u can refer to : https://stackify.com/java-remote-debugging/

How to create CSV Excel file C#?

great work on this class. Simple and easy to use. I modified the class to include a title in the first row of the export; figured I would share:

use:

CsvExport myExport = new CsvExport();
myExport.addTitle = String.Format("Name: {0},{1}", lastName, firstName));

class:

public class CsvExport
{
    List<string> fields = new List<string>();

    public string addTitle { get; set; } // string for the first row of the export

    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> currentRow
    {
        get
        {
            return rows[rows.Count - 1];
        }
    }

    public object this[string field]
    {
        set
        {
            if (!fields.Contains(field)) fields.Add(field);
            currentRow[field] = value;
        }
    }

    public void AddRow()
    {
        rows.Add(new Dictionary<string, object>());
    }

    string MakeValueCsvFriendly(object value)
    {
        if (value == null) return "";
        if (value is Nullable && ((INullable)value).IsNull) return "";
        if (value is DateTime)
        {
            if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
                return ((DateTime)value).ToString("yyyy-MM-dd");
            return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
        }
        string output = value.ToString();
        if (output.Contains(",") || output.Contains("\""))
            output = '"' + output.Replace("\"", "\"\"") + '"';
        return output;

    }

    public string Export()
    {
        StringBuilder sb = new StringBuilder();

        // if there is a title
        if (!string.IsNullOrEmpty(addTitle))
        {
            // escape chars that would otherwise break the row / export
            char[] csvTokens = new[] { '\"', ',', '\n', '\r' };

            if (addTitle.IndexOfAny(csvTokens) >= 0)
            {
                addTitle = "\"" + addTitle.Replace("\"", "\"\"") + "\"";
            }
            sb.Append(addTitle).Append(",");
            sb.AppendLine();
        }


        // The header
        foreach (string field in fields)
        sb.Append(field).Append(",");
        sb.AppendLine();

        // The rows
        foreach (Dictionary<string, object> row in rows)
        {
            foreach (string field in fields)
                sb.Append(MakeValueCsvFriendly(row[field])).Append(",");
            sb.AppendLine();
        }

        return sb.ToString();
    }

    public void ExportToFile(string path)
    {
        File.WriteAllText(path, Export());
    }

    public byte[] ExportToBytes()
    {
        return Encoding.UTF8.GetBytes(Export());
    }
}

Ansible: How to delete files and folders inside a directory?

There is an issue open with respect to this.

For now, the solution works for me: create a empty folder locally and synchronize it with the remote one.

Here is a sample playbook:

- name: "Empty directory"
  hosts: *
  tasks:
    - name: "Create an empty directory (locally)"
      local_action:
        module: file
        state: directory
        path: "/tmp/empty"

    - name: Empty remote directory
      synchronize:
        src: /tmp/empty/
        dest: /home/mydata/web/
        delete: yes
        recursive: yes

Difference between System.DateTime.Now and System.DateTime.Today

The DateTime.Now property returns the current date and time, for example 2011-07-01 10:09.45310.

The DateTime.Today property returns the current date with the time compnents set to zero, for example 2011-07-01 00:00.00000.

The DateTime.Today property actually is implemented to return DateTime.Now.Date:

public static DateTime Today {
  get {
    DateTime now = DateTime.Now;
    return now.Date;
  }
}

Python pandas: how to specify data types when reading an Excel file?

If you don't know the column names and you want to specify str data type to all columns:

table = pd.read_excel("path_to_filename")
cols = table.columns
conv = dict(zip(cols ,[str] * len(cols)))
table = pd.read_excel("path_to_filename", converters=conv)

How do I clear a C++ array?

std::fill_n(array, elementCount, 0);

Assuming array is a normal array (e.g. int[])

SSL Connection / Connection Reset with IISExpress

In my case, I created a self-signed certificate and had it working, except I was getting an error in the browser because the certificate was untrusted. So, I moved the cert into the Trusted Root Certification Authorities > Certificates folder in the Certificates snapin. It worked, and then I closed Visual Studio for the day.

The following day, I started my project and I received the error mentioned in the original question. The issue is that the certificate you configured IISExpress with must exist in the Personal > Certificates folder or HTTPS will stop working. Once IIS Express successfully starts, you can drag the cert back to the trusted location. It'll continue to work until you restart IIS Express.

Not wanting to fuss with dragging the cert back and forth every time, I just place a copy of the certificate in both places and now everything works fine.

Read file line by line using ifstream in C++

First, make an ifstream:

#include <fstream>
std::ifstream infile("thefile.txt");

The two standard methods are:

  1. Assume that every line consists of two numbers and read token by token:

    int a, b;
    while (infile >> a >> b)
    {
        // process pair (a,b)
    }
    
  2. Line-based parsing, using string streams:

    #include <sstream>
    #include <string>
    
    std::string line;
    while (std::getline(infile, line))
    {
        std::istringstream iss(line);
        int a, b;
        if (!(iss >> a >> b)) { break; } // error
    
        // process pair (a,b)
    }
    

You shouldn't mix (1) and (2), since the token-based parsing doesn't gobble up newlines, so you may end up with spurious empty lines if you use getline() after token-based extraction got you to the end of a line already.

Using @property versus getters and setters

I feel like properties are about letting you get the overhead of writing getters and setters only when you actually need them.

Java Programming culture strongly advise to never give access to properties, and instead, go through getters and setters, and only those which are actually needed. It's a bit verbose to always write these obvious pieces of code, and notice that 70% of the time they are never replaced by some non-trivial logic.

In Python, people actually care for that kind of overhead, so that you can embrace the following practice :

  • Do not use getters and setters at first, when if they not needed
  • Use @property to implement them without changing the syntax of the rest of your code.

Get driving directions using Google Maps API v2

This is what I am using,

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );     
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);

How to filter rows in pandas by regex

Write a Boolean function that checks the regex and use apply on the column

foo[foo['b'].apply(regex_function)]

Does JavaScript have the interface type (such as Java's 'interface')?

This is an old question, nevertheless this topic never ceases to bug me.

As many of the answers here and across the web focus on "enforcing" the interface, I'd like to suggest an alternative view:

I feel the lack of interfaces the most when I'm using multiple classes that behave similarly (i.e. implement an interface).

For example, I have an Email Generator that expects to receive Email Sections Factories, that "know" how to generate the sections' content and HTML. Hence, they all need to have some sort of getContent(id) and getHtml(content) methods.

The closest pattern to interfaces (albeit it's still a workaround) I could think of is using a class that'll get 2 arguments, which will define the 2 interface methods.

The main challenge with this pattern is that the methods either have to be static, or to get as argument the instance itself, in order to access its properties. However there are cases in which I find this trade-off worth the hassle.

_x000D_
_x000D_
class Filterable {_x000D_
  constructor(data, { filter, toString }) {_x000D_
    this.data = data;_x000D_
    this.filter = filter;_x000D_
    this.toString = toString;_x000D_
    // You can also enforce here an Iterable interface, for example,_x000D_
    // which feels much more natural than having an external check_x000D_
  }_x000D_
}_x000D_
_x000D_
const evenNumbersList = new Filterable(_x000D_
  [1, 2, 3, 4, 5, 6], {_x000D_
    filter: (lst) => {_x000D_
      const evenElements = lst.data.filter(x => x % 2 === 0);_x000D_
      lst.data = evenElements;_x000D_
    },_x000D_
    toString: lst => `< ${lst.data.toString()} >`,_x000D_
  }_x000D_
);_x000D_
_x000D_
console.log('The whole list:    ', evenNumbersList.toString(evenNumbersList));_x000D_
evenNumbersList.filter(evenNumbersList);_x000D_
console.log('The filtered list: ', evenNumbersList.toString(evenNumbersList));
_x000D_
_x000D_
_x000D_

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

I needed to update and add suffix to few rows of the dataframe on conditional basis based on the another column's value of the same dataframe -

df with column Feature and Entity and need to update Entity based on specific feature type

df2= df1 df.loc[df.Feature == 'dnb', 'Entity'] = 'duns_' + df.loc[df.Feature == 'dnb','Entity']

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Spring is an application framework which deals with IOC (Inversion of Control).

Struts 2 is a web application MVC framework which deals with actions.

Hibernate is an ORM (Object-Relational Mapping) that deals with persistent data.

Facebook how to check if user has liked page and show content?

Here's a working example, which is a fork of this answer:

$(document).ready(function(){
    FB.login(function(response) {
        if (response.status == 'connected') {
            var user_id = response.authResponse.userID;
            var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
            var fql_query = "SELECT uid FROM page_fan WHERE page_id="+page_id+" and uid="+user_id;

            FB.api({
                method: 'fql.query',
                query: fql_query
            },
            function(response){
                if (response[0]) {
                    $("#container_like").show();
                } else {
                    $("#container_notlike").show();
                }
            }
            );    
        } else {
        // user is not logged in
        }
    });
});

I used the FB.api method (JavaScript SDK), instead of FB.Data.query, which is deprecated. Or you can use the Graph API like with this example:

$(document).ready(function() {
    FB.login(function(response) {
        if (response.status == 'connected') {
            var user_id = response.authResponse.userID;
            var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
            var fql_query = "SELECT uid FROM page_fan WHERE page_id=" + page_id + " and uid=" + user_id;

            FB.api('/me/likes/'+page_id, function(response) {
                if (response.data[0]) {
                    $("#container_like").show();
                } else {
                    $("#container_notlike").show();
                }
            });
        } else {
            // user is not logged in
        }
    });
});?

Is it possible to open developer tools console in Chrome on Android phone?

When you don't have a PC on hand, you could use Eruda, which is devtools for mobile browsers https://github.com/liriliri/eruda
It is provided as embeddable javascript and also a bookmarklet (pasting bookmarklet in chrome removes the javascript: prefix, so you have to type it yourself)

How to compare different branches in Visual Studio Code

Update: As of November, 2020, Gitlens appears within VSCode's builtin Source Control Panel

I would recommend to use: Git Lens.

enter image description here

Field 'browser' doesn't contain a valid alias configuration

In my case, it is due to a case-sensitivity typo in import path. For example,

Should be:

import Dashboard from './Dashboard/dashboard';

Instead of:

import Dashboard from './Dashboard/Dashboard';

How to use SVG markers in Google Maps API v3

As mentioned by others in this thread, don't forget to explicitly set the width and height attributes in the svg like so:

<svg id="some_id" data-name="some_name" xmlns="http://www.w3.org/2000/svg"
     viewBox="0 0 26 42"
     width="26px" height="42px">

if you don't do that no js manipulation can help you as gmaps will not have a frame of reference and always use a standard size.

(i know it has been mentioned in some comments, but they are easy to miss. This information helped me in various cases)

How do I assert my exception message with JUnit Test annotation?

I would prefer AssertJ for this.

        assertThatExceptionOfType(ExpectedException.class)
        .isThrownBy(() -> {
            // method call
        }).withMessage("My message");

How to pass a URI to an intent?

you can do like this. imageuri can be converted into string like this.

intent.putExtra("imageUri", imageUri.toString());

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

An alternative to using LINQ:

var set = new HashSet<int>(values);
return (1 == set.Count) ? values.First() : otherValue;

I have found using HashSet<T> is quicker for lists of up to ~ 6,000 integers compared with:

var value1 = items.First();
return values.All(v => v == value1) ? value1: otherValue;

Bringing a subview to be in front of all other views

What if the ad provider's view is not added to self.view but to something like [UIApplication sharedApplication].keyWindow?

Try something like:

[[UIApplication sharedApplication].keyWindow addSubview:yourSubview]

or

[[UIApplication sharedApplication].keyWindow bringSubviewToFront:yourSubview]

What's the difference between django OneToOneField and ForeignKey?

OneToOneField (one-to-one) realizes, in object orientation, the notion of composition, while ForeignKey (one-to-many) relates to agregation.

Vue.JS: How to call function after page loaded?

You import the function from outside the main instance, and don't add it to the methods block. so the context of this is not the vm.

Either do this:

ready() {
  checkAuth.call(this)
}

or add the method to your methods first (which will make Vue bind this correctly for you) and call this method:

methods: {
  checkAuth: checkAuth
},
ready() {
  this.checkAuth()
}

Removing all script tags from html with JS Regular Expression

jQuery uses a regex to remove script tags in some cases and I'm pretty sure its devs had a damn good reason to do so. Probably some browser does execute scripts when inserting them using innerHTML.

Here's the regex:

/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi

And before people start crying "but regexes for HTML are evil": Yes, they are - but for script tags they are safe because of the special behaviour - a <script> section may not contain </script> at all unless it should end at this position. So matching it with a regex is easily possible. However, from a quick look the regex above does not account for trailing whitespace inside the closing tag so you'd have to test if </script    etc. will still work.

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

How to make Python speak

A simple Google led me to pyTTS, and a few documents about it. It looks unmaintained and specific to Microsoft's speech engine, however.

On at least Mac OS X, you can use subprocess to call out to the say command, which is quite fun for messing with your coworkers but might not be terribly useful for your needs.

It sounds like Festival has a few public APIs, too:

Festival offers a BSD socket-based interface. This allows Festival to run as a server and allow client programs to access it. Basically the server offers a new command interpreter for each client that attaches to it. The server is forked for each client but this is much faster than having to wait for a Festival process to start from scratch. Also the server can run on a bigger machine, offering much faster synthesis. linky

There's also a full-featured C++ API, which you might be able to make a Python module out of (it's fun!). Festival also offers a pared-down C API -- keep scrolling in that document -- which you might be able to throw ctypes at for a one-off.

Perhaps you've identified a hole in the market?

Python Iterate Dictionary by Index

There are some very good answers here. I'd like to add the following here as well:

some_dict = {
    "foo": "bar",
    "lorem": "ipsum"
}

for index, (key, value) in enumerate(some_dict.items()):
    print(index, key, value)

results in

0 foo bar
1 lorem ipsum

Appears to work with Python 2.7 and 3.5

m2eclipse not finding maven dependencies, artifacts not found

One of the reason I found was why it doesn't find a jar from repository might be because the .pom file for that particular jar might be missing or corrupt. Just correct it and try to load from local repository.

Popup window in PHP?

You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.

How to convert DateTime? to DateTime

You can also try Nullable(T) Properties:

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue 
    ? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;

How would you count occurrences of a string (actually a char) within a string?

string s = "HOWLYH THIS ACTUALLY WORKSH WOWH";
int count = 0;
for (int i = 0; i < s.Length; i++)
   if (s[i] == 'H') count++;

It just checks every character in the string, if the character is the character you are searching for, add one to count.

How do I print out the value of this boolean? (Java)

There are a couple of ways to address your problem, however this is probably the most straightforward:

Your main method is static, so it does not have access to instance members (isLeapYear field and isLeapYear method. One approach to rectify this is to make both the field and the method static as well:

static boolean isLeapYear;
/* (snip) */
public static boolean isLeapYear(int year)
{
  /* (snip) */
}

Lastly, you're not actually calling your isLeapYear method (which is why you're not seeing any results). Add this line after int year = kboard.nextInt();:

isLeapYear(year);

That should be a start. There are some other best practices you could follow but for now just focus on getting your code to work; you can refactor later.

How can I query a value in SQL Server XML column

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

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

Let's suppose that data column has this:

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

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

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

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

Querying XML fields using t-sql

Flattening XML Data in SQL Server

EDIT

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

Given this table structure:

create table MyTable (Roles XML)

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

We can query it like this:

select * from 

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

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

where RoleName like '%ga%'

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

How to use: while not in

In your case, ('AND' and 'OR' and 'NOT') evaluates to "NOT", which may or may not be in your list...

while 'AND' not in MyList and 'OR' not in MyList and 'NOT' not in MyList:
    print 'No Boolean Operator'

System.IO.IOException: file used by another process

After coming across this error and not finding anything on the web that set me right, I thought I'd add another reason for getting this Exception - namely that the source and destination paths in the File Copy command are the same. It took me a while to figure it out, but it may help to add code somewhere to throw an exception if source and destination paths are pointing to the same file.

Good luck!

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = new Date();_x000D_
  var timeDiff = endTime - startTime; //in ms_x000D_
  // strip the ms_x000D_
  timeDiff /= 1000;_x000D_
_x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document's lifetime.

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = performance.now();_x000D_
  var timeDiff = endTime - startTime; //in ms _x000D_
  // strip the ms _x000D_
  timeDiff /= 1000; _x000D_
  _x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

How do I rename a repository on GitHub?

  • Navigate to your repository path.
  • Click on setting button which is there in right panne.
  • Replace old repository name to new name.
  • Click on Rename button

How to parse a string to an int in C++?

In the new C++11 there are functions for that: stoi, stol, stoll, stoul and so on.

int myNr = std::stoi(myString);

It will throw an exception on conversion error.

Even these new functions still have the same issue as noted by Dan: they will happily convert the string "11x" to integer "11".

See more: http://en.cppreference.com/w/cpp/string/basic_string/stol

Is there a way to run Bash scripts on Windows?

There's one more theoretical possibility to do it: professional versions of Windows have built-in POSIX support, so bash could have been compiled for Windows natively.

Pity, but I still haven't found a compiled one myself...

UITableViewCell, show delete button on swipe

This code shows how to implement the delete.

#pragma mark - UITableViewDataSource

// Swipe to delete.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [_chats removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

Optionally, in your initialization override, add the line below to show the Edit button item:

self.navigationItem.leftBarButtonItem = self.editButtonItem;

MVC 4 Edit modal form using Bootstrap

In reply to Dimitrys answer but using Ajax.BeginForm the following works at least with MVC >5 (4 not tested).

  1. write a model as shown in the other answers,

  2. In the "parent view" you will probably use a table to show the data. Model should be an ienumerable. I assume, the model has an id-property. Howeverm below the template, a placeholder for the modal and corresponding javascript

    <table>
    @foreach (var item in Model)
    {
        <tr> <td id="[email protected]"> 
            @Html.Partial("dataRowView", item)
        </td> </tr>
    }
    </table>
    
    <div class="modal fade" id="editor-container" tabindex="-1" 
         role="dialog" aria-labelledby="editor-title">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content" id="editor-content-container"></div>
        </div>
    </div> 
    
    <script type="text/javascript">
        $(function () {
            $('.editor-container').click(function () {
                var url = "/area/controller/MyEditAction";  
                var id = $(this).attr('data-id');  
                $.get(url + '/' + id, function (data) {
                    $('#editor-content-container').html(data);
                    $('#editor-container').modal('show');
                });
            });
        });
    
        function success(data,status,xhr) {
            $('#editor-container').modal('hide');
            $('#editor-content-container').html("");
        }
    
        function failure(xhr,status,error) {
            $('#editor-content-container').html(xhr.responseText);
            $('#editor-container').modal('show');
        }
    </script>
    

note the "editor-success-id" in data table rows.

  1. The dataRowView is a partial containing the presentation of an model's item.

    @model ModelView
    @{
        var item = Model;
    }
    <div class="row">
            // some data 
            <button type="button" class="btn btn-danger editor-container" data-id="@item.Id">Edit</button>
    </div>
    
  2. Write the partial view that is called by clicking on row's button (via JS $('.editor-container').click(function () ... ).

    @model Model
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title" id="editor-title">Title</h4>
    </div>
    @using (Ajax.BeginForm("MyEditAction", "Controller", FormMethod.Post,
                        new AjaxOptions
                        {
                            InsertionMode = InsertionMode.Replace,
                            HttpMethod = "POST",
                            UpdateTargetId = "editor-success-" + @Model.Id,
                            OnSuccess = "success",
                            OnFailure = "failure",
                        }))
    {
        @Html.ValidationSummary()
        @Html.AntiForgeryToken()
        @Html.HiddenFor(model => model.Id)
        <div class="modal-body">
            <div class="form-horizontal">
                // Models input fields
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Save</button>
        </div>
    }
    

This is where magic happens: in AjaxOptions, UpdateTargetId will replace the data row after editing, onfailure and onsuccess will control the modal.

This is, the modal will only close when editing was successful and there have been no errors, otherwise the modal will be displayed after the ajax-posting to display error messages, e.g. the validation summary.

But how to get ajaxform to know if there is an error? This is the controller part, just change response.statuscode as below in step 5:

  1. the corresponding controller action method for the partial edit modal

    [HttpGet]
    public async Task<ActionResult> EditPartData(Guid? id)
    {
        // Find the data row and return the edit form
        Model input = await db.Models.FindAsync(id);
        return PartialView("EditModel", input);
    }
    
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> MyEditAction([Bind(Include =
       "Id,Fields,...")] ModelView input)
    {
        if (TryValidateModel(input))
        {  
            // save changes, return new data row  
            // status code is something in 200-range
            db.Entry(input).State = EntityState.Modified;
            await db.SaveChangesAsync();
            return PartialView("dataRowView", (ModelView)input);
        }
    
        // set the "error status code" that will redisplay the modal
        Response.StatusCode = 400;
        // and return the edit form, that will be displayed as a 
        // modal again - including the modelstate errors!
        return PartialView("EditModel", (Model)input);
    }
    

This way, if an error occurs while editing Model data in a modal window, the error will be displayed in the modal with validationsummary methods of MVC; but if changes were committed successfully, the modified data table will be displayed and the modal window disappears.

Note: you get ajaxoptions working, you need to tell your bundles configuration to bind jquery.unobtrusive-ajax.js (may be installed by NuGet):

        bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
                    "~/Scripts/jquery.unobtrusive-ajax.js"));

how to open a jar file in Eclipse

Try JadClipse.It will open all your .class file. Add library to your project and when you try to open any object declared in the lib file it will open just like your .java file.

In eclipse->help-> marketplace -> go to popular tab. There you can find plugins for the same.

Update: For those who are unable to find above plug-in, try downloading this: https://github.com/java-decompiler/jd-eclipse/releases/download/v1.0.0/jd-eclipse-site-1.0.0-RC2.zip

Then import it into Eclipse.

If you have issues importing above plug-in, refer: How to install plugin for Eclipse from .zip

How to get value of Radio Buttons?

An alterntive is to use an enum and a component class that extends the standard RadioButton.

public enum Genders
{
    Male,
    Female
}

[ToolboxBitmap(typeof(RadioButton))]
public partial class GenderRadioButton : RadioButton
{
    public GenderRadioButton()
    {
        InitializeComponent();
    }

    public GenderRadioButton (IContainer container)
    {
        container.Add(this);

        InitializeComponent();
    }

    public Genders gender{ get; set; }
}

Use a common event handler for the GenderRadioButtons

private void Gender_CheckedChanged(Object sender, EventArgs e)
{
    if (((RadioButton)sender).Checked)
    {
        //get selected value
        Genders myGender = ((GenderRadioButton)sender).Gender;
        //get the name of the enum value
        string GenderName = Enum.GetName(typeof(Genders ), myGender);
        //do any work required when you change gender
        switch (myGender)
        {
            case Genders.Male:
                break;
            case Genders.Female:
                break;
            default:
                break;
        }
    }
}

How to create a listbox in HTML without allowing multiple selection?

For Asp.Net MVC

@Html.ListBox("parameterName", ViewBag.ParameterValueList as MultiSelectList, 
 new { 
 @class = "chosen-select form-control"
 }) 

or

  @Html.ListBoxFor(model => model.parameterName,
  ViewBag.ParameterValueList as MultiSelectList,
   new{
       data_placeholder = "Select Options ",
       @class = "chosen-select form-control"
   })

Data binding for TextBox

I Recommend you implement INotifyPropertyChanged and change your databinding code to this:

this.textBox.DataBindings.Add("Text",
                                this.Food,
                                "Name",
                                false,
                                DataSourceUpdateMode.OnPropertyChanged);

That'll fix it.

Note that the default DataSourceUpdateMode is OnValidation, so if you don't specify OnPropertyChanged, the model object won't be updated until after your validations have occurred.

Can I check if Bootstrap Modal Shown / Hidden?

its an old question but anyway heres something i used incase someone was looking for the same thing

if (!$('#myModal').is(':visible')) {
    // if modal is not shown/visible then do something
}

What is the best JavaScript code to create an img element

oImg.setAttribute('width', '1px');

px is for CSS only. Use either:

oImg.width = '1';

to set a width through HTML, or:

oImg.style.width = '1px';

to set it through CSS.

Note that old versions of IE don't create a proper image with document.createElement(), and old versions of KHTML don't create a proper DOM Node with new Image(), so if you want to be fully backwards compatible use something like:

// IEWIN boolean previously sniffed through eg. conditional comments

function img_create(src, alt, title) {
    var img = IEWIN ? new Image() : document.createElement('img');
    img.src = src;
    if ( alt != null ) img.alt = alt;
    if ( title != null ) img.title = title;
    return img;
}

Also be slightly wary of document.body.appendChild if the script may execute as the page is in the middle of loading. You can end up with the image in an unexpected place, or a weird JavaScript error on IE. If you need to be able to add it at load-time (but after the <body> element has started), you could try inserting it at the start of the body using body.insertBefore(body.firstChild).

To do this invisibly but still have the image actually load in all browsers, you could insert an absolutely-positioned-off-the-page <div> as the body's first child and put any tracking/preload images you don't want to be visible in there.

Uri not Absolute exception getting while calling Restful Webservice

For others who landed in this error and it's not 100% related to the OP question, please check that you are passing the value and it is not null in case of spring-boot: @Value annotation.

How to replace (null) values with 0 output in PIVOT

You have to account for all values in the pivot set. you can accomplish this using a cartesian product.

select pivoted.*
from (
    select cartesian.key1, cartesian.key2, isnull(relationship.[value],'nullvalue') as [value]
    from (
      select k1.key1, k2.key2
      from ( select distinct key1 from relationship) k1
          ,( select distinct key2 from relationship) k2
    ) cartesian
      left outer join relationship on relationship.key1 = cartesian.key1 and  relationship.key2 = carterisan.key2
) data
  pivot (
    max(data.value) for ([key2_v1], [key2_v2], [key2_v3], ...)
  ) pivoted

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

/*Maximum value that can be entered is 2,147,483,647
 * Program to convert entered number into string
 * */
import java.util.Scanner;

public class NumberToWords 
{

public static void main(String[] args) 
{
    double num;//for taking input number
    Scanner obj=new Scanner(System.in);
    do
    {
        System.out.println("\n\nEnter the Number (Maximum value that can be entered is 2,147,483,647)");
        num=obj.nextDouble();
        if(num<=2147483647)//checking if entered number exceeds maximum integer value
        {
            int number=(int)num;//type casting double number to integer number
            splitNumber(number);//calling splitNumber-it will split complete number in pairs of 3 digits
        }
        else
            System.out.println("Enter smaller value");//asking user to enter a smaller value compared to 2,147,483,647
    }while(num>2147483647);
}
//function to split complete number into pair of 3 digits each
public static void splitNumber(int number)
{   //splitNumber array-contains the numbers in pair of 3 digits
    int splitNumber[]=new int[4],temp=number,i=0,index;
    //splitting number into pair of 3
    if(temp==0)
        System.out.println("zero");
    while(temp!=0)
    {
        splitNumber[i++]=temp%1000;
        temp/=1000;
    }
    //passing each pair of 3 digits to another function
    for(int j=i-1;j>-1;j--)
    {   //toWords function will split pair of 3 digits to separate digits
        if(splitNumber[j]!=0)
            {toWords(splitNumber[j]);
        if(j==3)//if the number contained more than 9 digits
            System.out.print("billion,");
        else if(j==2)//if the number contained more than 6 digits & less than 10 digits
            System.out.print("million,");
        else if(j==1)
            System.out.print("thousand,");//if the number contained more than 3 digits & less than 7 digits
            }
            }       
}
//function that splits number into individual digits
public static void toWords(int number)
    //splitSmallNumber array contains individual digits of number passed to this function
{   int splitSmallNumber[]=new int[3],i=0,j;
    int temp=number;//making temporary copy of the number
    //logic to split number into its constituent digits

    while(temp!=0)
    {
        splitSmallNumber[i++]=temp%10;
        temp/=10;
    }
    //printing words for each digit
    for(j=i-1;j>-1;j--)
      //{   if the digit is greater than zero
        if(splitSmallNumber[j]>=0)
            //if the digit is at 3rd place or if digit is at (1st place with digit at 2nd place not equal to zero)
        {   if(j==2||(j==0 && (splitSmallNumber[1]!=1)))
            {
                switch(splitSmallNumber[j])
                {

                    case 1:System.out.print("one ");break;
                    case 2:System.out.print("two ");break;
                    case 3:System.out.print("three ");break;
                    case 4:System.out.print("four ");break;
                    case 5:System.out.print("five ");break;
                    case 6:System.out.print("six ");break;
                    case 7:System.out.print("seven ");break;
                    case 8:System.out.print("eight ");break;
                    case 9:System.out.print("nine ");break;

            }

        }
        //if digit is at 2nd place
        if(j==1)
        {       //if digit at 2nd place is 0 or 1
                if(((splitSmallNumber[j]==0)||(splitSmallNumber[j]==1))&& splitSmallNumber[2]!=0 )
                System.out.print("hundred ");
            switch(splitSmallNumber[1])
            {   case 1://if digit at 2nd place is 1 example-213
                        switch(splitSmallNumber[0])
                        {
                        case 1:System.out.print("eleven ");break;
                        case 2:System.out.print("twelve ");break;
                        case 3:System.out.print("thirteen ");break;
                        case 4:System.out.print("fourteen ");break;
                        case 5:System.out.print("fifteen ");break;
                        case 6:System.out.print("sixteen ");break;
                        case 7:System.out.print("seventeen ");break;
                        case 8:System.out.print("eighteen ");break;
                        case 9:System.out.print("nineteen ");break;
                        case 0:System.out.print("ten ");break;
                        }break;
                        //if digit at 2nd place is not 1
                    case 2:System.out.print("twenty ");break;
                    case 3:System.out.print("thirty ");break;
                    case 4:System.out.print("forty ");break;
                    case 5:System.out.print("fifty ");break;
                    case 6:System.out.print("sixty ");break;
                    case 7:System.out.print("seventy ");break;
                    case 8:System.out.print("eighty ");break;
                    case 9:System.out.print("ninety ");break;
                    //case 0:   System.out.println("hundred ");break;

            }                           
        }           
    }
  }

}

jQuery hover and class selector

I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript.

You can use the ":hover" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an "a" element.

.menuItem
{
    display: inline;
    background-color: #000;

    /* width and height should not work on inline elements */
    /* if this works, your browser is doing the rendering  */
    /* in quirks mode which will not be compatible with    */
    /* other browsers - but this will not work on touch mobile devices like android */

}
.menuItem a:hover 
{
    background-color:#F00;
}

Why do I need to override the equals and hashCode methods in Java?

Both the methods are defined in Object class. And both are in its simplest implementation. So when you need you want add some more implementation to these methods then you have override in your class.

For Ex: equals() method in object only checks its equality on the reference. So if you need compare its state as well then you can override that as it is done in String class.

Rounding up to next power of 2

I'm trying to get nearest lower power of 2 and made this function. May it help you.Just multiplied nearest lower number times 2 to get nearest upper power of 2

int nearest_upper_power(int number){
    int temp=number;
    while((number&(number-1))!=0){
        temp<<=1;
        number&=temp;
    }
    //Here number is closest lower power 
    number*=2;
    return number;
}

CSS text-transform capitalize on all caps

if you are using jQuery; this is one a way to do it:

$('.link').each(function() {
    $(this).css('text-transform','capitalize').text($(this).text().toLowerCase());
});

Here is an easier to read version doing the same thing:

//Iterate all the elements in jQuery object
$('.link').each(function() {

    //get text from element and make it lower-case
    var string = $(this).text().toLowerCase();

    //set element text to the new string that is lower-case
    $(this).text(string);

    //set the css to capitalize
    $(this).css('text-transform','capitalize');
});

Demo

Bytes of a string in Java

A string is a list of characters (i.e. code points). The number of bytes taken to represent the string depends entirely on which encoding you use to turn it into bytes.

That said, you can turn the string into a byte array and then look at its size as follows:

// The input string for this test
final String string = "Hello World";

// Check length, in characters
System.out.println(string.length()); // prints "11"

// Check encoded sizes
final byte[] utf8Bytes = string.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "11"

final byte[] utf16Bytes= string.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "24"

final byte[] utf32Bytes = string.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "44"

final byte[] isoBytes = string.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "11"

final byte[] winBytes = string.getBytes("CP1252");
System.out.println(winBytes.length); // prints "11"

So you see, even a simple "ASCII" string can have different number of bytes in its representation, depending which encoding is used. Use whichever character set you're interested in for your case, as the argument to getBytes(). And don't fall into the trap of assuming that UTF-8 represents every character as a single byte, as that's not true either:

final String interesting = "\uF93D\uF936\uF949\uF942"; // Chinese ideograms

// Check length, in characters
System.out.println(interesting.length()); // prints "4"

// Check encoded sizes
final byte[] utf8Bytes = interesting.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "12"

final byte[] utf16Bytes= interesting.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "10"

final byte[] utf32Bytes = interesting.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "16"

final byte[] isoBytes = interesting.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "4" (probably encoded "????")

final byte[] winBytes = interesting.getBytes("CP1252");
System.out.println(winBytes.length); // prints "4" (probably encoded "????")

(Note that if you don't provide a character set argument, the platform's default character set is used. This might be useful in some contexts, but in general you should avoid depending on defaults, and always use an explicit character set when encoding/decoding is required.)

.NET - Get protocol, host, and port

Very similar to Holger's answer. If you need to grab the URL can do something like:

Uri uri = Context.Request.Url;         
var scheme = uri.Scheme // returns http, https
var scheme2 = uri.Scheme + Uri.SchemeDelimiter; // returns http://, https://
var host = uri.Host; // return www.mywebsite.com
var port = uri.Port; // returns port number

The Uri class provides a whole range of methods, many which I have not listed.

In my instance, I needed to grab LocalHost along with the Port Number, so this is what I did:

var Uri uri = Context.Request.Url;
var host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port; 

Which successfully grabbed: http://localhost:12345

Semaphore vs. Monitors - what's the difference?

When a semaphore is used to guard a critical region, there is no direct relationship between the semaphore and the data being protected. This is part of the reason why semaphores may be dispersed around the code, and why it is easy to forget to call wait or notify, in which case the result will be, respectively, to violate mutual exclusion or to lock the resource permanently.

In contrast, niehter of these bad things can happen with a monitor. A monitor is tired directly to the data (it encapsulates the data) and, because the monitor operations are atomic actions, it is impossible to write code that can access the data without calling the entry protocol. The exit protocol is called automatically when the monitor operation is completed.

A monitor has a built-in mechanism for condition synchronisation in the form of condition variable before proceeding. If the condition is not satisfied, the process has to wait until it is notified of a change in the condition. When a process is waiting for condition synchronisation, the monitor implementation takes care of the mutual exclusion issue, and allows another process to gain access to the monitor.

Taken from The Open University M362 Unit 3 "Interacting process" course material.

Grant Select on all Tables Owned By Specific User

Well, it's not a single statement, but it's about as close as you can get with oracle:

BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
      EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
   END LOOP;
END; 

C# DataRow Empty-check

Maybe a better solution would be to add an extra column that is automatically set to 1 on each row. As soon as there is an element that is not null change it to a 0.

then

If(drEntitity.rows[i].coulmn[8] = 1)
{
   dtEntity.Rows.Add(drEntity);
}
 else
 {
   //don't add, will create a new one (drEntity = dtEntity.NewRow();)
 }

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

My 2 cents on the problem: I was experiencing the same problem, while some part of my path was in Cyrillic. So check the path to your project for special characters. Once I removed this, the problem was fixed

Replace a value in a data frame based on a conditional (`if`) statement

If you are working with character variables (note that stringsAsFactors is false here) you can use replace:

junk <- data.frame(x <- rep(LETTERS[1:4], 3), y <- letters[1:12], stringsAsFactors = FALSE)
colnames(junk) <- c("nm", "val")

junk$nm <- replace(junk$nm, junk$nm == "B", "b")
junk
#    nm val
# 1   A   a
# 2   b   b
# 3   C   c
# 4   D   d
# ...

Get all files that have been modified in git branch

The following batch file is based on twalberg's answer but will work in Windows:

@ECHO OFF
C:                               :: <== OR USE A DIFFERENT DRIVE
CD \path\to\where\git\files\are  :: <== CHANGE TO THE ACTUAL PATH
SET /p b="Enter full path of an ALREADY MERGED branch to compare with origin/master: "
bash --login -i -c "git diff --name-only %b% $(git merge-base %b1% origin/drop2/master)"
PAUSE

The above assumes that the main branch is origin/master and that git bash was included when Git was installed (and its location is in the path environment). I actually needed to show the actual differences using a configured diff tool (kdiff3) so substituted the following bash command above:

bash --login -i -c "git difftool --dir-diff %b% $(git merge-base %b1% origin/drop2/master)"

Printing all properties in a Javascript Object

What about this:

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

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

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

Update 2019.

You can now use the object-fit css property that accepts the following values: fill | contain | cover | none | scale-down

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

As an example, you could have a container that holds an image.

<div class="container">
    <img src="" class="container_img" />
</div>

.container {
    height: 50px;
    width: 50%;

.container_img {
    height: 100%;
    width: 100%;
    object-fit: cover;

How to connect android emulator to the internet

I think sometimes it's just enogh to simply restart the virtual device. :-)

android on Text Change Listener

Add background dynamically in onCreate method:

getWindow().setBackgroundDrawableResource(R.drawable.background);

also remove background from XML.

Strtotime() doesn't work with dd/mm/YYYY format

This workaround is simpler and more elegant than explode:

$my_date = str_replace("/", ".", $my_date);
$my_date = strtotime($my_date);
$my_date = date("Y-m-d", $my_date);

You don't have to know what format you're getting the date in, but if it comes with slashes they are replaced with full stops and it is treated as European by strtotime.

Java Equivalent of C# async/await?

Java itself has no equivalent features, but third-party libraries exist which offer similar functionality, e.g.Kilim.

How to use WebRequest to POST some data and read response?

Here's what works for me. I'm sure it can be improved, so feel free to make suggestions or edit to make it better.

const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod";
//This string is untested, but I think it's ok.
string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\"  }"; 
try
{       
    var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.Timeout = 20000;
        webRequest.ContentType = "application/json";

    using (System.IO.Stream s = webRequest.GetRequestStream())
    {
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
            sw.Write(jsonData);
    }

    using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
    {
        using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
        {
            var jsonResponse = sr.ReadToEnd();
            System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse));
        }
    }
}
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.ToString());
}

php $_GET and undefined index

I was having the same problem in localhost with xampp. Now I'm using this combination of parameters:

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

php.net: http://php.net/manual/pt_BR/function.error-reporting.php

How to create virtual column using MySQL SELECT?

You could use a CASE statement, like

SELECT name
       ,address
       ,CASE WHEN a < b THEN '1' 
             ELSE '2' END AS one_or_two
FROM ...

How to exit an if clause

There is another way which doesn't rely on defining functions (because sometimes that's less readable for small code snippets), doesn't use an extra outer while loop (which might need special appreciation in the comments to even be understandable on first sight), doesn't use goto (...) and most importantly let's you keep your indentation level for the outer if so you don't have to start nesting stuff.

if some_condition:
   ...
   if condition_a:
       # do something
       exit_if=True # and then exit the outer if block
if some condition and not exit_if: # if and only if exit_if wasn't set we want to execute the following code
   # keep doing something
   if condition_b:
       # do something
       exit_if=True # and then exit the outer if block
if some condition and not exit_if:
   # keep doing something

Yes, that also needs a second look for readability, however, if the snippets of code are small this doesn't require to track any while loops that will never repeat and after understanding what the intermediate ifs are for, it's easily readable, all in one place and with the same indentation.

And it should be pretty efficient.

Set Value of Input Using Javascript Function

The following works in MVC5:

document.getElementById('theID').value = 'new value';

Any way to select without causing locking in MySQL?

You may want to read this page of the MySQL manual. How a table gets locked is dependent on what type of table it is.

MyISAM uses table locks to achieve a very high read speed, but if you have an UPDATE statement waiting, then future SELECTS will queue up behind the UPDATE.

InnoDB tables use row-level locking, and you won't have the whole table lock up behind an UPDATE. There are other kind of locking issues associated with InnoDB, but you might find it fits your needs.

CSS transition shorthand with multiple properties?

This helped me understand / streamline, only what I needed to animate:

// SCSS - Multiple Animation: Properties | durations | etc.
// on hover, animate div (width/opacity) - from: {0px, 0} to: {100vw, 1}

.base {
  max-width: 0vw;
  opacity: 0;

  transition-property: max-width, opacity; // relative order
  transition-duration: 2s, 4s; // effects relatively ordered animation properties
  transition-delay: 6s; // effects delay of all animation properties
  animation-timing-function: ease;

  &:hover {
    max-width: 100vw;
    opacity: 1;

    transition-duration: 5s; // effects duration of all aniomation properties
    transition-delay: 2s, 7s; // effects relatively ordered animation properties
  }
}

~ This applies for all transition properties (duration, transition-timing-function, etc.) within the '.base' class

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

import React, {Component} from 'react';
import {StyleSheet, View} from 'react-native';


export default class App extends Component {
  render() {
    return (
       <View>// you need to wrap the two Views an another View
          <View style={styles.box1}></View>
          <View style={styles.box2}></View>
       </View> 
    );
  }
}

const styles = StyleSheet.create({
  box1:{
    height:100,
    width:100,
    backgroundColor:'red'
  },
  box2:{
    height:100,
    width:100,
    backgroundColor:'green',
    position: 'absolute',
    top:10,
    left:30

  },
});

Get Locale Short Date Format using javascript

function getLocaleShortDateString(d)
{
    var f={"ar-SA":"dd/MM/yy","bg-BG":"dd.M.yyyy","ca-ES":"dd/MM/yyyy","zh-TW":"yyyy/M/d","cs-CZ":"d.M.yyyy","da-DK":"dd-MM-yyyy","de-DE":"dd.MM.yyyy","el-GR":"d/M/yyyy","en-US":"M/d/yyyy","fi-FI":"d.M.yyyy","fr-FR":"dd/MM/yyyy","he-IL":"dd/MM/yyyy","hu-HU":"yyyy. MM. dd.","is-IS":"d.M.yyyy","it-IT":"dd/MM/yyyy","ja-JP":"yyyy/MM/dd","ko-KR":"yyyy-MM-dd","nl-NL":"d-M-yyyy","nb-NO":"dd.MM.yyyy","pl-PL":"yyyy-MM-dd","pt-BR":"d/M/yyyy","ro-RO":"dd.MM.yyyy","ru-RU":"dd.MM.yyyy","hr-HR":"d.M.yyyy","sk-SK":"d. M. yyyy","sq-AL":"yyyy-MM-dd","sv-SE":"yyyy-MM-dd","th-TH":"d/M/yyyy","tr-TR":"dd.MM.yyyy","ur-PK":"dd/MM/yyyy","id-ID":"dd/MM/yyyy","uk-UA":"dd.MM.yyyy","be-BY":"dd.MM.yyyy","sl-SI":"d.M.yyyy","et-EE":"d.MM.yyyy","lv-LV":"yyyy.MM.dd.","lt-LT":"yyyy.MM.dd","fa-IR":"MM/dd/yyyy","vi-VN":"dd/MM/yyyy","hy-AM":"dd.MM.yyyy","az-Latn-AZ":"dd.MM.yyyy","eu-ES":"yyyy/MM/dd","mk-MK":"dd.MM.yyyy","af-ZA":"yyyy/MM/dd","ka-GE":"dd.MM.yyyy","fo-FO":"dd-MM-yyyy","hi-IN":"dd-MM-yyyy","ms-MY":"dd/MM/yyyy","kk-KZ":"dd.MM.yyyy","ky-KG":"dd.MM.yy","sw-KE":"M/d/yyyy","uz-Latn-UZ":"dd/MM yyyy","tt-RU":"dd.MM.yyyy","pa-IN":"dd-MM-yy","gu-IN":"dd-MM-yy","ta-IN":"dd-MM-yyyy","te-IN":"dd-MM-yy","kn-IN":"dd-MM-yy","mr-IN":"dd-MM-yyyy","sa-IN":"dd-MM-yyyy","mn-MN":"yy.MM.dd","gl-ES":"dd/MM/yy","kok-IN":"dd-MM-yyyy","syr-SY":"dd/MM/yyyy","dv-MV":"dd/MM/yy","ar-IQ":"dd/MM/yyyy","zh-CN":"yyyy/M/d","de-CH":"dd.MM.yyyy","en-GB":"dd/MM/yyyy","es-MX":"dd/MM/yyyy","fr-BE":"d/MM/yyyy","it-CH":"dd.MM.yyyy","nl-BE":"d/MM/yyyy","nn-NO":"dd.MM.yyyy","pt-PT":"dd-MM-yyyy","sr-Latn-CS":"d.M.yyyy","sv-FI":"d.M.yyyy","az-Cyrl-AZ":"dd.MM.yyyy","ms-BN":"dd/MM/yyyy","uz-Cyrl-UZ":"dd.MM.yyyy","ar-EG":"dd/MM/yyyy","zh-HK":"d/M/yyyy","de-AT":"dd.MM.yyyy","en-AU":"d/MM/yyyy","es-ES":"dd/MM/yyyy","fr-CA":"yyyy-MM-dd","sr-Cyrl-CS":"d.M.yyyy","ar-LY":"dd/MM/yyyy","zh-SG":"d/M/yyyy","de-LU":"dd.MM.yyyy","en-CA":"dd/MM/yyyy","es-GT":"dd/MM/yyyy","fr-CH":"dd.MM.yyyy","ar-DZ":"dd-MM-yyyy","zh-MO":"d/M/yyyy","de-LI":"dd.MM.yyyy","en-NZ":"d/MM/yyyy","es-CR":"dd/MM/yyyy","fr-LU":"dd/MM/yyyy","ar-MA":"dd-MM-yyyy","en-IE":"dd/MM/yyyy","es-PA":"MM/dd/yyyy","fr-MC":"dd/MM/yyyy","ar-TN":"dd-MM-yyyy","en-ZA":"yyyy/MM/dd","es-DO":"dd/MM/yyyy","ar-OM":"dd/MM/yyyy","en-JM":"dd/MM/yyyy","es-VE":"dd/MM/yyyy","ar-YE":"dd/MM/yyyy","en-029":"MM/dd/yyyy","es-CO":"dd/MM/yyyy","ar-SY":"dd/MM/yyyy","en-BZ":"dd/MM/yyyy","es-PE":"dd/MM/yyyy","ar-JO":"dd/MM/yyyy","en-TT":"dd/MM/yyyy","es-AR":"dd/MM/yyyy","ar-LB":"dd/MM/yyyy","en-ZW":"M/d/yyyy","es-EC":"dd/MM/yyyy","ar-KW":"dd/MM/yyyy","en-PH":"M/d/yyyy","es-CL":"dd-MM-yyyy","ar-AE":"dd/MM/yyyy","es-UY":"dd/MM/yyyy","ar-BH":"dd/MM/yyyy","es-PY":"dd/MM/yyyy","ar-QA":"dd/MM/yyyy","es-BO":"dd/MM/yyyy","es-SV":"dd/MM/yyyy","es-HN":"dd/MM/yyyy","es-NI":"dd/MM/yyyy","es-PR":"dd/MM/yyyy","am-ET":"d/M/yyyy","tzm-Latn-DZ":"dd-MM-yyyy","iu-Latn-CA":"d/MM/yyyy","sma-NO":"dd.MM.yyyy","mn-Mong-CN":"yyyy/M/d","gd-GB":"dd/MM/yyyy","en-MY":"d/M/yyyy","prs-AF":"dd/MM/yy","bn-BD":"dd-MM-yy","wo-SN":"dd/MM/yyyy","rw-RW":"M/d/yyyy","qut-GT":"dd/MM/yyyy","sah-RU":"MM.dd.yyyy","gsw-FR":"dd/MM/yyyy","co-FR":"dd/MM/yyyy","oc-FR":"dd/MM/yyyy","mi-NZ":"dd/MM/yyyy","ga-IE":"dd/MM/yyyy","se-SE":"yyyy-MM-dd","br-FR":"dd/MM/yyyy","smn-FI":"d.M.yyyy","moh-CA":"M/d/yyyy","arn-CL":"dd-MM-yyyy","ii-CN":"yyyy/M/d","dsb-DE":"d. M. yyyy","ig-NG":"d/M/yyyy","kl-GL":"dd-MM-yyyy","lb-LU":"dd/MM/yyyy","ba-RU":"dd.MM.yy","nso-ZA":"yyyy/MM/dd","quz-BO":"dd/MM/yyyy","yo-NG":"d/M/yyyy","ha-Latn-NG":"d/M/yyyy","fil-PH":"M/d/yyyy","ps-AF":"dd/MM/yy","fy-NL":"d-M-yyyy","ne-NP":"M/d/yyyy","se-NO":"dd.MM.yyyy","iu-Cans-CA":"d/M/yyyy","sr-Latn-RS":"d.M.yyyy","si-LK":"yyyy-MM-dd","sr-Cyrl-RS":"d.M.yyyy","lo-LA":"dd/MM/yyyy","km-KH":"yyyy-MM-dd","cy-GB":"dd/MM/yyyy","bo-CN":"yyyy/M/d","sms-FI":"d.M.yyyy","as-IN":"dd-MM-yyyy","ml-IN":"dd-MM-yy","en-IN":"dd-MM-yyyy","or-IN":"dd-MM-yy","bn-IN":"dd-MM-yy","tk-TM":"dd.MM.yy","bs-Latn-BA":"d.M.yyyy","mt-MT":"dd/MM/yyyy","sr-Cyrl-ME":"d.M.yyyy","se-FI":"d.M.yyyy","zu-ZA":"yyyy/MM/dd","xh-ZA":"yyyy/MM/dd","tn-ZA":"yyyy/MM/dd","hsb-DE":"d. M. yyyy","bs-Cyrl-BA":"d.M.yyyy","tg-Cyrl-TJ":"dd.MM.yy","sr-Latn-BA":"d.M.yyyy","smj-NO":"dd.MM.yyyy","rm-CH":"dd/MM/yyyy","smj-SE":"yyyy-MM-dd","quz-EC":"dd/MM/yyyy","quz-PE":"dd/MM/yyyy","hr-BA":"d.M.yyyy.","sr-Latn-ME":"d.M.yyyy","sma-SE":"yyyy-MM-dd","en-SG":"d/M/yyyy","ug-CN":"yyyy-M-d","sr-Cyrl-BA":"d.M.yyyy","es-US":"M/d/yyyy"};

    var l=navigator.language?navigator.language:navigator['userLanguage'],y=d.getFullYear(),m=d.getMonth()+1,d=d.getDate();
    f=(l in f)?f[l]:"MM/dd/yyyy";
    function z(s){s=''+s;return s.length>1?s:'0'+s;}
    f=f.replace(/yyyy/,y);f=f.replace(/yy/,String(y).substr(2));
    f=f.replace(/MM/,z(m));f=f.replace(/M/,m);
    f=f.replace(/dd/,z(d));f=f.replace(/d/,d);
    return f;
}

using:

shortedDate=getLocaleShortDateString(new Date(1992, 0, 7));

_x000D_
_x000D_
shortedDate = getLocaleShortDateString(new Date(1992, 0, 7));_x000D_
console.log(shortedDate);_x000D_
_x000D_
function getLocaleShortDateString(d) {_x000D_
  var f={"ar-SA":"dd/MM/yy","bg-BG":"dd.M.yyyy","ca-ES":"dd/MM/yyyy","zh-TW":"yyyy/M/d","cs-CZ":"d.M.yyyy","da-DK":"dd-MM-yyyy","de-DE":"dd.MM.yyyy","el-GR":"d/M/yyyy","en-US":"M/d/yyyy","fi-FI":"d.M.yyyy","fr-FR":"dd/MM/yyyy","he-IL":"dd/MM/yyyy","hu-HU":"yyyy. MM. dd.","is-IS":"d.M.yyyy","it-IT":"dd/MM/yyyy","ja-JP":"yyyy/MM/dd","ko-KR":"yyyy-MM-dd","nl-NL":"d-M-yyyy","nb-NO":"dd.MM.yyyy","pl-PL":"yyyy-MM-dd","pt-BR":"d/M/yyyy","ro-RO":"dd.MM.yyyy","ru-RU":"dd.MM.yyyy","hr-HR":"d.M.yyyy","sk-SK":"d. M. yyyy","sq-AL":"yyyy-MM-dd","sv-SE":"yyyy-MM-dd","th-TH":"d/M/yyyy","tr-TR":"dd.MM.yyyy","ur-PK":"dd/MM/yyyy","id-ID":"dd/MM/yyyy","uk-UA":"dd.MM.yyyy","be-BY":"dd.MM.yyyy","sl-SI":"d.M.yyyy","et-EE":"d.MM.yyyy","lv-LV":"yyyy.MM.dd.","lt-LT":"yyyy.MM.dd","fa-IR":"MM/dd/yyyy","vi-VN":"dd/MM/yyyy","hy-AM":"dd.MM.yyyy","az-Latn-AZ":"dd.MM.yyyy","eu-ES":"yyyy/MM/dd","mk-MK":"dd.MM.yyyy","af-ZA":"yyyy/MM/dd","ka-GE":"dd.MM.yyyy","fo-FO":"dd-MM-yyyy","hi-IN":"dd-MM-yyyy","ms-MY":"dd/MM/yyyy","kk-KZ":"dd.MM.yyyy","ky-KG":"dd.MM.yy","sw-KE":"M/d/yyyy","uz-Latn-UZ":"dd/MM yyyy","tt-RU":"dd.MM.yyyy","pa-IN":"dd-MM-yy","gu-IN":"dd-MM-yy","ta-IN":"dd-MM-yyyy","te-IN":"dd-MM-yy","kn-IN":"dd-MM-yy","mr-IN":"dd-MM-yyyy","sa-IN":"dd-MM-yyyy","mn-MN":"yy.MM.dd","gl-ES":"dd/MM/yy","kok-IN":"dd-MM-yyyy","syr-SY":"dd/MM/yyyy","dv-MV":"dd/MM/yy","ar-IQ":"dd/MM/yyyy","zh-CN":"yyyy/M/d","de-CH":"dd.MM.yyyy","en-GB":"dd/MM/yyyy","es-MX":"dd/MM/yyyy","fr-BE":"d/MM/yyyy","it-CH":"dd.MM.yyyy","nl-BE":"d/MM/yyyy","nn-NO":"dd.MM.yyyy","pt-PT":"dd-MM-yyyy","sr-Latn-CS":"d.M.yyyy","sv-FI":"d.M.yyyy","az-Cyrl-AZ":"dd.MM.yyyy","ms-BN":"dd/MM/yyyy","uz-Cyrl-UZ":"dd.MM.yyyy","ar-EG":"dd/MM/yyyy","zh-HK":"d/M/yyyy","de-AT":"dd.MM.yyyy","en-AU":"d/MM/yyyy","es-ES":"dd/MM/yyyy","fr-CA":"yyyy-MM-dd","sr-Cyrl-CS":"d.M.yyyy","ar-LY":"dd/MM/yyyy","zh-SG":"d/M/yyyy","de-LU":"dd.MM.yyyy","en-CA":"dd/MM/yyyy","es-GT":"dd/MM/yyyy","fr-CH":"dd.MM.yyyy","ar-DZ":"dd-MM-yyyy","zh-MO":"d/M/yyyy","de-LI":"dd.MM.yyyy","en-NZ":"d/MM/yyyy","es-CR":"dd/MM/yyyy","fr-LU":"dd/MM/yyyy","ar-MA":"dd-MM-yyyy","en-IE":"dd/MM/yyyy","es-PA":"MM/dd/yyyy","fr-MC":"dd/MM/yyyy","ar-TN":"dd-MM-yyyy","en-ZA":"yyyy/MM/dd","es-DO":"dd/MM/yyyy","ar-OM":"dd/MM/yyyy","en-JM":"dd/MM/yyyy","es-VE":"dd/MM/yyyy","ar-YE":"dd/MM/yyyy","en-029":"MM/dd/yyyy","es-CO":"dd/MM/yyyy","ar-SY":"dd/MM/yyyy","en-BZ":"dd/MM/yyyy","es-PE":"dd/MM/yyyy","ar-JO":"dd/MM/yyyy","en-TT":"dd/MM/yyyy","es-AR":"dd/MM/yyyy","ar-LB":"dd/MM/yyyy","en-ZW":"M/d/yyyy","es-EC":"dd/MM/yyyy","ar-KW":"dd/MM/yyyy","en-PH":"M/d/yyyy","es-CL":"dd-MM-yyyy","ar-AE":"dd/MM/yyyy","es-UY":"dd/MM/yyyy","ar-BH":"dd/MM/yyyy","es-PY":"dd/MM/yyyy","ar-QA":"dd/MM/yyyy","es-BO":"dd/MM/yyyy","es-SV":"dd/MM/yyyy","es-HN":"dd/MM/yyyy","es-NI":"dd/MM/yyyy","es-PR":"dd/MM/yyyy","am-ET":"d/M/yyyy","tzm-Latn-DZ":"dd-MM-yyyy","iu-Latn-CA":"d/MM/yyyy","sma-NO":"dd.MM.yyyy","mn-Mong-CN":"yyyy/M/d","gd-GB":"dd/MM/yyyy","en-MY":"d/M/yyyy","prs-AF":"dd/MM/yy","bn-BD":"dd-MM-yy","wo-SN":"dd/MM/yyyy","rw-RW":"M/d/yyyy","qut-GT":"dd/MM/yyyy","sah-RU":"MM.dd.yyyy","gsw-FR":"dd/MM/yyyy","co-FR":"dd/MM/yyyy","oc-FR":"dd/MM/yyyy","mi-NZ":"dd/MM/yyyy","ga-IE":"dd/MM/yyyy","se-SE":"yyyy-MM-dd","br-FR":"dd/MM/yyyy","smn-FI":"d.M.yyyy","moh-CA":"M/d/yyyy","arn-CL":"dd-MM-yyyy","ii-CN":"yyyy/M/d","dsb-DE":"d. M. yyyy","ig-NG":"d/M/yyyy","kl-GL":"dd-MM-yyyy","lb-LU":"dd/MM/yyyy","ba-RU":"dd.MM.yy","nso-ZA":"yyyy/MM/dd","quz-BO":"dd/MM/yyyy","yo-NG":"d/M/yyyy","ha-Latn-NG":"d/M/yyyy","fil-PH":"M/d/yyyy","ps-AF":"dd/MM/yy","fy-NL":"d-M-yyyy","ne-NP":"M/d/yyyy","se-NO":"dd.MM.yyyy","iu-Cans-CA":"d/M/yyyy","sr-Latn-RS":"d.M.yyyy","si-LK":"yyyy-MM-dd","sr-Cyrl-RS":"d.M.yyyy","lo-LA":"dd/MM/yyyy","km-KH":"yyyy-MM-dd","cy-GB":"dd/MM/yyyy","bo-CN":"yyyy/M/d","sms-FI":"d.M.yyyy","as-IN":"dd-MM-yyyy","ml-IN":"dd-MM-yy","en-IN":"dd-MM-yyyy","or-IN":"dd-MM-yy","bn-IN":"dd-MM-yy","tk-TM":"dd.MM.yy","bs-Latn-BA":"d.M.yyyy","mt-MT":"dd/MM/yyyy","sr-Cyrl-ME":"d.M.yyyy","se-FI":"d.M.yyyy","zu-ZA":"yyyy/MM/dd","xh-ZA":"yyyy/MM/dd","tn-ZA":"yyyy/MM/dd","hsb-DE":"d. M. yyyy","bs-Cyrl-BA":"d.M.yyyy","tg-Cyrl-TJ":"dd.MM.yy","sr-Latn-BA":"d.M.yyyy","smj-NO":"dd.MM.yyyy","rm-CH":"dd/MM/yyyy","smj-SE":"yyyy-MM-dd","quz-EC":"dd/MM/yyyy","quz-PE":"dd/MM/yyyy","hr-BA":"d.M.yyyy.","sr-Latn-ME":"d.M.yyyy","sma-SE":"yyyy-MM-dd","en-SG":"d/M/yyyy","ug-CN":"yyyy-M-d","sr-Cyrl-BA":"d.M.yyyy","es-US":"M/d/yyyy"};_x000D_
_x000D_
  var l = navigator.language ? navigator.language : navigator['userLanguage'],_x000D_
    y = d.getFullYear(),_x000D_
    m = d.getMonth() + 1,_x000D_
    d = d.getDate();_x000D_
  f = (l in f) ? f[l] : "MM/dd/yyyy";_x000D_
_x000D_
  function z(s) {_x000D_
    s = '' + s;_x000D_
    return s.length > 1 ? s : '0' + s;_x000D_
  }_x000D_
  f = f.replace(/yyyy/, y);_x000D_
  f = f.replace(/yy/, String(y).substr(2));_x000D_
  f = f.replace(/MM/, z(m));_x000D_
  f = f.replace(/M/, m);_x000D_
  f = f.replace(/dd/, z(d));_x000D_
  f = f.replace(/d/, d);_x000D_
  return f;_x000D_
}
_x000D_
_x000D_
_x000D_

How to get the last element of an array in Ruby?

Use -1 index (negative indices count backward from the end of the array):

a[-1] # => 5
b[-1] # => 6

or Array#last method:

a.last # => 5
b.last # => 6

Defining a `required` field in Bootstrap

To make a field required, use required or required="true"

I think required="required" has been deprecated in version 3 of bootstrap.

How do I find out my root MySQL password?

It is actually very simple. You don't have to go through a lot of stuff. Just run the following command in terminal and follow on-screen instructions.

sudo mysql_secure_installation

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

You can use regex.findall():

import re
line = " I am having a very nice day."
count = len(re.findall(r'\w+', line))
print (count)

MySQL Great Circle Distance (Haversine formula)

$greatCircleDistance = acos( cos($latitude0) * cos($latitude1) * cos($longitude0 - $longitude1) + sin($latitude0) * sin($latitude1));

with latitude and longitude in radian.

so

SELECT 
  acos( 
      cos(radians( $latitude0 ))
    * cos(radians( $latitude1 ))
    * cos(radians( $longitude0 ) - radians( $longitude1 ))
    + sin(radians( $latitude0 )) 
    * sin(radians( $latitude1 ))
  ) AS greatCircleDistance 
 FROM yourTable;

is your SQL query

to get your results in Km or miles, multiply the result with the mean radius of Earth (3959 miles,6371 Km or 3440 nautical miles)

The thing you are calculating in your example is a bounding box. If you put your coordinate data in a spatial enabled MySQL column, you can use MySQL's build in functionality to query the data.

SELECT 
  id
FROM spatialEnabledTable
WHERE 
  MBRWithin(ogc_point, GeomFromText('Polygon((0 0,0 3,3 3,3 0,0 0))'))

How to write a large buffer into a binary file in C++, fast?

Could you use FILE* instead, and the measure the performance you've gained? A couple of options is to use fwrite/write instead of fstream:

#include <stdio.h>

int main ()
{
  FILE * pFile;
  char buffer[] = { 'x' , 'y' , 'z' };
  pFile = fopen ( "myfile.bin" , "w+b" );
  fwrite (buffer , 1 , sizeof(buffer) , pFile );
  fclose (pFile);
  return 0;
}

If you decide to use write, try something similar:

#include <unistd.h>
#include <fcntl.h>

int main(void)
{
    int filedesc = open("testfile.txt", O_WRONLY | O_APPEND);

    if (filedesc < 0) {
        return -1;
    }

    if (write(filedesc, "This will be output to testfile.txt\n", 36) != 36) {
        write(2, "There was an error writing to testfile.txt\n", 43);
        return -1;
    }

    return 0;
}

I would also advice you to look into memory map. That may be your answer. Once I had to process a 20GB file in other to store it in the database, and the file as not even opening. So the solution as to utilize moemory map. I did that in Python though.

How do you check what version of SQL Server for a database using TSQL?

SELECT 
@@SERVERNAME AS ServerName,
CASE WHEN LEFT(CAST(serverproperty('productversion') as char), 1) = 9 THEN '2005'
 WHEN LEFT(CAST(serverproperty('productversion') as char), 2) = 10 THEN '2008'
 WHEN LEFT(CAST(serverproperty('productversion') as char), 2) = 11 THEN '2012'
END AS MajorVersion,
SERVERPROPERTY ('productlevel') AS MinorVersion, 
SERVERPROPERTY('productversion') AS FullVersion, 
SERVERPROPERTY ('edition') AS Edition

How can I fill out a Python string with spaces?

A nice trick to use in place of the various print formats:

(1) Pad with spaces to the right:

('hi' + '        ')[:8]

(2) Pad with leading zeros on the left:

('0000' + str(2))[-4:]

How to check if a network port is open on linux?

Just added to mrjandro's solution a quick hack to get rid of simple connection errors / timeouts.

You can adjust the threshold changing max_error_count variable value and add notifications of any sort.

import socket

max_error_count = 10

def increase_error_count():
    # Quick hack to handle false Port not open errors 
    with open('ErrorCount.log') as f:
        for line in f:
            error_count = line
    error_count = int(error_count)
    print "Error counter: " + str(error_count)
    file = open('ErrorCount.log', 'w')
    file.write(str(error_count + 1))
    file.close()
    if error_count == max_error_count:
        # Send email, pushover, slack or do any other fancy stuff
        print "Sending out notification"
        # Reset error counter so it won't flood you with notifications
        file = open('ErrorCount.log', 'w')
        file.write('0')
        file.close()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2) 
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
        print "Port is open"
else:
        print "Port is not open"
        increase_error_count()

And here you find a Python 3 compatible version (just fixed print syntax):

import socket

max_error_count = 10

def increase_error_count():
    # Quick hack to handle false Port not open errors
    with open('ErrorCount.log') as f:
        for line in f:
            error_count = line
    error_count = int(error_count)
    print ("Error counter: " + str(error_count))
    file = open('ErrorCount.log', 'w')
    file.write(str(error_count + 1))
    file.close()
    if error_count == max_error_count:
        # Send email, pushover, slack or do any other fancy stuff
        print ("Sending out notification")
        # Reset error counter so it won't flood you with notifications
        file = open('ErrorCount.log', 'w')
        file.write('0')
        file.close()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2) 
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
        print ("Port is open")
else:
        print ("Port is not open")
        increase_error_count()

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

This suggestion is based on pixel manipulation in canvas 2d context.

From MDN:

You can directly manipulate pixel data in canvases at the byte level

To manipulate pixels we'll use two functions here - getImageData and putImageData.

getImageData usage:

var myImageData = context.getImageData(left, top, width, height);

The putImageData syntax:

context.putImageData(myImageData, x, y); 

Where context is your canvas 2d context, and x and y are the position on the canvas.

So to get red green blue and alpha values, we'll do the following:

var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];

Where x is the horizontal offset, y is the vertical offset.

The code making image half-transparent:

var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var img = new Image();
img.onload  = function() {
   c.drawImage(img, 0, 0);
   var ImageData = c.getImageData(0,0,img.width,img.height);
   for(var i=0;i<img.height;i++)
      for(var j=0;j<img.width;j++)
         ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255]
   c.putImageData(ImageData,0,0);//put image data back
}
img.src = 'image.jpg';

You can make you own "shaders" - see full MDN article here

Cannot find or open the PDB file in Visual Studio C++ 2010

If you have more as one Project in your Project Map use THE SAME hard coded PathFile PDB Name in all your Sub-Projects:

Use e.g.

D:\Visual Studio Projects\my_app\MyFile.pdb

Dont use e.g.

$(IntDir)\MyFile.pdb

in all the Sub-Projects !!!

= Compiler Param /Fd

How to make execution pause, sleep, wait for X seconds in R?

Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).

This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.

for (i in 1:1000)
{
  print(i)
  date_time<-Sys.time()
  while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

I also encountered this problem when I tried to present a UIViewController in viewDidLoad. James Bedford's answer worked, but my app showed the background first for 1 or 2 seconds.

After some research, I've found a way to solve this using the addChildViewController.

- (void)viewDidLoad
{
    ...
    [self.view addSubview: navigationViewController.view];
    [self addChildViewController: navigationViewController];
    ...
}

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

how to change directory using Windows command line

Another alternative is pushd, which will automatically switch drives as needed. It also allows you to return to the previous directory via popd:

C:\Temp>pushd D:\some\folder
D:\some\folder>popd
C:\Temp>_

How to construct a WebSocket URI relative to the page URI?

Dead easy solution, ws and port, tested:

var ws = new WebSocket("ws://" + window.location.host + ":6666");

ws.onopen = function() { ws.send( .. etc

Show a popup/message box from a Windows batch file

Here's a PowerShell variant that doesn't require loading assemblies prior to creating the window, however it runs noticeably slower (~+50%) than the PowerShell MessageBox command posted here by @npocmaka:

powershell (New-Object -ComObject Wscript.Shell).Popup("""Operation Completed""",0,"""Done""",0x0)

You can change the last parameter from "0x0" to a value below to display icons in the dialog (see Popup Method for further reference):

        Stop 0x10 Stop
        Question Mark 0x20 Question Mark
        Exclamation Mark 0x30 Exclamation Mark
        Information Mark 0x40 Information Mark

Adapted from the Microsoft TechNet article PowerTip: Use PowerShell to Display Pop-Up Window.

How to drop columns by name in a data frame

I changed the code to:

# read data
dat<-read.dta("file.dta")

# vars to delete
var.in<-c("iden", "name", "x_serv", "m_serv")

# what I'm keeping
var.out<-setdiff(names(dat),var.in)

# keep only the ones I want       
dat <- dat[var.out]

Anyway, juba's answer is the best solution to my problem!

How can I get the average (mean) of selected columns

Try using rowMeans:

z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)

  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

How to add icon to mat-icon-button

My preference is to utilize the inline attribute. This will cause the icon to correctly scale with the size of the button.

    <button mat-button>
      <mat-icon inline=true>local_movies</mat-icon>
      Movies
    </button>

    <!-- Link button -->
    <a mat-flat-button color="accent" routerLink="/create"><mat-icon inline=true>add</mat-icon> Create</a>

I add this to my styles.css to:

  • solve the vertical alignment problem of the icon inside the button
  • material icon fonts are always a little too small compared to button text
button.mat-button .mat-icon,
a.mat-button .mat-icon,
a.mat-raised-button .mat-icon,
a.mat-flat-button .mat-icon,
a.mat-stroked-button .mat-icon {
  vertical-align: top;
  font-size: 1.25em;
}