Programs & Examples On #Breezingforms

Android Studio error: "Environment variable does not point to a valid JVM installation"

Do step by step as shown in this YouTube Video

Go to: System -> Advanced system settings -> Environment Variables

Add a new variable to you profile NAME=JAVA_HOME STRING: Program Files/java/"your string" Save and Start Android Studio ;)

enter image description here

Where's the DateTime 'Z' format specifier?

I was dealing with DateTimeOffset and unfortunately the "o" prints out "+0000" not "Z".

So I ended up with:

dateTimeOffset.UtcDateTime.ToString("o")

Setting a log file name to include current date in Log4j

I don't know if it is possible in Java, but in .NET the property StaticLogFileName on RollingFileAppender gives you what you want. The default is true.

<staticLogFileName value="false"/>

Full config:

<appender name="DefaultFileAppender" type="log4net.Appender.RollingFileAppender">
  <file value="application"/>
  <staticLogFileName value="false"/>
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <datePattern value="yyyy-MM-dd&quot;.log&quot;" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  </layout>
</appender>

&quot;.log&quot; is for not letting the dateformat recognice the global date pattern 'g' in log.

What is the fastest factorial function in JavaScript?

Old question but i find this approach quite readable and straightforward

function factorialize(num) {
  var arr = [];
  var result;
  if ( num === 0 || num === 1 ) {
    return 1;
  } else {
    for (var i = num; i > 0; i--) {
      arr.push(i);
      result = arr.reduce(function(previousVal, nextVal){
                return previousVal * nextVal;
              });
    }
    return result;
  }
}

Getting a list of associative array keys

Try this:

var keys = [];
for (var key in dictionary) {
  if (dictionary.hasOwnProperty(key)) {
    keys.push(key);
  }
}

hasOwnProperty is needed because it's possible to insert keys into the prototype object of dictionary. But you typically don't want those keys included in your list.

For example, if you do this:

Object.prototype.c = 3;
var dictionary = {a: 1, b: 2};

and then do a for...in loop over dictionary, you'll get a and b, but you'll also get c.

Check if the number is integer

[UPDATE] ==============================================================

Respect to the [OLD] answer here below, I have discovered that it worked because I have put all the numbers in a single atomic vector; one of them was a character, so every one become characters.

If we use a list (hence, coercion does not happen) all the test pass correctly but one: 1/(1 - 0.98), which remains a numeric. This because the tol parameter is by default 100 * .Machine$double.eps and that number is far from 50 little less than the double of that. So, basically, for this kind of numbers, we have to decide our tolerance!

So if you want all test became TRUE, you can assertive::is_whole_number(x, tol = 200 * .Machine$double.eps)

Anyway, I confirm that IMO assertive remains the best solution.

Here below a reprex for this [UPDATE].

expect_trues_c <- c(
  cl = sqrt(2)^2,
  pp = 9.0,
  t = 1 / (1 - 0.98),
  ar0 = 66L,
  ar1 = 66,
  ar2 = 1 + 2^-50,
  v = 222e3,
  w1 = 1e4,
  w2 = 1e5,
  v2 = "1000000000000000000000000000000000001",
  an = 2 / 49 * 49,
  ju1 = 1e22,
  ju2 = 1e24,
  al = floor(1),
  v5 = 1.0000000000000001 # this is under machine precision!
)

str(expect_trues_c)
#>  Named chr [1:15] "2" "9" "50" "66" "66" "1" "222000" "10000" "1e+05" ...
#>  - attr(*, "names")= chr [1:15] "cl" "pp" "t" "ar0" ...
assertive::is_whole_number(expect_trues_c)
#> Warning: Coercing expect_trues_c to class 'numeric'.
#>                      2                      9                     50 
#>                   TRUE                   TRUE                   TRUE 
#>                     66                     66                      1 
#>                   TRUE                   TRUE                   TRUE 
#>                 222000                  10000                 100000 
#>                   TRUE                   TRUE                   TRUE 
#>                  1e+36                      2                  1e+22 
#>                   TRUE                   TRUE                   TRUE 
#> 9.9999999999999998e+23                      1                      1 
#>                   TRUE                   TRUE                   TRUE



expect_trues_l <- list(
  cl = sqrt(2)^2,
  pp = 9.0,
  t = 1 / (1 - 0.98),
  ar0 = 66L,
  ar1 = 66,
  ar2 = 1 + 2^-50,
  v = 222e3,
  w1 = 1e4,
  w2 = 1e5,
  v2 = "1000000000000000000000000000000000001",
  an = 2 / 49 * 49,
  ju1 = 1e22,
  ju2 = 1e24,
  al = floor(1),
  v5 = 1.0000000000000001 # this is under machine precision!
)

str(expect_trues_l)
#> List of 15
#>  $ cl : num 2
#>  $ pp : num 9
#>  $ t  : num 50
#>  $ ar0: int 66
#>  $ ar1: num 66
#>  $ ar2: num 1
#>  $ v  : num 222000
#>  $ w1 : num 10000
#>  $ w2 : num 1e+05
#>  $ v2 : chr "1000000000000000000000000000000000001"
#>  $ an : num 2
#>  $ ju1: num 1e+22
#>  $ ju2: num 1e+24
#>  $ al : num 1
#>  $ v5 : num 1
assertive::is_whole_number(expect_trues_l)
#> Warning: Coercing expect_trues_l to class 'numeric'.
#> There was 1 failure:
#>   Position              Value      Cause
#> 1        3 49.999999999999957 fractional
assertive::is_whole_number(expect_trues_l, tol = 200 * .Machine$double.eps)
#> Warning: Coercing expect_trues_l to class 'numeric'.
#>     2.0000000000000004                      9     49.999999999999957 
#>                   TRUE                   TRUE                   TRUE 
#>                     66                     66     1.0000000000000009 
#>                   TRUE                   TRUE                   TRUE 
#>                 222000                  10000                 100000 
#>                   TRUE                   TRUE                   TRUE 
#>                  1e+36     1.9999999999999998                  1e+22 
#>                   TRUE                   TRUE                   TRUE 
#> 9.9999999999999998e+23                      1                      1 
#>                   TRUE                   TRUE                   TRUE



expect_falses <- list(
  bb = 5 - 1e-8,
  pt1 = 1.0000001,
  pt2 = 1.00000001,
  v3 = 3243.34,
  v4 = "sdfds"
)

str(expect_falses)
#> List of 5
#>  $ bb : num 5
#>  $ pt1: num 1
#>  $ pt2: num 1
#>  $ v3 : num 3243
#>  $ v4 : chr "sdfds"
assertive::is_whole_number(expect_falses)
#> Warning: Coercing expect_falses to class 'numeric'.
#> Warning in as.this_class(x): NAs introduced by coercion
#> There were 5 failures:
#>   Position              Value      Cause
#> 1        1 4.9999999900000001 fractional
#> 2        2 1.0000001000000001 fractional
#> 3        3 1.0000000099999999 fractional
#> 4        4 3243.3400000000001 fractional
#> 5        5               <NA>    missing
assertive::is_whole_number(expect_falses, tol = 200 * .Machine$double.eps)
#> Warning: Coercing expect_falses to class 'numeric'.

#> Warning: NAs introduced by coercion
#> There were 5 failures:
#>   Position              Value      Cause
#> 1        1 4.9999999900000001 fractional
#> 2        2 1.0000001000000001 fractional
#> 3        3 1.0000000099999999 fractional
#> 4        4 3243.3400000000001 fractional
#> 5        5               <NA>    missing

Created on 2019-07-23 by the reprex package (v0.3.0)

[OLD] =================================================================

IMO the best solution comes from the assertive package (which, for the moment, solve all positive and negative examples in this thread):

are_all_whole_numbers <- function(x) {
  all(assertive::is_whole_number(x), na.rm = TRUE)
}

are_all_whole_numbers(c(
  cl = sqrt(2)^2,
  pp = 9.0,
  t = 1 / (1 - 0.98),
  ar0 = 66L,
  ar1 = 66,
  ar2 = 1 + 2^-50,
  v = 222e3,
  w1 = 1e4,
  w2 = 1e5,
  v2 = "1000000000000000000000000000000000001",
  an = 2 / 49 * 49,
  ju1 = 1e22,
  ju2 = 1e24,
  al = floor(1),
  v5 = 1.0000000000000001 # difference is under machine precision!
))
#> Warning: Coercing x to class 'numeric'.
#> [1] TRUE

are_all_not_whole_numbers <- function(x) {
  all(!assertive::is_whole_number(x), na.rm = TRUE)
}

are_all_not_whole_numbers(c(
  bb = 5 - 1e-8,
  pt1 = 1.0000001,
  pt2 = 1.00000001,
  v3 = 3243.34,
  v4 = "sdfds"
))
#> Warning: Coercing x to class 'numeric'.
#> Warning in as.this_class(x): NAs introduced by coercion
#> [1] TRUE

Created on 2019-07-23 by the reprex package (v0.3.0)

How to Remove Line Break in String

just this:

str = Replace(str, vbCrLf, "")

Refreshing Web Page By WebDriver When Waiting For Specific Condition

In R you can use the refresh method, but to start with we navigate to a url using navigate method:

remDr$navigate("https://...")
remDr$refresh()

Add a month to a Date

addedMonth <- seq(as.Date('2004-01-01'), length=2, by='1 month')[2]
addedQuarter <- seq(as.Date('2004-01-01'), length=2, by='1 quarter')[2]

How do I do an insert with DATETIME now inside of SQL server mgmt studioÜ

Just use GETDATE() or GETUTCDATE() (if you want to get the "universal" UTC time, instead of your local server's time-zone related time).

INSERT INTO [Business]
           ([IsDeleted]
           ,[FirstName]
           ,[LastName]
           ,[LastUpdated]
           ,[LastUpdatedBy])
     VALUES
           (0, 'Joe', 'Thomas', 
           GETDATE(),  <LastUpdatedBy, nvarchar(50),>)

How do I check if a given Python string is a substring of another one?

string.find("substring") will help you. This function returns -1 when there is no substring.

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

This is the general structure of an html document.

<html>
    <head>
        Title, meta-data, scripts, etc go here... Don't confuse with header
    </head>
    <body>
        You body stuff comes here...
        <footer>
            Your footer stuff goes here...
        </footer>
    </body>
</html>

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

async at console app in C#?

As a quick and very scoped solution:

Task.Result

Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.

When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.

notasync

How to fix a collation conflict in a SQL Server query?

Adding to the accepted answer, you can used DATABASE_DEFAULT as encoding.

This allows database to make choice for you and your code becomes more portable.

SELECT MyColumn
FROM 
    FirstTable a
        INNER JOIN SecondTable b
            ON a.MyID COLLATE DATABASE_DEFAULT = b.YourID COLLATE DATABASE_DEFAULT

Uncaught ReferenceError: jQuery is not defined

you need to put it after wp_head(); Because that loads your jQuery and you need to load jQuery first and then your js

Changing the size of a column referenced by a schema-bound view in SQL Server

The views are probably created using the WITH SCHEMABINDING option and this means they are explicitly wired up to prevent such changes. Looks like the schemabinding worked and prevented you from breaking those views, lucky day, heh? Contact your database administrator and ask him to do the change, after it asserts the impact on the database.

From MSDN:

SCHEMABINDING

Binds the view to the schema of the underlying table or tables. When SCHEMABINDING is specified, the base table or tables cannot be modified in a way that would affect the view definition. The view definition itself must first be modified or dropped to remove dependencies on the table that is to be modified.

Eclipse interface icons very small on high resolution screen in Windows 8.1

Had same problem, to resolve it, create a shortcut of the launcher, right click > properties > compatibility > tick on 'Override high DPI scaling behaviour' and select System Enhanced from the dropdown as shown on pic below. Relaunch eclipse after changes.

enter image description here

Auto-increment primary key in SQL tables

Although the following is not way to do it in GUI but you can get autoincrementing simply using the IDENTITY datatype(start, increment):

CREATE TABLE "dbo"."TableName"
(
   id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
   name varchar(20),
);

the insert statement should list all columns except the id column (it will be filled with autoincremented value):

INSERT INTO "dbo"."TableName" (name) VALUES ('alpha');
INSERT INTO "dbo"."TableName" (name) VALUES ('beta');

and the result of

SELECT id, name FROM "dbo"."TableName";

will be

id    name
--------------------------
1     alpha
2     beta

How to delete a whole folder and content?

If you dont need to delete things recursively you can try something like this:

File file = new File(context.getExternalFilesDir(null), "");
    if (file != null && file.isDirectory()) {
        File[] files = file.listFiles();
        if(files != null) {
            for(File f : files) {   
                f.delete();
            }
        }
    }

Use tab to indent in textarea

var textareas = document.getElementsByTagName('textarea');
var count = textareas.length;
for(var i=0;i<count;i++){
    textareas[i].onkeydown = function(e){
        if(e.keyCode==9 || e.which==9){
            e.preventDefault();
            var s = this.selectionStart;
            this.value = this.value.substring(0,this.selectionStart) + "\t" + this.value.substring(this.selectionEnd);
            this.selectionEnd = s+1; 
        }
    }
}

This solution does not require jQuery and will enable tab functionality on all textareas on a page.

Modifying Objects within stream in Java8 while iterating

Instead of creating strange things, you can just filter() and then map() your result.

This is much more readable and sure. Streams will make it in only one loop.

How to pass a user / password in ansible command

I used the command

ansible -i inventory example -m ping -u <your_user_name> --ask-pass

And it will ask for your password.

For anyone who gets the error:

to use the 'ssh' connection type with passwords, you must install the sshpass program

On MacOS, you can follow below instructions to install sshpass:

  1. Download the Source Code
  2. Extract it and cd into the directory
  3. ./configure
  4. sudo make install

Random "Element is no longer attached to the DOM" StaleElementReferenceException

I was facing the same problem today and made up a wrapper class, which checks before every method if the element reference is still valid. My solution to retrive the element is pretty simple so i thought i'd just share it.

private void setElementLocator()
{
    this.locatorVariable = "selenium_" + DateTimeMethods.GetTime().ToString();
    ((IJavaScriptExecutor)this.driver).ExecuteScript(locatorVariable + " = arguments[0];", this.element);
}

private void RetrieveElement()
{
    this.element = (IWebElement)((IJavaScriptExecutor)this.driver).ExecuteScript("return " + locatorVariable);
}

You see i "locate" or rather save the element in a global js variable and retrieve the element if needed. If the page gets reloaded this reference will not work anymore. But as long as only changes are made to doom the reference stays. And that should do the job in most cases.

Also it avoids re-searching the element.

John

Cannot change column used in a foreign key constraint

When you set keys (primary or foreign) you are setting constraints on how they can be used, which in turn limits what you can do with them. If you really want to alter the column, you could re-create the table without the constraints, although I'd recommend against it. Generally speaking, if you have a situation in which you want to do something, but it is blocked by a constraint, it's best resolved by changing what you want to do rather than the constraint.

the MySQL service on local computer started and then stopped

This error happened in my case when secure-file-priv was pointing to unexistent folder, make sure it exists and readable.

The line of code example in my.ini: secure-file-priv="D:/MySQL/uploads"

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle

Everyone: I Solved the problem like this. In Android Studio go to File menu and select the Invalidate Caches/Restart... I hope it will work for you. Thanks

How to select ALL children (in any level) from a parent in jQuery?

It seems that the original test case is wrong.

I can confirm that the selector #my_parent_element * works with unbind().

Let's take the following html as an example:

<div id="#my_parent_element">
  <div class="div1">
    <div class="div2">hello</div>
    <div class="div3">my</div>
  </div>
  <div class="div4">name</div>
  <div class="div5">
    <div class="div6">is</div>
    <div class="div7">
      <div class="div8">marco</div>
      <div class="div9">(try and click on any word)!</div>
    </div>
  </div>
</div>
<button class="unbind">Now, click me and try again</button>

And the jquery bit:

$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
  alert('hi!');
})
$('button.unbind').click(function() {
  $('#my_parent_element *').unbind('click');
})

