Programs & Examples On #Number systems

Anything related to number systems, i.e. the way of representing numbers (the abstract mathematical entities) as finite sequences of symbols. Usually this tag is relevant on questions involving conversion from the representation in a number system to another (e.g. from decimal to binary).

Quickest way to convert a base 10 number to any base in .NET?

I had a similar need, except I needed to do math on the "numbers" as well. I took some of the suggestions here and created a class that will do all this fun stuff. It allows for any unicode character to be used to represent a number and it works with decimals too.

This class is pretty easy to use. Just create a number as a type of New BaseNumber, set a few properties, and your off. The routines take care of switching between base 10 and base x automatically and the value you set is preserved in the base you set it in, so no accuracy is lost (until conversion that is, but even then precision loss should be very minimal since this routine uses Double and Long where ever possible).

I can't command on the speed of this routine. It is probably quite slow, so I'm not sure if it will suit the needs of the one who asked the question, but it certain is flexible, so hopefully someone else can use this.

For anyone else that may need this code for calculating the next column in Excel, I will include the looping code I used that leverages this class.

Public Class BaseNumber

    Private _CharacterArray As List(Of Char)

    Private _BaseXNumber As String
    Private _Base10Number As Double?

    Private NumberBaseLow As Integer
    Private NumberBaseHigh As Integer

    Private DecimalSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
    Private GroupSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator

    Public Sub UseCapsLetters()
        'http://unicodelookup.com
        TrySetBaseSet(65, 90)
    End Sub

    Public Function GetCharacterArray() As List(Of Char)
        Return _CharacterArray
    End Function

    Public Sub SetCharacterArray(CharacterArray As String)
        _CharacterArray = New List(Of Char)
        _CharacterArray.AddRange(CharacterArray.ToList)

        TrySetBaseSet(_CharacterArray)
    End Sub

    Public Sub SetCharacterArray(CharacterArray As List(Of Char))
        _CharacterArray = CharacterArray
        TrySetBaseSet(_CharacterArray)
    End Sub

    Public Sub SetNumber(Value As String)
        _BaseXNumber = Value
        _Base10Number = Nothing
    End Sub

    Public Sub SetNumber(Value As Double)
        _Base10Number = Value
        _BaseXNumber = Nothing
    End Sub

    Public Function GetBaseXNumber() As String
        If _BaseXNumber IsNot Nothing Then
            Return _BaseXNumber
        Else
            Return ToBaseString()
        End If
    End Function

    Public Function GetBase10Number() As Double
        If _Base10Number IsNot Nothing Then
            Return _Base10Number
        Else
            Return ToBase10()
        End If
    End Function

    Private Sub TrySetBaseSet(Values As List(Of Char))
        For Each value As Char In _BaseXNumber
            If Not Values.Contains(value) Then
                Throw New ArgumentOutOfRangeException("The string has a value, " & value & ", not contained in the selected 'base' set.")
                _CharacterArray.Clear()
                DetermineNumberBase()
            End If
        Next

        _CharacterArray = Values

    End Sub

    Private Sub TrySetBaseSet(LowValue As Integer, HighValue As Integer)

        Dim HighLow As KeyValuePair(Of Integer, Integer) = GetHighLow()

        If HighLow.Key < LowValue OrElse HighLow.Value > HighValue Then
            Throw New ArgumentOutOfRangeException("The string has a value not contained in the selected 'base' set.")
            _CharacterArray.Clear()
            DetermineNumberBase()
        End If

        NumberBaseLow = LowValue
        NumberBaseHigh = HighValue

    End Sub

    Private Function GetHighLow(Optional Values As List(Of Char) = Nothing) As KeyValuePair(Of Integer, Integer)
        If Values Is Nothing Then
            Values = _BaseXNumber.ToList
        End If

        Dim lowestValue As Integer = Convert.ToInt32(Values(0))
        Dim highestValue As Integer = Convert.ToInt32(Values(0))

        Dim currentValue As Integer

        For Each value As Char In Values

            If value <> DecimalSeparator AndAlso value <> GroupSeparator Then
                currentValue = Convert.ToInt32(value)
                If currentValue > highestValue Then
                    highestValue = currentValue
                End If
                If currentValue < lowestValue Then
                    currentValue = lowestValue
                End If
            End If
        Next

        Return New KeyValuePair(Of Integer, Integer)(lowestValue, highestValue)

    End Function

    Public Sub New(BaseXNumber As String)
        _BaseXNumber = BaseXNumber
        DetermineNumberBase()
    End Sub

    Public Sub New(BaseXNumber As String, NumberBase As Integer)
        Me.New(BaseXNumber, Convert.ToInt32("0"c), NumberBase)
    End Sub

    Public Sub New(BaseXNumber As String, NumberBaseLow As Integer, NumberBaseHigh As Integer)
        _BaseXNumber = BaseXNumber
        Me.NumberBaseLow = NumberBaseLow
        Me.NumberBaseHigh = NumberBaseHigh
    End Sub

    Public Sub New(Base10Number As Double)
        _Base10Number = Base10Number
    End Sub

    Private Sub DetermineNumberBase()
        Dim highestValue As Integer

        Dim currentValue As Integer

        For Each value As Char In _BaseXNumber

            currentValue = Convert.ToInt32(value)
            If currentValue > highestValue Then
                highestValue = currentValue
            End If
        Next

        NumberBaseHigh = highestValue
        NumberBaseLow = Convert.ToInt32("0"c) 'assume 0 is the lowest

    End Sub

    Private Function ToBaseString() As String
        Dim Base10Number As Double = _Base10Number

        Dim intPart As Long = Math.Truncate(Base10Number)
        Dim fracPart As Long = (Base10Number - intPart).ToString.Replace(DecimalSeparator, "")

        Dim intPartString As String = ConvertIntToString(intPart)
        Dim fracPartString As String = If(fracPart <> 0, DecimalSeparator & ConvertIntToString(fracPart), "")

        Return intPartString & fracPartString

    End Function

    Private Function ToBase10() As Double
        Dim intPartString As String = _BaseXNumber.Split(DecimalSeparator)(0).Replace(GroupSeparator, "")
        Dim fracPartString As String = If(_BaseXNumber.Contains(DecimalSeparator), _BaseXNumber.Split(DecimalSeparator)(1), "")

        Dim intPart As Long = ConvertStringToInt(intPartString)
        Dim fracPartNumerator As Long = ConvertStringToInt(fracPartString)
        Dim fracPartDenominator As Long = ConvertStringToInt(GetEncodedChar(1) & String.Join("", Enumerable.Repeat(GetEncodedChar(0), fracPartString.ToString.Length)))

        Return Convert.ToDouble(intPart + fracPartNumerator / fracPartDenominator)

    End Function

    Private Function ConvertIntToString(ValueToConvert As Long) As String
        Dim result As String = String.Empty
        Dim targetBase As Long = GetEncodingCharsLength()

        Do
            result = GetEncodedChar(ValueToConvert Mod targetBase) & result
            ValueToConvert = ValueToConvert \ targetBase
        Loop While ValueToConvert > 0

        Return result
    End Function

    Private Function ConvertStringToInt(ValueToConvert As String) As Long
        Dim result As Long
        Dim targetBase As Integer = GetEncodingCharsLength()
        Dim startBase As Integer = GetEncodingCharsStartBase()

        Dim value As Char
        For x As Integer = 0 To ValueToConvert.Length - 1
            value = ValueToConvert(x)
            result += GetDecodedChar(value) * Convert.ToInt32(Math.Pow(GetEncodingCharsLength, ValueToConvert.Length - (x + 1)))
        Next

        Return result

    End Function

    Private Function GetEncodedChar(index As Integer) As Char
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray(index)
        Else
            Return Convert.ToChar(index + NumberBaseLow)
        End If
    End Function

    Private Function GetDecodedChar(character As Char) As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray.IndexOf(character)
        Else
            Return Convert.ToInt32(character) - NumberBaseLow
        End If
    End Function

    Private Function GetEncodingCharsLength() As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray.Count
        Else
            Return NumberBaseHigh - NumberBaseLow + 1
        End If
    End Function

    Private Function GetEncodingCharsStartBase() As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return GetHighLow.Key
        Else
            Return NumberBaseLow
        End If
    End Function
End Class

And now for the code to loop through Excel columns:

    Public Function GetColumnList(DataSheetID As String) As List(Of String)
        Dim workingColumn As New BaseNumber("A")
        workingColumn.SetCharacterArray("@ABCDEFGHIJKLMNOPQRSTUVWXYZ")

        Dim listOfPopulatedColumns As New List(Of String)
        Dim countOfEmptyColumns As Integer

        Dim colHasData As Boolean
        Dim cellHasData As Boolean

        Do
            colHasData = True
            cellHasData = False
            For r As Integer = 1 To GetMaxRow(DataSheetID)
                cellHasData = cellHasData Or XLGetCellValue(DataSheetID, workingColumn.GetBaseXNumber & r) <> ""
            Next
            colHasData = colHasData And cellHasData

            'keep trying until we get 4 empty columns in a row
            If colHasData Then
                listOfPopulatedColumns.Add(workingColumn.GetBaseXNumber)
                countOfEmptyColumns = 0
            Else
                countOfEmptyColumns += 1
            End If

            'we are already starting with column A, so increment after we check column A
            Do
                workingColumn.SetNumber(workingColumn.GetBase10Number + 1)
            Loop Until Not workingColumn.GetBaseXNumber.Contains("@")

        Loop Until countOfEmptyColumns > 3

        Return listOfPopulatedColumns

    End Function

You'll note the important part of the Excel part is that 0 is identified by a @ in the re-based number. So I just filter out all the numbers that have an @ in them and I get the proper sequence (A, B, C, ..., Z, AA, AB, AC, ...).

How do I center this form in css?

You can use the following CSS to center the form (note that it is important to set the width to something that isn´t 'auto' for this to work):

form {
   margin-left:auto;
   margin-right:auto;
   width:100px;
}

Android LinearLayout : Add border with shadow around a LinearLayout

This is so simple:

Create a drawable file with a gradient like this:

for shadow below a view below_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">   
<gradient
    android:startColor="#20000000"
    android:endColor="@android:color/transparent"
    android:angle="270" >
</gradient>
</shape>

for shadow above a view above_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">   
<gradient
    android:startColor="#20000000"
    android:endColor="@android:color/transparent"
    android:angle="90" >
</gradient>
</shape>

and so on for right and left shadow just change the angle of the gradient :)

How can I change the size of a Bootstrap checkbox?

<div id="rr-element">
   <label for="rr-1">
      <input type="checkbox" value="1" id="rr-1" name="rr[]">
      Value 1
   </label>
</div>
//do this on the css
div label input { margin-right:100px; }

specifying goal in pom.xml

You need to set the path of maven under Global setting like MAVEN_HOME

/user/share/maven

and make sure the workbench have permission of read, write and delete "777"

How to count string occurrence in string?

You can try this:

_x000D_
_x000D_
var theString = "This is a string.";_x000D_
console.log(theString.split("is").length - 1);
_x000D_
_x000D_
_x000D_

IBOutlet and IBAction

IBAction and IBOutlet are macros defined to denote variables and methods that can be referred to in Interface Builder.

IBAction resolves to void and IBOutlet resolves to nothing, but they signify to Xcode and Interface builder that these variables and methods can be used in Interface builder to link UI elements to your code.

If you're not going to be using Interface Builder at all, then you don't need them in your code, but if you are going to use it, then you need to specify IBAction for methods that will be used in IB and IBOutlet for objects that will be used in IB.

How to set the style -webkit-transform dynamically using JavaScript?

Try using

img.style.webkitTransform = "rotate(60deg)"

Tomcat 8 is not able to handle get request with '|' in query parameters?

This behavior is introduced in all major Tomcat releases:

  • Tomcat 7.0.73, 8.0.39, 8.5.7

To fix, do one of the following:

  • set relaxedQueryChars to allow this character (recommended, see Lincoln's answer)
  • set requestTargetAllow option (deprecated in Tomcat 8.5) (see Jérémie's answer).
  • you can downgrade to one of older versions (not recommended - security)

Based on changelog, those changes could affect this behavior:

Tomcat 8.5.3:

Ensure that requests with HTTP method names that are not tokens (as required by RFC 7231) are rejected with a 400 response

Tomcat 8.5.7:

Add additional checks for valid characters to the HTTP request line parsing so invalid request lines are rejected sooner.


The best option (following the standard) - you want to encode your URL on client:

encodeURI("http://localhost:8080/app/handleResponse?msg=name|id|")
> http://localhost:8080/app/handleResponse?msg=name%7Cid%7C

or just query string:

encodeURIComponent("msg=name|id|")
> msg%3Dname%7Cid%7C

It will secure you from other problematic characters (list of invalid URI characters).

Launching an application (.EXE) from C#?

Here's a snippet of helpful code:

using System.Diagnostics;

// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = arguments; 
// Enter the executable to run, including the complete path
start.FileName = ExeName;
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
int exitCode;


// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
     proc.WaitForExit();

     // Retrieve the app's exit code
     exitCode = proc.ExitCode;
}

There is much more you can do with these objects, you should read the documentation: ProcessStartInfo, Process.

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

The accepted answer didn't help but simple step below fix it !

Under system PATH: instead of using M2%, use %M2_HOME%\bin, as simple as that.

N.B my %M2_HOME% is pointing to %MV3_HOME% instead of actual absolute path bcos I have multiple version of maven installed and trying to be clever (switch between maven versions on the same box for different project).

How do I install a custom font on an HTML site

Yes, you can use the CSS feature named @font-face. It has only been officially approved in CSS3, but been proposed and implemented in CSS2 and has been supported in IE for quite a long time.

You declare it in the CSS like this:

 @font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); } 
 @font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf');}

Then, you can just reference it like the other standard fonts:

 h3 { font-family: Delicious, sans-serif; }

So, in this case,

<html>
   <head>
    <style>
      @font-face { font-family: JuneBug; src: url('JUNEBUG.TTF'); } 
      h1 {
         font-family: JuneBug
      }
    </style>
   </head>
   <body>
      <h1>Hey, June</h1>
   </body>
</html>

And you just need to put the JUNEBUG.TFF in the same location as the html file.

I downloaded the font from the dafont.com website:

http://www.dafont.com/junebug.font

Match the path of a URL, minus the filename extension

http:[\/]{2}.+?[.][^\/]+(.+)[.].+

let's see, what it done:

http:[\/]{2}.+?[.][^\/] - non-capture group for http://php.net

(.+)[.] - capture part until last dot occur: /manual/en/function.preg-match

[.].+ - matching extension of file like this: .php

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

This typed error-message also shows while an if-statement comparison is done where there is an array and for example a bool or int. See for example:

... code snippet ...

if dataset == bool:
    ....

... code snippet ...

This clause has dataset as array and bool is euhm the "open door"... True or False.

In case the function is wrapped within a try-statement you will receive with except Exception as error: the message without its error-type:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How to set java.net.preferIPv4Stack=true at runtime?

you can set the environment variable JAVA_TOOL_OPTS like as follows, which will be picked by JVM for any application.

set JAVA_TOOL_OPTS=-Djava.net.preferIPv4Stack=true

You can set this from the command prompt or set in system environment variables, based on your need. Note that this will reflect into all the java applications that run in your machine, even if it's a java interpreter that you have in a private setup.

Why do you create a View in a database?

Views can be a godsend when when doing reporting on legacy databases. In particular, you can use sensical table names instead of cryptic 5 letter names (where 2 of those are a common prefix!), or column names full of abbreviations that I'm sure made sense at the time.

AngularJS - value attribute for select

What you first tried should work, but the HTML is not what we would expect. I added an option to handle the initial "no item selected" case:

<select ng-options="region.code as region.name for region in regions" ng-model="region">
   <option style="display:none" value="">select a region</option>
</select>
<br>selected: {{region}}

The above generates this HTML:

<select ng-options="..." ng-model="region" class="...">
   <option style="display:none" value class>select a region</option>
   <option value="0">Alabama</option>
   <option value="1">Alaska</option>
   <option value="2">American Samoa</option>
</select>

Fiddle

Even though Angular uses numeric integers for the value, the model (i.e., $scope.region) will be set to AL, AK, or AS, as desired. (The numeric value is used by Angular to lookup the correct array entry when an option is selected from the list.)

This may be confusing when first learning how Angular implements its "select" directive.

Types in Objective-C on iOS

This is a good overview:

http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html

or run this code:

32 bit process:

  NSLog(@"Primitive sizes:");
  NSLog(@"The size of a char is: %d.", sizeof(char));
  NSLog(@"The size of short is: %d.", sizeof(short));
  NSLog(@"The size of int is: %d.", sizeof(int));
  NSLog(@"The size of long is: %d.", sizeof(long));
  NSLog(@"The size of long long is: %d.", sizeof(long long));
  NSLog(@"The size of a unsigned char is: %d.", sizeof(unsigned char));
  NSLog(@"The size of unsigned short is: %d.", sizeof(unsigned short));
  NSLog(@"The size of unsigned int is: %d.", sizeof(unsigned int));
  NSLog(@"The size of unsigned long is: %d.", sizeof(unsigned long));
  NSLog(@"The size of unsigned long long is: %d.", sizeof(unsigned long long));
  NSLog(@"The size of a float is: %d.", sizeof(float));
  NSLog(@"The size of a double is %d.", sizeof(double));

  NSLog(@"Ranges:");
  NSLog(@"CHAR_MIN:   %c",   CHAR_MIN);
  NSLog(@"CHAR_MAX:   %c",   CHAR_MAX);
  NSLog(@"SHRT_MIN:   %hi",  SHRT_MIN);    // signed short int
  NSLog(@"SHRT_MAX:   %hi",  SHRT_MAX);
  NSLog(@"INT_MIN:    %i",   INT_MIN);
  NSLog(@"INT_MAX:    %i",   INT_MAX);
  NSLog(@"LONG_MIN:   %li",  LONG_MIN);    // signed long int
  NSLog(@"LONG_MAX:   %li",  LONG_MAX);
  NSLog(@"ULONG_MAX:  %lu",  ULONG_MAX);   // unsigned long int
  NSLog(@"LLONG_MIN:  %lli", LLONG_MIN);   // signed long long int
  NSLog(@"LLONG_MAX:  %lli", LLONG_MAX);
  NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX);  // unsigned long long int

When run on an iPhone 3GS (iPod Touch and older iPhones should yield the same result) you get:

Primitive sizes:
The size of a char is: 1.                
The size of short is: 2.                 
The size of int is: 4.                   
The size of long is: 4.                  
The size of long long is: 8.             
The size of a unsigned char is: 1.       
The size of unsigned short is: 2.        
The size of unsigned int is: 4.          
The size of unsigned long is: 4.         
The size of unsigned long long is: 8.    
The size of a float is: 4.               
The size of a double is 8.               
Ranges:                                  
CHAR_MIN:   -128                         
CHAR_MAX:   127                          
SHRT_MIN:   -32768                       
SHRT_MAX:   32767                        
INT_MIN:    -2147483648                  
INT_MAX:    2147483647                   
LONG_MIN:   -2147483648                  
LONG_MAX:   2147483647                   
ULONG_MAX:  4294967295                   
LLONG_MIN:  -9223372036854775808         
LLONG_MAX:  9223372036854775807          
ULLONG_MAX: 18446744073709551615 

64 bit process:

The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 8.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 8.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

Make iframe automatically adjust height according to the contents without using scrollbar?

I did it with AngularJS. Angular doesn't have an ng-load, but a 3rd party module was made; install with bower below, or find it here: https://github.com/andrefarzat/ng-load

Get the ngLoad directive: bower install ng-load --save

Setup your iframe:

<iframe id="CreditReportFrame" src="about:blank" frameborder="0" scrolling="no" ng-load="resizeIframe($event)" seamless></iframe>

Controller resizeIframe function:

$scope.resizeIframe = function (event) {
    console.log("iframe loaded!");
    var iframe = event.target;
    iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
};

this in equals method

You are comparing two objects for equality. The snippet:

if (obj == this) {     return true; } 

is a quick test that can be read

"If the object I'm comparing myself to is me, return true"

. You usually see this happen in equals methods so they can exit early and avoid other costly comparisons.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Your json contains an array, but you're trying to parse it as an object. This error occurs because objects must start with {.

You have 2 options:

  1. You can get rid of the ShopContainer class and use Shop[] instead

    ShopContainer response  = restTemplate.getForObject(
        url, ShopContainer.class);
    

    replace with

    Shop[] response  = restTemplate.getForObject(url, Shop[].class);
    

    and then make your desired object from it.

  2. You can change your server to return an object instead of a list

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
    

    replace with

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
        new ShopContainer(list));
    

How to copy Java Collections list

b has a capacity of 3, but a size of 0. The fact that ArrayList has some sort of buffer capacity is an implementation detail - it's not part of the List interface, so Collections.copy(List, List) doesn't use it. It would be ugly for it to special-case ArrayList.

As MrWiggles has indicated, using the ArrayList constructor which takes a collection is the way to in the example provided.

For more complicated scenarios (which may well include your real code), you may find the collections within Guava useful.

How do I discard unstaged changes in Git?

simply say

git stash

It will remove all your local changes. You also can use later by saying

git stash apply 

or git stash pop

python numpy vector math

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

    In [1]: import math
    
    In [2]: import numpy as np
    
    In [3]: a = np.array([4,2,7])
    
    In [4]: np.linalg.norm(a)
    Out[4]: 8.3066238629180749
    
    In [5]: math.sqrt(sum([n**2 for n in a]))
    Out[5]: 8.306623862918075
    
    In [6]: b = a/np.linalg.norm(a)
    
    In [7]: np.linalg.norm(b)
    Out[7]: 1.0
    

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

How do you render primitives as wireframes in OpenGL?

If it's OpenGL ES 2.0 you're dealing with, you can choose one of draw mode constants from

GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES, to draw lines,

GL_POINTS (if you need to draw only vertices), or

GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, and GL_TRIANGLES to draw filled triangles

as first argument to your

glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid * indices)

or

glDrawArrays(GLenum mode, GLint first, GLsizei count) calls.

How to detect if user select cancel InputBox VBA Excel

Following example uses InputBox method to validate user entry to unhide sheets: Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.

Sub unhidesheet()

Dim ws As Worksheet
Dim pw As String

pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets")
If StrPtr(pw) = 0 Then

   Exit Sub
ElseIf pw = NullString Then
   Exit Sub
ElseIf pw = 123456 Then
    For Each ws In ThisWorkbook.Worksheets
        ws.Visible = xlSheetVisible
    Next
End If
End Sub

Why does Java have an "unreachable statement" compiler error?

It is Nanny. I feel .Net got this one right - it raises a warning for unreachable code, but not an error. It is good to be warned about it, but I see no reason to prevent compilation (especially during debugging sessions where it is nice to throw a return in to bypass some code).

When to use React setState callback

Consider setState call

this.setState({ counter: this.state.counter + 1 })

IDEA

setState may be called in async function

So you cannot rely on this. If the above call was made inside a async function this will refer to state of component at that point of time but we expected this to refer to property inside state at time setState calling or beginning of async task. And as task was async call thus that property may have changed in time being. Thus it is unreliable to use this keyword to refer to some property of state thus we use callback function whose arguments are previousState and props which means when async task was done and it was time to update state using setState call prevState will refer to state now when setState has not started yet. Ensuring reliability that nextState would not be corrupted.

Wrong Code: would lead to corruption of data

this.setState(
   {counter:this.state.counter+1}
 );

Correct Code with setState having call back function:

 this.setState(
       (prevState,props)=>{
           return {counter:prevState.counter+1};
        }
    );

Thus whenever we need to update our current state to next state based on value possed by property just now and all this is happening in async fashion it is good idea to use setState as callback function.

I have tried to explain it in codepen here CODE PEN

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Unfortunately triggering the onsubmit or submit events wont work in all browsers.

  • Works in IE and Chrome: #('form#ajaxForm')trigger('onsubmit');
  • Works in Firefox and Safari: #('form#ajaxForm')trigger('submit');

Also, if you trigger('submit') in Chrome or IE, it causes the entire page to be posted rather than doing an AJAX behavior.

What works for all browsers is removing the onsubmit event behavior and just calling submit() on the form itself.

<script type="text/javascript">
$(function() {

    $('form#ajaxForm').submit(function(event) { 
        eval($(this).attr('onsubmit')); return false; 
        });

    $('form#ajaxForm').find('a.submit-link').click( function() { 
        $'form#ajaxForm').submit();
        });

  }
</script>
  <% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id },
     new AjaxOptions
     {
       UpdateTargetId = "DescriptionDiv",
       HttpMethod = "post"
     }, new { id = "ajaxForm" } )) {%>
   Description:
   <%= Html.TextBox("Description", Model.Description) %><br />
   <a href="#" class="submit-link">Save</a> 
<% } %>

Also, the link doesn't have to be contained within the form in order for this to work.

How to test web service using command line curl

Answering my own question.

curl -X GET --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X DELETE --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \
     -d 'param2_name=param2_value' https://www.example.com/mobile/resource

POSTing a file and additional parameter

curl -X POST -F 'param_name=@/filepath/filename' \
     -F 'extra_param_name=extra_param_value' --basic --user username:password \
     https://www.example.com/mobile/resource

Fuzzy matching using T-SQL

In addition to the other good info here, you might want to consider using the Double Metaphone phonetic algorithm which is generally considered to be better than SOUNDEX.

Tim Pfeiffer details an implementation in SQL in his article Double Metaphone Sounds Great Convert the C++ Double Metaphone algorithm to T-SQL (originally in SQL Mag & then in SQL Server Pro).

That will assist in matching names with slight misspellings, e.g., Carl vs. Karl.

Update: The actual downloadable code seems to be gone, but here's an implementation found on a github repo that appears to have cloned the original code

How can I get useful error messages in PHP?

You can register your own error handler in PHP. Dumping all errors to a file might help you in these obscure cases, for example. Note that your function will get called, no matter what your current error_reporting is set to. Very basic example:

function dump_error_to_file($errno, $errstr) {
    file_put_contents('/tmp/php-errors', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
set_error_handler('dump_error_to_file');

Check if a string is null or empty in XSLT

test="categoryName != ''"

Edit: This covers the most likely interpretation, in my opinion, of "[not] null or empty" as inferred from the question, including it's pseudo-code and my own early experience with XSLT. I.e., "What is the equivalent of the following Java?":

!(categoryName == null || categoryName.equals(""))

For more details e.g., distinctly identifying null vs. empty, see johnvey's answer below and/or the XSLT 'fiddle' I've adapted from that answer, which includes the option in Michael Kay's comment as well as the sixth possible interpretation.

img onclick call to JavaScript function

This should work(with or without 'javascript:' part):

<img onclick="javascript:exportToForm('1.6','55','10','50','1')" src="China-Flag-256.png" />
<script>
function exportToForm(a, b, c, d, e) {
     alert(a, b);
 }
</script>

What's an Aggregate Root?

Aggregate is where you protect your invariants and force consistency by limiting its access thought aggregate root. Do not forget, aggregate should design upon your project business rules and invariants, not database relationship. you should not inject any repository and no queries are not allowed.

How do I split a string in Rust?

There are three simple ways:

  1. By separator:

     s.split("separator")  |  s.split('/')  |  s.split(char::is_numeric)
    
  2. By whitespace:

     s.split_whitespace()
    
  3. By newlines:

     s.lines()
    
  4. By regex: (using regex crate)

     Regex::new(r"\s").unwrap().split("one two three")
    

The result of each kind is an iterator:

let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());

assert_eq!(None, lines.next());

What is the difference between URL parameters and query strings?

Parameters are key-value pairs that can appear inside URL path, and start with a semicolon character (;).

Query string appears after the path (if any) and starts with a question mark character (?).

Both parameters and query string contain key-value pairs.

In a GET request, parameters appear in the URL itself:

<scheme>://<username>:<password>@<host>:<port>/<path>;<parameters>?<query>#<fragment>

In a POST request, parameters can appear in the URL itself, but also in the datastream (as known as content).

Query string is always a part of the URL.

Parameters can be buried in form-data datastream when using POST method so they may not appear in the URL. Yes a POST request can define parameters as form data and in the URL, and this is not inconsistent because parameters can have several values.

I've found no explaination for this behavior so far. I guess it might be useful sometimes to "unhide" parameters from a POST request, or even let the code handling a GET request share some parts with the code handling a POST. Of course this can work only with server code supporting parameters in a URL.

Until you get better insights, I suggest you to use parameters only in form-data datastream of POST requests.

Sources:

What Every Developer Should Know About URLs

RFC 3986

How to generate Javadoc from command line

Let's say you have the following directory structure where you want to generate javadocs on file1.java and file2.java (package com.test), with the javadocs being placed in C:\javadoc\test:

C:\
|
+--javadoc\
|  |
|  +--test\
|
+--projects\
   |
   +--com\
      |
      +--test\
         |
         +--file1.java
         +--file2.java

In the command terminal, navigate to the root of your package: C:\projects. If you just want to generate the standard javadocs on all the java files inside the project, run the following command (for multiple packages, separate the package names by spaces):

C:\projects> javadoc -d [path to javadoc destination directory] [package name]

C:\projects> javadoc -d C:\javadoc\test com.test

If you want to run javadocs from elsewhere, you'll need to specify the sourcepath. For example, if you were to run javadocs in in C:\, you would modify the command as such:

C:\> javadoc -d [path to javadoc destination directory] -sourcepath [path to package directory] [package name]

C:\> javadoc -d C:\javadoc\test -sourcepath C:\projects com.test

If you want to run javadocs on only selected .java files, then add the source filenames separated by spaces (you can use an asterisk (*) for a wildcard). Make sure to include the path to the files:

C:\> javadoc -d [path to javadoc destination directory] [source filenames]

C:\> javadoc -d C:\javadoc\test C:\projects\com\test\file1.java

More information/scenarios can be found here.

The requested resource does not support HTTP method 'GET'

In my case, the route signature was different from the method parameter. I had id, but I was accepting documentId as parameter, that caused the problem.

[Route("Documents/{id}")]   <--- caused the webapi error
[Route("Documents/{documentId}")] <-- solved
public Document Get(string documentId)
{
  ..
}

Firefox and SSL: sec_error_unknown_issuer

If you got your cert from COMODO your need to add this line, the file is on the zip file you received.

SSLCertificateChainFile /path/COMODORSADomainValidationSecureServerCA.crt

Login failed for user 'DOMAIN\MACHINENAME$'

I also had this error with a SQL Server authenticated user

I tried some of the fixes, but they did not work.

The solution in my case was to configure its "Server Authentication Mode" to allow SQL Server authentication, under Management Studio: Properties/Security.

Set environment variables from file of key/value pairs

I use this:

source <(cat .env \
  | sed -E '/^\s*#.*/d' \
  | tr '\n' '\000' \
  | sed -z -E 's/^([^=]+)=(.*)/\1\x0\2/g' \
  | xargs -0 -n2 bash -c 'printf "export %s=%q;\n" "${@}"' /dev/null)

First Removing comments:

sed -E '/^\s*#.*/d'

Then converting to null delimiters instead of newline:

tr '\n' '\000'

Then replacing equal with null:

sed -z -E 's/^([^=]+)=(.*)/\1\x0\2/g'

Then printing pairs to valid quoted bash exports (using bash printf for %q):

xargs -0 -n2 bash -c 'printf "export %s=%q;\n" "${@}"' /dev/null

Then finally sourcing all of that.

It should work for just about all cases with all special characters.

Rails: How to run `rails generate scaffold` when the model already exists?

TL;DR: rails g scaffold_controller <name>

Even though you already have a model, you can still generate the necessary controller and migration files by using the rails generate option. If you run rails generate -h you can see all of the options available to you.

Rails:
  controller
  generator
  helper
  integration_test
  mailer
  migration
  model
  observer
  performance_test
  plugin
  resource
  scaffold
  scaffold_controller
  session_migration
  stylesheets

If you'd like to generate a controller scaffold for your model, see scaffold_controller. Just for clarity, here's the description on that:

Stubs out a scaffolded controller and its views. Pass the model name, either CamelCased or under_scored, and a list of views as arguments. The controller name is retrieved as a pluralized version of the model name.

To create a controller within a module, specify the model name as a path like 'parent_module/controller_name'.

This generates a controller class in app/controllers and invokes helper, template engine and test framework generators.

To create your resource, you'd use the resource generator, and to create a migration, you can also see the migration generator (see, there's a pattern to all of this madness). These provide options to create the missing files to build a resource. Alternatively you can just run rails generate scaffold with the --skip option to skip any files which exist :)

I recommend spending some time looking at the options inside of the generators. They're something I don't feel are documented extremely well in books and such, but they're very handy.

How to return PDF to browser in MVC?

I got it working with this code.

using iTextSharp.text;
using iTextSharp.text.pdf;

public FileStreamResult pdf()
{
    MemoryStream workStream = new MemoryStream();
    Document document = new Document();
    PdfWriter.GetInstance(document, workStream).CloseStream = false;

    document.Open();
    document.Add(new Paragraph("Hello World"));
    document.Add(new Paragraph(DateTime.Now.ToString()));
    document.Close();

    byte[] byteInfo = workStream.ToArray();
    workStream.Write(byteInfo, 0, byteInfo.Length);
    workStream.Position = 0;

    return new FileStreamResult(workStream, "application/pdf");    
}

How can I mock requests and the response?

this is how you mock requests.post, change it to your http method

@patch.object(requests, 'post')
def your_test_method(self, mockpost):
    mockresponse = Mock()
    mockpost.return_value = mockresponse
    mockresponse.text = 'mock return'

    #call your target method now

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

require_once('../web/a.php');

If this is not working for anyone, following is the good Idea to include file anywhere in the project.

require_once dirname(__FILE__)."/../../includes/enter.php";

This code will get the file from 2 directory outside of the current directory.

Drawing Circle with OpenGL

We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say base=X and Y=vertical. Now we can write X=hypotenuse*cos? and Y=hypotenuse*sin?. We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say X=base and Y=vertical. Now we can write X=hypotenuse * cos? and Y=hypotenuse * sin?.

Now look at this code

void display(){
float x,y;
glColor3f(1, 1, 0);
for(double i =0; i <= 360;){
    glBegin(GL_TRIANGLES);
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    i=i+.5;
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    glVertex2d(0, 0);
    glEnd();
    i=i+.5;
}
glEnd();

glutSwapBuffers();
}