You can try it here: http://jsfiddle.net/fLvwbazk/7/

How to backup Sql Database Programmatically in C#

            SqlConnection con = new SqlConnection();
            SqlCommand sqlcmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            DataTable dt = new DataTable();

            con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
            string backupDIR = "~/BackupDB";
            string path = Server.MapPath(backupDIR);

            try
            {
                var databaseName = "MyFirstDatabase";
                con.Open();
                string saveFileName = "HiteshBackup";
                sqlcmd = new SqlCommand("backup database" +databaseName.BKSDatabaseName + "to disk='" + path + "\\" + saveFileName + ".Bak'", con);
                sqlcmd.ExecuteNonQuery();
                con.Close();                 


                ViewBag.Success = "Backup database successfully";
                return View("Create");
            }
            catch (Exception ex)
            {
                ViewBag.Error = "Error Occured During DB backup process !<br>" + ex.ToString();
                return View("Create");
            }

Partition Function COUNT() OVER possible using DISTINCT

I think the only way of doing this in SQL-Server 2008R2 is to use a correlated subquery, or an outer apply:

SELECT  datekey,
        COALESCE(RunningTotal, 0) AS RunningTotal,
        COALESCE(RunningCount, 0) AS RunningCount,
        COALESCE(RunningDistinctCount, 0) AS RunningDistinctCount
FROM    document
        OUTER APPLY
        (   SELECT  SUM(Amount) AS RunningTotal,
                    COUNT(1) AS RunningCount,
                    COUNT(DISTINCT d2.dateKey) AS RunningDistinctCount
            FROM    Document d2
            WHERE   d2.DateKey <= document.DateKey
        ) rt;

This can be done in SQL-Server 2012 using the syntax you have suggested:

SELECT  datekey,
        SUM(Amount) OVER(ORDER BY DateKey) AS RunningTotal
FROM    document

However, use of DISTINCT is still not allowed, so if DISTINCT is required and/or if upgrading isn't an option then I think OUTER APPLY is your best option

What does void* mean and how to use it?

it means pointer you can use this link to get more info about pointer http://www.cprogramming.com/tutorial/c/lesson6.html

How do I get a list of all the duplicate items using pandas in python?

For my database duplicated(keep=False) did not work until the column was sorted.

data.sort_values(by=['Order ID'], inplace=True)
df = data[data['Order ID'].duplicated(keep=False)]

Finding all the subsets of a set

here is my recursive solution.

vector<vector<int> > getSubsets(vector<int> a){


//base case
    //if there is just one item then its subsets are that item and empty item
    //for example all subsets of {1} are {1}, {}

    if(a.size() == 1){
        vector<vector<int> > temp;
        temp.push_back(a);

        vector<int> b;
        temp.push_back(b);

        return temp;

    }
    else
    {


         //here is what i am doing

         // getSubsets({1, 2, 3})
         //without = getSubsets({1, 2})
         //without = {1}, {2}, {}, {1, 2}

         //with = {1, 3}, {2, 3}, {3}, {1, 2, 3}

         //total = {{1}, {2}, {}, {1, 2}, {1, 3}, {2, 3}, {3}, {1, 2, 3}}

         //return total

        int last = a[a.size() - 1];

        a.pop_back();

        vector<vector<int> > without = getSubsets(a);

        vector<vector<int> > with = without;

        for(int i=0;i<without.size();i++){

            with[i].push_back(last);

        }

        vector<vector<int> > total;

        for(int j=0;j<without.size();j++){
            total.push_back(without[j]);
        }

        for(int k=0;k<with.size();k++){
            total.push_back(with[k]);
        }


        return total;
    }


}

How to redirect the output of print to a TXT file

A slightly hackier way (that is different than the answers above, which are all valid) would be to just direct the output into a file via console.

So imagine you had main.py

if True:
    print "hello world"
else:
    print "goodbye world"

You can do

python main.py >> text.log

and then text.log will get all of the output.

This is handy if you already have a bunch of print statements and don't want to individually change them to print to a specific file. Just do it at the upper level and direct all prints to a file (only drawback is that you can only print to a single destination).

Image size (Python, OpenCV)

Here is a method that returns the image dimensions:

from PIL import Image
import os

def get_image_dimensions(imagefile):
    """
    Helper function that returns the image dimentions

    :param: imagefile str (path to image)
    :return dict (of the form: {width:<int>, height=<int>, size_bytes=<size_bytes>)
    """
    # Inline import for PIL because it is not a common library
    with Image.open(imagefile) as img:
        # Calculate the width and hight of an image
        width, height = img.size

    # calculat ethe size in bytes
    size_bytes = os.path.getsize(imagefile)

    return dict(width=width, height=height, size_bytes=size_bytes)

Can I use jQuery to check whether at least one checkbox is checked?

if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }

Error inflating class android.support.v7.widget.Toolbar?

For me, the error was that I had:

    <android:support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"/>

instead of:

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"/>

Specifically, I had a colon between "android" and "support" on the first line instead of a period.

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

How can I perform a short delay in C# without using sleep?

You can probably use timers : http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

Timers can provide you a precision up to 1 millisecond. Depending on the tick interval an event will be generated. Do your stuff inside the tick event.

CardView not showing Shadow in Android L

You can add this line of code for shadow in card view

card_view:cardElevation="3dp"

Below you have an example

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="@android:color/white"
    android:foreground="?android:attr/selectableItemBackground"
    card_view:cardElevation="3dp"
    card_view:cardCornerRadius="4dp">

Hope this helps!

Read file line by line using ifstream in C++

Expanding on the accepted answer, if the input is:

1,NYC
2,ABQ
...

you will still be able to apply the same logic, like this:

#include <fstream>

std::ifstream infile("thefile.txt");
if (infile.is_open()) {
    int number;
    std::string str;
    char c;
    while (infile >> number >> c >> str && c == ',')
        std::cout << number << " " << str << "\n";
}
infile.close();

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Try to use the latest com.fasterxml.jackson.core/jackson-databind. I upgraded it to 2.9.4 and it works now.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.4</version>
</dependency>

SFTP in Python? (platform independent)

Paramiko supports SFTP. I've used it, and I've used Twisted. Both have their place, but you might find it easier to start with Paramiko.

How to use sed to extract substring

You should not parse XML using tools like sed, or awk. It's error-prone.

If input changes, and before name parameter you will get new-line character instead of space it will fail some day producing unexpected results.

If you are really sure, that your input will be always formated this way, you can use cut. It's faster than sed and awk:

cut -d'"' -f2 < input.txt

It will be better to first parse it, and extract only parameter name attribute:

xpath -q -e //@name input.txt | cut -d'"' -f2

To learn more about xpath, see this tutorial: http://www.w3schools.com/xpath/

php REQUEST_URI

You can simply use $_GET especially if you know the othervar's name. If you want to be on the safe side, use if (isset ($_GET ['varname'])) to test for existence.

Iterate over the lines of a string

If I read Modules/cStringIO.c correctly, this should be quite efficient (although somewhat verbose):

from cStringIO import StringIO

def iterbuf(buf):
    stri = StringIO(buf)
    while True:
        nl = stri.readline()
        if nl != '':
            yield nl.strip()
        else:
            raise StopIteration

IIS Manager in Windows 10

Press the Windows Key and type Windows Features, select the first entry Turn Windows Features On or Off.

Make sure the box next to IIS is checked. You good to go.

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

Creating .pem file for APNS?

There is a easiest way to create .Pem file if you have already apns p12 file in your key chain access.

Open terminal and enter the below command:

For Devlopment openssl pkcs12 -in apns-div-cert.p12 -out apns-div-cert.pem -nodes -clcerts

For Production openssl pkcs12 -in apns-dist-cert.p12 -out apns-dist-cert.pem -nodes -clcerts

Rename your P12 file with this name : apns-div-cert.p12 otherwise instead of this you need to enter your filename. Thanks!!

Pandas Split Dataframe into two Dataframes at a specific row

use np.split(..., axis=1):

Demo:

In [255]: df = pd.DataFrame(np.random.rand(5, 6), columns=list('abcdef'))

In [256]: df
Out[256]:
          a         b         c         d         e         f
0  0.823638  0.767999  0.460358  0.034578  0.592420  0.776803
1  0.344320  0.754412  0.274944  0.545039  0.031752  0.784564
2  0.238826  0.610893  0.861127  0.189441  0.294646  0.557034
3  0.478562  0.571750  0.116209  0.534039  0.869545  0.855520
4  0.130601  0.678583  0.157052  0.899672  0.093976  0.268974

In [257]: dfs = np.split(df, [4], axis=1)

In [258]: dfs[0]
Out[258]:
          a         b         c         d
0  0.823638  0.767999  0.460358  0.034578
1  0.344320  0.754412  0.274944  0.545039
2  0.238826  0.610893  0.861127  0.189441
3  0.478562  0.571750  0.116209  0.534039
4  0.130601  0.678583  0.157052  0.899672

In [259]: dfs[1]
Out[259]:
          e         f
0  0.592420  0.776803
1  0.031752  0.784564
2  0.294646  0.557034
3  0.869545  0.855520
4  0.093976  0.268974

np.split() is pretty flexible - let's split an original DF into 3 DFs at columns with indexes [2,3]:

In [260]: dfs = np.split(df, [2,3], axis=1)

In [261]: dfs[0]
Out[261]:
          a         b
0  0.823638  0.767999
1  0.344320  0.754412
2  0.238826  0.610893
3  0.478562  0.571750
4  0.130601  0.678583

In [262]: dfs[1]
Out[262]:
          c
0  0.460358
1  0.274944
2  0.861127
3  0.116209
4  0.157052

In [263]: dfs[2]
Out[263]:
          d         e         f
0  0.034578  0.592420  0.776803
1  0.545039  0.031752  0.784564
2  0.189441  0.294646  0.557034
3  0.534039  0.869545  0.855520
4  0.899672  0.093976  0.268974

What are the advantages and disadvantages of recursion?

For the most part recursion is slower, and takes up more of the stack as well. The main advantage of recursion is that for problems like tree traversal it make the algorithm a little easier or more "elegant". Check out some of the comparisons:

link

How can I set the default value for an HTML <select> element?

if you want to use the values from a Form and keep it dynamic try this with php

<form action="../<SamePage>/" method="post">


<?php
    $selected = $_POST['select'];
?>

<select name="select" size="1">

  <option <?php if($selected == '1'){echo("selected");}?>>1</option>
  <option <?php if($selected == '2'){echo("selected");}?>>2</option>

</select>
</form>

Facebook development in localhost

There is ! My solution works when you create an app, but you want to use facebook authentification on your website. This solution below is NOT needed when you want to create an app integrated to FB page.

The thing is that you can't put "localhost" as a domain in the facebook configuration page of your app. Security reasons ?

You need to go to your host file, in OSX / Linux etc/hosts and add the following line : 127.0.0.1 dev.yourdomain.com

The domain you put whatever you want. One mistake is to add this line : localhost dev.yourdomain.com (at least on osx snow leopard in doesnt work).

Then you have to clear your dns cache. On OSX : type dscacheutil -flushcache in the terminal. Finally, go back to the online facebook developer website, and in the configuration page of your app, you can add the domain "dev.yourdomain.com".

If you use a program such as Mamp, Easyphp or whatever, make sure the port for Apache is 80.

This solution should work for Windows because it also has a hosts file. Nevertheless, as far as I remember Windows 7 doesnt use this file anymore, but this trick should work if you find a way to force windows to use a hosts file.

How, in general, does Node.js handle 10,000 concurrent requests?

What you seem to be thinking is that most of the processing is handled in the node event loop. Node actually farms off the I/O work to threads. I/O operations typically take orders of magnitude longer than CPU operations so why have the CPU wait for that? Besides, the OS can handle I/O tasks very well already. In fact, because Node does not wait around it achieves much higher CPU utilisation.

By way of analogy, think of NodeJS as a waiter taking the customer orders while the I/O chefs prepare them in the kitchen. Other systems have multiple chefs, who take a customers order, prepare the meal, clear the table and only then attend to the next customer.

How to retrieve the LoaderException property?

Another Alternative for those who are probing around and/or in interactive mode:

$Error[0].Exception.LoaderExceptions

Note: [0] grabs the most recent Error from the stack

How to hide close button in WPF window?

I just add my implementation of Joe White's answer using Interactivity Behavior (you need to reference System.Windows.Interactivity).

code:

public class HideCloseButtonOnWindow : Behavior<Window>
{
    #region bunch of native methods

    private const int GWL_STYLE = -16;
    private const int WS_SYSMENU = 0x80000;

    [DllImport("user32.dll", SetLastError = true)]
    private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

    [DllImport("user32.dll")]
    private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

    #endregion

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Loaded += OnLoaded;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Loaded -= OnLoaded;
        base.OnDetaching();
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        var hwnd = new WindowInteropHelper(AssociatedObject).Handle;
        SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
    }
}

usage:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:w="clr-namespace:WpfApplication2">

    <i:Interaction.Behaviors>
        <w:HideCloseButtonOnWindow />
    </i:Interaction.Behaviors>

</Window>

How to overlay one div over another div

This is what you need:

_x000D_
_x000D_
function showFrontLayer() {_x000D_
  document.getElementById('bg_mask').style.visibility='visible';_x000D_
  document.getElementById('frontlayer').style.visibility='visible';_x000D_
}_x000D_
function hideFrontLayer() {_x000D_
  document.getElementById('bg_mask').style.visibility='hidden';_x000D_
  document.getElementById('frontlayer').style.visibility='hidden';_x000D_
}
_x000D_
#bg_mask {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;  bottom: 0;_x000D_
  left: 0;_x000D_
  margin: auto;_x000D_
  margin-top: 0px;_x000D_
  width: 981px;_x000D_
  height: 610px;_x000D_
  background : url("img_dot_white.jpg") center;_x000D_
  z-index: 0;_x000D_
  visibility: hidden;_x000D_
} _x000D_
_x000D_
#frontlayer {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  margin: 70px 140px 175px 140px;_x000D_
  padding : 30px;_x000D_
  width: 700px;_x000D_
  height: 400px;_x000D_
  background-color: orange;_x000D_
  visibility: hidden;_x000D_
  border: 1px solid black;_x000D_
  z-index: 1;_x000D_
} _x000D_
_x000D_
_x000D_
</style>
_x000D_
<html>_x000D_
  <head>_x000D_
    <META HTTP-EQUIV="EXPIRES" CONTENT="-1" />_x000D_
_x000D_
  </head>_x000D_
  <body>_x000D_
    <form action="test.html">_x000D_
      <div id="baselayer">_x000D_
_x000D_
        <input type="text" value="testing text"/>_x000D_
        <input type="button" value="Show front layer" onclick="showFrontLayer();"/> Click 'Show front layer' button<br/><br/><br/>_x000D_
_x000D_
        Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text_x000D_
        Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text_x000D_
        Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing textsting text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text_x000D_
        <div id="bg_mask">_x000D_
          <div id="frontlayer"><br/><br/>_x000D_
            Now try to click on "Show front layer" button or the text box. It is not active.<br/><br/><br/>_x000D_
            Use position: absolute to get the one div on top of another div.<br/><br/><br/>_x000D_
            The bg_mask div is between baselayer and front layer.<br/><br/><br/>_x000D_
            In bg_mask, img_dot_white.jpg(1 pixel in width and height) is used as background image to avoid IE browser transparency issue;<br/><br/><br/>_x000D_
            <input type="button" value="Hide front layer" onclick="hideFrontLayer();"/>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </form>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Run Java Code Online

rextester runs java snippets

Also accessible as runjavaonline.com

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Convert an integer to a float number

Type Conversions T() where T is the desired datatype of the result are quite simple in GoLang.

In my program, I scan an integer i from the user input, perform a type conversion on it and store it in the variable f. The output prints the float64 equivalent of the int input. float32 datatype is also available in GoLang

Code:

package main
import "fmt"
func main() {
    var i int
    fmt.Println("Enter an Integer input: ")
    fmt.Scanf("%d", &i)
    f := float64(i)
    fmt.Printf("The float64 representation of %d is %f\n", i, f)
}

Solution:

>>> Enter an Integer input:
>>> 232332
>>> The float64 representation of 232332 is 232332.000000

How can I make a CSS table fit the screen width?

Set font-size in viewport-width-related units, e.g.:

table { font-size: 0.9vw; }

This will make font unreadable when page is too narrow, but sometimes this is acceptable.

How to fix Error: this class is not key value coding-compliant for the key tableView.'

You have your storyboard set up to expect an outlet called tableView but the actual outlet name is myTableView.

If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.

How to remove time portion of date in C# in DateTime object only?

Use date.ToShortDateString() to get the date without the time component

var date = DateTime.Now
var shortDate = date.ToShortDateString() //will give you 16/01/2019

use date.ToString() to customize the format of the date

var date = DateTime.Now
var shortDate = date.ToString('dd-MMM-yyyy') //will give you 16-Jan-2019

Install IPA with iTunes 12

For iTunes 12.7.0 and above, you just need to Cmd+c your app and Cmd+v into your device on iTunes. Any tab works, including Summary, Music, Movies.

typescript - cloning object

function instantiateEmptyObject(obj: object): object {
    if (obj == null) { return {}; }

    const prototype = Object.getPrototypeOf(obj);
    if (!prototype) {
        return {};
    }

    return Object.create(prototype);
}

function quickCopy(src: object, dest: object): object {
    if (dest == null) { return dest; }

    return { ...src, ...dest };
}

quickCopy(src, instantiateEmptyObject(new Customer()));

Marker in leaflet, click event

I found the solution:

function onClick(e) {alert(this.getLatLng());}

used the method getLatLng() of the marker

How to get the current time in milliseconds in C Programming

There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().

Stop setInterval call in JavaScript

Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).

// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);

// Add task(s) based on tick intervals.
timer.add({
    id: 'job1',         // unique id of the task
    tickInterval: 5,    // run every 5 ticks (5 x interval = 5000 ms)
    totalRuns: 10,      // run 10 times only. (omit for unlimited times)
    callback(task) {
        // code to be executed on each run
        console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
        // stop the timer anytime you like
        if (someCondition()) timer.stop();
        // or simply remove this task if you have others
        if (someCondition()) timer.remove(task.id);
    }
});

// Start the timer
timer.start();

In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.

See more here.

Writing file to web server - ASP.NET

Keep in mind you'll also have to give the IUSR account write access for the folder once you upload to your web server.

Personally I recommend not allowing write access to the root folder unless you have a good reason for doing so. And then you need to be careful what sort of files you allow to be saved so you don't inadvertently allow someone to write their own ASPX pages.

In which conda environment is Jupyter executing?

Adding to the above answers, you can also use

!which python

Type this in a cell and this will show the path of the environment. I'm not sure of the reason, but in my installation, there is no segregation of environments in the notebook, but on activating the environment and launching jupyter notebook, the path used is the python installed in the environment.

Set NOW() as Default Value for datetime datatype?