Change value of input and submit form in JavaScript

Here is simple code. You must set an id for your input. Here call it 'myInput':

var myform = document.getElementById('myform');
myform.onsubmit = function(){
    document.getElementById('myInput').value = '1';
    myform.submit();
};

Create PDF with Java

Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.

Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.

CSS to make table 100% of max-width

max-width is definitely not well supported. If you're going to use it, use it in a media query in your style tag. ios, android, and windows phone default mail all support them. (gmail and outlook mobile don't)

http://www.campaignmonitor.com/guides/mobile/targeting/

Look at the starbucks example at the bottom

jquery 3.0 url.indexOf error

Jquery 3.0 has some breaking changes that remove certain methods due to conflicts. Your error is most likely due to one of these changes such as the removal of the .load() event.

Read more in the jQuery Core 3.0 Upgrade Guide

To fix this you either need to rewrite the code to be compatible with Jquery 3.0 or else you can use the JQuery Migrate plugin which restores the deprecated and/or removed APIs and behaviours.

How to convert HTML to PDF using iTextSharp

@Chris Haas has explained very well how to use itextSharp to convert HTML to PDF, very helpful
my add is:
By using HtmlTextWriter I put html tags inside HTML table + inline CSS i got my PDF as I wanted without using XMLWorker .
Edit: adding sample code:
ASPX page:

<asp:Panel runat="server" ID="PendingOrdersPanel">
 <!-- to be shown on PDF-->
 <table style="border-spacing: 0;border-collapse: collapse;width:100%;display:none;" >
 <tr><td><img src="abc.com/webimages/logo1.png" style="display: none;" width="230" /></td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla.</td></tr>
 <tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla.</td></tr>
 <tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:11px;color:#10466E;padding:0px;text-align:center;"><i>blablabla</i> Pending orders report<br /></td></tr>
 </table>
<asp:GridView runat="server" ID="PendingOrdersGV" RowStyle-Wrap="false" AllowPaging="true" PageSize="10" Width="100%" CssClass="Grid" AlternatingRowStyle-CssClass="alt" AutoGenerateColumns="false"
   PagerStyle-CssClass="pgr" HeaderStyle-ForeColor="White" PagerStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" RowStyle-HorizontalAlign="Center" DataKeyNames="Document#" 
      OnPageIndexChanging="PendingOrdersGV_PageIndexChanging" OnRowDataBound="PendingOrdersGV_RowDataBound" OnRowCommand="PendingOrdersGV_RowCommand">
   <EmptyDataTemplate><div style="text-align:center;">no records found</div></EmptyDataTemplate>
    <Columns>                                           
     <asp:ButtonField CommandName="PendingOrders_Details" DataTextField="Document#" HeaderText="Document #" SortExpression="Document#" ItemStyle-ForeColor="Black" ItemStyle-Font-Underline="true"/>
      <asp:BoundField DataField="Order#" HeaderText="order #" SortExpression="Order#"/>
     <asp:BoundField DataField="Order Date" HeaderText="Order Date" SortExpression="Order Date" DataFormatString="{0:d}"></asp:BoundField> 
    <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status"></asp:BoundField>
    <asp:BoundField DataField="Amount" HeaderText="Amount" SortExpression="Amount" DataFormatString="{0:C2}"></asp:BoundField> 
   </Columns>
    </asp:GridView>
</asp:Panel>

C# code:

protected void PendingOrdersPDF_Click(object sender, EventArgs e)
{
    if (PendingOrdersGV.Rows.Count > 0)
    {
        //to allow paging=false & change style.
        PendingOrdersGV.HeaderStyle.ForeColor = System.Drawing.Color.Black;
        PendingOrdersGV.BorderColor = Color.Gray;
        PendingOrdersGV.Font.Name = "Tahoma";
        PendingOrdersGV.DataSource = clsBP.get_PendingOrders(lbl_BP_Id.Text);
        PendingOrdersGV.AllowPaging = false;
        PendingOrdersGV.Columns[0].Visible = false; //export won't work if there's a link in the gridview
        PendingOrdersGV.DataBind();

        //to PDF code --Sam
        string attachment = "attachment; filename=report.pdf";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/pdf";
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        htextw.AddStyleAttribute("font-size", "8pt");
        htextw.AddStyleAttribute("color", "Grey");

        PendingOrdersPanel.RenderControl(htextw); //Name of the Panel
        Document document = new Document();
        document = new Document(PageSize.A4, 5, 5, 15, 5);
        FontFactory.GetFont("Tahoma", 50, iTextSharp.text.BaseColor.BLUE);
        PdfWriter.GetInstance(document, Response.OutputStream);
        document.Open();

        StringReader str = new StringReader(stw.ToString());
        HTMLWorker htmlworker = new HTMLWorker(document);
        htmlworker.Parse(str);

        document.Close();
        Response.Write(document);
    }
}

of course include iTextSharp Refrences to cs file

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using iTextSharp.tool.xml;

Hope this helps!
Thank you

Changing the default icon in a Windows Forms application

Select your project properties from Project Tab Then Application->Resource->Icon And Manifest->change the default icon

This works in Visual studio 2019 finely Note:Only files with .ico format can be added as icon

Best way to simulate "group by" from bash?

You probably can use the file system itself as a hash table. Pseudo-code as follows:

for every entry in the ip address file; do
  let addr denote the ip address;

  if file "addr" does not exist; then
    create file "addr";
    write a number "0" in the file;
  else 
    read the number from "addr";
    increase the number by 1 and write it back;
  fi
done

In the end, all you need to do is to traverse all the files and print the file names and numbers in them. Alternatively, instead of keeping a count, you could append a space or a newline each time to the file, and in the end just look at the file size in bytes.

setInterval in a React app

Updating state every second in the react class. Note the my index.js passes a function that return current time.

import React from "react";

class App extends React.Component {
  constructor(props){
    super(props)

    this.state = {
      time: this.props.time,

    }        
  }
  updateMe() {
    setInterval(()=>{this.setState({time:this.state.time})},1000)        
  }
  render(){
  return (
    <div className="container">
      <h1>{this.state.time()}</h1>
      <button onClick={() => this.updateMe()}>Get Time</button>
    </div>
  );
}
}
export default App;

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

If you are building a windows app try to build as x64 instead of Any CPU. It should work fine.

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

Add column to SQL Server

Use this query:

ALTER TABLE tablename ADD columname DATATYPE(size);

And here is an example:

ALTER TABLE Customer ADD LastName VARCHAR(50);

How to make String.Contains case insensitive?

bool b = list.Contains("Hello", StringComparer.CurrentCultureIgnoreCase);

[EDIT] extension code:

public static bool Contains(this string source, string cont
                                                    , StringComparison compare)
{
    return source.IndexOf(cont, compare) >= 0;
}

This could work :)

How to get a microtime in Node.js?

I'm not so proud about this solution but you can have timestamp in microsecond or nanosecond in this way:

const microsecond = () => Number(Date.now() + String(process.hrtime()[1]).slice(3,6))
const nanosecond = () => Number(Date.now() + String(process.hrtime()[1]).slice(3))

// usage
microsecond() // return 1586878008997591
nanosecond()  // return 1586878009000645600

// Benchmark with 100 000 iterations
// Date.now: 7.758ms
// microsecond: 33.382ms
// nanosecond: 31.252ms

Know that:

  • This solution works exclusively with node.js,
  • This is about 3 to 10 times slower than Date.now()
  • Weirdly, it seems very accurate, hrTime seems to follow exactly js timestamp ticks.
  • You can replace Date.now() by Number(new Date()) to get timestamp in milliseconds

Edit:

Here a solution to have microsecond with comma, however, the number version will be rounded natively by javascript. So if you want the same format every time, you should use the String version of it.

const microsecondWithCommaString = () => (Date.now() + '.' + String(process.hrtime()[1]).slice(3,7))
const microsecondWithComma = () => Number(Date.now() + '.' + String(process.hrtime()[1]).slice(3,7))

microsecondWithCommaString() // return "1586883629984.8997"
microsecondWithComma() // return 1586883629985.966

Temporarily switch working copy to a specific Git commit

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

SQL: How to perform string does not equal

select * from table
where tester NOT LIKE '%username%';

How to filter an array from all elements of another array

All the above solutions "work", but are less than optimal for performance and are all approach the problem in the same way which is linearly searching all entries at each point using Array.prototype.indexOf or Array.prototype.includes. A far faster solution (far faster even than a binary search for most cases) would be to sort the arrays and skip ahead as you go along as seen below. However, one downside is that this requires all entries in the array to be numbers or strings. Also however, binary search may in some rare cases be faster than the progressive linear search. These cases arise from the fact that my progressive linear search has a complexity of O(2n1+n2) (only O(n1+n2) in the faster C/C++ version) (where n1 is the searched array and n2 is the filter array), whereas the binary search has a complexity of O(n1ceil(log2n2)) (ceil = round up -- to the ceiling), and, lastly, the indexOf search has a highly variable complexity between O(n1) and O(n1n2), averaging out to O(n1ceil(n2÷2)). Thus, indexOf will only be the fastest, on average, in the cases of (n1,n2) equaling {1,2}, {1,3}, or {x,1|x?N}. However, this is still not a perfect representation of modern hardware. IndexOf is natively optimized to the fullest extent imaginable in most modern browsers, making it very subject to the laws of branch prediction. Thus, if we make the same assumption on indexOf as we do with progressive linear and binary search -- that the array is presorted -- then, according to the stats listed in the link, we can expect roughly a 6x speed up for IndexOf, shifting its complexity to between O(n1÷6) and O(n1n2), averaging out to O(n1ceil(n27÷12)). Finally, take note that the below solution will never work with objects because objects in JavaScript cannot be compared by pointers in JavaScript.

function sortAnyArray(a,b) { return a>b ? 1 : (a===b ? 0 : -1); }
function sortIntArray(a,b) { return (a|0) - (b|0) |0; }
function fastFilter(array, handle) {
    var out=[], value=0;
    for (var i=0,  len=array.length|0; i < len; i=i+1|0)
        if (handle(value = array[i])) 
            out.push( value );
    return out;
}

const Math_clz32 = Math.clz32 || (function(log, LN2){
  return function(x) {
    return 31 - log(x >>> 0) / LN2 | 0; // the "| 0" acts like math.floor
  };
})(Math.log, Math.LN2);

/* USAGE:
  filterArrayByAnotherArray(
      [1,3,5],
      [2,3,4]
  ) yields [1, 5], and it can work with strings too
*/
function filterArrayByAnotherArray(searchArray, filterArray) {
    if (
        // NOTE: This does not check the whole array. But, if you know
        //        that there are only strings or numbers (not a mix of
        //        both) in the array, then this is a safe assumption.
        // Always use `==` with `typeof` because browsers can optimize
        //  the `==` into `===` (ONLY IN THIS CIRCUMSTANCE)
        typeof searchArray[0] == "number" &&
        typeof filterArray[0] == "number" &&
        (searchArray[0]|0) === searchArray[0] &&
        (filterArray[0]|0) === filterArray[0]
    ) {filterArray
        // if all entries in both arrays are integers
        searchArray.sort(sortIntArray);
        filterArray.sort(sortIntArray);
    } else {
        searchArray.sort(sortAnyArray);
        filterArray.sort(sortAnyArray);
    }
    var searchArrayLen = searchArray.length, filterArrayLen = filterArray.length;
    var progressiveLinearComplexity = ((searchArrayLen<<1) + filterArrayLen)>>>0
    var binarySearchComplexity= (searchArrayLen * (32-Math_clz32(filterArrayLen-1)))>>>0;
    // After computing the complexity, we can predict which algorithm will be the fastest
    var i = 0;
    if (progressiveLinearComplexity < binarySearchComplexity) {
        // Progressive Linear Search
        return fastFilter(searchArray, function(currentValue){
            while (filterArray[i] < currentValue) i=i+1|0;
            // +undefined = NaN, which is always false for <, avoiding an infinite loop
            return filterArray[i] !== currentValue;
        });
    } else {
        // Binary Search
        return fastFilter(
            searchArray,
            fastestBinarySearch(filterArray)
        );
    }
}

// see https://stackoverflow.com/a/44981570/5601591 for implementation
//  details about this binary search algorithm