`ALTER TABLE  `table_name` CHANGE `column_name` 
    timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP

Can be used to update the timestamp on update.

How do I set up curl to permanently use a proxy?

You can make a alias in your ~/.bashrc file :

alias curl="curl -x <proxy_host>:<proxy_port>"

Another solution is to use (maybe the better solution) the ~/.curlrc file (create it if it does not exist) :

proxy = <proxy_host>:<proxy_port>

How do I configure Notepad++ to use spaces instead of tabs?

In my Notepad++ 7.2.2, the Preferences section it's a bit different.

The option is located at: Settings / Preferences / Language / Replace by space as in the Screenshot.

Screenshot of the windows with preferences

Stopping Docker containers by image name - Ubuntu

Two ways to stop running a container:

1. $docker stop container_ID

2. $docker kill container_ID

You can get running containers using the following command:

$docker ps

Following links for more information:

PHP array() to javascript array()

When we convert PHP array into JS array then we get all values in string. For example:

var ars= '<?php echo json_encode($abc); ?>';

The issue in above method is when we try to get the first element of ars[0] then it gives us bracket where as in we need first element as compare to bracket so the better way to this is

var packing_slip_orders = JSON.parse('<?php echo json_encode($packing_slip_orders); ?>');

You should use json_parse after json_encode to get the accurate array result.

Share cookie between subdomain and domain

Simple solution

setcookie("NAME", "VALUE", time()+3600, '/', EXAMPLE.COM);

Setcookie's 5th parameter determines the (sub)domains that the cookie is available to. Setting it to (EXAMPLE.COM) makes it available to any subdomain (eg: SUBDOMAIN.EXAMPLE.COM )

Reference: http://php.net/manual/en/function.setcookie.php

How to split string using delimiter char using T-SQL?

For your specific data, you can use

Select col1, col2, LTRIM(RTRIM(SUBSTRING(
    STUFF(col3, CHARINDEX('|', col3,
    PATINDEX('%|Client Name =%', col3) + 14), 1000, ''),
    PATINDEX('%|Client Name =%', col3) + 14, 1000))) col3
from Table01

EDIT - charindex vs patindex

Test

select col3='Clent ID = 4356hy|Client Name = B B BOB|Client Phone = 667-444-2626|Client Fax = 666-666-0151|Info = INF8888877 -MAC333330554/444400800'
into t1m
from master..spt_values a
cross join master..spt_values b
where a.number < 100
-- (711704 row(s) affected)

set statistics time on

dbcc dropcleanbuffers
dbcc freeproccache
select a=CHARINDEX('|Client Name =', col3) into #tmp1 from t1m
drop table #tmp1

dbcc dropcleanbuffers
dbcc freeproccache
select a=PATINDEX('%|Client Name =%', col3) into #tmp2 from t1m
drop table #tmp2

set statistics time off

Timings

CHARINDEX:

 SQL Server Execution Times (1):
   CPU time = 5656 ms,  elapsed time = 6418 ms.
 SQL Server Execution Times (2):
   CPU time = 5813 ms,  elapsed time = 6114 ms.
 SQL Server Execution Times (3):
   CPU time = 5672 ms,  elapsed time = 6108 ms.

PATINDEX:

 SQL Server Execution Times (1):
   CPU time = 5906 ms,  elapsed time = 6296 ms.
 SQL Server Execution Times (2):
   CPU time = 5860 ms,  elapsed time = 6404 ms.
 SQL Server Execution Times (3):
   CPU time = 6109 ms,  elapsed time = 6301 ms.

Conclusion

The timings for CharIndex and PatIndex for 700k calls are within 3.5% of each other, so I don't think it would matter whichever is used. I use them interchangeably when both can work.

Delete all local git branches

The 'git branch -d' subcommand can delete more than one branch. So, simplifying @sblom's answer but adding a critical xargs:

git branch -D `git branch --merged | grep -v \* | xargs`

or, further simplified to:

git branch --merged | grep -v \* | xargs git branch -D 

Importantly, as noted by @AndrewC, using git branch for scripting is discouraged. To avoid it use something like:

git for-each-ref --format '%(refname:short)' refs/heads | grep -v master | xargs git branch -D

Caution warranted on deletes!

$ mkdir br
$ cd br; git init
Initialized empty Git repository in /Users/ebg/test/br/.git/
$ touch README; git add README; git commit -m 'First commit'
[master (root-commit) 1d738b5] First commit
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 README
$ git branch Story-123-a
$ git branch Story-123-b
$ git branch Story-123-c
$ git branch --merged
  Story-123-a
  Story-123-b
  Story-123-c
* master
$ git branch --merged | grep -v \* | xargs
Story-123-a Story-123-b Story-123-c
$ git branch --merged | grep -v \* | xargs git branch -D
Deleted branch Story-123-a (was 1d738b5).
Deleted branch Story-123-b (was 1d738b5).
Deleted branch Story-123-c (was 1d738b5).

Jackson and generic type reference

This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.

In this case, tester method needs to have access to Class, and you can construct

JavaType type = mapper.getTypeFactory().
  constructCollectionType(List.class, Foo.class)

and then

List<Foo> list = mapper.readValue(new File("input.json"), type);

Convert UTF-8 encoded NSData to NSString

With Swift 5, you can use String's init(data:encoding:) initializer in order to convert a Data instance into a String instance using UTF-8. init(data:encoding:) has the following declaration:

init?(data: Data, encoding: String.Encoding)

Returns a String initialized by converting given data into Unicode characters using a given encoding.

The following Playground code shows how to use it:

import Foundation

let json = """
{
"firstName" : "John",
"lastName" : "Doe"
}
"""

let data = json.data(using: String.Encoding.utf8)!

let optionalString = String(data: data, encoding: String.Encoding.utf8)
print(String(describing: optionalString))

/*
 prints:
 Optional("{\n\"firstName\" : \"John\",\n\"lastName\" : \"Doe\"\n}")
*/

How can I calculate the time between 2 Dates in typescript

This is how it should be done in typescript:

(new Date()).valueOf() - (new Date("2013-02-20T12:01:04.753Z")).valueOf()

Better readability:

      var eventStartTime = new Date(event.startTime);
      var eventEndTime = new Date(event.endTime);
      var duration = eventEndTime.valueOf() - eventStartTime.valueOf();

How to find all positions of the maximum value in a list?

>>> max(enumerate([1,2,3,32,1,5,7,9]),key=lambda x: x[1])
>>> (3, 32)

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

I hadn't renewed my hosting and the database was read-only. Joomla needed to write the session and couldn't do it.

Output (echo/print) everything from a PHP Array

Similar to karim's, but with print_r which has a much small output and I find is usually all you need:

function PrintR($var) {
    echo '<pre>';
    print_r($var);
    echo '</pre>';
}

How to set up tmux so that it starts up with specified windows opened?

tmuxp support JSON or YAML session configuration and a python API. A simple tmuxp configuration file to create a new session in YAML syntax is:

session_name: 2-pane-vertical
windows:
  - window_name: my test window
    panes:
      - pwd
      - pwd

Check if my SSL Certificate is SHA1 or SHA2

I had to modify this slightly to be used on a Windows System. Here's the one-liner version for a windows box.

openssl.exe s_client -connect yoursitename.com:443 > CertInfo.txt && openssl x509 -text -in CertInfo.txt | find "Signature Algorithm" && del CertInfo.txt /F

Tested on Server 2012 R2 using http://iweb.dl.sourceforge.net/project/gnuwin32/openssl/0.9.8h-1/openssl-0.9.8h-1-bin.zip

Concatenate a vector of strings/character

Matt Turner's answer is definitely the right answer. However, in the spirit of Ken Williams' answer, you could also do:

capture.output(cat(sdata, sep="")) 

SQL Server Convert Varchar to Datetime

You can have all the different styles to datetime conversion :

https://www.w3schools.com/sql/func_sqlserver_convert.asp

This has range of values :-

CONVERT(data_type(length),expression,style)

For style values,
Choose anyone you need like I needed 106.

Getting Textbox value in Javascript

        <script type="text/javascript">
            function MyFunction() {
                var FNumber = Number(document.getElementById('txtFirstNumber').value);
                var SNumber = Number(document.getElementById("txtSecondNumber").value);
                var Sum = FNumber + SNumber;
                alert(Sum);
            }

        </script>

        <table class="auto-style1">
            <tr>
                <td>FirstNaumber</td>
                <td>
                    <asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>SecondNumber</td>
                <td>
                    <asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:TextBox ID="txtSum" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="BtnSubmit" runat="server" Text="Submit" OnClientClick="MyFunction()" />
                </td>
            </tr>
        </table>
    </div>
</form>

SQL Server PRINT SELECT (Print a select query result)?

You know, there might be an easier way but the first thing that pops to mind is:

Declare @SumVal int;
Select @SumVal=Sum(Amount) From Expense;
Print @SumVal;

You can, of course, print any number of fields from the table in this way. Of course, if you want to print all of the results from a query that returns multiple rows, you'd just direct your output appropriately (e.g. to Text).

Convert row names into first column

You can both remove row names and convert them to a column by reference (without reallocating memory using ->) using setDT and its keep.rownames = TRUE argument from the data.table package

library(data.table)
setDT(df, keep.rownames = TRUE)[]
#    rn     VALUE  ABS_CALL DETECTION     P.VALUE
# 1:  1 1007_s_at  957.7292         P 0.004862793
# 2:  2   1053_at  320.6327         P 0.031335632
# 3:  3    117_at  429.8423         P 0.017000453
# 4:  4    121_at 2395.7364         P 0.011447358
# 5:  5 1255_g_at  116.4936         A 0.397993682
# 6:  6   1294_at  739.9271         A 0.066864977

As mentioned by @snoram, you can give the new column any name you want, e.g. setDT(df, keep.rownames = "newname") would add "newname" as the rows column.

How to iterate over the file in python

This is probably because an empty line at the end of your input file.

Try this:

for x in f:
    try:
        print int(x.strip(),16)
    except ValueError:
        print "Invalid input:", x

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

To people using Codeigniter (i'm on C3):

The index.php file overwrite php.ini configuration, so on index.php file, line 68:

case 'development':
        error_reporting(-1);
        ini_set('display_errors', 1);
    break;

You can change this option to set what you need. Here's the complete list:

1   E_ERROR
2   E_WARNING
4   E_PARSE
8   E_NOTICE
16  E_CORE_ERROR
32  E_CORE_WARNING
64  E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024    E_USER_NOTICE
6143    E_ALL
2048    E_STRICT
4096    E_RECOVERABLE_ERROR

Hope it helps.

Setting up a JavaScript variable from Spring model by using Thymeleaf

According to the documentation there are several ways to do the inlining.
The right way you must choose based on the situation.

1) Simply put the variable from server to javascript :

<script th:inline="javascript">
/*<![CDATA[*/

var message = [[${message}]];
alert(message);

/*]]>*/
</script>

2) Combine javascript variables with server side variables, e.g. you need to create link for requesting inside the javascript:

<script th:inline="javascript">
        /*<![CDATA[*/
        function sampleGetByJquery(v) {
            /*[+
            var url = [[@{/my/get/url(var1=${#httpServletRequest.getParameter('var1')})}]] 
                      + "&var2="+v;
             +]*/
            $("#myPanel").load(url, function() {});
        }
        /*]]>*/
        </script>

The one situation I can't resolve - then I need to pass javascript variable inside the Java method calling inside the template (it's impossible I guess).

Setting default value for TypeScript object passed as argument

Without destructuring, you can create a defaults params and pass it in

interface Name {
   firstName: string;
   lastName: string;
}

export const defaultName extends Omit<Name, 'firstName'> {
    lastName: 'Smith'
}

sayName({ ...defaultName, firstName: 'Bob' })

How can I create an array with key value pairs?

Use the square bracket syntax:

if (!empty($row["title"])) {
    $catList[$row["datasource_id"]] = $row["title"];
}

$row["datasource_id"] is the key for where the value of $row["title"] is stored in.

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

The problem is that the CASE statement won't work in the way you're trying to use it. You can only use it to switch the value of one field in a query. If I understand what you're trying to do, you might need this:

SELECT 
   ActivityID,
   FieldName = CASE 
                  WHEN ActivityTypeID <> 2 THEN
                      (Some Aggregate Sub Query)
                  ELSE
                     (Some Aggregate Sub Query with diff result)
               END,
   FieldName2 = CASE
                  WHEN ActivityTypeID <> 2 THEN
                      (Some Aggregate Sub Query)
                  ELSE
                     (Some Aggregate Sub Query with diff result)
               END

What is the height of iPhone's onscreen keyboard?

Do remember that, with iOS 8, the onscreen keyboard's size can vary. Don't assume that the onscreen keyboard will always be visible (with a specific height) or invisible.

Now, with iOS 8, the user can also swipe the text-prediction area on and off... and when they do this, it would kick off an app's keyboardWillShow event again.

This will break a lot of legacy code samples, which recommended writing a keyboardWillShow event, which merely measures the current height of the onscreen keyboard, and shifting your controls up or down on the page by this (absolute) amount.

enter image description here

In other words, if you see any sample code, which just tells you to add a keyboardWillShow event, measure the keyboard height, then resize your controls' heights by this amount, this will no longer always work.

In my example above, I used the sample code from the following site, which animates the vertical constraints constant value.

Practicing AutoLayout

In my app, I added a constraint to my UITextView, set to the bottom of the screen. When the screen first appeared, I stored this initial vertical distance.

Then, whenever my keyboardWillShow event gets kicked off, I add the (new) keyboard height to this original constraint value (so the constraint resizes the control's height).

enter image description here

Yeah. It's ugly.

And I'm a little annoyed/surprised that XCode 6's horribly-painful AutoLayout doesn't just allow us to attach the bottoms of controls to either the bottom of the screen, or the top of onscreen keyboard.

Perhaps I'm missing something.

Other than my sanity.

Why doesn't java.util.Set have get(int index)?

Actually this is a recurring question when writing JavaEE applications which use Object-Relational Mapping (for example with Hibernate); and from all the people who replied here, Andreas Petersson is the only one who understood the real issue and offered the correct answer to it: Java is missing a UniqueList! (or you can also call it OrderedSet, or IndexedSet).

Maxwing mentioned this use-case (in which you need ordered AND unique data) and he suggested the SortedSet, but this is not what Marty Pitt really needed.

This "IndexedSet" is NOT the same as a SortedSet - in a SortedSet the elements are sorted by using a Comparator (or using their "natural" ordering).

But instead it is closer to a LinkedHashSet (which others also suggested), or even more so to an (also inexistent) "ArrayListSet", because it guarantees that the elements are returned in the same order as they were inserted.

But the LinkedHashSet is an implementation, not an interface! What is needed is an IndexedSet (or ListSet, or OrderedSet, or UniqueList) interface! This will allow the programmer to specify that he needs a collection of elements that have a specific order and without duplicates, and then instantiate it with any implementation (for example an implementation provided by Hibernate).

Since JDK is open-source, maybe this interface will be finally included in Java 7...

Fastest way to get the first n elements of a List into an Array

Option 1 Faster Than Option 2

Because Option 2 creates a new List reference, and then creates an n element array from the List (option 1 perfectly sizes the output array). However, first you need to fix the off by one bug. Use < (not <=). Like,

String[] out = new String[n];
for(int i = 0; i < n; i++) {
    out[i] = in.get(i);
}

The zip() function in Python 3

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

Using ALTER to drop a column if it exists in MySQL

Chase Seibert's answer works, but I'd add that if you have several schemata you want to alter the SELECT thus:

select * from information_schema.columns where table_schema in (select schema()) and table_name=...

Simplest code for array intersection in javascript

If your environment supports ECMAScript 6 Set, one simple and supposedly efficient (see specification link) way:

function intersect(a, b) {
  var setA = new Set(a);
  var setB = new Set(b);
  var intersection = new Set([...setA].filter(x => setB.has(x)));
  return Array.from(intersection);
}

Shorter, but less readable (also without creating the additional intersection Set):

function intersect(a, b) {
  var setB = new Set(b);
  return [...new Set(a)].filter(x => setB.has(x));
}

Note that when using sets you will only get distinct values, thus new Set([1, 2, 3, 3]).size evaluates to 3.

printf with std::string?

The main reason is probably that a C++ string is a struct that includes a current-length value, not just the address of a sequence of chars terminated by a 0 byte. Printf and its relatives expect to find such a sequence, not a struct, and therefore get confused by C++ strings.

Speaking for myself, I believe that printf has a place that can't easily be filled by C++ syntactic features, just as table structures in html have a place that can't easily be filled by divs. As Dykstra wrote later about the goto, he didn't intend to start a religion and was really only arguing against using it as a kludge to make up for poorly-designed code.

It would be quite nice if the GNU project would add the printf family to their g++ extensions.

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

The simple solution is follow this screenshot then crash will go away:

enter image description here

Noted: This is Xcode 11.5

How can I permanently enable line numbers in IntelliJ?

IntelliJ IDEA 15

5 approaches


Global change

  1. File > Settings... > Editor > General > Appearance > Show line numbers

    show line numbers

  2. Hit Shift twice > write "line numbers" > Show Line Numbers (that one that has the toggle) > change the toggle to ON

    shift shift


Change for the Active Editor

  1. Right click on the left side bar > Show Line Numbers

    right click

  2. Hit Shift twice > write "line" > Show Line Numbers (the line doesn't have the toggle)

    shift shift line

  3. Ctrl + Shift + A > write "Show line" > Active Editor: Show Line Numbers > change the toggle to ON

    Ctrl Shift A

Circle line-segment collision detection algorithm?

I know it's been a while since this thread was open. From the answer given by chmike and improved by Aqib Mumtaz. They give a good answer but only works for a infinite line as said Aqib. So I add some comparisons to know if the line segment touch the circle, I write it in Python.

def LineIntersectCircle(c, r, p1, p2):
    #p1 is the first line point
    #p2 is the second line point
    #c is the circle's center
    #r is the circle's radius

    p3 = [p1[0]-c[0], p1[1]-c[1]]
    p4 = [p2[0]-c[0], p2[1]-c[1]]

    m = (p4[1] - p3[1]) / (p4[0] - p3[0])
    b = p3[1] - m * p3[0]

    underRadical = math.pow(r,2)*math.pow(m,2) + math.pow(r,2) - math.pow(b,2)

    if (underRadical < 0):
        print("NOT")
    else:
        t1 = (-2*m*b+2*math.sqrt(underRadical)) / (2 * math.pow(m,2) + 2)
        t2 = (-2*m*b-2*math.sqrt(underRadical)) / (2 * math.pow(m,2) + 2)
        i1 = [t1+c[0], m * t1 + b + c[1]]
        i2 = [t2+c[0], m * t2 + b + c[1]]

        if p1[0] > p2[0]:                                           #Si el punto 1 es mayor al 2 en X
            if (i1[0] < p1[0]) and (i1[0] > p2[0]):                 #Si el punto iX esta entre 2 y 1 en X
                if p1[1] > p2[1]:                                   #Si el punto 1 es mayor al 2 en Y
                    if (i1[1] < p1[1]) and (i1[1] > p2[1]):         #Si el punto iy esta entre 2 y 1
                        print("Intersection")
                if p1[1] < p2[1]:                                   #Si el punto 2 es mayo al 2 en Y
                    if (i1[1] > p1[1]) and (i1[1] < p2[1]):         #Si el punto iy esta entre 1 y 2
                        print("Intersection")

        if p1[0] < p2[0]:                                           #Si el punto 2 es mayor al 1 en X
            if (i1[0] > p1[0]) and (i1[0] < p2[0]):                 #Si el punto iX esta entre 1 y 2 en X
                if p1[1] > p2[1]:                                   #Si el punto 1 es mayor al 2 en Y
                    if (i1[1] < p1[1]) and (i1[1] > p2[1]):         #Si el punto iy esta entre 2 y 1
                        print("Intersection")
                if p1[1] < p2[1]:                                   #Si el punto 2 es mayo al 2 en Y
                    if (i1[1] > p1[1]) and (i1[1] < p2[1]):         #Si el punto iy esta entre 1 y 2
                        print("Intersection")

        if p1[0] > p2[0]:                                           #Si el punto 1 es mayor al 2 en X
            if (i2[0] < p1[0]) and (i2[0] > p2[0]):                 #Si el punto iX esta entre 2 y 1 en X
                if p1[1] > p2[1]:                                   #Si el punto 1 es mayor al 2 en Y
                    if (i2[1] < p1[1]) and (i2[1] > p2[1]):         #Si el punto iy esta entre 2 y 1
                        print("Intersection")
                if p1[1] < p2[1]:                                   #Si el punto 2 es mayo al 2 en Y
                    if (i2[1] > p1[1]) and (i2[1] < p2[1]):         #Si el punto iy esta entre 1 y 2
                        print("Intersection")

        if p1[0] < p2[0]:                                           #Si el punto 2 es mayor al 1 en X
            if (i2[0] > p1[0]) and (i2[0] < p2[0]):                 #Si el punto iX esta entre 1 y 2 en X
                if p1[1] > p2[1]:                                   #Si el punto 1 es mayor al 2 en Y
                    if (i2[1] < p1[1]) and (i2[1] > p2[1]):         #Si el punto iy esta entre 2 y 1
                        print("Intersection")
                if p1[1] < p2[1]:                                   #Si el punto 2 es mayo al 2 en Y
                    if (i2[1] > p1[1]) and (i2[1] < p2[1]):         #Si el punto iy esta entre 1 y 2
                        print("Intersection")

Get the item doubleclick event of listview

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <EventSetter Event="MouseDoubleClick" Handler="listViewItem_MouseDoubleClick" />
    </Style>
</ListView.ItemContainerStyle>

The only difficulty then is if you are interested in the underlying object the listviewitem maps to e.g.

private void listViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    ListViewItem item = sender as ListViewItem;
    object obj = item.Content;
}

Shell Script — Get all files modified after <date>

I would simply do the following to backup all new files from 7 days ago

tar --newer $(date -d'7 days ago' +"%d-%b") -zcf thisweek.tgz .

note you can also replace '7 days ago' with anything that suits your need

Can be : date -d'yesterday' +"%d-%b"

Or even : date -d'first Sunday last month' +"%d-%b"

Why won't eclipse switch the compiler to Java 8?

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

Setting top and left CSS attributes

Your problem is that the top and left properties require a unit of measure, not just a bare number:

div.style.top = "200px";
div.style.left = "200px";

How to save an HTML5 Canvas as an image on a server?

In addition to Salvador Dali's answer:

on the server side don't forget that the data comes in base64 string format. It's important because in some programming languages you need to explisitely say that this string should be regarded as bytes not simple Unicode string.

Otherwise decoding won't work: the image will be saved but it will be an unreadable file.

Java constructor/method with optional parameters?

Java doesn't support default parameters. You will need to have two constructors to do what you want.

An alternative if there are lots of possible values with defaults is to use the Builder pattern, whereby you use a helper object with setters.

e.g.

   public class Foo {
     private final String param1;
     private final String param2;

     private Foo(Builder builder) {
       this.param1 = builder.param1;
       this.param2 = builder.param2;
     }
     public static class Builder {
       private String param1 = "defaultForParam1";
       private String param2 = "defaultForParam2";

       public Builder param1(String param1) {
         this.param1 = param1;
         return this;
       }
       public Builder param2(String param1) {
         this.param2 = param2;
         return this;
       }
       public Foo build() {
         return new Foo(this);
       }
     }
   }

which allows you to say:

Foo myFoo = new Foo.Builder().param1("myvalue").build();

which will have a default value for param2.

How to simulate a click with JavaScript?

var elem = document.getElementById('mytest1');

// Simulate clicking on the specified element.
triggerEvent( elem, 'click' );

/**
 * Trigger the specified event on the specified element.
 * @param  {Object} elem  the target element.
 * @param  {String} event the type of the event (e.g. 'click').
 */
function triggerEvent( elem, event ) {
  var clickEvent = new Event( event ); // Create the event.
  elem.dispatchEvent( clickEvent );    // Dispatch the event.
}

Reference

How to uninstall/upgrade Angular CLI?

remove global reference

npm uninstall -g angular-cli
npm cache clean

How do I append to a table in Lua

You are looking for the insert function, found in the table section of the main library.

foo = {}
table.insert(foo, "bar")
table.insert(foo, "baz")

Javascript replace with reference to matched group?

For the replacement string and the replacement pattern as specified by $. here a resume:

enter image description here

link to doc : here

"hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")



Note:

If you want to have a $ in the replacement string use $$. Same as with vscode snippet system.

Regular expression that doesn't contain certain string

I the following code I had to replace add a GET-parameter to all references to JS-files EXCEPT one.

<link rel="stylesheet" type="text/css" href="/login/css/ABC.css" />
<script type="text/javascript" language="javascript" src="/localization/DEF.js"></script>
<script type="text/javascript" language="javascript" src="/login/jslib/GHI.js"></script>
<script type="text/javascript" language="javascript" src="/login/jslib/md5.js"></script>
sendRequest('/application/srvc/EXCEPTION.js', handleChallengeResponse, null);
sendRequest('/application/srvc/EXCEPTION.js",handleChallengeResponse, null);

This is the Matcher used:

(?<!EXCEPTION)(\.js)

What that does is look for all occurences of ".js" and if they are preceeded by the "EXCEPTION" string, discard that result from the result array. That's called negative lookbehind. Since I spent a day on finding out how to do this I thought I should share.

Limiting the number of characters in a string, and chopping off the rest

For readability, I prefer this:

if (inputString.length() > maxLength) {
    inputString = inputString.substring(0, maxLength);
}

over the accepted answer.

int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);

File loading by getClass().getResource()

The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):

public static File getResourceAsFile(String resourcePath) {
    try {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
        if (in == null) {
            return null;
        }

        File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            //copy stream
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

DATEDIFF function in Oracle

In Oracle, you can simply subtract two dates and get the difference in days. Also note that unlike SQL Server or MySQL, in Oracle you cannot perform a select statement without a from clause. One way around this is to use the builtin dummy table, dual:

SELECT TO_DATE('2000-01-02', 'YYYY-MM-DD') -  
       TO_DATE('2000-01-01', 'YYYY-MM-DD') AS DateDiff
FROM   dual

CSS background-image - What is the correct usage?

  1. No you don’t need quotes.

  2. Yes you can. But note that relative URLs are resolved from the URL of your stylesheet.

  3. Better don’t use quotes. I think there are clients that don’t understand them.

Writing List of Strings to Excel CSV File in Python

Very simple to fix, you just need to turn the parameter to writerow into a list.

for item in RESULTS:
     wr.writerow([item,])

Passing parameters in Javascript onClick event

This happens because the i propagates up the scope once the function is invoked. You can avoid this issue using a closure.

for (var i = 0; i < 10; i++) {
   var link = document.createElement('a');
   link.setAttribute('href', '#');
   link.innerHTML = i + '';
   link.onclick = (function() {
      var currentI = i;
      return function() { 
          onClickLink(currentI + '');
      }
   })();
   div.appendChild(link);
   div.appendChild(document.createElement('BR'));
}

Or if you want more concise syntax, I suggest you use Nick Craver's solution.

Excel formula to search if all cells in a range read "True", if not, then show "False"

As it appears you have the values as text, and not the numeric True/False, then you can use either COUNTIF or SUMPRODUCT

=IF(SUMPRODUCT(--(A2:D2="False")),"False","True")
=IF(COUNTIF(A3:D3,"False*"),"False","True")

How to resolve git's "not something we can merge" error

This answer is not related to the above question, but I faced a similar issue, and maybe this will be useful to someone. I am trying to merge my feature branch to master like below:

$ git merge fix-load

for this got the following error message:

merge: fix-load - not something we can merge

I looked into above all solutions, but not none of the worked.

Finally, I realized the issue cause is a spelling mistake on my branch name (actually, the merge branch name is fix-loads).

How to add display:inline-block in a jQuery show() function?

Best way is to add !important suffix to the selector .

Example:

 #selector{
     display: inline-block !important;                   
}

Best way to "push" into C# array

C# is a little different in this respect with JavaScript. Because of the strict checks, you define the size of the array and you are supposed to know everything about the array such as its bounds, where the last item was put and what items are unused. You are supposed to copy all the elements of the array into a new, bigger one, if you want to resize it.

So, if you use a raw array, there's no other way other than to maintain the last empty, available index assign items to the array at this index, like you're already doing.

However, if you'd like to have the runtime maintain this information and completely abstract away the array, but still use an array underneath, then C# provides a class named ArrayList that provides this abstraction.

The ArrayList abstracts a loosely typed array of Objects. See the source here.

It takes care of all the issues like resizing the array, maintaining the last index that is available, etc. However, it abstracts / encapsulates this information from you. All you use is the ArrayList.

To push an item of any type into the underlying array at the end of the underlying array, call the Add method on the ArrayList like so:

/* you may or may not define a size using a constructor overload */
var arrayList = new ArrayList(); 

arrayList.Add("Foo");

EDIT: A note about type restriction

Like every programming language and runtime does, C# categorizes heap objects from those that will not go on the heap and will only stay on the function's argument stack. C# notes this distinction by the name Value types vs. Reference types. All things whose value goes on the stack are called Value types, and those that will go on the heap are called Reference types. This is loosely similar to JavaScript's distinction between objects and literals.

You can put anything into an ArrayList in C#, whether the thing is a value type or a reference type. This makes it closest to the JavaScript array in terms of typelessness, although neither of the three -- the JavaScript array, the JavaScript language and the C# ArrayList -- are actually type-less.

So, you could put a number literal, a string literal, an object of a class you made up, a boolean, a float, a double, a struct, just about anything you wanted into an ArrayList.

That is because the ArrayList internally maintains and stores all that you put into it, into an array of Objects, as you will have noted in my original answer and the linked source code.

And when you put something that isn't an object, C# creates a new object of type Object, stores the value of the thing you put into the ArrayList into this new Object type object. This process is called boxing and isn't very much unlike the JavaScript boxing mechanism.

For e.g. in JavaScript, while you could use a numeric literal to invoke a function on the Number object, you couldn't add something to the number literal's prototype.

// Valid javascript
var s = 4.toString();

// Invalid JavaScript code
4.prototype.square = () => 4 * 4;
var square = 4.square();

Just like JavaScript boxes the numeric literal 4 in the call to the toString method, C# boxes all things that are not objects into an Object type when putting them into an ArrayList.

var arrayList = new ArrayList();

arrayList.Add(4); // The value 4 is boxed into a `new Object()` first and then that new object is inserted as the last element in the `ArrayList`.

This involves a certain penalty, as it does in the case of JavaScript as well.

In C#, you can avoid this penalty as C# provides a strongly typed version of the ArrayList, known as the List<T>. So it follows that you cannot put anything into a List<T>; just T types.

However, I assume from your question's text that you already knew that C# had generic structures for strongly typed items. And your question was to have a JavaScript like data structure exhibiting the semantics of typelessness and elasticity, like the JavaScript Array object. In this case, the ArrayList comes closest.

It is also clear from your question that your interest was academic and not to use the structure in a production application.

So, I assume that for a production application, you would already know that a generic / strongly typed data structure (List<T> for example) is better performing than its non-typed one (ArrayList for example).

MYSQL query between two timestamps

Try:

SELECT * 
FROM eventList 
WHERE  `date` BETWEEN FROM_UNIXTIME(1364256001) AND FROM_UNIXTIME(1364342399)

Or

SELECT * 
FROM eventList WHERE  `date` 
BETWEEN '2013-03-26 00:00:01' AND '2013-03-26 23:59:59'

What are the differences between normal and slim package of jquery?

Looking at the code I found the following differences between jquery.js and jquery.slim.js:

In the jquery.slim.js, the following features are removed:

  1. jQuery.fn.extend
  2. jquery.fn.load
  3. jquery.each // Attach a bunch of functions for handling common AJAX events
  4. jQuery.expr.filters.animated
  5. ajax settings like jQuery.ajaxSettings.xhr, jQuery.ajaxPrefilter, jQuery.ajaxSetup, jQuery.ajaxPrefilter, jQuery.ajaxTransport, jQuery.ajaxSetup
  6. xml parsing like jQuery.parseXML,
  7. animation effects like jQuery.easing, jQuery.Animation, jQuery.speed

Can you delete multiple branches in one command with Git?

You can use this command: git branch -D $(printf "%s\n" $(git branch) | grep '3.2')

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

If you want the structure to have a certain size with GCC for example use __attribute__((packed)).

On Windows you can set the alignment to one byte when using the cl.exe compier with the /Zp option.

Usually it is easier for the CPU to access data that is a multiple of 4 (or 8), depending platform and also on the compiler.

So it is a matter of alignment basically.

You need to have good reasons to change it.

WAMP 403 Forbidden message on Windows 7

The access to your Apache server is forbidden from addresses other than 127.0.0.1 in httpd.conf (Apache's config file) :

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
</Directory>

The same goes for your PHPMyAdmin access, the config file is phpmyadmin.conf :

<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order Deny,Allow
        Deny from all
        Allow from 127.0.0.1
</Directory>

You can set them to allow connections from all IP addresses like follows :

AllowOverride All
Order allow,deny
Allow from all

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

For users which have flavors in the project and found this thread:

Notice, that if your module dependency has different flavors, you should use one of the strategies:

  1. Module that tightens dependencies should have the same flavors and dimensions as the dependency module
  2. You should explicitly indicate which configuration you target in the module

Like that:

dependencies {
    compile project(path: ':module', configuration:'alphaDebug') 
}

How do I convert a String to a BigInteger?

Using the constructor

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

Javadoc

Why can't I do <img src="C:/localfile.jpg">?

I have tried a lot of techniques and finally found one in C# side and JS Side. You cannot give a physical path to src attribute but you can give the base64 string as a src to Img tag. Lets look into the below C# code example.

<asp:Image ID="imgEvid" src="#" runat="server" Height="99px"/>

C# code

 if (File.Exists(filepath)
                            {
                                byte[] imageArray = System.IO.File.ReadAllBytes(filepath);
                                string base64ImageRepresentation = Convert.ToBase64String(imageArray);
                                var val = $"data: image/png; base64,{base64ImageRepresentation}";
                                imgEvid.Attributes.Add("src", val);
                            }

Hope this will help

Refreshing all the pivot tables in my excel workbook with a macro

This VBA code will refresh all pivot tables/charts in the workbook.

Sub RefreshAllPivotTables()

Dim PT As PivotTable
Dim WS As Worksheet

    For Each WS In ThisWorkbook.Worksheets

        For Each PT In WS.PivotTables
          PT.RefreshTable
        Next PT

    Next WS

End Sub

Another non-programatic option is:

  • Right click on each pivot table
  • Select Table options
  • Tick the 'Refresh on open' option.
  • Click on the OK button

This will refresh the pivot table each time the workbook is opened.

How to access route, post, get etc. parameters in Zend Framework 2

The easiest way to do that would be to use the Params plugin, introduced in beta5. It has utility methods to make it easy to access different types of parameters. As always, reading the tests can prove valuable to understand how something is supposed to be used.

Get a single value

To get the value of a named parameter in a controller, you will need to select the appropriate method for the type of parameter you are looking for and pass in the name.

Examples:

$this->params()->fromPost('paramname');   // From POST
$this->params()->fromQuery('paramname');  // From GET
$this->params()->fromRoute('paramname');  // From RouteMatch
$this->params()->fromHeader('paramname'); // From header
$this->params()->fromFiles('paramname');  // From file being uploaded

 

Default values

All of these methods also support default values that will be returned if no parameter with the given name is found.

Example:

$orderBy = $this->params()->fromQuery('orderby', 'name');

When visiting http://example.com/?orderby=birthdate, $orderBy will have the value birthdate.
When visiting http://example.com/, $orderBy will have the default value name.
 

Get all parameters

To get all parameters of one type, just don't pass in anything and the Params plugin will return an array of values with their names as keys.

Example:

$allGetValues = $this->params()->fromQuery(); // empty method call

When visiting http://example.com/?orderby=birthdate&filter=hasphone $allGetValues will be an array like

array(
    'orderby' => 'birthdate',
    'filter'  => 'hasphone',
);

 

Not using Params plugin

If you check the source code for the Params plugin, you will see that it's just a thin wrapper around other controllers to allow for more consistent parameter retrieval. If you for some reason want/need to access them directly, you can see in the source code how it's done.

Example:

$this->getRequest()->getRequest('name', 'default');
$this->getEvent()->getRouteMatch()->getParam('name', 'default');

NOTE: You could have used the superglobals $_GET, $_POST etc., but that is discouraged.

If statement in select (ORACLE)

SELECT (CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 1 ELSE 0 END) AS ISSUES
    --  <add any columns to outer select from inner query> 
  FROM
 (  -- your query here --
   select 'CARAT Issue Open' issue_comment, ...., ..., 
          substr(gcrs.stream_name,1,case when instr(gcrs.stream_name,' (')=0 then 100 else  instr(gcrs.stream_name,' (')-1 end) ISSUE_DIVISION,
          case when gcrs.STREAM_NAME like 'NON-GT%' THEN 'NON-GT' ELSE gcrs.STREAM_NAME END as ISSUE_DIVISION_2
     from ....
    where UPPER(ISSUE_STATUS) like '%OPEN%'
 )
 WHERE... -- optional --

Updating Anaconda fails: Environment Not Writable Error

start your command prompt with run as administrator

What is a good alternative to using an image map generator?

This service is the best in online image map editing I found so far : http://www.image-maps.com/

... but it is in fact a bit weak and I personnaly don't use it anymore. I switched to GIMP and it is indeed pretty good.

The answer from mobius is not wrong but in some cases you must use imagemaps even if it seems a bit old and rusty. For instance, in a newsletter, where you can't use HTML/CSS to do what you want.

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

Did have identical problem with on XP machine when installing javacv and opencv in combination with Eclipse. It turned out that I was missing the following files:

  • msvcp100.dll
  • msvcr100.dll

Once these were installed, the project compiled and ran OK.

How to install latest version of openssl Mac OS X El Capitan

I reached this page when I searched for information about openssl being keg-only. I believe I have understood the reason why Homebrew is taking this action now. My solution may work for you:

  • Use the following command to make the new openssl command available (assuming you have adjusted PATH to put /usr/local/bin before /usr/bin): ln -s /usr/local/opt/openssl/bin/openssl /usr/local/bin/

  • When compiling with openssl, follow Homebrew's advice and use -I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib

  • Alternatively, you can make these settings permanent by putting the following lines in your .bash_profile or .bashrc: export CPATH=/usr/local/opt/openssl/include export LIBRARY_PATH=/usr/local/opt/openssl/lib

How to fire a button click event from JavaScript in ASP.NET

You can just place this line in a JavaScript function:

__doPostBack('btnSubmit','OnClick');

Or do something like this:

$('#btnSubmit').trigger('click');

How to show progress dialog in Android?

ProgressDialog dialog = 
   ProgressDialog.show(yourActivity.this, "", "Please Wait...");

Can you have if-then-else logic in SQL?

You can make the following sql query

IF ((SELECT COUNT(*) FROM table1 WHERE project = 1) > 0) 
    SELECT product, price FROM table1 WHERE project = 1
ELSE IF ((SELECT COUNT(*) FROM table1 WHERE project = 2) > 0) 
    SELECT product, price FROM table1 WHERE project = 2
ELSE IF ((SELECT COUNT(*) FROM table1 WHERE project = 3) > 0)
    SELECT product, price FROM table1 WHERE project = 3

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

Preventing console window from closing on Visual Studio C/C++ Console application

If you're using .NET, put Console.ReadLine() before the end of the program.

It will wait for <ENTER>.

Asynchronous shell exec in PHP

I used at for this, as it is really starting an independent process.

<?php
    `echo "the command"|at now`;
?>

Undefined symbols for architecture x86_64 on Xcode 6.1

I just had the exact same error, and solved it by restarting xcode.

For me the issue occurred after an svn update, the file in question was added to the projects folder, but it never appeared in xcode(9.3.1) – until I restarted it.

window.location.href and window.open () methods in JavaScript

window.location.href is not a method, it's a property that will tell you the current URL location of the browser. Changing the value of the property will redirect the page.

window.open() is a method that you can pass a URL to that you want to open in a new window. For example:

window.location.href example:

window.location.href = 'http://www.google.com'; //Will take you to Google.

window.open() example:

window.open('http://www.google.com'); //This will open Google in a new window.

Additional Information:

window.open() can be passed additional parameters. See: window.open tutorial

String to object in JS

In your case

var KeyVal = string.split(", ");
var obj = {};
var i;
for (i in KeyVal) {
    KeyVal[i] = KeyVal[i].split(":");
    obj[eval(KeyVal[i][0])] = eval(KeyVal[i][1]);
}

How to make rectangular image appear circular with CSS

My 2cents because the comments for the only answer are getting kinda crazy. This is what I normally do. For a circle, you need to start with a square. This code forces a square and will stretch the image. If you know that the image is going to be at least the width and height of the round div you can remove the img style rules for it to not be stretch but only cut off.

<html>
    <head>
        <style>
            .round {
                border-radius: 50%;
                overflow: hidden;
                width: 150px;
                height: 150px;
            }
            .round img {
                display: block;
            /* Stretch 
                  height: 100%;
                  width: 100%; */
            min-width: 100%;
            min-height: 100%;
            }
        </style>
    </head>
    <body>
        <div class="round">
            <img src="image.jpg" />
        </div>
    </body>
</html>

What are the differences between .so and .dylib on osx?

The file .so is not a UNIX file extension for shared library.

It just happens to be a common one.

Check line 3b at ArnaudRecipes sharedlib page

Basically .dylib is the mac file extension used to indicate a shared lib.

How to pick a new color for each plotted line within a figure in matplotlib?

As Ciro's answer notes, you can use prop_cycle to set a list of colors for matplotlib to cycle through. But how many colors? What if you want to use the same color cycle for lots of plots, with different numbers of lines?

One tactic would be to use a formula like the one from https://gamedev.stackexchange.com/a/46469/22397, to generate an infinite sequence of colors where each color tries to be significantly different from all those that preceded it.

Unfortunately, prop_cycle won't accept infinite sequences - it will hang forever if you pass it one. But we can take, say, the first 1000 colors generated from such a sequence, and set it as the color cycle. That way, for plots with any sane number of lines, you should get distinguishable colors.

Example:

from matplotlib import pyplot as plt
from matplotlib.colors import hsv_to_rgb
from cycler import cycler

# 1000 distinct colors:
colors = [hsv_to_rgb([(i * 0.618033988749895) % 1.0, 1, 1])
          for i in range(1000)]
plt.rc('axes', prop_cycle=(cycler('color', colors)))

for i in range(20):
    plt.plot([1, 0], [i, i])

plt.show()

Output:

Graph output by the code above

Now, all the colors are different - although I admit that I struggle to distinguish a few of them!

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

I came into this issue when I copy my local repository.

sudo cp -r original_repo backup_repo
cd backup_repo
git status
fatal: Not a git repository (or any parent up to mount point /data)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).

I've try git init as some answer suggested, but it doesn't work.

sudo git init
Reinitialized existing Git repository in /data/HQ/SC_Educations/hq_htdocs/HQ_Educations_bak/.git/

I solved it by change the owner of the repo

sudo chown -R www:www ../backup_repo
git status
# On branch develop
nothing to commit, working directory clean

How can I get CMake to find my alternative Boost installation?

The short version

You only need BOOST_ROOT, but you're going to want to disable searching the system for your local Boost if you have multiple installations or cross-compiling for iOS or Android. In which case add Boost_NO_SYSTEM_PATHS is set to false.

set( BOOST_ROOT "" CACHE PATH "Boost library path" )
set( Boost_NO_SYSTEM_PATHS on CACHE BOOL "Do not search system for Boost" )

Normally this is passed on the CMake command-line using the syntax -D<VAR>=value.

The longer version

Officially speaking the FindBoost page states these variables should be used to 'hint' the location of Boost.

This module reads hints about search locations from variables:

BOOST_ROOT             - Preferred installation prefix
 (or BOOSTROOT)
BOOST_INCLUDEDIR       - Preferred include directory e.g. <prefix>/include
BOOST_LIBRARYDIR       - Preferred library directory e.g. <prefix>/lib
Boost_NO_SYSTEM_PATHS  - Set to ON to disable searching in locations not
                         specified by these hint variables. Default is OFF.
Boost_ADDITIONAL_VERSIONS
                       - List of Boost versions not known to this module
                         (Boost install locations may contain the version)

This makes a theoretically correct incantation:

cmake -DBoost_NO_SYSTEM_PATHS=TRUE \
      -DBOOST_ROOT=/path/to/boost-dir

When you compile from source

include( ExternalProject )

set( boost_URL "http://sourceforge.net/projects/boost/files/boost/1.63.0/boost_1_63_0.tar.bz2" )
set( boost_SHA1 "9f1dd4fa364a3e3156a77dc17aa562ef06404ff6" )
set( boost_INSTALL ${CMAKE_CURRENT_BINARY_DIR}/third_party/boost )
set( boost_INCLUDE_DIR ${boost_INSTALL}/include )
set( boost_LIB_DIR ${boost_INSTALL}/lib )

ExternalProject_Add( boost
        PREFIX boost
        URL ${boost_URL}
        URL_HASH SHA1=${boost_SHA1}
        BUILD_IN_SOURCE 1
        CONFIGURE_COMMAND
        ./bootstrap.sh
        --with-libraries=filesystem
        --with-libraries=system
        --with-libraries=date_time
        --prefix=<INSTALL_DIR>
        BUILD_COMMAND
        ./b2 install link=static variant=release threading=multi runtime-link=static
        INSTALL_COMMAND ""
        INSTALL_DIR ${boost_INSTALL} )

set( Boost_LIBRARIES
        ${boost_LIB_DIR}/libboost_filesystem.a
        ${boost_LIB_DIR}/libboost_system.a
        ${boost_LIB_DIR}/libboost_date_time.a )
message( STATUS "Boost static libs: " ${Boost_LIBRARIES} )

Then when you call this script you'll need to include the boost.cmake script (mine is in the a subdirectory), include the headers, indicate the dependency, and link the libraries.

include( boost )
include_directories( ${boost_INCLUDE_DIR} )
add_dependencies( MyProject boost )
target_link_libraries( MyProject
                       ${Boost_LIBRARIES} )

How to generate a random int in C?

STL doesn't exist for C. You have to call rand, or better yet, random. These are declared in the standard library header stdlib.h. rand is POSIX, random is a BSD spec function.

The difference between rand and random is that random returns a much more usable 32-bit random number, and rand typically returns a 16-bit number. The BSD manpages show that the lower bits of rand are cyclic and predictable, so rand is potentially useless for small numbers.

Python, print all floats to 2 decimal places in output

Not directly in the way you want to write that, no. One of the design tenets of Python is "Explicit is better than implicit" (see import this). This means that it's better to describe what you want rather than having the output format depend on some global formatting setting or something. You could of course format your code differently to make it look nicer:

print         '%.2f' % var1, \
      'kg =' ,'%.2f' % var2, \
      'lb =' ,'%.2f' % var3, \
      'gal =','%.2f' % var4, \
      'l'

Why are the Level.FINE logging messages not showing?

WHY

As mentioned by @Sheepy, the reason why it doesn't work is that java.util.logging.Logger has a root logger that defaults to Level.INFO, and the ConsoleHandler attached to that root logger also defaults to Level.INFO. Therefore, in order to see the FINE (, FINER or FINEST) output, you need to set the default value of the root logger and its ConsoleHandler to Level.FINE as follows:

Logger.getLogger("").setLevel(Level.FINE);
Logger.getLogger("").getHandlers()[0].setLevel(Level.FINE);


The problem of your Update (solution)

As mentioned by @mins, you will have the messages printed twice on the console for INFO and above: first by the anonymous logger, then by its parent, the root logger which also has a ConsoleHandler set to INFO by default. To disable the root logger, you need to add this line of code: logger.setUseParentHandlers(false);

There are other ways to prevent logs from being processed by default Console handler of the root logger mentioned by @Sheepy, e.g.:

Logger.getLogger("").getHandlers()[0].setLevel( Level.OFF );

But Logger.getLogger("").setLevel( Level.OFF ); won't work because it only blocks the message passed directly to the root logger, not the message comes from a child logger. To illustrate how the Logger Hierarchy works, I draw the following diagram:

enter image description here

public void setLevel(Level newLevel) set the log level specifying which message levels will be logged by this logger. Message levels lower than this value will be discarded. The level value Level.OFF can be used to turn off logging. If the new level is null, it means that this node should inherit its level from its nearest ancestor with a specific (non-null) level value.

How do you run JavaScript script through the Terminal?

If you have a Mac you can get jsc a javascript console in OS X (Terminal) by typing

/System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Resources/jsc

in Terminal.app.

You could also run one of your .js script by adding its name as an argument for jsc, like this:

jsc your_awesome_script_name.js

Notice: I use console.log() during development but jsc needs the debug() function instead.

On Ubuntu you have some nice ECMAScript shells at your disposal. Between them it's worth to mention SpiderMonkey. You can add It by sudo apt-get install spidermonkey

On Windows as other people said you can rely on cscript and wscript directly built on the OS.

I would add also another :) way of thinking to the problem, if you have time and like to learn new things i'd like to mention coffee-script that has its own compiler/console and gives you super-correct Javascript out. You can try it also on your browser (link "try coffeescript").

How do you share constants in NodeJS modules?

I recommend doing it with webpack (assumes you're using webpack).

Defining constants is as simple as setting the webpack config file:

var webpack = require('webpack');
module.exports = {
    plugins: [
        new webpack.DefinePlugin({
            'APP_ENV': '"dev"',
            'process.env': {
                'NODE_ENV': '"development"'
            }
        })
    ],    
};

This way you define them outside your source, and they will be available in all your files.

Does adding a duplicate value to a HashSet/HashMap replace the previous value

To say it differently: When you insert a key-value-pair into a HashMap where the key already exists (in a sense hashvalue() gives the same value und equal() is true, but the two objects can still differ in several ways), the key isn't replaced but the value is overwritten. The key is just used to get the hashvalue() and find the value in the table with it. Since HashSet uses the keys of a HashMap and sets arbitrary values which don't really matter (to the user) as a result the Elements of the Set aren't replaced either.

Shell command to tar directory excluding certain files/folders

I found this somewhere else so I won't take credit, but it worked better than any of the solutions above for my mac specific issues (even though this is closed):

tar zc --exclude __MACOSX --exclude .DS_Store -f <archive> <source(s)>

Insert into C# with SQLCommand

Try confirm the data type (SqlDbType) for each parameter in the database and do it this way;

 using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connSpionshopString"].ConnectionString))
 {
            connection.Open();
            string sql =  "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";
            using(SqlCommand cmd = new SqlCommand(sql,connection)) 
            {
                  cmd.Parameters.Add("@param1", SqlDbType.Int).value = klantId;  
                  cmd.Parameters.Add("@param2", SqlDbType.Varchar, 50).value = klantNaam;
                  cmd.Parameters.Add("@param3", SqlDbType.Varchar, 50).value = klantVoornaam;
                  cmd.CommandType = CommandType.Text;
                  cmd.ExecuteNonQuery(); 
            }
 }

How do I make bootstrap table rows clickable?

That code transforms any bootstrap table row that has data-href attribute set into a clickable element

Note: data-href attribute is a valid tr attribute (HTML5), href attributes on tr element are not.

$(function(){
    $('.table tr[data-href]').each(function(){
        $(this).css('cursor','pointer').hover(
            function(){ 
                $(this).addClass('active'); 
            },  
            function(){ 
                $(this).removeClass('active'); 
            }).click( function(){ 
                document.location = $(this).attr('data-href'); 
            }
        );
    });
});

'LIKE ('%this%' OR '%that%') and something=else' not working

Break out the LIKE clauses into 2 separate statements, i.e.:

(fieldname1 LIKE '%this%' or fieldname1 LIKE '%that%' ) and something=else

How do I break out of a loop in Scala?

The third-party breakable package is one possible alternative

https://github.com/erikerlandson/breakable

Example code:

scala> import com.manyangled.breakable._
import com.manyangled.breakable._

scala> val bkb2 = for {
     |   (x, xLab) <- Stream.from(0).breakable   // create breakable sequence with a method
     |   (y, yLab) <- breakable(Stream.from(0))  // create with a function
     |   if (x % 2 == 1) continue(xLab)          // continue to next in outer "x" loop
     |   if (y % 2 == 0) continue(yLab)          // continue to next in inner "y" loop
     |   if (x > 10) break(xLab)                 // break the outer "x" loop
     |   if (y > x) break(yLab)                  // break the inner "y" loop
     | } yield (x, y)
bkb2: com.manyangled.breakable.Breakable[(Int, Int)] = com.manyangled.breakable.Breakable@34dc53d2

scala> bkb2.toVector
res0: Vector[(Int, Int)] = Vector((2,1), (4,1), (4,3), (6,1), (6,3), (6,5), (8,1), (8,3), (8,5), (8,7), (10,1), (10,3), (10,5), (10,7), (10,9))

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

One of the reasons for this error is the use of the jaxb implementation from the jdk. I am not sure why such a problem can appear in pretty simple xml parsing situations. You may use the latest version of the jaxb library from a public maven repository:

http://mvnrepository.com

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.12</version>
</dependency>

How to generate a random string of 20 characters

public String randomString(String chars, int length) {
  Random rand = new Random();
  StringBuilder buf = new StringBuilder();
  for (int i=0; i<length; i++) {
    buf.append(chars.charAt(rand.nextInt(chars.length())));
  }
  return buf.toString();
}

package javax.mail and javax.mail.internet do not exist

I just resolved this for myself, so hope this helps. My project runs on GlassFish 4, Eclipse MARS, with JDK 1.8 and JavaEE 7.

Firstly, you can find javax.mail.jar in the extracted glassfish folder: glassfish4->glassfish->modules

Next, in Eclipse, Right Click on your project in the explorer and navigate the following: Properties->Java Build Path->Libraries->Add External JARs-> Go to the aforementioned folder to add javax.mail.jar

ant warning: "'includeantruntime' was not set"

As @Daniel Kutik mentioned, presetdef is a good option. Especially if one is working on a project with many build.xml files which one cannot, or prefers not to, edit (e.g., those from third-parties.)

To use presetdef, add these lines in your top-level build.xml file:

  <presetdef name="javac">
    <javac includeantruntime="false" />
  </presetdef>

Now all subsequent javac tasks will essentially inherit includeantruntime="false". If your projects do actually need ant runtime libraries, you can either add them explicitly to your build files OR set includeantruntime="true". The latter will also get rid of warnings.

Subsequent javac tasks can still explicitly change this if desired, for example:

<javac destdir="out" includeantruntime="true">
  <src path="foo.java" />
  <src path="bar.java" />
</javac>

I'd recommend against using ANT_OPTS. It works, but it defeats the purpose of the warning. The warning tells one that one's build might behave differently on another system. Using ANT_OPTS makes this even more likely because now every system needs to use ANT_OPTS in the same way. Also, ANT_OPTS will apply globally, suppressing warnings willy-nilly in all your projects

How can I make my own event in C#?

I have a full discussion of events and delegates in my events article. For the simplest kind of event, you can just declare a public event and the compiler will create both an event and a field to keep track of subscribers:

public event EventHandler Foo;

If you need more complicated subscription/unsubscription logic, you can do that explicitly:

public event EventHandler Foo
{
    add
    {
        // Subscription logic here
    }
    remove
    {
        // Unsubscription logic here
    }
}

Bootstrap modal link

Please remove . from your target it should be a id

<a href="#bannerformmodal" data-toggle="modal" data-target="#bannerformmodal">Load me</a>

Also you have to give your modal id like below

<div class="modal fade bannerformmodal" tabindex="-1" role="dialog" aria-labelledby="bannerformmodal" aria-hidden="true" id="bannerformmodal">

Here is the solution in a fiddle.

Replace substring with another substring C++

the impoved version by @Czarek Tomczak.
allow both std::string and std::wstring.

template <typename charType>
void ReplaceSubstring(std::basic_string<charType>& subject,
    const std::basic_string<charType>& search,
    const std::basic_string<charType>& replace)
{
    if (search.empty()) { return; }
    typename std::basic_string<charType>::size_type pos = 0;
    while((pos = subject.find(search, pos)) != std::basic_string<charType>::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

programmatically add column & rows to WPF Datagrid

I had the same problem. Adding new rows to WPF DataGrid requires a trick. DataGrid relies on property fields of an item object. ExpandoObject enables to add new properties dynamically. The code below explains how to do it:

// using System.Dynamic;

DataGrid dataGrid;

string[] labels = new string[] { "Column 0", "Column 1", "Column 2" };

foreach (string label in labels)
{
    DataGridTextColumn column = new DataGridTextColumn();
    column.Header = label;
    column.Binding = new Binding(label.Replace(' ', '_'));

    dataGrid.Columns.Add(column);
}

int[] values = new int[] { 0, 1, 2 };

dynamic row = new ExpandoObject();

for (int i = 0; i < labels.Length; i++)
    ((IDictionary<String, Object>)row)[labels[i].Replace(' ', '_')] = values[i];

dataGrid.Items.Add(row);

//edit:

Note that this is not the way how the component should be used, however, it simplifies a lot if you have only programmatically generated data (eg. in my case: a sequence of features and neural network output).

Process escape sequences in a string in Python

The actually correct and convenient answer for python 3:

>>> import codecs
>>> myString = "spam\\neggs"
>>> print(codecs.escape_decode(bytes(myString, "utf-8"))[0].decode("utf-8"))
spam
eggs
>>> myString = "naïve \\t test"
>>> print(codecs.escape_decode(bytes(myString, "utf-8"))[0].decode("utf-8"))
naïve    test

Details regarding codecs.escape_decode:

  • codecs.escape_decode is a bytes-to-bytes decoder
  • codecs.escape_decode decodes ascii escape sequences, such as: b"\\n" -> b"\n", b"\\xce" -> b"\xce".
  • codecs.escape_decode does not care or need to know about the byte object's encoding, but the encoding of the escaped bytes should match the encoding of the rest of the object.

Background:

  • @rspeer is correct: unicode_escape is the incorrect solution for python3. This is because unicode_escape decodes escaped bytes, then decodes bytes to unicode string, but receives no information regarding which codec to use for the second operation.
  • @Jerub is correct: avoid the AST or eval.
  • I first discovered codecs.escape_decode from this answer to "how do I .decode('string-escape') in Python3?". As that answer states, that function is currently not documented for python 3.

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

You have more static resources that the cache has room for. You can do one of the following:

  • Increase the size of the cache
  • Decrease the TTL for the cache
  • Disable caching

For more details see the documentation for these configuration options.

Differences between SP initiated SSO and IDP initiated SSO

IDP Initiated SSO

From PingFederate documentation :- https://docs.pingidentity.com/bundle/pf_sm_supportedStandards_pf82/page/task/idpInitiatedSsoPOST.html

In this scenario, a user is logged on to the IdP and attempts to access a resource on a remote SP server. The SAML assertion is transported to the SP via HTTP POST.

Processing Steps:

  1. A user has logged on to the IdP.
  2. The user requests access to a protected SP resource. The user is not logged on to the SP site.
  3. Optionally, the IdP retrieves attributes from the user data store.
  4. The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP.

SP Initiated SSO

From PingFederate documentation:- http://documentation.pingidentity.com/display/PF610/SP-Initiated+SSO--POST-POST

In this scenario a user attempts to access a protected resource directly on an SP Web site without being logged on. The user does not have an account on the SP site, but does have a federated account managed by a third-party IdP. The SP sends an authentication request to the IdP. Both the request and the returned SAML assertion are sent through the user’s browser via HTTP POST.

Processing Steps:

  1. The user requests access to a protected SP resource. The request is redirected to the federation server to handle authentication.
  2. The federation server sends an HTML form back to the browser with a SAML request for authentication from the IdP. The HTML form is automatically posted to the IdP’s SSO service.
  3. If the user is not already logged on to the IdP site or if re-authentication is required, the IdP asks for credentials (e.g., ID and password) and the user logs on.
  4. Additional information about the user may be retrieved from the user data store for inclusion in the SAML response. (These attributes are predetermined as part of the federation agreement between the IdP and the SP)

  5. The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP. NOTE: SAML specifications require that POST responses be digitally signed.

  6. (Not shown) If the signature and assertion are valid, the SP establishes a session for the user and redirects the browser to the target resource.

c# foreach (property in object)... Is there a simple way of doing this?

Give this a try:

foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
   // do stuff here
}

Also please note that Type.GetProperties() has an overload which accepts a set of binding flags so you can filter out properties on a different criteria like accessibility level, see MSDN for more details: Type.GetProperties Method (BindingFlags) Last but not least don't forget to add the "system.Reflection" assembly reference.

For instance to resolve all public properties:

foreach (var propertyInfo in obj.GetType()
                                .GetProperties(
                                        BindingFlags.Public 
                                        | BindingFlags.Instance))
{
   // do stuff here
}

Please let me know whether this works as expected.

How to calculate moving average without keeping the count and data-total?

From a blog on running sample variance calculations, where the mean is also calculated using Welford's method:

enter image description here

Too bad we can't upload SVG images.

How to search for file names in Visual Studio?

With Visual Studio 2017 Community edition on mac, the shortcut is:

  • Cmd+Shift+D: Find by file name
  • Cmd+Shift+T: Find by type name

To see these commands, navigate to the top menu: Search > Go To

What is the proper REST response code for a valid request but an empty data?

In this scenario Ruby on Rails responses with 404 Not Found.

404 Not Found is more appropriate.

Split bash string by newline characters

There is another way if all you want is the text up to the first line feed:

x='some
thing'

y=${x%$'\n'*}

After that y will contain some and nothing else (no line feed).

What is happening here?

We perform a parameter expansion substring removal (${PARAMETER%PATTERN}) for the shortest match up to the first ANSI C line feed ($'\n') and drop everything that follows (*).

How to set MimeBodyPart ContentType to "text/html"?

Don't know why (the method is not documented), but by looking at the source code, this line should do it :

mime_body_part.setHeader("Content-Type", "text/html");

Ajax passing data to php script

You can also use bellow code for pass data using ajax.

var dataString = "album" + title;
$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: dataString,
    success: function(response) {
        content.html(response);
    }
});

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

As stated by user2246674, using success and error as parameter of the ajax function is valid.

To be consistent with precedent answer, reading the doc :

Deprecation Notice:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

If you are using the callback-manipulation function (using method-chaining for example), use .done(), .fail() and .always() instead of success(), error() and complete().

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

Gulp doesn't offer any kind of util for that, but you can use one of the many command args parsers. I like yargs. Should be:

var argv = require('yargs').argv;

gulp.task('my-task', function() {
    return gulp.src(argv.a == 1 ? options.SCSS_SOURCE : options.OTHER_SOURCE)
        .pipe(sass({style:'nested'}))
        .pipe(autoprefixer('last 10 version'))
        .pipe(concat('style.css'))
        .pipe(gulp.dest(options.SCSS_DEST));
});

You can also combine it with gulp-if to conditionally pipe the stream, very useful for dev vs. prod building:

var argv = require('yargs').argv,
    gulpif = require('gulp-if'),
    rename = require('gulp-rename'),
    uglify = require('gulp-uglify');

gulp.task('my-js-task', function() {
  gulp.src('src/**/*.js')
    .pipe(concat('out.js'))
    .pipe(gulpif(argv.production, uglify()))
    .pipe(gulpif(argv.production, rename({suffix: '.min'})))
    .pipe(gulp.dest('dist/'));
});

And call with gulp my-js-task or gulp my-js-task --production.

Get all child views inside LinearLayout at once

Get all views from any type of layout

public List<View> getAllViews(ViewGroup layout){
        List<View> views = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            views.add(layout.getChildAt(i));
        }
        return views;
}

Get all TextView from any type of layout

public List<TextView> getAllTextViews(ViewGroup layout){
        List<TextView> views = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            View v =layout.getChildAt(i);
            if(v instanceof TextView){
                views.add((TextView)v);
            }
        }
        return views;
}

Vendor code 17002 to connect to SQLDeveloper

Listed are the steps that could rectify the error:

  1. Press Windows+R
  2. Type services.msc and strike Enter
  3. Find all services
  4. Starting with ora start these services and wait!!
  5. When your server specific service is initialized (in my case it was orcl)
  6. Now run mysql or whatever you are using and start coding.P

Catching an exception while using a Python 'with' statement

from __future__ import with_statement

try:
    with open( "a.txt" ) as f :
        print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
    print 'oops'

If you want different handling for errors from the open call vs the working code you could do:

try:
    f = open('foo.txt')
except IOError:
    print('error')
else:
    with f:
        print f.readlines()

Android Emulator sdcard push error: Read-only file system

I increased the virtual memory of sdcard up to 512 MB for the emulator and that was enough

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

What's the best CRLF (carriage return, line feed) handling strategy with Git?

--- UPDATE 3 --- (does not conflict with UPDATE 2)

Considering the case that windows users prefer working on CRLF and linux/mac users prefer working on LF on text files. Providing the answer from the perspective of a repository maintainer:

For me the best strategy(less problems to solve) is: keep all text files with LF inside git repo even if you are working on a windows-only project. Then give the freedom to clients to work on the line-ending style of their preference, provided that they pick a core.autocrlf property value that will respect your strategy (LF on repo) while staging files for commit.

Staging is what many people confuse when trying to understand how newline strategies work. It is essential to undestand the following points before picking the correct value for core.autocrlf property:

  • Adding a text file for commit (staging it) is like copying the file to another place inside .git/ sub-directory with converted line-endings (depending on core.autocrlf value on your client config). All this is done locally.
  • setting core.autocrlf is like providing an answer to the question (exact same question on all OS):
    • "Should git-client a. convert LF-to-CRLF when checking-out (pulling) the repo changes from the remote or b. convert CRLF-to-LF when adding a file for commit?" and the possible answers (values) are:
    • false: "do none of the above",
    • input: "do only b"
    • true: "do a and and b"
    • note that there is NO "do only a"

Fortunately

  • git client defaults (windows: core.autocrlf: true, linux/mac: core.autocrlf: false) will be compatible with LF-only-repo strategy.
    Meaning: windows clients will by default convert to CRLF when checking-out the repository and convert to LF when adding for commit. And linux clients will by default not do any conversions. This theoretically keeps your repo lf-only.

Unfortunately:

  • There might be GUI clients that do not respect the git core.autocrlf value
  • There might be people that don't use a value to respect your lf-repo strategy. E.g. they use core.autocrlf=false and add a file with CRLF for commit.

To detect ASAP non-lf text files committed by the above clients you can follow what is described on --- update 2 ---: (git grep -I --files-with-matches --perl-regexp '\r' HEAD, on a client compiled using: --with-libpcre flag)

And here is the catch:. I as a repo maintainer keep a git.autocrlf=input so that I can fix any wrongly committed files just by adding them again for commit. And I provide a commit text: "Fixing wrongly committed files".

As far as .gitattributes is concearned. I do not count on it, because there are more ui clients that do not understand it. I only use it to provide hints for text and binary files, and maybe flag some exceptional files that should everywhere keep the same line-endings:

*.java          text !eol # Don't do auto-detection. Treat as text (don't set any eol rule. use client's)
*.jpg           -text     # Don't do auto-detection. Treat as binary
*.sh            text eol=lf # Don't do auto-detection. Treat as text. Checkout and add with eol=lf
*.bat           text eol=crlf # Treat as text. Checkout and add with eol=crlf

Question: But why are we interested at all in newline handling strategy?

Answer: To avoid a single letter change commit, appear as a 5000-line change, just because the client that performed the change auto-converted the full file from crlf to lf (or the opposite) before adding it for commit. This can be rather painful when there is a conflict resolution involved. Or it could in some cases be the cause of unreasonable conflicts.


--- UPDATE 2 ---

The dafaults of git client will work in most cases. Even if you only have windows only clients, linux only clients or both. These are:

  • windows: core.autocrlf=true means convert lines to CRLF on checkout and convert lines to LF when adding files.
  • linux: core.autocrlf=input means don't convert lines on checkout (no need to since files are expected to be committed with LF) and convert lines to LF (if needed) when adding files. (-- update3 -- : Seems that this is false by default, but again it is fine)

The property can be set in different scopes. I would suggest explicitly setting in the --global scope, to avoid some IDE issues described at the end.

git config core.autocrlf
git config --global core.autocrlf
git config --system core.autocrlf
git config --local core.autocrlf
git config --show-origin core.autocrlf

Also I would strongly discourage using on windows git config --global core.autocrlf false (in case you have windows only clients) in contrast to what is proposed to git documentation. Setting to false will commit files with CRLF in the repo. But there is really no reason. You never know whether you will need to share the project with linux users. Plus it's one extra step for each client that joins the project instead of using defaults.

Now for some special cases of files (e.g. *.bat *.sh) which you want them to be checked-out with LF or with CRLF you can use .gitattributes

To sum-up for me the best practice is:

  • Make sure that every non-binary file is committed with LF on git repo (default behaviour).
  • Use this command to make sure that no files are committed with CRLF: git grep -I --files-with-matches --perl-regexp '\r' HEAD (Note: on windows clients works only through git-bash and on linux clients only if compiled using --with-libpcre in ./configure).
  • If you find any such files by executing the above command, correct them. This in involves (at least on linux):
    • set core.autocrlf=input (--- update 3 --)
    • change the file
    • revert the change(file is still shown as changed)
    • commit it
  • Use only the bare minimum .gitattributes
  • Instruct the users to set the core.autocrlf described above to its default values.
  • Do not count 100% on the presence of .gitattributes. git-clients of IDEs may ignore them or treat them differrently.

As said some things can be added in git attributes:

# Always checkout with LF
*.sh            text eol=lf
# Always checkout with CRLF
*.bat           text eol=crlf

I think some other safe options for .gitattributes instead of using auto-detection for binary files:

  • -text (e.g for *.zip or *.jpg files: Will not be treated as text. Thus no line-ending conversions will be attempted. Diff might be possible through conversion programs)
  • text !eol (e.g. for *.java,*.html: Treated as text, but eol style preference is not set. So client setting is used.)
  • -text -diff -merge (e.g for *.hugefile: Not treated as text. No diff/merge possible)

--- PREVIOUS UPDATE ---

One painful example of a client that will commit files wrongly:

netbeans 8.2 (on windows), will wrongly commit all text files with CRLFs, unless you have explicitly set core.autocrlf as global. This contradicts to the standard git client behaviour, and causes lots of problems later, while updating/merging. This is what makes some files appear different (although they are not) even when you revert.
The same behaviour in netbeans happens even if you have added correct .gitattributes to your project.

Using the following command after a commit, will at least help you detect early whether your git repo has line ending issues: git grep -I --files-with-matches --perl-regexp '\r' HEAD

I have spent hours to come up with the best possible use of .gitattributes, to finally realize, that I cannot count on it.
Unfortunately, as long as JGit-based editors exist (which cannot handle .gitattributes correctly), the safe solution is to force LF everywhere even on editor-level.

Use the following anti-CRLF disinfectants.