function fastestBinarySearch(array){
  var initLen = (array.length|0) - 1 |0;
  
  const compGoto = Math_clz32(initLen) & 31;
  return function(sValue) {
    var len = initLen |0;
    switch (compGoto) {
      case 0:
        if (len & 0x80000000) {
          const nCB = len & 0x80000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 1:
        if (len & 0x40000000) {
          const nCB = len & 0xc0000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 2:
        if (len & 0x20000000) {
          const nCB = len & 0xe0000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 3:
        if (len & 0x10000000) {
          const nCB = len & 0xf0000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 4:
        if (len & 0x8000000) {
          const nCB = len & 0xf8000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 5:
        if (len & 0x4000000) {
          const nCB = len & 0xfc000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 6:
        if (len & 0x2000000) {
          const nCB = len & 0xfe000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 7:
        if (len & 0x1000000) {
          const nCB = len & 0xff000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 8:
        if (len & 0x800000) {
          const nCB = len & 0xff800000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 9:
        if (len & 0x400000) {
          const nCB = len & 0xffc00000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 10:
        if (len & 0x200000) {
          const nCB = len & 0xffe00000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 11:
        if (len & 0x100000) {
          const nCB = len & 0xfff00000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 12:
        if (len & 0x80000) {
          const nCB = len & 0xfff80000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 13:
        if (len & 0x40000) {
          const nCB = len & 0xfffc0000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 14:
        if (len & 0x20000) {
          const nCB = len & 0xfffe0000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 15:
        if (len & 0x10000) {
          const nCB = len & 0xffff0000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 16:
        if (len & 0x8000) {
          const nCB = len & 0xffff8000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 17:
        if (len & 0x4000) {
          const nCB = len & 0xffffc000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 18:
        if (len & 0x2000) {
          const nCB = len & 0xffffe000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 19:
        if (len & 0x1000) {
          const nCB = len & 0xfffff000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 20:
        if (len & 0x800) {
          const nCB = len & 0xfffff800;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 21:
        if (len & 0x400) {
          const nCB = len & 0xfffffc00;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 22:
        if (len & 0x200) {
          const nCB = len & 0xfffffe00;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 23:
        if (len & 0x100) {
          const nCB = len & 0xffffff00;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 24:
        if (len & 0x80) {
          const nCB = len & 0xffffff80;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 25:
        if (len & 0x40) {
          const nCB = len & 0xffffffc0;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 26:
        if (len & 0x20) {
          const nCB = len & 0xffffffe0;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 27:
        if (len & 0x10) {
          const nCB = len & 0xfffffff0;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 28:
        if (len & 0x8) {
          const nCB = len & 0xfffffff8;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 29:
        if (len & 0x4) {
          const nCB = len & 0xfffffffc;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 30:
        if (len & 0x2) {
          const nCB = len & 0xfffffffe;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 31:
        if (len & 0x1) {
          const nCB = len & 0xffffffff;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
    }
    // MODIFICATION: Instead of returning the index, this binary search
    //                instead returns whether something was found or not.
    if (array[len|0] !== sValue) {
       return true; // preserve the value at this index
    } else {
       return false; // eliminate the value at this index
    }
  };
}

Please see my other post here for more details on the binary search algorithm used

If you are squeamish about file size (which I respect), then you can sacrifice a little performance in order to greatly reduce the file size and increase maintainability.

function sortAnyArray(a,b) { return a>b ? 1 : (a===b ? 0 : -1); }
function sortIntArray(a,b) { return (a|0) - (b|0) |0; }
function fastFilter(array, handle) {
    var out=[], value=0;
    for (var i=0,  len=array.length|0; i < len; i=i+1|0)
        if (handle(value = array[i])) 
            out.push( value );
    return out;
}

/* USAGE:
  filterArrayByAnotherArray(
      [1,3,5],
      [2,3,4]
  ) yields [1, 5], and it can work with strings too
*/
function filterArrayByAnotherArray(searchArray, filterArray) {
    if (
        // NOTE: This does not check the whole array. But, if you know
        //        that there are only strings or numbers (not a mix of
        //        both) in the array, then this is a safe assumption.
        typeof searchArray[0] == "number" &&
        typeof filterArray[0] == "number" &&
        (searchArray[0]|0) === searchArray[0] &&
        (filterArray[0]|0) === filterArray[0]
    ) {
        // if all entries in both arrays are integers
        searchArray.sort(sortIntArray);
        filterArray.sort(sortIntArray);
    } else {
        searchArray.sort(sortAnyArray);
        filterArray.sort(sortAnyArray);
    }
    // Progressive Linear Search
    var i = 0;
    return fastFilter(searchArray, function(currentValue){
        while (filterArray[i] < currentValue) i=i+1|0;
        // +undefined = NaN, which is always false for <, avoiding an infinite loop
        return filterArray[i] !== currentValue;
    });
}

To prove the difference in speed, let us examine some JSPerfs. For filtering an array of 16 elements, binary search is roughly 17% faster than indexOf while filterArrayByAnotherArray is roughly 93% faster than indexOf. For filtering an array of 256 elements, binary search is roughly 291% faster than indexOf while filterArrayByAnotherArray is roughly 353% faster than indexOf. For filtering an array of 4096 elements, binary search is roughly 2655% faster than indexOf while filterArrayByAnotherArray is roughly 4627% faster than indexOf.

Reverse-filtering (like an AND gate)

The previous section provided code to take array A and array B, and remove all elements from A that exist in B:

filterArrayByAnotherArray(
    [1,3,5],
    [2,3,4]
);
// yields [1, 5]

This next section will provide code for reverse-filtering, where we remove all elements from A that DO NOT exist in B. This process is functionally equivalent to only retaining the elements common to both A and B, like an AND gate:

reverseFilterArrayByAnotherArray(
    [1,3,5],
    [2,3,4]
);
// yields [3]

Here is the code for reverse filtering:

function sortAnyArray(a,b) { return a>b ? 1 : (a===b ? 0 : -1); }
function sortIntArray(a,b) { return (a|0) - (b|0) |0; }
function fastFilter(array, handle) {
    var out=[], value=0;
    for (var i=0,  len=array.length|0; i < len; i=i+1|0)
        if (handle(value = array[i])) 
            out.push( value );
    return out;
}

const Math_clz32 = Math.clz32 || (function(log, LN2){
  return function(x) {
    return 31 - log(x >>> 0) / LN2 | 0; // the "| 0" acts like math.floor
  };
})(Math.log, Math.LN2);

/* USAGE:
  reverseFilterArrayByAnotherArray(
      [1,3,5],
      [2,3,4]
  ) yields [3], and it can work with strings too
*/
function reverseFilterArrayByAnotherArray(searchArray, filterArray) {
    if (
        // NOTE: This does not check the whole array. But, if you know
        //        that there are only strings or numbers (not a mix of
        //        both) in the array, then this is a safe assumption.
        // Always use `==` with `typeof` because browsers can optimize
        //  the `==` into `===` (ONLY IN THIS CIRCUMSTANCE)
        typeof searchArray[0] == "number" &&
        typeof filterArray[0] == "number" &&
        (searchArray[0]|0) === searchArray[0] &&
        (filterArray[0]|0) === filterArray[0]
    ) {
        // if all entries in both arrays are integers
        searchArray.sort(sortIntArray);
        filterArray.sort(sortIntArray);
    } else {
        searchArray.sort(sortAnyArray);
        filterArray.sort(sortAnyArray);
    }
    var searchArrayLen = searchArray.length, filterArrayLen = filterArray.length;
    var progressiveLinearComplexity = ((searchArrayLen<<1) + filterArrayLen)>>>0
    var binarySearchComplexity= (searchArrayLen * (32-Math_clz32(filterArrayLen-1)))>>>0;
    // After computing the complexity, we can predict which algorithm will be the fastest
    var i = 0;
    if (progressiveLinearComplexity < binarySearchComplexity) {
        // Progressive Linear Search
        return fastFilter(searchArray, function(currentValue){
            while (filterArray[i] < currentValue) i=i+1|0;
            // +undefined = NaN, which is always false for <, avoiding an infinite loop
            // For reverse filterning, I changed !== to ===
            return filterArray[i] === currentValue;
        });
    } else {
        // Binary Search
        return fastFilter(
            searchArray,
            inverseFastestBinarySearch(filterArray)
        );
    }
}

// see https://stackoverflow.com/a/44981570/5601591 for implementation
//  details about this binary search algorithim

function inverseFastestBinarySearch(array){
  var initLen = (array.length|0) - 1 |0;
  
  const compGoto = Math_clz32(initLen) & 31;
  return function(sValue) {
    var len = initLen |0;
    switch (compGoto) {
      case 0:
        if (len & 0x80000000) {
          const nCB = len & 0x80000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 1:
        if (len & 0x40000000) {
          const nCB = len & 0xc0000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 2:
        if (len & 0x20000000) {
          const nCB = len & 0xe0000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 3:
        if (len & 0x10000000) {
          const nCB = len & 0xf0000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 4:
        if (len & 0x8000000) {
          const nCB = len & 0xf8000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 5:
        if (len & 0x4000000) {
          const nCB = len & 0xfc000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 6:
        if (len & 0x2000000) {
          const nCB = len & 0xfe000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 7:
        if (len & 0x1000000) {
          const nCB = len & 0xff000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 8:
        if (len & 0x800000) {
          const nCB = len & 0xff800000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 9:
        if (len & 0x400000) {
          const nCB = len & 0xffc00000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 10:
        if (len & 0x200000) {
          const nCB = len & 0xffe00000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 11:
        if (len & 0x100000) {
          const nCB = len & 0xfff00000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 12:
        if (len & 0x80000) {
          const nCB = len & 0xfff80000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 13:
        if (len & 0x40000) {
          const nCB = len & 0xfffc0000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 14:
        if (len & 0x20000) {
          const nCB = len & 0xfffe0000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 15:
        if (len & 0x10000) {
          const nCB = len & 0xffff0000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 16:
        if (len & 0x8000) {
          const nCB = len & 0xffff8000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 17:
        if (len & 0x4000) {
          const nCB = len & 0xffffc000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 18:
        if (len & 0x2000) {
          const nCB = len & 0xffffe000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 19:
        if (len & 0x1000) {
          const nCB = len & 0xfffff000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 20:
        if (len & 0x800) {
          const nCB = len & 0xfffff800;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 21:
        if (len & 0x400) {
          const nCB = len & 0xfffffc00;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 22:
        if (len & 0x200) {
          const nCB = len & 0xfffffe00;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 23:
        if (len & 0x100) {
          const nCB = len & 0xffffff00;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 24:
        if (len & 0x80) {
          const nCB = len & 0xffffff80;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 25:
        if (len & 0x40) {
          const nCB = len & 0xffffffc0;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 26:
        if (len & 0x20) {
          const nCB = len & 0xffffffe0;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 27:
        if (len & 0x10) {
          const nCB = len & 0xfffffff0;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 28:
        if (len & 0x8) {
          const nCB = len & 0xfffffff8;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 29:
        if (len & 0x4) {
          const nCB = len & 0xfffffffc;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 30:
        if (len & 0x2) {
          const nCB = len & 0xfffffffe;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 31:
        if (len & 0x1) {
          const nCB = len & 0xffffffff;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
    }
    // MODIFICATION: Instead of returning the index, this binary search
    //                instead returns whether something was found or not.
    // For reverse filterning, I swapped true with false and vice-versa
    if (array[len|0] !== sValue) {
       return false; // preserve the value at this index
    } else {
       return true; // eliminate the value at this index
    }
  };
}

For the slower smaller version of the reverse filtering code, see below.

function sortAnyArray(a,b) { return a>b ? 1 : (a===b ? 0 : -1); }
function sortIntArray(a,b) { return (a|0) - (b|0) |0; }
function fastFilter(array, handle) {
    var out=[], value=0;
    for (var i=0,  len=array.length|0; i < len; i=i+1|0)
        if (handle(value = array[i])) 
            out.push( value );
    return out;
}

/* USAGE:
  reverseFilterArrayByAnotherArray(
      [1,3,5],
      [2,3,4]
  ) yields [3], and it can work with strings too
*/
function reverseFilterArrayByAnotherArray(searchArray, filterArray) {
    if (
        // NOTE: This does not check the whole array. But, if you know
        //        that there are only strings or numbers (not a mix of
        //        both) in the array, then this is a safe assumption.
        typeof searchArray[0] == "number" &&
        typeof filterArray[0] == "number" &&
        (searchArray[0]|0) === searchArray[0] &&
        (filterArray[0]|0) === filterArray[0]
    ) {
        // if all entries in both arrays are integers
        searchArray.sort(sortIntArray);
        filterArray.sort(sortIntArray);
    } else {
        searchArray.sort(sortAnyArray);
        filterArray.sort(sortAnyArray);
    }
    // Progressive Linear Search
    var i = 0;
    return fastFilter(searchArray, function(currentValue){
        while (filterArray[i] < currentValue) i=i+1|0;
        // +undefined = NaN, which is always false for <, avoiding an infinite loop
        // For reverse filter, I changed !== to ===
        return filterArray[i] === currentValue;
    });
}

How to remove index.php from URLs?

I tried everything on the post but nothing had worked. I then changed the .htaccess snippet that ErJab put up to read:

RewriteRule ^(.*)$ 'folder_name'/index.php/$1 [L]

The above line fixed it for me. where *folder_name* is the magento root folder.

Hope this helps!

How can I run a PHP script inside a HTML file?

Yes, you can run PHP in an HTML page.

I have successfully executed PHP code in my HTML files for many years. (For the curious, this is because I have over 8,000 static HTML files created by me and others over the last 20 years and I didn't want to lose search engine ranking by changing them and, more importantly, I have too many other things to work on).

I am not an expert -- below is what I've tried and what works for me. Please don't ask me to explain it.

Everything below involves adding a line or two to your .htaccess file.

Here is what one host ( http://simolyhosting.net ) support did for me in 2008 -- but it no longer works for me now.

AddHandler application/x-httpd-php5 .html .htm
AddType application/x-httpd-php5 .htm .html

That solution appears to be deprecated now, though it might work for you.

Here's what's working for me now:

AddType application/x-httpd-lsphp .htm .html

(This page has PHP code that executes properly with the above solution -- http://mykindred.com/bumstead/steeplehistory.htm )


Below are other solutions I found -- they are NOT MINE:


https://forums.cpanel.net/threads/cant-execute-php-in-html-since-ea4-upgrade.569531

I'm seeing this across many servers I've recently upgraded to EA4. Using cPanel Apache handlers or adding this directly in to .htaccess (same as cPanel does through gui add handlers):

AddHandler application/x-httpd-php5 .html

Sep 9, 2016

AddHandler application/x-httpd-ea-php56 .html

https://help.1and1.com/hosting-c37630/scripts-and-programming-languages-c85099/php-c37728/parsing-php-code-within-html-pages-a602364.html

Open a text editor such as wordpad, notepad, nano, etc. and add the following line:

AddHandler x-mapp-php5 .html .htm

If you want to use PHP 5.4 instead of PHP 5.2 then use the following line instead:

AddHandler x-mapp-php6 .html .htm

https://www.godaddy.com/community/Developer-Cloud-Portal/Running-php-in-html-files/td-p/2776

To run HTML using FastCGI/PHP, try adding this code to the .htaccess file for the directory the script is in:

Options +ExecCGI
AddHandler fcgid-script .html
FCGIWrapper /usr/local/cpanel/cgi-sys/php5 .html

You can add additional lines for other file extensions if needed.

Checking if an Android application is running in the background

I recommend reading through this page: http://developer.android.com/reference/android/app/Activity.html

In short, your activity is no longer visible after onStop() has been called.

Please add a @Pipe/@Directive/@Component annotation. Error

Another solution is below way and It was my fault that when happened I put HomeService in declaration section in app.module.ts whereas I should put HomeService in Providers section that as you see below HomeService in declaration:[] is not in a correct place and HomeService is in Providers :[] section in a correct place that should be.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule  } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component'; 
import { HomeService } from './components/home/home.service';


@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,  
    HomeService // You will get error here
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule
  ],
  providers: [
    HomeService // Right place to set HomeService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

hope this help you.

Android Studio with Google Play Services

Most of these answers only address compile-time dependencies, but you'll find a host of NoClassDef exceptions at runtime. That's because you need more than the google-play-services.jar. It references resources that are part of the library project, and those are not included correctly if you only have the jar.

What worked best for me was to first get the project setup correctly in eclipse. Have your project structured so that it includes both your app and the library, as described here: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Multi-project-setup

Then export your app project from eclipse, and import into Android Studio as described here: http://developer.android.com/sdk/installing/migrate.html. Make sure to export both your app project and the google play services library project. When importing it will detect the library project and import it as a module. I just accepted all defaults during the project import process.

Add multiple items to a list

Another useful way is with Concat.
More information in the official documentation.

List<string> first = new List<string> { "One", "Two", "Three" };
List<string> second = new List<string>() { "Four", "Five" };
first.Concat(second);

The output will be.

One
Two
Three
Four
Five

And there is another similar answer.

R dates "origin" must be supplied

My R use 1970-01-01:

>as.Date(15103, origin="1970-01-01")
[1] "2011-05-09"

and this matches the calculation from

>as.numeric(as.Date(15103, origin="1970-01-01"))

Print out the values of a (Mat) matrix in OpenCV C++

I think using the matrix.at<type>(x,y) is not the best way to iterate trough a Mat object! If I recall correctly matrix.at<type>(x,y) will iterate from the beginning of the matrix each time you call it(I might be wrong though). I would suggest using cv::MatIterator_

cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
    std::cout << *_it << std::endl;
}

Adding iOS UITableView HeaderView (not section header)

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.frame.size.width,30)];
    headerView.backgroundColor=[[UIColor redColor]colorWithAlphaComponent:0.5f];
    headerView.layer.borderColor=[UIColor blackColor].CGColor;
    headerView.layer.borderWidth=1.0f;

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5,100,20)];

    headerLabel.textAlignment = NSTextAlignmentRight;
    headerLabel.text = @"LeadCode ";
    //headerLabel.textColor=[UIColor whiteColor];
    headerLabel.backgroundColor = [UIColor clearColor];


    [headerView addSubview:headerLabel];

    UILabel *headerLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, headerView.frame.size.width-120.0, headerView.frame.size.height)];

    headerLabel1.textAlignment = NSTextAlignmentRight;
    headerLabel1.text = @"LeadName";
    headerLabel.textColor=[UIColor whiteColor];
    headerLabel1.backgroundColor = [UIColor clearColor];

    [headerView addSubview:headerLabel1];

    return headerView;

}

How to read XML using XPath in Java

This shows you how to

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

We will call the code with the following statement

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

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

Full code

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

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

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

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

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

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

Prints

<creatorName>Fosmire, Michael</creatorName>

<creatorName>Wertz, Ruth</creatorName>

<creatorName>Purzer, Senay</creatorName>

For book.xml

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

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

To run org.apache.http.legacy perfectely in Android 9.0 Pie create an xml file res/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
      <base-config cleartextTrafficPermitted="true">
       <trust-anchors>
        <certificates src="system" />
       </trust-anchors>
      </base-config>
    </network-security-config>

And add 2 tags tag in your AndroidManifest.xml

android:networkSecurityConfig="@xml/network_security_config" android:name="org.apache.http.legacy"

<?xml version="1.0" encoding="utf-8"?>
 <manifest......>
  <application android:networkSecurityConfig="@xml/network_security_config">
   <activity..../> 
   ......
   ......
 <uses-library
        android:name="org.apache.http.legacy"
        android:required="false"/>
</application>

Also add useLibrary 'org.apache.http.legacy' in your app build gradle

android {
compileSdkVersion 28
defaultConfig {
    applicationId "your application id"
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    useLibrary 'org.apache.http.legacy'
}

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

I know this is an old thread, but I just cannot steer away from posting some useful info on this. I see the Zip question come up a lot and this answers nearlly most of the common questions.

To get around framework issues of using 4.5+... Their is a ZipStorer class created by jaime-olivares: https://github.com/jaime-olivares/zipstorer, he also has added an example of how to use this class as well and has also added an example of how to search for a specific filename as well.

And for reference on how to use this and iterate through for a certain file extension as example you could do this:

#region
/// <summary>
/// Custom Method - Check if 'string' has '.png' or '.PNG' extension.
/// </summary>
static bool HasPNGExtension(string filename)
{
    return Path.GetExtension(filename).Equals(".png", StringComparison.InvariantCultureIgnoreCase)
        || Path.GetExtension(filename).Equals(".PNG", StringComparison.InvariantCultureIgnoreCase);
}
#endregion

private void button1_Click(object sender, EventArgs e)
{
    //NOTE: I recommend you add path checking first here, added the below as example ONLY.
    string ZIPfileLocationHere = @"C:\Users\Name\Desktop\test.zip";
    string EXTRACTIONLocationHere = @"C:\Users\Name\Desktop";

    //Opens existing zip file.
    ZipStorer zip = ZipStorer.Open(ZIPfileLocationHere, FileAccess.Read);

    //Read all directory contents.
    List<ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

    foreach (ZipStorer.ZipFileEntry entry in dir)
    {
        try
        {
            //If the files in the zip are "*.png or *.PNG" extract them.
            string path = Path.Combine(EXTRACTIONLocationHere, (entry.FilenameInZip));
            if (HasPNGExtension(path))
            {
                //Extract the file.
                zip.ExtractFile(entry, path);
            }
        }
        catch (InvalidDataException)
        {
            MessageBox.Show("Error: The ZIP file is invalid or corrupted");
            continue;
        }
        catch
        {
            MessageBox.Show("Error: An unknown error ocurred while processing the ZIP file.");
            continue;
        }
    }
    zip.Close();
}

Get JSONArray without array name?

JSONArray has a constructor which takes a String source (presumed to be an array).

So something like this

JSONArray array = new JSONArray(yourJSONArrayAsString);

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

How can I check whether an array is null / empty?

ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty

git replacing LF with CRLF

A GitHub's article on line endings is commonly mentioned when talking about this topic.

My personal experience with using the often recommended core.autocrlf config setting was very mixed.

I'm using Windows with Cygwin, dealing with both Windows and UNIX projects at different times. Even my Windows projects sometimes use bash shell scripts, which require UNIX (LF) line endings.

Using GitHub's recommended core.autocrlf setting for Windows, if I check out a UNIX project (which does work perfectly on Cygwin - or maybe I'm contributing to a project that I use on my Linux server), the text files are checked out with Windows (CRLF) line endings, creating problems.

Basically, for a mixed environment like I have, setting the global core.autocrlf to any of the options will not work well in some cases. This option might be set on a local (repository) git config, but even that wouldn't be good enough for a project that contains both Windows- and UNIX-related stuff (e.g. I have a Windows project with some bash utility scripts).

The best choice I've found is to create per-repository .gitattributes files. The GitHub article mentions it.
Example from that article:

# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto

# Explicitly declare text files you want to always be normalized and converted
# to native line endings on checkout.
*.c text
*.h text

# Declare files that will always have CRLF line endings on checkout.
*.sln text eol=crlf

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary

In one of my project's repository:

* text=auto

*.txt         text eol=lf
*.xml         text eol=lf
*.json        text eol=lf
*.properties  text eol=lf
*.conf        text eol=lf

*.awk  text eol=lf
*.sed  text eol=lf
*.sh   text eol=lf

*.png  binary
*.jpg  binary

*.p12  binary

It's a bit more things to set up, but do it once per project, and any contributor on any OS should have no troubles with line endings when working with this project.

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

This is because the LEFT OUTER Join is doing more work than an INNER Join BEFORE sending the results back.

The Inner Join looks for all records where the ON statement is true (So when it creates a new table, it only puts in records that match the m.SubID = a.SubID). Then it compares those results to your WHERE statement (Your last modified time).

The Left Outer Join...Takes all of the records in your first table. If the ON statement is not true (m.SubID does not equal a.SubID), it simply NULLS the values in the second table's column for that recordset.

The reason you get the same number of results at the end is probably coincidence due to the WHERE clause that happens AFTER all of the copying of records.

Join (SQL) Wikipedia

nvm keeps "forgetting" node in new terminal session

Also in case you had node installed before nvm check in your ~/.bash_profile to not have something like :

export PATH=/bin:/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:$PATH

If you do have it, comment/remove it and nvm should start handling the default node version.

Postgres user does not exist?

I get exactly the same errors as kryshah with su - postgres and sudo -u postgres psql. DanielM's answer gives also errors.

Outputs when wrong settings

Answer however from przbabu's comment.

masi$ psql
psql: FATAL:  database "masi" does not exist
masi$ psql -U postgres
psql: FATAL:  role "postgres" does not exist
masi$ psql postgres
psql (9.4.1)
Type "help" for help.

I think the some part of this problem may be in owner settings in OSX

masi$ ls -al /Users/
total 0
drwxr-xr-x   7 root      admin  238 Jul  3 09:50 .
drwxr-xr-x  37 root      wheel 1326 Jul  2 19:02 ..
-rw-r--r--   1 root      wheel    0 Sep 10  2014 .localized
drwxrwxrwt   7 root      wheel  238 Apr  9 19:49 Shared
drwxr-xr-x   2 root      admin   68 Jul  3 09:50 postgres
drwxr-xr-x+ 71 masi      staff 2414 Jul  3 09:50 masi

but doing sudo chown -R postgres:staff /Users/postgres gives chown: invalid user: ‘postgres:staff’.

In short, this is not the solution the problem. Use the tools provided by the postgres installation to create a user and database.

To get right settings and outputs

There are specific commands after postgres installation to add a new user to the database system. After initdb, run the following as described here

createuser --pwprompt postgres
createdb -Opostgres -Eutf8 masi_development
psql -U postgres -W masi_development

To avoid the password request all the time, you have three choices as described here.

Decode JSON with unknown structure

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

package main

import (
    "fmt"
    "encoding/json"
)

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

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

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

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

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

What is the purpose of Order By 1 in SQL select statement?

it simply means sorting the view or table by 1st column of query's result.

Detect a finger swipe through JavaScript on the iPhone and Android

jQuery Mobile also includes swipe support: http://api.jquerymobile.com/swipe/

Example

$("#divId").on("swipe", function(event) {
    alert("It's a swipe!");
});

How to save a Seaborn plot into a file

You should just be able to use the savefig method of sns_plot directly.

sns_plot.savefig("output.png")

For clarity with your code if you did want to access the matplotlib figure that sns_plot resides in then you can get it directly with

fig = sns_plot.fig

In this case there is no get_figure method as your code assumes.

Closing a file after File.Create

File.WriteAllText(file,content)

create write close

File.WriteAllBytes--   type binary

:)

How do I "un-revert" a reverted Git commit?

Reverting the revert will do the trick

For example,

If abcdef is your commit and ghijkl is the commit you have when you reverted the commit abcdef, then run:

git revert ghijkl

This will revert the revert

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

In my case, it's because I deleted the chrome update folder. After chrome reinstall, it's working fine.

No matching bean of type ... found for dependency

I had a similar issue but I was missing the (@Service or @Component) from the implementation of com.example.my.services.myUser.MyUserServiceImpl

Laravel-5 'LIKE' equivalent (Eloquent)

I have scopes for this, hope it help somebody. https://laravel.com/docs/master/eloquent#local-scopes

public function scopeWhereLike($query, $column, $value)
{
    return $query->where($column, 'like', '%'.$value.'%');
}

public function scopeOrWhereLike($query, $column, $value)
{
    return $query->orWhere($column, 'like', '%'.$value.'%');
}

Usage:

$result = BookingDates::whereLike('email', $email)->orWhereLike('name', $name)->get();

what does "dead beef" mean?

It's a made up expression using only the letters A-F, often used when a recognisable hexadecimal number is required. Some systems use it for various purposes such as showing memory which has been freed and should not be referenced again. In a debugger this value showing up could be a sign that you have made an error. From Wikipedia:

0xDEADBEEF ("dead beef") is used by IBM RS/6000 systems, Mac OS on 32-bit PowerPC processors and the Commodore Amiga as a magic debug value. On Sun Microsystems' Solaris, it marks freed kernel memory. On OpenVMS running on Alpha processors, DEAD_BEEF can be seen by pressing CTRL-T.

The number 0xDEADBEEF is equal to the less recognisable decimal number 3735928559 (unsigned) or -559038737 (signed).

exception.getMessage() output with class name

My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.

Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:

public class Test {
    public static void main(String[] args) {
        try {
            failingMethod();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }       

    private static void failingMethod() {
        throw new RuntimeException("Just the message");
    }
}

Output:

Error: Just the message

Where does the slf4j log file get saved?

The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)

-Dlogging.config={file_location}\log4j2.xml 

or this:

-Dlog4j.configurationFile={file_location}\log4j2.xml

SQL Server Insert Example

I hope this will help you

Create table :

create table users (id int,first_name varchar(10),last_name varchar(10));

Insert values into the table :

insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');

Convert NVARCHAR to DATETIME in SQL Server 2008

What you exactly wan't to do ?. To change Datatype of column you can simple use alter command as

ALTER TABLE table_name ALTER COLUMN LoginDate DateTime;

But remember there should valid Date only in this column however data-type is nvarchar.

If you wan't to convert data type while fetching data then you can use CONVERT function as,

CONVERT(data_type(length),expression,style)

eg:

SELECT CONVERT(DateTime, loginDate, 6)

This will return 29 AUG 13. For details about CONVERT function you can visit ,

http://www.w3schools.com/sql/func_convert.asp.

Remember, Always use DataTime data type for DateTime column.

Thank You

Accessing a local website from another computer inside the local network in IIS 7

Find the local IP address of computer A and find the port that your website is running on. Then from computer B open a web browser and go to IP:port. Example: 192.168.1.5:80 if computer A's IP is 192.168.1.5 and your website is running on port 80

Printing leading 0's in C

You will save yourself a heap of trouble (long term) if you store a ZIP Code as a character string, which it is, rather than a number, which it is not.

How do I get the current date in JavaScript?

You can use Date.js library which extens Date object, thus you can have .today() method.

How to configure Git post commit hook

As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:

#!/usr/bin/python

import sys
from subprocess import call

if __name__ == '__main__':
    for line in sys.stdin.xreadlines():
        old, new, ref = line.strip().split(' ')
        if ref == 'refs/heads/master':
            print "=============================================="
            print "Pushing to master. Triggering jenkins.        "
            print "=============================================="
            sys.stdout.flush()
            call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])

In this case I trigger jenkins jobs only when pushing to master and not other branches.

Can I invoke an instance method on a Ruby module without including it?

Another way to do it if you "own" the module is to use module_function.

module UsefulThings
  def a
    puts "aaay"
  end
  module_function :a

  def b
    puts "beee"
  end
end

def test
  UsefulThings.a
  UsefulThings.b # Fails!  Not a module method
end

test

HTML5 canvas ctx.fillText won't do line breaks?

Here is my function to draw multiple lines of text center in canvas (only break the line, don't break-word)

_x000D_
_x000D_
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

let text = "Hello World \n Hello World 2222 \n AAAAA \n thisisaveryveryveryveryveryverylongword. "
ctx.font = "20px Arial";

fillTextCenter(ctx, text, 0, 0, c.width, c.height)

function fillTextCenter(ctx, text, x, y, width, height) {
    ctx.textBaseline = 'middle';
    ctx.textAlign = "center";

    const lines = text.match(/[^\r\n]+/g);
    for(let i = 0; i < lines.length; i++) {
        let xL = (width - x) / 2
        let yL =  y + (height / (lines.length + 1)) * (i+1)

        ctx.fillText(lines[i], xL, yL)
    }
}
_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000;"></canvas>
_x000D_
_x000D_
_x000D_

If you want to fit text size to canvas, you can also check here

Convert `List<string>` to comma-separated string

That's the way I'd prefer to see if I was maintaining your code. If you manage to find a faster solution, it's going to be very esoteric, and you should really bury it inside of a method that describes what it does.

(does it still work without the ToArray)?

Elegant ways to support equivalence ("equality") in Python classes

The 'is' test will test for identity using the builtin 'id()' function which essentially returns the memory address of the object and therefore isn't overloadable.

However in the case of testing the equality of a class you probably want to be a little bit more strict about your tests and only compare the data attributes in your class:

import types

class ComparesNicely(object):

    def __eq__(self, other):
        for key, value in self.__dict__.iteritems():
            if (isinstance(value, types.FunctionType) or 
                    key.startswith("__")):
                continue

            if key not in other.__dict__:
                return False

            if other.__dict__[key] != value:
                return False

         return True

This code will only compare non function data members of your class as well as skipping anything private which is generally what you want. In the case of Plain Old Python Objects I have a base class which implements __init__, __str__, __repr__ and __eq__ so my POPO objects don't carry the burden of all that extra (and in most cases identical) logic.

How to avoid page refresh after button click event in asp.net

I think I also have this problem, I was trying to make calendar visible after clicking a button but the page keeps refreshing after clicking the button

MaintainScrollPositionOnPostBack="true"

This actually answered my problem.

I cant vote or comment, I just joined SO today

How do I remove the first characters of a specific column in a table?

Here's a simple mock-up of what you're trying to do :)

CREATE TABLE Codes
(
code1 varchar(10),
code2 varchar(10)
)

INSERT INTO Codes (CODE1, CODE2) vALUES ('ABCD1234','')


UPDATE Codes
SET code2 = SUBSTRING(Code1, 5, LEN(CODE1) -4)

So, use the last statement against the field you want to trim :)

The SUBSTRING function trims down Code1, starting at the FIFTH character, and continuing for the length of CODE1 less 4 (the number of characters skipped at the start).

How to pass ArrayList of Objects from one to another activity using Intent in android?

To set the data in kotlin

val offerIds = ArrayList<Offer>()
offerIds.add(Offer(1))
retrunIntent.putExtra(C.OFFER_IDS, offerIds)

To get the data

 val offerIds = data.getSerializableExtra(C.OFFER_IDS) as ArrayList<Offer>?

Now access the arraylist

Choosing a jQuery datagrid plugin?

A good plugin that I have used before is DataTables.

How to get the name of the current method from code

You can also use MethodBase.GetCurrentMethod() which will inhibit the JIT compiler from inlining the method where it's used.


Update:

This method contains a special enumeration StackCrawlMark that from my understanding will specify to the JIT compiler that the current method should not be inlined.

This is my interpretation of the comment associated to that enumeration present in SSCLI. The comment follows:

// declaring a local var of this enum type and passing it by ref into a function 
// that needs to do a stack crawl will both prevent inlining of the calle and 
// pass an ESP point to stack crawl to
// 
// Declaring these in EH clauses is illegal; 
// they must declared in the main method body

Best way to do multiple constructors in PHP

Another option is to use default arguments in the constructor like this

class Student {

    private $id;
    private $name;
    //...

    public function __construct($id, $row=array()) {
        $this->id = $id;
        foreach($row as $key => $value) $this->$key = $value;
    }
}

This means you'll need to instantiate with a row like this: $student = new Student($row['id'], $row) but keeps your constructor nice and clean.

On the other hand, if you want to make use of polymorphism then you can create two classes like so:

class Student {

    public function __construct($row) {
         foreach($row as $key => $value) $this->$key = $value;
    }
}

class EmptyStudent extends Student {

    public function __construct($id) {
        parent::__construct(array('id' => $id));
    }
}

How to set default values in Rails?

i answered a similar question here.. a clean way to do this is using Rails attr_accessor_with_default

class SOF
  attr_accessor_with_default :is_awesome,true
end

sof = SOF.new
sof.is_awesome

=> true

UPDATE

attr_accessor_with_default has been deprecated in Rails 3.2.. you could do this instead with pure Ruby

class SOF
  attr_writer :is_awesome

  def is_awesome
    @is_awesome ||= true
  end
end

sof = SOF.new
sof.is_awesome

#=> true

How do you check "if not null" with Eloquent?

If someone like me want to do it with query builder in Laravel 5.2.23 it can be done like ->

 $searchResultQuery = Users::query(); 
 $searchResultQuery->where('status_message', '<>', '', 'and'); // is not null
 $searchResultQuery->where('is_deleted', 'IS NULL', null, 'and'); // is null 

Or with scope in model :

public function scopeNotNullOnly($query){

    return $query->where('status_message', '<>', '');
}

Where can I find MySQL logs in phpMyAdmin?

I had the same problem of @rutherford, today the new phpMyAdmin's 3.4.11.1 GUI is different, so I figure out it's better if someone improves the answers with updated info.

Full mysql logs can be found in:

"Status"->"Binary Log"

This is the answer, doesn't matter if you're using MAMP, XAMPP, LAMP, etc.

Can PHP cURL retrieve response headers AND body in a single request?

My way is

$response = curl_exec($ch);
$x = explode("\r\n\r\n", $v, 3);
$header=http_parse_headers($x[0]);
if ($header=['Response Code']==100){ //use the other "header"
    $header=http_parse_headers($x[1]);
    $body=$x[2];
}else{
    $body=$x[1];
}

If needed apply a for loop and remove the explode limit.

Why use argparse rather than optparse?

The best source for rationale for a Python addition would be its PEP: PEP 389: argparse - New Command Line Parsing Module, in particular, the section entitled, Why aren't getopt and optparse enough?

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

Late to the party, but grappelli was the reason for my error as well. I looked up the compatible version on pypi and that fixed it for me.

What version of Java is running in Eclipse?

If you want to check if your -vm eclipse.ini option worked correctly you can use this to see under what JVM the IDE itself runs: menu Help > About Eclipse > Installation Details > Configuration tab. Locate the line that says: java.runtime.version=....

How to change the plot line color from blue to black?

If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:

plt.axes[0].get_lines()[0].set_color('black')

What is Python Whitespace and how does it work?

Whitespace just means characters which are used for spacing, and have an "empty" representation. In the context of python, it means tabs and spaces (it probably also includes exotic unicode spaces, but don't use them). The definitive reference is here: http://docs.python.org/2/reference/lexical_analysis.html#indentation

I'm not sure exactly how to use it.

Put it at the front of the line you want to indent. If you mix spaces and tabs, you'll likely see funky results, so stick with one or the other. (The python community usually follows PEP8 style, which prescribes indentation of four spaces).

You need to create a new indent level after each colon:

for x in range(0, 50):
    print x
    print 2*x

print x

In this code, the first two print statements are "inside" the body of the for statement because they are indented more than the line containing the for. The third print is outside because it is indented less than the previous (nonblank) line.

If you don't indent/unindent consistently, you will get indentation errors. In addition, all compound statements (i.e. those with a colon) can have the body supplied on the same line, so no indentation is required, but the body must be composed of a single statement.

Finally, certain statements, like lambda feature a colon, but cannot have a multiline block as the body.

How to find whether a number belongs to a particular range in Python?

To check whether some number n is in the inclusive range denoted by the two number a and b you do either

if   a <= n <= b:
    print "yes"
else:
    print "no"

use the replace >= and <= with > and < to check whether n is in the exclusive range denoted by a and b (i.e. a and b are not themselves members of the range).

Range will produce an arithmetic progression defined by the two (or three) arguments converted to integers. See the documentation. This is not what you want I guess.

Compare two objects in Java with possible null values

This is what Java internal code uses (on other compare methods):

public static boolean compare(String str1, String str2) {
    return (str1 == null ? str2 == null : str1.equals(str2));
}

List comprehension vs. lambda + filter

I find the second way more readable. It tells you exactly what the intention is: filter the list.
PS: do not use 'list' as a variable name

How can I tell if a DOM element is visible in the current viewport?

Most of the usages in previous answers are failing at these points:

-When any pixel of an element is visible, but not "a corner",

-When an element is bigger than viewport and centered,

-Most of them are checking only for a singular element inside a document or window.

Well, for all these problems I've a solution and the plus sides are:

-You can return visible when only a pixel from any sides shows up and is not a corner,

-You can still return visible while element bigger than viewport,

-You can choose your parent element or you can automatically let it choose,

-Works on dynamically added elements too.

If you check the snippets below you will see the difference in using overflow-scroll in element's container will not cause any trouble and see that unlike other answers here even if a pixel shows up from any side or when an element is bigger than viewport and we are seeing inner pixels of the element it still works.

Usage is simple:

// For checking element visibility from any sides
isVisible(element)

// For checking elements visibility in a parent you would like to check
var parent = document; // Assuming you check if 'element' inside 'document'
isVisible(element, parent)

// For checking elements visibility even if it's bigger than viewport
isVisible(element, null, true) // Without parent choice
isVisible(element, parent, true) // With parent choice

A demonstration without crossSearchAlgorithm which is usefull for elements bigger than viewport check element3 inner pixels to see:

_x000D_
_x000D_
function isVisible(element, parent, crossSearchAlgorithm) {_x000D_
    var rect = element.getBoundingClientRect(),_x000D_
            prect = (parent != undefined) ? parent.getBoundingClientRect() : element.parentNode.getBoundingClientRect(),_x000D_
        csa = (crossSearchAlgorithm != undefined) ? crossSearchAlgorithm : false,_x000D_
        efp = function (x, y) { return document.elementFromPoint(x, y) };_x000D_
    // Return false if it's not in the viewport_x000D_
    if (rect.right < prect.left || rect.bottom < prect.top || rect.left > prect.right || rect.top > prect.bottom) {_x000D_
        return false;_x000D_
    }_x000D_
    var flag = false;_x000D_
    // Return true if left to right any border pixel reached_x000D_
    for (var x = rect.left; x < rect.right; x++) {_x000D_
        if (element.contains(efp(rect.top, x)) || element.contains(efp(rect.bottom, x))) {_x000D_
        flag = true;_x000D_
        break;_x000D_
      }_x000D_
    }_x000D_
    // Return true if top to bottom any border pixel reached_x000D_
    if (flag == false) {_x000D_
      for (var y = rect.top; y < rect.bottom; y++) {_x000D_
        if (element.contains(efp(rect.left, y)) || element.contains(efp(rect.right, y))) {_x000D_
          flag = true;_x000D_
          break;_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    if(csa) {_x000D_
      // Another algorithm to check if element is centered and bigger than viewport_x000D_
      if (flag == false) {_x000D_
        var x = rect.left;_x000D_
        var y = rect.top;_x000D_
        // From top left to bottom right_x000D_
        while(x < rect.right || y < rect.bottom) {_x000D_
          if (element.contains(efp(x,y))) {_x000D_
            flag = true;_x000D_
            break;_x000D_
          }_x000D_
          if(x < rect.right) { x++; }_x000D_
          if(y < rect.bottom) { y++; }_x000D_
        }_x000D_
        if (flag == false) {_x000D_
          x = rect.right;_x000D_
          y = rect.top;_x000D_
          // From top right to bottom left_x000D_
          while(x > rect.left || y < rect.bottom) {_x000D_
            if (element.contains(efp(x,y))) {_x000D_
              flag = true;_x000D_
              break;_x000D_
            }_x000D_
            if(x > rect.left) { x--; }_x000D_
            if(y < rect.bottom) { y++; }_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    return flag;_x000D_
}_x000D_
_x000D_
// Check multiple elements visibility_x000D_
document.getElementById('container').addEventListener("scroll", function() {_x000D_
    var elementList = document.getElementsByClassName("element");_x000D_
  var console = document.getElementById('console');_x000D_
    for (var i=0; i < elementList.length; i++) {_x000D_
      // I did not define parent, so it will be element's parent_x000D_
    if (isVisible(elementList[i])) {_x000D_
          console.innerHTML = "Element with id[" + elementList[i].id + "] is visible!";_x000D_
      break;_x000D_
    } else {_x000D_
        console.innerHTML = "Element with id[" + elementList[i].id + "] is hidden!";_x000D_
    }_x000D_
  }_x000D_
});_x000D_
_x000D_
// Dynamically added elements_x000D_
for(var i=4; i <= 6; i++) {_x000D_
  var newElement = document.createElement("div");_x000D_
  newElement.id = "element" + i;_x000D_
  newElement.classList.add("element");_x000D_
  document.getElementById('container').appendChild(newElement);_x000D_
}
_x000D_
#console { background-color: yellow; }_x000D_
#container {_x000D_
  width: 300px;_x000D_
  height: 100px;_x000D_
  background-color: lightblue;_x000D_
  overflow-y: auto;_x000D_
  padding-top: 150px;_x000D_
  margin: 45px;_x000D_
}_x000D_
.element {_x000D_
  margin: 400px;_x000D_
  width: 400px;_x000D_
  height: 320px;_x000D_
  background-color: green;_x000D_
}_x000D_
#element3 {_x000D_
  position: relative;_x000D_
  margin: 40px;_x000D_
  width: 720px;_x000D_
  height: 520px;_x000D_
  background-color: green;_x000D_
}_x000D_
#element3::before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: -10px;_x000D_
  left: -10px;_x000D_
  margin: 0px;_x000D_
  width: 740px;_x000D_
  height: 540px;_x000D_
  border: 5px dotted green;_x000D_
  background: transparent;_x000D_
}
_x000D_
<div id="console"></div>_x000D_
<div id="container">_x000D_
    <div id="element1" class="element"></div>_x000D_
    <div id="element2" class="element"></div>_x000D_
    <div id="element3" class="element"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You see, when you are inside the element3 it fails to tell if it's visible or not, because we are only checking if the element is visible from sides or corners.

And this one includes crossSearchAlgorithm which allows you to still return visible when the element is bigger than the viewport:

_x000D_
_x000D_
function isVisible(element, parent, crossSearchAlgorithm) {_x000D_
    var rect = element.getBoundingClientRect(),_x000D_
            prect = (parent != undefined) ? parent.getBoundingClientRect() : element.parentNode.getBoundingClientRect(),_x000D_
        csa = (crossSearchAlgorithm != undefined) ? crossSearchAlgorithm : false,_x000D_
        efp = function (x, y) { return document.elementFromPoint(x, y) };_x000D_
    // Return false if it's not in the viewport_x000D_
    if (rect.right < prect.left || rect.bottom < prect.top || rect.left > prect.right || rect.top > prect.bottom) {_x000D_
        return false;_x000D_
    }_x000D_
    var flag = false;_x000D_
    // Return true if left to right any border pixel reached_x000D_
    for (var x = rect.left; x < rect.right; x++) {_x000D_
        if (element.contains(efp(rect.top, x)) || element.contains(efp(rect.bottom, x))) {_x000D_
        flag = true;_x000D_
        break;_x000D_
      }_x000D_
    }_x000D_
    // Return true if top to bottom any border pixel reached_x000D_
    if (flag == false) {_x000D_
      for (var y = rect.top; y < rect.bottom; y++) {_x000D_
        if (element.contains(efp(rect.left, y)) || element.contains(efp(rect.right, y))) {_x000D_
          flag = true;_x000D_
          break;_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    if(csa) {_x000D_
      // Another algorithm to check if element is centered and bigger than viewport_x000D_
      if (flag == false) {_x000D_
        var x = rect.left;_x000D_
        var y = rect.top;_x000D_
        // From top left to bottom right_x000D_
        while(x < rect.right || y < rect.bottom) {_x000D_
          if (element.contains(efp(x,y))) {_x000D_
            flag = true;_x000D_
            break;_x000D_
          }_x000D_
          if(x < rect.right) { x++; }_x000D_
          if(y < rect.bottom) { y++; }_x000D_
        }_x000D_
        if (flag == false) {_x000D_
          x = rect.right;_x000D_
          y = rect.top;_x000D_
          // From top right to bottom left_x000D_
          while(x > rect.left || y < rect.bottom) {_x000D_
            if (element.contains(efp(x,y))) {_x000D_
              flag = true;_x000D_
              break;_x000D_
            }_x000D_
            if(x > rect.left) { x--; }_x000D_
            if(y < rect.bottom) { y++; }_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    return flag;_x000D_
}_x000D_
_x000D_
// Check multiple elements visibility_x000D_
document.getElementById('container').addEventListener("scroll", function() {_x000D_
    var elementList = document.getElementsByClassName("element");_x000D_
  var console = document.getElementById('console');_x000D_
    for (var i=0; i < elementList.length; i++) {_x000D_
      // I did not define parent so it will be element's parent_x000D_
    // and it will do crossSearchAlgorithm_x000D_
    if (isVisible(elementList[i],null,true)) {_x000D_
          console.innerHTML = "Element with id[" + elementList[i].id + "] is visible!";_x000D_
      break;_x000D_
    } else {_x000D_
        console.innerHTML = "Element with id[" + elementList[i].id + "] is hidden!";_x000D_
    }_x000D_
  }_x000D_
});_x000D_
// Dynamically added elements_x000D_
for(var i=4; i <= 6; i++) {_x000D_
  var newElement = document.createElement("div");_x000D_
  newElement.id = "element" + i;_x000D_
  newElement.classList.add("element");_x000D_
  document.getElementById('container').appendChild(newElement);_x000D_
}
_x000D_
#console { background-color: yellow; }_x000D_
#container {_x000D_
  width: 300px;_x000D_
  height: 100px;_x000D_
  background-color: lightblue;_x000D_
  overflow-y: auto;_x000D_
  padding-top: 150px;_x000D_
  margin: 45px;_x000D_
}_x000D_
.element {_x000D_
  margin: 400px;_x000D_
  width: 400px;_x000D_
  height: 320px;_x000D_
  background-color: green;_x000D_
}_x000D_
#element3 {_x000D_
  position: relative;_x000D_
  margin: 40px;_x000D_
  width: 720px;_x000D_
  height: 520px;_x000D_
  background-color: green;_x000D_
}_x000D_
#element3::before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: -10px;_x000D_
  left: -10px;_x000D_
  margin: 0px;_x000D_
  width: 740px;_x000D_
  height: 540px;_x000D_
  border: 5px dotted green;_x000D_
  background: transparent;_x000D_
}
_x000D_
<div id="console"></div>_x000D_
<div id="container">_x000D_
    <div id="element1" class="element"></div>_x000D_
    <div id="element2" class="element"></div>_x000D_
    <div id="element3" class="element"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSFiddle to play with: http://jsfiddle.net/BerkerYuceer/grk5az2c/

This code is made for more precise information if any part of the element is shown in the view or not. For performance options or only vertical slides, do not use this! This code is more effective in drawing cases.

Can the Android drawable directory contain subdirectories?

#!/usr/bin/env ruby

# current dir should be drawable-hdpi/ etc

# nuke all symlinks
Dir.foreach('.') {|f|
    File.delete(f) if File.symlink?(f)
}

# symlink all resources renaming with underscores
Dir.glob("**/*.png") {|f|
    system "ln -s #{f} #{f.gsub('/', '_')}" if f.include?("/")
}

How to move the layout up when the soft keyboard is shown android

Accoding to this guide, the correct way to achieve this is by declaring in your manifest:

<activity name="EditContactActivity"
        android:windowSoftInputMode="stateVisible|adjustResize">

    </activity>

twitter bootstrap navbar fixed top overlapping site

I put this before the yield container:

<div id="fix-for-navbar-fixed-top-spacing" style="height: 42px;">&nbsp;</div>

I like this approach because it documents the hack needed to get it work, plus it also works for the mobile nav.

EDIT - this works much better:

@media (min-width: 980px) {
  body {
    padding-top: 60px;
    padding-bottom: 42px;
  }
}

Command not found error in Bash variable assignment

When you define any variable then you do not have to put in any extra spaces.

E.g.

name = "Stack Overflow"  
// it is not valid, you will get an error saying- "Command not found"

So remove spaces:

name="Stack Overflow" 

and it will work fine.

jQuery issue - #<an Object> has no method

This problem can also arise if you include jQuery more than once.

How do you determine the size of a file in C?

I have a function that works well with only stdio.h. I like it a lot and it works very well and is pretty concise:

size_t fsize(FILE *File) {
    size_t FSZ;
    fseek(File, 0, 2);
    FSZ = ftell(File);
    rewind(File);
    return FSZ;
}

Mysql: Select rows from a table that are not in another

You need to do the subselect based on a column name, not *.

For example, if you had an id field common to both tables, you could do:

SELECT * FROM Table1 WHERE id NOT IN (SELECT id FROM Table2)

Refer to the MySQL subquery syntax for more examples.

Bootstrap - floating navbar button right

You would need to use the following markup. If you want to float any menu items to the right, create a separate <ul class="nav navbar-nav"> with navbar-right class to it.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
    <div class="container">_x000D_
      <div class="navbar-header">_x000D_
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
            <span class="sr-only">Toggle navigation</span>_x000D_
            <span class="icon-bar"></span>_x000D_
            <span class="icon-bar"></span>_x000D_
            <span class="icon-bar"></span>_x000D_
          </button>_x000D_
        <a class="navbar-brand" href="#">Project name</a>_x000D_
      </div>_x000D_
      <div class="collapse navbar-collapse">_x000D_
        <ul class="nav navbar-nav">_x000D_
          <li class="active"><a href="#">Home</a></li>_x000D_
          <li><a href="#about">About</a></li>_x000D_
_x000D_
        </ul>_x000D_
        <ul class="nav navbar-nav navbar-right">_x000D_
          <li><a href="#contact">Contact</a></li>_x000D_
        </ul>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to change sa password in SQL Server 2008 express?

You need to follow the steps described in Troubleshooting: Connecting to SQL Server When System Administrators Are Locked Out and add your own Windows user as a member of sysadmin:

  • shutdown MSSQL$EXPRESS service (or whatever the name of your SQL Express service is)
  • start add the -m and -f startup parameters (or you can start sqlservr.exe -c -sEXPRESS -m -f from console)
  • connect to DAC: sqlcmd -E -A -S .\EXPRESS or from SSMS use admin:.\EXPRESS
  • run create login [machinename\username] from windows to create your Windows login in SQL
  • run sp_addsrvrolemember 'machinename\username', 'sysadmin'; to make urself sysadmin member
  • restart service w/o the -m -f

Resizing an iframe based on content

This is an old thread, but in 2020 it's still a relevant question. I've actually posted this answer in another old thread as well^^ (https://stackoverflow.com/a/64110252/4383587)


Just wanted to share my solution and excitement. It took me four entire days of intensive research and failure, but I think I've found a neat way of making iframes entirely responsive! Yey!

I tried a ton of different approaches... I didn't want to use a two-way communication tunnel as with postMessage because it's awkward for same-origin and complicated for cross-origin (as no admin wants to open doors and implement this on your behalf).

I've tried using MutationObservers and still needed several EventListeners (resize, click,..) to ensure that every change of the layout was handled correctly. - What if a script toggles the visibility of an element? Or what if it dynamically preloads more content on demand? - Another issue was getting an accurate height of the iframe contents from somewhere. Most people suggest using scrollHeight or offsetHeight, or combination of it by using Math.max. The problem is, that these values don't get updated until the iframe element changes its dimensions. To achieve that you could simply reset the iframe.height = 0 before grabbing the scrollHeight, but there are even more caveats to this. So, screw this.

Then, I had another idea to experiment with requestAnimationFrame to get rid of my events and observers hell. Now, I could react to every layout change immediately, but I still had no reliable source to infer the content height of the iframe from. And theeen I discovered getComputedStyle, by accident! This was an enlightenment! Everything just clicked.

Well, see the code I could eventually distill from my countless attempts.

function fit() {
    var iframes = document.querySelectorAll("iframe.gh-fit")

    for(var id = 0; id < iframes.length; id++) {
        var win = iframes[id].contentWindow
        var doc = win.document
        var html = doc.documentElement
        var body = doc.body
        var ifrm = iframes[id] // or win.frameElement

        if(body) {
            body.style.overflowX = "scroll" // scrollbar-jitter fix
            body.style.overflowY = "hidden"
        }
        if(html) {
            html.style.overflowX = "scroll" // scrollbar-jitter fix
            html.style.overflowY = "hidden"
            var style = win.getComputedStyle(html)
            ifrm.width = parseInt(style.getPropertyValue("width")) // round value
            ifrm.height = parseInt(style.getPropertyValue("height"))
        }
    }

    requestAnimationFrame(fit)
}

addEventListener("load", requestAnimationFrame.bind(this, fit))

That is it, yes! - In your HTML code write <iframe src="page.html" class="gh-fit gh-fullwidth"></iframe>. The gh-fit is a just fake CSS class, used to identify which iframe elements in your DOM should be affect by the script. The gh-fullwidth is a simple CSS class with one rule width: 100%;.

The above script automatically fetches all iframes from the DOM, that have a .gh-fit class assigned. It then grabs and uses the pre-calculated style values for width and height from document.getComputedStyle(iframe), which always contain a pixel-perfect size of that element!!! Just perfect!

Note, this solution doesn't work cross-origin (nor does any other solution, without a two-way communication strategy like IFrameResizer). JS simply can't access the DOM of an iframe, if it doesn't belong to you.

The only other cross-origin solution I can think of, is to use a proxy like https://github.com/gnuns/allorigins. But this would involve deep-copying every request you make - in other words - you 'steal' the entire page source code (to make it yours and let JS access the DOM) and you patch every link/path in this source, so that it goes through the proxy as well. The re-linking routine is a tough one, but doable.

I'll probably try myself at this cross-origin problem, but that's for another day. Enjoy the code! :)

Detect change to selected date with bootstrap-datepicker

Based on Irvin Dominin example, I've created 2 examples supporting Paste and hit Enter.

This works in Chrome: http://jsfiddle.net/lhernand/0a8woLev/

$(document).ready(function() {
   $('#date-daily').datepicker({
      format: 'dd/mm/yyyy',
      assumeNearbyYear: true,
      autoclose: true,
      orientation: 'bottom right',
      todayHighlight: true,
      keyboardNavigation: false
    })
    /* On 'paste' -> loses focus, hide calendar and trigger 'change' */
    .on('paste', function(e) {
      $(this).blur();
      $('#date-daily').datepicker('hide');
    })
    /* On 'enter' keypress -> loses focus and trigger 'change' */
    .on('keydown', function(e) {

      if (e.which === 13) {
         console.log('enter');
         $(this).blur();
      }
    })
    .change(function(e) {
      console.log('change');
      $('#stdout').append($('#date-daily').val() + ' change\n');
    });
});

But not in IE, so I created another example for IE11: https://jsbin.com/timarum/14/edit?html,js,console,output

$(document).ready(function() {
   $('#date-daily').datepicker({
      format: 'dd/mm/yyyy',
      assumeNearbyYear: true,
      autoclose: true,
      orientation: 'bottom right',
      todayHighlight: true,
      keyboardNavigation: false
    })
    // OnEnter -> lose focus
    .on('keydown', function(e) {
         if (e.which === 13){ 
           $(this).blur();
         }
    })
    // onPaste -> hide and lose focus
    .on('keyup', function(e) {
         if (e.which === 86){ 
            $(this).blur();
            $(this).datepicker('hide');
          }
    })
    .change(function(e) {
       $('#stdout').append($('#date-daily').val() + ' change\n');
    });
});

If last example still doesn't work in IE11, you can try splitting the setup:

// DatePicker setup
$('.datepicker').datepicker({
    format: 'dd/mm/yyyy',
    assumeNearbyYear: true,      /* manually-entered dates with two-digit years, such as '5/1/15', will be parsed as '2015', not '15' */
    autoclose: true,             /* close the datepicker immediately when a date is selected */
    orientation: 'bottom rigth',
    todayHighlight: true,        /* today appears with a blue box */
    keyboardNavigation: false    /* select date only onClick. when true, is too difficult free typing  */
}); 

And the event handlers: (note I'm not using $('.datepicker').datepicker({)

   // Smoker DataPicker behaviour
    $('#inputStoppedDate')
    // OnEnter -> lose focus
    .on('keydown', function (e) {
        if (e.which === 13){ 
            $(this).blur();
        }
    })
    // onPaste -> hide and lose focus
    .on('keyup', function (e) {
        if (e.which === 86){ 
            $(this).blur();
            $(this).datepicker('hide');
        }
    })
    .change(function (e) {
        // do saomething
    });

Swift programmatically navigate to another view controller/scene

The above code works well but if you want to navigate from an NSObject class, where you can not use self.present:

let storyBoard = UIStoryboard(name:"Main", bundle: nil)
if let conVC = storyBoard.instantiateViewController(withIdentifier: "SoundViewController") as? SoundViewController,
    let navController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {
    
    navController.pushViewController(conVC, animated: true)
}

Java Enum Methods - return opposite direction enum

For those lured here by title: yes, you can define your own methods in your enum. If you are wondering how to invoke such non-static method, you do it same way as with any other non-static method - you invoke it on instance of type which defines or inherits that method. In case of enums such instances are simply ENUM_CONSTANTs.

So all you need is EnumType.ENUM_CONSTANT.methodName(arguments).


Now lets go back to problem from question. One of solutions could be

public enum Direction {

    NORTH, SOUTH, EAST, WEST;

    private Direction opposite;

    static {
        NORTH.opposite = SOUTH;
        SOUTH.opposite = NORTH;
        EAST.opposite = WEST;
        WEST.opposite = EAST;
    }

    public Direction getOppositeDirection() {
        return opposite;
    }

}

Now Direction.NORTH.getOppositeDirection() will return Direction.SOUTH.


Here is little more "hacky" way to illustrate @jedwards comment but it doesn't feel as flexible as first approach since adding more fields or changing their order will break our code.

public enum Direction {
    NORTH, EAST, SOUTH, WEST;

    // cached values to avoid recreating such array each time method is called
    private static final Direction[] VALUES = values();

    public Direction getOppositeDirection() {
        return VALUES[(ordinal() + 2) % 4]; 
    }
}

jQuery .search() to any string

search() is a String method.

You are executing the attr function on every <li> element. You need to invoke each and use the this reference within.

Example:

$('li').each(function() {
    var isFound = $(this).attr('title').search(/string/i);
    //do something based on isFound...
});

What's the fastest way to delete a large folder in Windows?

use the command prompt, as suggested. I figured out why explorer is so slow a while ago, it gives you an estimate of how long it will take to delete the files/folders. To do this, it has to scan the number of items and the size. This takes ages, hence the ridiculous wait with large folders.

Also, explorer will stop if there is a particular problem with a file,

How would you implement an LRU cache in Java?

Well for a cache you will generally be looking up some piece of data via a proxy object, (a URL, String....) so interface-wise you are going to want a map. but to kick things out you want a queue like structure. Internally I would maintain two data structures, a Priority-Queue and a HashMap. heres an implementation that should be able to do everything in O(1) time.

Here's a class I whipped up pretty quick:

import java.util.HashMap;
import java.util.Map;
public class LRUCache<K, V>
{
    int maxSize;
    int currentSize = 0;

    Map<K, ValueHolder<K, V>> map;
    LinkedList<K> queue;

    public LRUCache(int maxSize)
    {
        this.maxSize = maxSize;
        map = new HashMap<K, ValueHolder<K, V>>();
        queue = new LinkedList<K>();
    }

    private void freeSpace()
    {
        K k = queue.remove();
        map.remove(k);
        currentSize--;
    }

    public void put(K key, V val)
    {
        while(currentSize >= maxSize)
        {
            freeSpace();
        }
        if(map.containsKey(key))
        {//just heat up that item
            get(key);
            return;
        }
        ListNode<K> ln = queue.add(key);
        ValueHolder<K, V> rv = new ValueHolder<K, V>(val, ln);
        map.put(key, rv);       
        currentSize++;
    }

    public V get(K key)
    {
        ValueHolder<K, V> rv = map.get(key);
        if(rv == null) return null;
        queue.remove(rv.queueLocation);
        rv.queueLocation = queue.add(key);//this ensures that each item has only one copy of the key in the queue
        return rv.value;
    }
}

class ListNode<K>
{
    ListNode<K> prev;
    ListNode<K> next;
    K value;
    public ListNode(K v)
    {
        value = v;
        prev = null;
        next = null;
    }
}

class ValueHolder<K,V>
{
    V value;
    ListNode<K> queueLocation;
    public ValueHolder(V value, ListNode<K> ql)
    {
        this.value = value;
        this.queueLocation = ql;
    }
}

class LinkedList<K>
{
    ListNode<K> head = null;
    ListNode<K> tail = null;

    public ListNode<K> add(K v)
    {
        if(head == null)
        {
            assert(tail == null);
            head = tail = new ListNode<K>(v);
        }
        else
        {
            tail.next = new ListNode<K>(v);
            tail.next.prev = tail;
            tail = tail.next;
            if(tail.prev == null)
            {
                tail.prev = head;
                head.next = tail;
            }
        }
        return tail;
    }

    public K remove()
    {
        if(head == null)
            return null;
        K val = head.value;
        if(head.next == null)
        {
            head = null;
            tail = null;
        }
        else
        {
            head = head.next;
            head.prev = null;
        }
        return val;
    }

    public void remove(ListNode<K> ln)
    {
        ListNode<K> prev = ln.prev;
        ListNode<K> next = ln.next;
        if(prev == null)
        {
            head = next;
        }
        else
        {
            prev.next = next;
        }
        if(next == null)
        {
            tail = prev;
        }
        else
        {
            next.prev = prev;
        }       
    }
}

Here's how it works. Keys are stored in a linked list with the oldest keys in the front of the list (new keys go to the back) so when you need to 'eject' something you just pop it off the front of the queue and then use the key to remove the value from the map. When an item gets referenced you grab the ValueHolder from the map and then use the queuelocation variable to remove the key from its current location in the queue and then put it at the back of the queue (its now the most recently used). Adding things is pretty much the same.

I'm sure theres a ton of errors here and I haven't implemented any synchronization. but this class will provide O(1) adding to the cache, O(1) removal of old items, and O(1) retrieval of cache items. Even a trivial synchronization (just synchronize every public method) would still have little lock contention due to the run time. If anyone has any clever synchronization tricks I would be very interested. Also, I'm sure there are some additional optimizations that you could implement using the maxsize variable with respect to the map.

Multi-threading in VBA

Sub MultiProcessing_Principle()
    Dim k As Long, j As Long
    k = Environ("NUMBER_OF_PROCESSORS")
    For j = 1 To k
        Shellm "msaccess", "C:\Autoexec.mdb"
    Next
    DoCmd.Quit
End Sub

Private Sub Shellm(a As String, b As String) ' Shell modificirani
    Const sn As String = """"
    Const r As String = """ """
    Shell sn & a & r & b & sn, vbMinimizedNoFocus
End Sub

Python datetime to string without microsecond component

Since not all datetime.datetime instances have a microsecond component (i.e. when it is zero), you can partition the string on a "." and take only the first item, which will always work:

unicode(datetime.datetime.now()).partition('.')[0]

Nginx location priority

It fires in this order.

  1. = (exactly)

    location = /path

  2. ^~ (forward match)

    location ^~ /path

  3. ~ (regular expression case sensitive)

    location ~ /path/

  4. ~* (regular expression case insensitive)

    location ~* .(jpg|png|bmp)

  5. /

    location /path

What is a singleton in C#?

I use it for lookup data. Load once from DB.

public sealed class APILookup
    {
        private static readonly APILookup _instance = new APILookup();
        private Dictionary<string, int> _lookup;

        private APILookup()
        {
            try
            {
                _lookup = Utility.GetLookup();
            }
            catch { }
        }

        static APILookup()
        {            
        }

        public static APILookup Instance
        {
            get
            {
                return _instance;
            }
        }
        public Dictionary<string, int> GetLookup()
        {
            return _lookup;
        }

    }

Android: How to add R.raw to project?

Create a raw android resource directory. enter image description here

Once the raw directory is created, Make sure to add a valid media file

  1. Make sure to follow proper naming conventions (lower case letters with underscore '_' as separators)
  2. Media file should have a proper encoding and formatted media file in one of the supported formats.

After following the above procedure, you should be able to access your media files by using R.raw.media_file

Data at the root level is invalid

This:

doc.LoadXml(HttpContext.Current.Server.MapPath("officeList.xml"));

should be:

doc.Load(HttpContext.Current.Server.MapPath("officeList.xml"));

LoadXml() is for loading an XML string, not a file name.

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

Is there a way to provide named parameters in a function call in JavaScript?

No - the object approach is JavaScript's answer to this. There is no problem with this provided your function expects an object rather than separate params.

Set background image in CSS using jquery

Try this:

<div class="rmz-srchbg">
    <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
    <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
    <br style="clear:both;">
</div>
<script>
$(function(){
   $('#globalsearchstr').on('focus mouseenter', function(){
    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
   });
});
</script>

Get lengths of a list in a jinja2 template

<span>You have {{products|length}} products</span>

You can also use this syntax in expressions like

{% if products|length > 1 %}

jinja2's builtin filters are documented here; and specifically, as you've already found, length (and its synonym count) is documented to:

Return the number of items of a sequence or mapping.

So, again as you've found, {{products|count}} (or equivalently {{products|length}}) in your template will give the "number of products" ("length of list")

List of enum values in java

This is a more generic solution, that can be use for any Enum object, so be free of used.

static public List<Object> constFromEnumToList(Class enumType) {
    List<Object> nueva = new ArrayList<Object>();
    if (enumType.isEnum()) {
        try {
            Class<?> cls = Class.forName(enumType.getCanonicalName());
            Object[] consts = cls.getEnumConstants();
            nueva.addAll(Arrays.asList(consts));
        } catch (ClassNotFoundException e) {
            System.out.println("No se localizo la clase");
        }
    }
    return nueva;
}

Now you must call this way:

constFromEnumToList(MiEnum.class);

Replace String in all files in Eclipse

  • "Search"->"File"
  • Enter text, file pattern and projects
  • "Replace"
  • Enter new text

Voilà...

C# '@' before a String

It also means you can use reserved words as variable names

say you want a class named class, since class is a reserved word, you can instead call your class class:

IList<Student> @class = new List<Student>();

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

Just adding my suggestion for a resolution, I had a copy of a VM server for developing and testing, I created the database on that with 'sa' having ownership on the db.

I then restored the database onto the live VM server but I was getting the same error mentioned even though the data was still returning correctly. I looked up the 'sa' user mappings and could see it wasn't mapped to the database when I tried to apply the mapping I got a another error "Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405". so I ran this instead

ALTER AUTHORIZATION ON DATABASE::dbname TO sa

I rechecked the user mappings and it was now assigned to my db and it fixed a lot of access issues for me.

Working with time DURATION, not time of day

With custom format of a cell you can insert a type like this: d "days", h:mm:ss, which will give you a result like 16 days, 13:56:15 in an excel-cell.

If you would like to show the duration in hours you use the following type [h]:mm:ss, which will lead to something like 397:56:15. Control check: 16 =(397 hours -13 hours)/24

enter image description here

Assigning the output of a command to a variable

Try:

output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output

Wrapping your command in $( ) tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)

I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.

Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:

jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD

jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD

Position an element relative to its container

You are right that CSS positioning is the way to go. Here's a quick run down:

position: relative will layout an element relative to itself. In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).

However, you're most likely interested in position: absolute which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has position: relative or position: absolute set on it, then it will act as the parent for positioning coordinates for its children.

To demonstrate:

_x000D_
_x000D_
#container {_x000D_
  position: relative;_x000D_
  border: 1px solid red;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
#box {_x000D_
  position: absolute;_x000D_
  top: 50px;_x000D_
  left: 20px;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="box">absolute</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In that example, the top left corner of #box would be 100px down and 50px left of the top left corner of #container. If #container did not have position: relative set, the coordinates of #box would be relative to the top left corner of the browser view port.

HTTP POST using JSON in Java

Try this code:

HttpClient httpClient = new DefaultHttpClient();

try {
    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
    request.addHeader("content-type", "application/json");
    request.addHeader("Accept","application/json");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);

    // handle response here...
}catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.getConnectionManager().shutdown();
}

Using the slash character in Git branch name

It is possible to have hierarchical branch names (branch names with slash). For example in my repository I have such branch(es). One caveat is that you can't have both branch 'foo' and branch 'foo/bar' in repository.

Your problem is not with creating branch with slash in name.

$ git branch foo/bar
error: unable to resolve reference refs/heads/labs/feature: Not a directory
fatal: Failed to lock ref for update: Not a directory

The above error message talks about 'labs/feature' branch, not 'foo/bar' (unless it is a mistake in copy'n'paste, i.e you edited parts of session). What is the result of git branch or git rev-parse --symbolic-full-name HEAD?

Equal height rows in a flex container

If you know the items you are mapping through, you can accomplish this by doing one row at a time. I know it's a workaround, but it works.

For me I had 4 items per row, so I broke it up into two rows of 4 with each row height: 50%, get rid of flex-grow, have <RowOne /> and <RowTwo /> in a <div> with flex-column. This will do the trick

<div class='flexbox flex-column height-100-percent'>
   <RowOne class='flex height-50-percent' />
   <RowTwo class='flex height-50-percent' />
</div>

Setting size for icon in CSS

you can change the size of an icon using the font size rather than setting the height and width of an icon. Here is how you do it:

<i class="fa fa-minus-square-o" style="font-size: 0.73em;"></i>

There are 4 ways to specify the dimensions of the icon.

px : give fixed pixels to your icon

em : dimensions with respect to your current font. Say ur current font is 12px then 1.5em will be 18px (12px + 6px).

pt : stands for points. Mostly used in print media

% : percentage. Refers to the size of the icon based on its original size.

Updating version numbers of modules in a multi-module Maven project

the easiest way is to change version in every pom.xml to arbitrary version. then check that dependency management to use the correct version of the module used in this module! for example, if u want increase versioning for a tow module project u must do like flowing:

in childe module :

    <parent>
       <artifactId>A-application</artifactId>
       <groupId>com.A</groupId>
       <version>new-version</version>
    </parent>

and in parent module :

<groupId>com.A</groupId>
<artifactId>A-application</artifactId>
<version>new-version</version>

PHP json_decode() returns NULL with valid JSON?

Just thought I'd add this, as I ran into this issue today. If there is any string padding surrounding your JSON string, json_decode will return NULL.

If you're pulling the JSON from a source other than a PHP variable, it would be wise to "trim" it first:

$jsonData = trim($jsonData);

How to get data by SqlDataReader.GetValue by column name

Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]); 

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

diff current working copy of a file with another branch's committed copy

The following works for me:

git diff master:foo foo

In the past, it may have been:

git diff foo master:foo

ldconfig error: is not a symbolic link

You need to include the path of the libraries inside /etc/ld.so.conf, and rerun ldconfig to upate the list

Other possibility is to include in the env variable LD_LIBRARY_PATH the path to your library, and rerun the executable.

check the symbolic links if they point to a valid library ...

You can add the path directly in /etc/ld.so.conf, without include...

run ldconfig -p to see whether your library is well included in the cache.

Model Binding to a List MVC 4

~Controller

namespace ListBindingTest.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            List<String> tmp = new List<String>();
            tmp.Add("one");
            tmp.Add("two");
            tmp.Add("Three");
            return View(tmp);
        }

        [HttpPost]
        public ActionResult Send(IList<String> input)
        {
            return View(input);
        }    
    }
}

~ Strongly Typed Index View

@model IList<String>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
    <div>
    @using(Html.BeginForm("Send", "Home", "POST"))
    {
        @Html.EditorFor(x => x)
        <br />
        <input type="submit" value="Send" />
    }
    </div>
</body>
</html>

~ Strongly Typed Send View

@model IList<String>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Send</title>
</head>
<body>
    <div>
    @foreach(var element in @Model)
    {
        @element
        <br />
    }
    </div>
</body>
</html>

This is all that you had to do man, change his MyViewModel model to IList.

How to import CSV file data into a PostgreSQL table?

In Python, you can use this code for automatic PostgreSQL table creation with column names:

import pandas, csv

from io import StringIO
from sqlalchemy import create_engine

def psql_insert_copy(table, conn, keys, data_iter):
    dbapi_conn = conn.connection
    with dbapi_conn.cursor() as cur:
        s_buf = StringIO()
        writer = csv.writer(s_buf)
        writer.writerows(data_iter)
        s_buf.seek(0)
        columns = ', '.join('"{}"'.format(k) for k in keys)
        if table.schema:
            table_name = '{}.{}'.format(table.schema, table.name)
        else:
            table_name = table.name
        sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(table_name, columns)
        cur.copy_expert(sql=sql, file=s_buf)

engine = create_engine('postgresql://user:password@localhost:5432/my_db')

df = pandas.read_csv("my.csv")
df.to_sql('my_table', engine, schema='my_schema', method=psql_insert_copy)

It's also relatively fast, I can import more than 3.3 million rows in about 4 minutes.

How to set the color of an icon in Angular Material?

color="white" is not a known attribute to Angular Material.

color attribute can changed to primary, accent, and warn. as said in this doc

your icon inside button works because its parent class button has css class of color:white, or may be your color="accent" is white. check the developer tools to find it.

By default, icons will use the current font color

How to get client's IP address using JavaScript?

Use ipdata.co.

The API also provides geolocation data and has 10 global endpoints each able to handle >800M requests a day!

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

_x000D_
_x000D_
$.get("https://api.ipdata.co?api-key=test", function (response) {_x000D_
    $("#response").html(response.ip);_x000D_
}, "jsonp");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<pre id="response"></pre>
_x000D_
_x000D_
_x000D_

What is the different between RESTful and RESTless

Here are summarized the key differences between RESTful and RESTless web services:

1. Protocol

  • RESTful services use REST architectural style,
  • RESTless services use SOAP protocol.

2. Business logic / Functionality

  • RESTful services use URL to expose business logic,
  • RESTless services use the service interface to expose business logic.

3. Security

  • RESTful inherits security from the underlying transport protocols,
  • RESTless defines its own security layer, thus it is considered as more secure.

4. Data format

  • RESTful supports various data formats such as HTML, JSON, text, etc,
  • RESTless supports XML format.

5. Flexibility

  • RESTful is easier and flexible,
  • RESTless is not as easy and flexible.

6. Bandwidth

  • RESTful services consume less bandwidth and resource,
  • RESTless services consume more bandwidth and resources.

How to decrypt Hash Password in Laravel

For compare hashed password with the plain text password string you can use the PHP password_verify

if(password_verify('1234567', $crypt_password_string)) {
    // in case if "$crypt_password_string" actually hides "1234567"
}

How can I create an editable combo box in HTML/Javascript?

Was looking for an Answer as well, but all I could find was outdated.

This Issue is solved since HTML5: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist

<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" /></label>
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Internet Explorer">
  <option value="Opera">
  <option value="Safari">
  <option value="Microsoft Edge">
</datalist>

If I had not found that, I would have gone with this approach:

http://www.dhtmlgoodies.com/scripts/form_widget_editable_select/form_widget_editable_select.html

Remove border from IFrame

After going mad trying to remove the border in IE7, I found that the frameBorder attribute is case sensitive.

You have to set the frameBorder attribute with a capital B.

<iframe frameBorder="0"></iframe>

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

Exchange rate from Euro to NOK on the first of January 2016:

=INDEX(GOOGLEFINANCE("CURRENCY:EURNOK"; "close"; DATE(2016;1;1)); 2; 2)

The INDEX() function is used because GOOGLEFINANCE() function actually prints out in 4 separate cells (2x2) when you call it with these arguments, with it the result will only be one cell.

Java constructor/method with optional parameters?

Why do you want to do that?

However, You can do this:

public void foo(int param1)
{
    int param2 = 2;
    // rest of code
}

or:

public void foo(int param1, int param2)
{
    // rest of code
}

public void foo(int param1)
{
    foo(param1, 2);
}

Check if any type of files exist in a directory using BATCH script

You can use this

@echo off
for /F %%i in ('dir /b "c:\test directory\*.*"') do (
   echo Folder is NON empty
   goto :EOF
)
echo Folder is empty or does not exist

Taken from here.

That should do what you need.

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

If you have a new database and you make a fresh clean import, the problem may come from inserting data that contains a '0' incrementation and this would transform to '1' with AUTO_INCREMENT and cause this error.

My solution was to use in the sql import file.

SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO';

Pandas rename column by position?

You can do this:

df.rename(columns={ df.columns[1]: "whatever" })

Export P7b file with all the certificate chain into CER file

The only problem is that any additional certificates in resulted file will not be recognized, as tools don't expect more than one certificate per PEM/DER encoded file. Even openssl itself. Try

openssl x509 -outform DER -in certificate.cer | openssl x509 -inform DER -outform PEM

and see for yourself.

Unable to execute dex: method ID not in [0, 0xffff]: 65536

As already stated, you have too many methods (more than 65k) in your project and libs.

Prevent the Problem: Reduce the number of methods with Play Services 6.5+ and support-v4 24.2+

Since often the Google Play services is one of the main suspects in "wasting" methods with its 20k+ methods. Google Play services version 6.5 or later, it is possible for you to include Google Play services in your application using a number of smaller client libraries. For example, if you only need GCM and maps you can choose to use these dependencies only:

dependencies {
    compile 'com.google.android.gms:play-services-base:6.5.+'
    compile 'com.google.android.gms:play-services-maps:6.5.+'
}

The full list of sub libraries and it's responsibilities can be found in the official google doc.

Update: Since Support Library v4 v24.2.0 it was split up into the following modules:

support-compat, support-core-utils, support-core-ui, support-media-compat and support-fragment

dependencies {
    compile 'com.android.support:support-fragment:24.2.+'
}

Do note however, if you use support-fragment, it will have dependencies to all the other modules (ie. if you use android.support.v4.app.Fragment there is no benefit)

See here the official release notes for support-v4 lib


Enable MultiDexing

Since Lollipop (aka build tools 21+) it is very easy to handle. The approach is to work around the 65k methods per dex file problem to create multiple dex files for your app. Add the following to your gradle build file (this is taken from the official google doc on applications with more than 65k methods):

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.0"

    defaultConfig {
        ...
        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

The second step is to either prepare your Application class or if you don't extend Application use the MultiDexApplication in your Android Manifest:

Either add this to your Application.java

@Override
  protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
  }

or use the provided application from the mutlidex lib

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

Prevent OutOfMemory with MultiDex

As further tip, if you run into OutOfMemory exceptions during the build phase you could enlarge the heap with

android {
    ...
    dexOptions {
        javaMaxHeapSize "4g"
    }
}

which would set the heap to 4 gigabytes.

See this question for more detail on the dex heap memory issue.


Analyze the source of the Problem

To analyze the source of the methods the gradle plugin https://github.com/KeepSafe/dexcount-gradle-plugin can help in combination with the dependency tree provided by gradle with e.g.

.\gradlew app:dependencies

See this answer and question for more information on method count in android

calculate the mean for each column of a matrix in R

try it ! also can calculate NA's data!

df <- data.frame(a1=1:10, a2=11:20)

df %>% summarise_each(funs( mean( .,na.rm = TRUE)))


# a1   a2
# 5.5 15.5

Fatal error: Call to a member function prepare() on null

You can try/catch PDOExceptions (your configs could differ but the important part is the try/catch):

try {
        $dbh = new PDO(
            DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_PERSISTENT            => true,
                PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE

            ]
        );
    } catch ( PDOException $e ) {
        echo 'ERROR!';
        print_r( $e );
    }

The print_r( $e ); line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'.

How do I enable the column selection mode in Eclipse?

To activate the cursor and select the columns you want to select use:

Windows: Alt+Shift+A

Mac: command + option + A

Linux-based OS: Alt+Shift+A

To deactivate, press the keys again.

This information was taken from DJ's Java Blog.

Get time difference between two dates in seconds

You can use new Date().getTime() for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms into s.

const start = new Date().getTime();
const end = new Date().getTime();

const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);

Regex Email validation

1

^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$

2

^(([^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$

Why is php not running?

You need to add the semicolon to the end of all php things like echo, functions, etc.

change <?php phpinfo() ?> to <?php phpinfo(); ?>

If that does not work, use php's function ini_set to show errors: ini_set('display_errors', 1);

Sorting std::map using value

If you want to present the values in a map in sorted order, then copy the values from the map to vector and sort the vector.

SQL Error: ORA-00913: too many values

If you are having 112 columns in one single table and you would like to insert data from source table, you could do as

create table employees as select * from source_employees where employee_id=100;

Or from sqlplus do as

copy from source_schema/password insert employees using select * from 
source_employees where employee_id=100;

How can I listen for keypress event on the whole page?

Be aware "document:keypress" is deprecated. We should use document:keydown instead.

Link: https://developer.mozilla.org/fr/docs/Web/API/Document/keypress_event

Get error message if ModelState.IsValid fails?

If Modal State is not Valid & the error cannot be seen on screen because your control is in collapsed accordion, then you can return the HttpStatusCode so that the actual error message is shown if you do F12. Also you can log this error to ELMAH error log. Below is the code

if (!ModelState.IsValid)
{
              var message = string.Join(" | ", ModelState.Values
                                            .SelectMany(v => v.Errors)
                                            .Select(e => e.ErrorMessage));

                //Log This exception to ELMAH:
                Exception exception = new Exception(message.ToString());
                Elmah.ErrorSignal.FromCurrentContext().Raise(exception);

                //Return Status Code:
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
}

But please note that this code will log all validation errors. So this should be used only when such situation arises where you cannot see the errors on screen.

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

The Microsoft way is this:

MSDN: How to determine Which .NET Framework Versions Are Installed (which directs you to the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\...)

If you want foolproof that's another thing. I wouldn't worry about an xcopy of the framework folder. If someone did that I would consider the computer broken.

The most foolproof way would be to write a small program that uses each version of .NET and the libraries that you care about and run them.

For a no install method, PowerBasic is an excellent tool. It creates small no runtime required exe's. It could automate the checks described in the MS KB article above.

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

Here is how I do it:

app.directive('example', function() {

    return function(scope, element, attrs) {
        angular.element(document).ready(function() {
                //MANIPULATE THE DOM
        });
    };

});

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

I'm looking at PostgreSQL full-text search right now, and it has all the right features of a modern search engine, really good extended character and multilingual support, nice tight integration with text fields in the database.

But it doesn't have user-friendly search operators like + or AND (uses & | !) and I'm not thrilled with how it works on their documentation site. While it has bolding of match terms in the results snippets, the default algorithm for which match terms is not great. Also, if you want to index rtf, PDF, MS Office, you have to find and integrate a file format converter.

OTOH, it's way better than the MySQL text search, which doesn't even index words of three letters or fewer. It's the default for the MediaWiki search, and I really think it's no good for end-users: http://www.searchtools.com/analysis/mediawiki-search/

In all cases I've seen, Lucene/Solr and Sphinx are really great. They're solid code and have evolved with significant improvements in usability, so the tools are all there to make search that satisfies almost everyone.

for SHAILI - SOLR includes the Lucene search code library and has the components to be a nice stand-alone search engine.

Swapping pointers in C (char, int)

The first thing you need to understand is that when you pass something to a function, that something is copied to the function's arguments.

Suppose you have the following:

void swap1(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
    assert(a == 17);
    assert(b == 42);
    // they're swapped!
}

int x = 42;
int y = 17;
swap1(x, y);
assert(x == 42);
assert(y == 17);
// no, they're not swapped!

The original variables will not be swapped, because their values are copied into the function's arguments. The function then proceeds to swap the values of those arguments, and then returns. The original values are not changed, because the function only swaps its own private copies.

Now how do we work around this? The function needs a way to refer to the original variables, not copies of their values. How can we refer to other variables in C? Using pointers.

If we pass pointers to our variables into the function, the function can swap the values in our variables, instead of its own argument copies.

void swap2(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
    assert(*a == 17);
    assert(*b == 42);
    // they're swapped!
}

int x = 42;
int y = 17;
swap2(&x, &y); // give the function pointers to our variables
assert(x == 17);
assert(y == 42);
// yes, they're swapped!

Notice how inside the function we're not assigning to the pointers, but assigning to what they point to. And the pointers point to our variables x and y. The function is changing directly the values stored in our variables through the pointers we give it. And that's exactly what we needed.

Now what happens if we have two pointer variables and want to swap the pointers themselves (as opposed to the values they point to)? If we pass pointers, the pointers will simply be copied (not the values they point to) to the arguments.

void swap3(int* a, int* b) {
    int* temp = a;
    a = b;
    b = temp;
    assert(*a == 17);
    assert(*b == 42);
    // they're swapped!
}
void swap4(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
    assert(*a == 17);
    assert(*b == 42);
    // they're swapped!
}

int x = 42;
int y = 17;
int* xp = &x;
int* yp = &y;
swap3(xp, yp);
assert(xp == &x);
assert(yp == &y);
assert(x == 42);
assert(y == 17);
// Didn't swap anything!
swap4(xp, yp);
assert(xp == &x);
assert(yp == &y);
assert(x == 17);
assert(y == 42);
// Swapped the stored values instead!

The function swap3 only swaps its own private copies of our pointers that it gets in its arguments. It's the same issue we had with swap1. And swap4 is changing the values our variables point to, not the pointers! We're giving the function a means to refer to the variables x and y but we want them to refer to xp and yp.

How do we do that? We pass it their addresses!

void swap5(int** a, int** b) {
    int* temp = *a;
    *a = *b;
    *b = temp;
    assert(**a == 17);
    assert(**b == 42);
    // they're swapped!
}


int x = 42;
int y = 17;
int* xp = &x;
int* yp = &y;
swap5(&xp, &yp);
assert(xp == &y);
assert(yp == &x);
assert(x == 42);
assert(y == 17);
// swapped only the pointers variables

This way it swaps our pointer variables (notice how xp now points to y) but not the values they point to. We gave it a way to refer to our pointer variables, so it can change them!

By now it should be easy to understand how to swap two strings in the form of char* variables. The swap function needs to receive pointers to char*.

void swapStrings(char** a, char** b){
    char *temp = *a;
    *a = *b;
    *b = temp;
    assert(strcmp(*a, "world") == 0);
    assert(strcmp(*b, "Hello") == 0);
}

char* x = "Hello";
char* y = "world";
swapStrings(&x, &y);
assert(strcmp(x, "world") == 0);
assert(strcmp(y, "Hello") == 0);

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

The mail server on CentOS 6 and other IPv6 capable server platforms may be bound to IPv6 localhost (::1) instead of IPv4 localhost (127.0.0.1).

Typical symptoms:

[root@host /]# telnet 127.0.0.1 25
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

[root@host /]# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 host ESMTP Exim 4.72 Wed, 14 Aug 2013 17:02:52 +0100

[root@host /]# netstat -plant | grep 25
tcp        0      0 :::25                       :::*                        LISTEN      1082/exim           

If this happens, make sure that you don't have two entries for localhost in /etc/hosts with different IP addresses, like this (bad) example:

[root@host /]# cat /etc/hosts
127.0.0.1 localhost.localdomain localhost localhost4.localdomain4 localhost4
::1       localhost localhost.localdomain localhost6 localhost6.localdomain6

To avoid confusion, make sure you only have one entry for localhost, preferably an IPv4 address, like this:

[root@host /]# cat /etc/hosts
127.0.0.1 localhost  localhost.localdomain   localhost4.localdomain4 localhost4
::1       localhost6 localhost6.localdomain6

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.