Programs & Examples On #Type conversion

Type conversion is the way of implicitly or explicitly changing an entity of one data type into another. This is done to take advantage of certain features of type hierarchies or type representations.

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.

Converting char[] to byte[]

char[] ch = ?
new String(ch).getBytes();

or

new String(ch).getBytes("UTF-8");

to get non-default charset.

Update: Since Java 7: new String(ch).getBytes(StandardCharsets.UTF_8);

How to convert DateTime to a number with a precision greater than days in T-SQL?

If the purpose of this is to create a unique value from the date, here is what I would do

DECLARE @ts TIMESTAMP 
SET @ts = CAST(getdate() AS TIMESTAMP)
SELECT @ts

This gets the date and declares it as a simple timestamp

Import pandas dataframe column as string not int

Since pandas 1.0 it became much more straightforward. This will read column 'ID' as dtype 'string':

pd.read_csv('sample.csv',dtype={'ID':'string'})

As we can see in this Getting started guide, 'string' dtype has been introduced (before strings were treated as dtype 'object').

how to write value into cell with vba code without auto type conversion?

Cells(1,1).Value2 = "'123,456"

note the single apostrophe before the number - this will signal to excel that whatever follows has to be interpreted as text.

How can I convert a string with dot and comma into a float in Python

If you don't know the locale and you want to parse any kind of number, use this parseNumber(text) function. It is not perfect but take into account most cases :

>>> parseNumber("a 125,00 €")
125
>>> parseNumber("100.000,000")
100000
>>> parseNumber("100 000,000")
100000
>>> parseNumber("100,000,000")
100000000
>>> parseNumber("100 000 000")
100000000
>>> parseNumber("100.001 001")
100.001
>>> parseNumber("$.3")
0.3
>>> parseNumber(".003")
0.003
>>> parseNumber(".003 55")
0.003
>>> parseNumber("3 005")
3005
>>> parseNumber("1.190,00 €")
1190
>>> parseNumber("1190,00 €")
1190
>>> parseNumber("1,190.00 €")
1190
>>> parseNumber("$1190.00")
1190
>>> parseNumber("$1 190.99")
1190.99
>>> parseNumber("1 000 000.3")
1000000.3
>>> parseNumber("1 0002,1.2")
10002.1
>>> parseNumber("")

>>> parseNumber(None)

>>> parseNumber(1)
1
>>> parseNumber(1.1)
1.1
>>> parseNumber("rrr1,.2o")
1
>>> parseNumber("rrr ,.o")

>>> parseNumber("rrr1rrr")
1

SQL error "ORA-01722: invalid number"

This is because:

You executed an SQL statement that tried to convert a string to a number, but it was unsuccessful.

As explained in:

To resolve this error:

Only numeric fields or character fields that contain numeric values can be used in arithmetic operations. Make sure that all expressions evaluate to numbers.

Converting List<String> to String[] in Java

You want

String[] strarray = strlist.toArray(new String[0]);

See here for the documentation and note that you can also call this method in such a way that it populates the passed array, rather than just using it to work out what type to return. Also note that maybe when you print your array you'd prefer

System.out.println(Arrays.toString(strarray));

since that will print the actual elements.

How to convert string to integer in C#

If you are sure that you have "real" number in your string, or you are comfortable of any exception that might arise, use this.

string s="4";
int a=int.Parse(s);

For some more control over the process, use

string s="maybe 4";
int a;
if (int.TryParse(s, out a)) {
    // it's int;
}
else {
    // it's no int, and there's no exception;
}

How do I convert a string to a number in PHP?

In PHP you can use intval(string) or floatval(string) functions to convert strings to numbers.

Setting a property by reflection with a string value

If you are writing Metro app, you should use other code:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetTypeInfo().GetDeclaredProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType));

Note:

ship.GetType().GetTypeInfo().GetDeclaredProperty("Latitude");

instead of

ship.GetType().GetProperty("Latitude");

java : convert float to String and String to float

Float to string - String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

String to Float - Float.parseFloat()

String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

How to convert QString to std::string?

You can use this;

QString data;
data.toStdString().c_str();

how to convert a string to a bool

Ignoring the specific needs of this question, and while its never a good idea to cast a string to a bool, one way would be to use the ToBoolean() method on the Convert class:

bool val = Convert.ToBoolean("true");

or an extension method to do whatever weird mapping you're doing:

public static class StringExtensions
{
    public static bool ToBoolean(this string value)
    {
        switch (value.ToLower())
        {
            case  "true":
                return true;
            case "t":
                return true;
            case "1":
                return true;
            case "0":
                return false;
            case "false":
                return false;
            case "f":
                return false;
            default:
                throw new InvalidCastException("You can't cast that value to a bool!");
        }
    }
}

Convert string to integer type in Go?

For example,

package main

import (
    "flag"
    "fmt"
    "os"
    "strconv"
)

func main() {
    flag.Parse()
    s := flag.Arg(0)
    // string to int
    i, err := strconv.Atoi(s)
    if err != nil {
        // handle error
        fmt.Println(err)
        os.Exit(2)
    }
    fmt.Println(s, i)
}

Ruby: How to convert a string to boolean

If you use Rails 5, you can do ActiveModel::Type::Boolean.new.cast(value).

In Rails 4.2, use ActiveRecord::Type::Boolean.new.type_cast_from_user(value).

The behavior is slightly different, as in Rails 4.2, the true value and false values are checked. In Rails 5, only false values are checked - unless the values is nil or matches a false value, it is assumed to be true. False values are the same in both versions: FALSE_VALUES = [false, 0, "0", "f", "F", "false", "FALSE", "off", "OFF"]

Rails 5 Source: https://github.com/rails/rails/blob/5-1-stable/activemodel/lib/active_model/type/boolean.rb

How to convert a Date to a formatted string in VB.net?

myDate.ToString("yyyy-MM-dd HH:mm:ss")

the capital HH is for 24 hours format as you specified

How to determine an interface{} value's "real" type?

You also can do type switches:

switch v := myInterface.(type) {
case int:
    // v is an int here, so e.g. v + 1 is possible.
    fmt.Printf("Integer: %v", v)
case float64:
    // v is a float64 here, so e.g. v + 1.0 is possible.
    fmt.Printf("Float64: %v", v)
case string:
    // v is a string here, so e.g. v + " Yeah!" is possible.
    fmt.Printf("String: %v", v)
default:
    // And here I'm feeling dumb. ;)
    fmt.Printf("I don't know, ask stackoverflow.")
}

How to convert char* to wchar_t*?

You're returning the address of a local variable allocated on the stack. When your function returns, the storage for all local variables (such as wc) is deallocated and is subject to being immediately overwritten by something else.

To fix this, you can pass the size of the buffer to GetWC, but then you've got pretty much the same interface as mbstowcs itself. Or, you could allocate a new buffer inside GetWC and return a pointer to that, leaving it up to the caller to deallocate the buffer.

How can I convert a char to int in Java?

If you want to get the ASCII value of a character, or just convert it into an int, you need to cast from a char to an int.

What's casting? Casting is when we explicitly convert from one primitve data type, or a class, to another. Here's a brief example.

public class char_to_int
{
  public static void main(String args[])
  {
       char myChar = 'a';
       int  i = (int) myChar; // cast from a char to an int
       System.out.println ("ASCII value - " + i);
  }

In this example, we have a character ('a'), and we cast it to an integer. Printing this integer out will give us the ASCII value of 'a'.

Convert String to double in Java

This is what I would do

    public static double convertToDouble(String temp){
       String a = temp;
       //replace all commas if present with no comma
       String s = a.replaceAll(",","").trim(); 
      // if there are any empty spaces also take it out.          
      String f = s.replaceAll(" ", ""); 
      //now convert the string to double
      double result = Double.parseDouble(f); 
    return result; // return the result
}

For example you input the String "4 55,63. 0 " the output will the double number 45563.0

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Converting string to double in C#

You can try this example out. A simple C# progaram to convert string to double

class Calculations{

protected double length;
protected double height;
protected double width;

public void get_data(){

this.length = Convert.ToDouble(Console.ReadLine());
this.width  = Convert.ToDouble(Console.ReadLine());
this.height = Convert.ToDouble(Console.ReadLine());

   }
}

Can I convert long to int?

Sometimes you're not actually interested in the actual value, but in its usage as checksum/hashcode. In this case, the built-in method GetHashCode() is a good choice:

int checkSumAsInt32 = checkSumAsIn64.GetHashCode();

Convert string to nullable type (int, double, etc...)

Here's something based on accepted answer. I removed the try/catch to make sure all the exceptions are not swallowed and not dealt with. Also made sure that the return variable (in accepted answer) is never initialized twice for nothing.

public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
    if (!string.IsNullOrWhiteSpace(s))
    {
        TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));

        return (T)conv.ConvertFrom(s);
    }

    return default(Nullable<T>);
}

Date Conversion from String to sql Date in Java giving different output?

While using the date formats, you may want to keep in mind to always use MM for months and mm for minutes. That should resolve your problem.

Returning Month Name in SQL Server Query

for me DATENAME was not accessable due to company restrictions.... but this worked very easy too.

FORMAT(date, 'MMMM') AS month

Converting integer to digit list

you can use:

First convert the value in a string to iterate it, Them each value can be convert to a Integer value = 12345

l = [ int(item) for item in str(value) ]

How to convert numbers between hexadecimal and decimal

class HexToDecimal
{
    static void Main()
    {
        while (true)
        {
            Console.Write("Enter digit number to convert: ");
            int n = int.Parse(Console.ReadLine()); // set hexadecimal digit number  
            Console.Write("Enter hexadecimal number: ");
            string str = Console.ReadLine();
            str.Reverse();

            char[] ch = str.ToCharArray();
            int[] intarray = new int[n];

            decimal decimalval = 0;

            for (int i = ch.Length - 1; i >= 0; i--)
            {
                if (ch[i] == '0')
                    intarray[i] = 0;
                if (ch[i] == '1')
                    intarray[i] = 1;
                if (ch[i] == '2')
                    intarray[i] = 2;
                if (ch[i] == '3')
                    intarray[i] = 3;
                if (ch[i] == '4')
                    intarray[i] = 4;
                if (ch[i] == '5')
                    intarray[i] = 5;
                if (ch[i] == '6')
                    intarray[i] = 6;
                if (ch[i] == '7')
                    intarray[i] = 7;
                if (ch[i] == '8')
                    intarray[i] = 8;
                if (ch[i] == '9')
                    intarray[i] = 9;
                if (ch[i] == 'A')
                    intarray[i] = 10;
                if (ch[i] == 'B')
                    intarray[i] = 11;
                if (ch[i] == 'C')
                    intarray[i] = 12;
                if (ch[i] == 'D')
                    intarray[i] = 13;
                if (ch[i] == 'E')
                    intarray[i] = 14;
                if (ch[i] == 'F')
                    intarray[i] = 15;

                decimalval += intarray[i] * (decimal)Math.Pow(16, ch.Length - 1 - i);

            }

            Console.WriteLine(decimalval);
        }

    }

}

convert double to int

if you use cast, that is, (int)SomeDouble you will truncate the fractional part. That is, if SomeDouble were 4.9999 the result would be 4, not 5. Converting to int doesn't round the number. If you want rounding use Math.Round

Convert a Unicode string to a string in Python (containing extra symbols)

>>> text=u'abcd'
>>> str(text)
'abcd'

If the string only contains ascii characters.

SQL Server: Error converting data type nvarchar to numeric

You might need to revise the data in the column, but anyway you can do one of the following:-

1- check if it is numeric then convert it else put another value like 0

Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA) 
ELSE 0 END AS COLUMNA

2- select only numeric values from the column

SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1

C++ floating point to integer type conversions

I believe you can do this using a cast:

float f_val = 3.6f;
int i_val = (int) f_val;

Convert data.frame column to a vector?

There's now an easy way to do this using dplyr.

dplyr::pull(aframe, a2)

Convert textbox text to integer

Suggest do this in your code-behind before sending down to SQL Server.

 int userVal = int.Parse(txtboxname.Text);

Perhaps try to parse and optionally let the user know.

int? userVal;
if (int.TryParse(txtboxname.Text, out userVal) 
{
  DoSomething(userVal.Value);
}
else
{ MessageBox.Show("Hey, we need an int over here.");   }

The exception you note means that you're not including the value in the call to the stored proc. Try setting a debugger breakpoint in your code at the time you call down into the code that builds the call to SQL Server.

Ensure you're actually attaching the parameter to the SqlCommand.

using (SqlConnection conn = new SqlConnection(connString))
{
    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.Parameters.Add("@ParamName", SqlDbType.Int);
    cmd.Parameters["@ParamName"].Value = newName;        
    conn.Open();
    string someReturn = (string)cmd.ExecuteScalar();        
}

Perhaps fire up SQL Profiler on your database to inspect the SQL statement being sent/executed.

How can I convert a string to a float in mysql?

It turns out I was just missing DECIMAL on the CAST() description:

DECIMAL[(M[,D])]

Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.

Thus, the following query worked:

UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));

How to convert UTF-8 byte[] to string?

There're at least four different ways doing this conversion.

  1. Encoding's GetString
    , but you won't be able to get the original bytes back if those bytes have non-ASCII characters.

  2. BitConverter.ToString
    The output is a "-" delimited string, but there's no .NET built-in method to convert the string back to byte array.

  3. Convert.ToBase64String
    You can easily convert the output string back to byte array by using Convert.FromBase64String.
    Note: The output string could contain '+', '/' and '='. If you want to use the string in a URL, you need to explicitly encode it.

  4. HttpServerUtility.UrlTokenEncode
    You can easily convert the output string back to byte array by using HttpServerUtility.UrlTokenDecode. The output string is already URL friendly! The downside is it needs System.Web assembly if your project is not a web project.

A full example:

byte[] bytes = { 130, 200, 234, 23 }; // A byte array contains non-ASCII (or non-readable) characters

string s1 = Encoding.UTF8.GetString(bytes); // ???
byte[] decBytes1 = Encoding.UTF8.GetBytes(s1);  // decBytes1.Length == 10 !!
// decBytes1 not same as bytes
// Using UTF-8 or other Encoding object will get similar results

string s2 = BitConverter.ToString(bytes);   // 82-C8-EA-17
String[] tempAry = s2.Split('-');
byte[] decBytes2 = new byte[tempAry.Length];
for (int i = 0; i < tempAry.Length; i++)
    decBytes2[i] = Convert.ToByte(tempAry[i], 16);
// decBytes2 same as bytes

string s3 = Convert.ToBase64String(bytes);  // gsjqFw==
byte[] decByte3 = Convert.FromBase64String(s3);
// decByte3 same as bytes

string s4 = HttpServerUtility.UrlTokenEncode(bytes);    // gsjqFw2
byte[] decBytes4 = HttpServerUtility.UrlTokenDecode(s4);
// decBytes4 same as bytes

How Do I Convert an Integer to a String in Excel VBA?

enter image description here

    Sub NumToText(ByRef sRng As String, Optional ByVal WS As Worksheet)
    '---Converting visible range form Numbers to Text
        Dim Temp As Double
        Dim vRng As Range
        Dim Cel As Object

        If WS Is Nothing Then Set WS = ActiveSheet
            Set vRng = WS.Range(sRng).SpecialCells(xlCellTypeVisible)
            For Each Cel In vRng
                If Not IsEmpty(Cel.Value) And IsNumeric(Cel.Value) Then
                    Temp = Cel.Value
                    Cel.ClearContents
                    Cel.NumberFormat = "@"
                    Cel.Value = CStr(Temp)
                End If
            Next Cel
    End Sub


    Sub Macro1()
        Call NumToText("A2:A100", ActiveSheet)
    End Sub

Reffer: MrExcel.com – Convert numbers to text with VBA

Difference between Convert.ToString() and .ToString()

You can create a class and override the toString method to do anything you want.

For example- you can create a class "MyMail" and override the toString method to send an email or do some other operation instead of writing the current object.

The Convert.toString converts the specified value to its equivalent string representation.

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

Documentation for parseDouble() says "Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.", so they should be identical.

Is true == 1 and false == 0 in JavaScript?

Use === to equate the variables instead of ==.

== checks if the value of the variables is similar

=== checks if the value of the variables and the type of the variables are similar

Notice how

if(0===false) {
    document.write("oh!!! that's true");
}?

and

if(0==false) {
    document.write("oh!!! that's true");
}?

give different results

Signed to unsigned conversion in C - is it always safe?

Referring to the bible:

  • Your addition operation causes the int to be converted to an unsigned int.
  • Assuming two's complement representation and equally sized types, the bit pattern does not change.
  • Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)
  • The rules are a little more complicated in the case of combining signed and unsigned of differing sizes.

How to convert a boolean array to an int array

Most of the time you don't need conversion:

>>>array([True,True,False,False]) + array([1,2,3,4])
array([2, 3, 3, 4])

The right way to do it is:

yourArray.astype(int)

or

yourArray.astype(float)

How to convert integer to string in C?

Making your own itoa is also easy, try this :

char* itoa(int i, char b[]){
    char const digit[] = "0123456789";
    char* p = b;
    if(i<0){
        *p++ = '-';
        i *= -1;
    }
    int shifter = i;
    do{ //Move to where representation ends
        ++p;
        shifter = shifter/10;
    }while(shifter);
    *p = '\0';
    do{ //Move back, inserting digits as u go
        *--p = digit[i%10];
        i = i/10;
    }while(i);
    return b;
}

or use the standard sprintf() function.

PHP Converting Integer to Date, reverse of strtotime

The time() function displays the seconds between now and the unix epoch , 01 01 1970 (00:00:00 GMT). The strtotime() transforms a normal date format into a time() format. So the representation of that date into seconds will be : 1388516401

Source: http://www.php.net/time

Convert string into Date type on Python

from datetime import datetime

a = datetime.strptime(f, "%Y-%m-%d")

How to convert a number to string and vice versa in C++

#include <iostream>
#include <string.h>
using namespace std;
int main() {
   string s="000101";
   cout<<s<<"\n";
   int a = stoi(s);
   cout<<a<<"\n";
   s=to_string(a);
   s+='1';
   cout<<s;
   return 0;
}

Output:

  • 000101
  • 101
  • 1011

Convert Map<String,Object> to Map<String,String>

The following will transform your existing entries.

TransformedMap.decorateTransform(params, keyTransformer, valueTransformer)

Where as

MapUtils.transformedMap(java.util.Map map, keyTransformer, valueTransformer)

only transforms new entries into your map

How can I convert string to datetime with format specification in JavaScript?

Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.

If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.

How to convert integer to decimal in SQL Server query?

You can either cast Height as a decimal:

select cast(@height as decimal(10, 5))/10 as heightdecimal

or you place a decimal point in your value you are dividing by:

declare @height int
set @height = 1023

select @height/10.0 as heightdecimal

see sqlfiddle with an example

pandas dataframe convert column type to string or categorical

To convert a column into a string type (that will be an object column per se in pandas), use astype:

df.zipcode = zipcode.astype(str)

If you want to get a Categorical column, you can pass the parameter 'category' to the function:

df.zipcode = zipcode.astype('category')

How to convert NUM to INT in R?

You can use convert from hablar to change a column of the data frame quickly.

library(tidyverse)
library(hablar)

x <- tibble(var = c(1.34, 4.45, 6.98))

x %>% 
  convert(int(var))

gives you:

# A tibble: 3 x 1
    var
  <int>
1     1
2     4
3     6

How to convert / cast long to String?

String longString = new String(""+long);

or

String longString = new Long(datelong).toString();

Converting a string to a date in JavaScript

Pass it as an argument to Date():

var st = "date in some format"
var dt = new Date(st);

You can access the date, month, year using, for example: dt.getMonth().

How do I convert Long to byte[] and back in java

I find this method to be most friendly.

var b = BigInteger.valueOf(x).toByteArray();

var l = new BigInteger(b);

Convert columns to string in Pandas

One way to convert to string is to use astype:

total_rows['ColumnID'] = total_rows['ColumnID'].astype(str)

However, perhaps you are looking for the to_json function, which will convert keys to valid json (and therefore your keys to strings):

In [11]: df = pd.DataFrame([['A', 2], ['A', 4], ['B', 6]])

In [12]: df.to_json()
Out[12]: '{"0":{"0":"A","1":"A","2":"B"},"1":{"0":2,"1":4,"2":6}}'

In [13]: df[0].to_json()
Out[13]: '{"0":"A","1":"A","2":"B"}'

Note: you can pass in a buffer/file to save this to, along with some other options...

Convert a character digit to the corresponding integer in C

Just use the atol()function:

#include <stdio.h>
#include <stdlib.h>

int main() 
{
    const char *c = "5";
    int d = atol(c);
    printf("%d\n", d);

}

Leading zeros for Int in Swift

in Xcode 8.3.2, iOS 10.3 Thats is good to now

Sample1:

let dayMoveRaw = 5 
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 05

Sample2:

let dayMoveRaw = 55 
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 55

PostgreSQL: how to convert from Unix epoch to date?

select to_timestamp(cast(epoch_ms/1000 as bigint))::date

worked for me

C convert floating point to int

If you want to round it to lower, just cast it.

float my_float = 42.8f;
int my_int;
my_int = (int)my_float;          // => my_int=42

For other purpose, if you want to round it to nearest, you can make a little function or a define like this:

#define FLOAT_TO_INT(x) ((x)>=0?(int)((x)+0.5):(int)((x)-0.5))

float my_float = 42.8f;
int my_int;
my_int = FLOAT_TO_INT(my_float); // => my_int=43

Be careful, ideally you should verify float is between INT_MIN and INT_MAX before casting it.

Convert INT to VARCHAR SQL

CONVERT(DATA_TYPE , Your_Column) is the syntax for CONVERT method in SQL. From this convert function we can convert the data of the Column which is on the right side of the comma (,) to the data type in the left side of the comma (,) Please see below example.

SELECT CONVERT (VARCHAR(10), ColumnName) FROM TableName

How could I convert data from string to long in c#

long l1 = Convert.ToInt64(strValue);

That should do it.

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

can you try if.else

> col2=ifelse(df1$col=="true",1,0)
> df1
$col
[1] "true"  "false"

> cbind(df1$col)
     [,1]   
[1,] "true" 
[2,] "false"
> cbind(df1$col,col2)
             col2
[1,] "true"  "1" 
[2,] "false" "0" 

How can I convert String to Int?

int myInt = int.Parse(TextBoxD1.Text)

Another way would be:

bool isConvertible = false;
int myInt = 0;

isConvertible = int.TryParse(TextBoxD1.Text, out myInt);

The difference between the two is that the first one would throw an exception if the value in your textbox can't be converted, whereas the second one would just return false.

How to convert string to char array in C++?

Simplest way I can think of doing it is:

string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());

For safety, you might prefer:

string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;

or could be in this fashion:

string temp = "cat";
char * tab2 = new char [temp.length()+1];
strcpy (tab2, temp.c_str());

Call int() function on every list element?

In Python 2.x another approach is to use map:

numbers = map(int, numbers)

Note: in Python 3.x map returns a map object which you can convert to a list if you want:

numbers = list(map(int, numbers))

Convert varchar into datetime in SQL Server

I found this helpful for my conversion, without string manipulation. https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

CONVERT(VARCHAR(23), @lastUploadEndDate, 121)

yyyy-mm-dd hh:mi:ss.mmm(24h) was the format I needed.

Convert integer to hexadecimal and back again

// Store integer 182
int intValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

from http://www.geekpedia.com/KB8_How-do-I-convert-from-decimal-to-hex-and-hex-to-decimal.html

Retrieving the first digit of a number

This example works for any double, not just positive integers and takes into account negative numbers or those less than one. For example, 0.000053 would return 5.

private static int getMostSignificantDigit(double value) {
    value = Math.abs(value);
    if (value == 0) return 0;
    while (value < 1) value *= 10;
    char firstChar = String.valueOf(value).charAt(0);
    return Integer.parseInt(firstChar + "");
}

To get the first digit, this sticks with String manipulation as it is far easier to read.

How to convert a data frame column to numeric type?

To convert character to numeric you have to convert it into factor by applying

BankFinal1 <- transform(BankLoan,   LoanApproval=as.factor(LoanApproval))
BankFinal1 <- transform(BankFinal1, LoanApp=as.factor(LoanApproval))

You have to make two columns with the same data, because one column cannot convert into numeric. If you do one conversion it gives the below error

transform(BankData, LoanApp=as.numeric(LoanApproval))
Warning message:
  In eval(substitute(list(...)), `_data`, parent.frame()) :
  NAs introduced by coercion

so, after doing two column of the same data apply

BankFinal1 <- transform(BankFinal1, LoanApp      = as.numeric(LoanApp), 
                                    LoanApproval = as.numeric(LoanApproval))

it will transform the character to numeric successfully

How to convert a char to a String?

As @WarFox stated - there are 6 methods to convert char to string. However, the fastest one would be via concatenation, despite answers above stating that it is String.valueOf. Here is benchmark that proves that:

@BenchmarkMode(Mode.Throughput)
@Fork(1)
@State(Scope.Thread)
@Warmup(iterations = 10, time = 1, batchSize = 1000, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, batchSize = 1000, timeUnit = TimeUnit.SECONDS)
public class CharToStringConversion {

    private char c = 'c';

    @Benchmark
    public String stringValueOf() {
        return String.valueOf(c);
    }

    @Benchmark
    public String stringValueOfCharArray() {
        return String.valueOf(new char[]{c});
    }

    @Benchmark
    public String characterToString() {
        return Character.toString(c);
    }

    @Benchmark
    public String characterObjectToString() {
        return new Character(c).toString();
    }

    @Benchmark
    public String concatBlankStringPre() {
        return c + "";
    }

    @Benchmark
    public String concatBlankStringPost() {
        return "" + c;
    }

    @Benchmark
    public String fromCharArray() {
        return new String(new char[]{c});
    }
}

And result:

Benchmark                                        Mode  Cnt       Score      Error  Units
CharToStringConversion.characterObjectToString  thrpt   10   82132.021 ± 6841.497  ops/s
CharToStringConversion.characterToString        thrpt   10  118232.069 ± 8242.847  ops/s
CharToStringConversion.concatBlankStringPost    thrpt   10  136960.733 ± 9779.938  ops/s
CharToStringConversion.concatBlankStringPre     thrpt   10  137244.446 ± 9113.373  ops/s
CharToStringConversion.fromCharArray            thrpt   10   85464.842 ± 3127.211  ops/s
CharToStringConversion.stringValueOf            thrpt   10  119281.976 ± 7053.832  ops/s
CharToStringConversion.stringValueOfCharArray   thrpt   10   86563.837 ± 6436.527  ops/s

As you can see, the fastest one would be c + "" or "" + c;

VM version: JDK 1.8.0_131, VM 25.131-b11

This performance difference is due to -XX:+OptimizeStringConcat optimization. You can read about it here.

How to convert an OrderedDict into a regular dict in python3

It is easy to convert your OrderedDict to a regular Dict like this:

dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))

If you have to store it as a string in your database, using JSON is the way to go. That is also quite simple, and you don't even have to worry about converting to a regular dict:

import json
d = OrderedDict([('method', 'constant'), ('data', '1.225')])
dString = json.dumps(d)

Or dump the data directly to a file:

with open('outFile.txt','w') as o:
    json.dump(d, o)

How to convert Nvarchar column to INT

CONVERT takes the column name, not a string containing the column name; your current expression tries to convert the string A.my_NvarcharColumn to an integer instead of the column content.

SELECT convert (int, N'A.my_NvarcharColumn') FROM A;

should instead be

SELECT convert (int, A.my_NvarcharColumn) FROM A;

Simple SQLfiddle here.

How do I convert a Python 3 byte-string variable into a regular string?

You had it nearly right in the last line. You want

str(bytes_string, 'utf-8')

because the type of bytes_string is bytes, the same as the type of b'abc'.

Converting Milliseconds to Minutes and Seconds?

To get actual hour, minute and seconds as appear on watch try this code

val sec = (milliSec/1000) % 60
val min = ((milliSec/1000) / 60) % 60
val hour = ((milliSec/1000) / 60) / 60

How to convert from []byte to int in Go Programming

Starting from a byte array you can use the binary package to do the conversions.

For example if you want to read ints :

buf := bytes.NewBuffer(b) // b is []byte
myfirstint, err := binary.ReadVarint(buf)
anotherint, err := binary.ReadVarint(buf)

The same package allows the reading of unsigned int or floats, with the desired byte orders, using the general Read function.

Checking if a string can be converted to float in Python

You can use the try-except-else clause , this will catch any conversion/ value errors raised when the value passed cannot be converted to a float


  def try_parse_float(item):
      result = None
      try:
        float(item)
      except:
        pass
      else:
        result = float(item)
      return result

How do I convert from int to String?

The expression

"" + i

leads to string conversion of i at runtime. The overall type of the expression is String. i is first converted to an Integer object (new Integer(i)), then String.valueOf(Object obj) is called. So it is equivalent to

"" + String.valueOf(new Integer(i));

Obviously, this is slightly less performant than just calling String.valueOf(new Integer(i)) which will produce the very same result.

The advantage of ""+i is that typing is easier/faster and some people might think, that it's easier to read. It is not a code smell as it does not indicate any deeper problem.

(Reference: JLS 15.8.1)

How do I convert a String to an int in Java?

public static int parseInt(String s)throws NumberFormatException

You can use Integer.parseInt() to convert a String to an int.

Convert a String, "20", to a primitive int:

String n = "20";
int r = Integer.parseInt(n); // Returns a primitive int
System.out.println(r);

Output-20

If the string does not contain a parsable integer, it will throw NumberFormatException:

String n = "20I"; // Throws NumberFormatException
int r = Integer.parseInt(n);
System.out.println(r);

public static Integer valueOf(String s)throws NumberFormatException

You can use Integer.valueOf(). In this it will return an Integer object.

String n = "20";
Integer r = Integer.valueOf(n); // Returns a new Integer() object.
System.out.println(r);

Output-20

References https://docs.oracle.com/en/

Int to Decimal Conversion - Insert decimal point at specified location

Declare it as a decimal which uses the int variable and divide this by 100

int number = 700
decimal correctNumber = (decimal)number / 100;

Edit: Bala was faster with his reaction

Convert boolean result into number/integer

I was just dealing with this issue in some code I was writing. My solution was to use a bitwise and.

var j = bool & 1;

A quicker way to deal with a constant problem would be to create a function. It's more readable by other people, better for understanding at the maintenance stage, and gets rid of the potential for writing something wrong.

function toInt( val ) {
    return val & 1;
}

var j = toInt(bool);

Edit - September 10th, 2014

No conversion using a ternary operator with the identical to operator is faster in Chrome for some reason. Makes no sense as to why it's faster, but I suppose it's some sort of low level optimization that makes sense somewhere along the way.

var j = boolValue === true ? 1 : 0;

Test for yourself: http://jsperf.com/boolean-int-conversion/2

In FireFox and Internet Explorer, using the version I posted is faster generally.

Edit - July 14th, 2017

Okay, I'm not going to tell you which one you should or shouldn't use. Every freaking browser has been going up and down in how fast they can do the operation with each method. Chrome at one point actually had the bitwise & version doing better than the others, but then it suddenly was much worse. I don't know what they're doing, so I'm just going to leave it at who cares. There's rarely any reason to care about how fast an operation like this is done. Even on mobile it's a nothing operation.

Also, here's a newer method for adding a 'toInt' prototype that cannot be overwritten.

Object.defineProperty(Boolean.prototype, "toInt", { value: function()
{
    return this & 1;
}});

How to convert number of minutes to hh:mm format in TSQL?

This function is to convert duration in minutes to readable hours and minutes format. i.e 2h30m. It eliminates the hours if the duration is less than one hour, and shows only the hours if the duration in hours with no extra minutes.

CREATE FUNCTION [dbo].[MinutesToDuration]
(
    @minutes int 
)
RETURNS nvarchar(30)

AS
BEGIN
declare @hours  nvarchar(20)

SET @hours = 
    CASE WHEN @minutes >= 60 THEN
        (SELECT CAST((@minutes / 60) AS VARCHAR(2)) + 'h' +  
                CASE WHEN (@minutes % 60) > 0 THEN
                    CAST((@minutes % 60) AS VARCHAR(2)) + 'm'
                ELSE
                    ''
                END)
    ELSE 
        CAST((@minutes % 60) AS VARCHAR(2)) + 'm'
    END

return @hours
END

To use this function :

SELECT dbo.MinutesToDuration(23)

Results: 23m

SELECT dbo.MinutesToDuration(120)

Results: 2h

SELECT dbo.MinutesToDuration(147)

Results: 2h27m

Hope this helps!

Why is datetime.strptime not working in this simple example?

You can also do the following,to import datetime

from datetime import datetime as dt

dt.strptime(date, '%Y-%m-%d')

Converting from byte to int in java

if you want to combine the 4 bytes into a single int you need to do

int i= (rno[0]<<24)&0xff000000|
       (rno[1]<<16)&0x00ff0000|
       (rno[2]<< 8)&0x0000ff00|
       (rno[3]<< 0)&0x000000ff;

I use 3 special operators | is the bitwise logical OR & is the logical AND and << is the left shift

in essence I combine the 4 8-bit bytes into a single 32 bit int by shifting the bytes in place and ORing them together

I also ensure any sign promotion won't affect the result with & 0xff

How do I convert a String to an InputStream in Java?

You can try cactoos for that.

final InputStream input = new InputStreamOf("example");

The object is created with new and not a static method for a reason.

Convert float to std::string in C++

As of C++11, the standard C++ library provides the function std::to_string(arg) with various supported types for arg.

Converting an integer to a string in PHP

As the answers here demonstrates nicely, yes, there are several ways. However, in PHP you rarely actually need to do that. The "dogmatic way" to write PHP is to rely on the language's loose typing system, which will transparently coerce the type as needed. For integer values, this is usually without trouble. You should be very careful with floating point values, though.

How do you change the datatype of a column in SQL Server?

Use the Alter table statement.

Alter table TableName Alter Column ColumnName nvarchar(100)

Convert bytes to int?

Lists of bytes are subscriptable (at least in Python 3.6). This way you can retrieve the decimal value of each byte individually.

>>> intlist = [64, 4, 26, 163, 255]
>>> bytelist = bytes(intlist)       # b'@x04\x1a\xa3\xff'

>>> for b in bytelist:
...    print(b)                     # 64  4  26  163  255

>>> [b for b in bytelist]           # [64, 4, 26, 163, 255]

>>> bytelist[2]                     # 26 

Create ArrayList from array

Simplest way to do so is by adding following code. Tried and Tested.

String[] Array1={"one","two","three"};
ArrayList<String> s1= new ArrayList<String>(Arrays.asList(Array1));

Conversion from Long to Double in Java

As already mentioned, you can simply cast long to double. But be careful with long to double conversion because long to double is a narrowing conversion in java.

Conversion from type double to type long requires a nontrivial translation from a 64-bit floating-point value to the 64-bit integer representation. Depending on the actual run-time value, information may be lost.

e.g. following program will print 1 not 0

    long number = 499999999000000001L;
    double converted = (double) number;
    System.out.println( number - (long) converted);

Convert double to Int, rounded down

If you explicitly cast double to int, the decimal part will be truncated. For example:

int x = (int) 4.97542;   //gives 4 only
int x = (int) 4.23544;   //gives 4 only

Moreover, you may also use Math.floor() method to round values in case you want double value in return.

How to cast/convert pointer to reference in C++

Call it like this:

foo(*ob);

Note that there is no casting going on here, as suggested in your question title. All we have done is de-referenced the pointer to the object which we then pass to the function.

How to convert string to float?

Unfortunately, there is no way to do this easily. Every solution has its drawbacks.

  1. Use atof() or strtof() directly: this is what most people will tell you to do and it will work most of the time. However, if the program sets a locale or it uses a library that sets the locale (for instance, a graphics library that displays localised menus) and the user has their locale set to a language where the decimal separator is not . (such as fr_FR where the separator is ,) these functions will stop parsing at the . and you will stil get 4.0.

  2. Use atof() or strtof() but change the locale; it's a matter of calling setlocale(LC_ALL|~LC_NUMERIC, ""); before any call to atof() or the likes. The problem with setlocale is that it will be global to the process and you might interfer with the rest of the program. Note that you might query the current locale with setlocale() and restore it after you're done.

  3. Write your own float parsing routine. This might be quite quick if you do not need advanced features such as exponent parsing or hexadecimal floats.

Also, note that the value 4.08 cannot be represented exactly as a float; the actual value you will get is 4.0799999237060546875.

Easiest way to convert int to string in C++

If you're using MFC, you can use CString:

int a = 10;
CString strA;
strA.Format("%d", a);

Converting String To Float in C#

You can use parsing with double instead of float to get more precision value.

Excel 2010 VBA Referencing Specific Cells in other worksheets

Sub Results2()

    Dim rCell As Range
    Dim shSource As Worksheet
    Dim shDest As Worksheet
    Dim lCnt As Long

    Set shSource = ThisWorkbook.Sheets("Sheet1")
    Set shDest = ThisWorkbook.Sheets("Sheet2")

    For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
        lCnt = lCnt + 1
        shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
    Next rCell

End Sub

This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.

To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.

I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,

Sub Results3()

    Dim i As Long, lCnt As Long
    Dim sh As Worksheet

    lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
    Set sh = ThisWorkbook.Sheets("Sheet2")

    Const sSOURCE As String = "Sheet1!"

    For i = 1 To lCnt
        sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
    Next i

End Sub

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

You can also join if the number of columns are not same in both tables and can map static value to table column

from t1 in Table1 
join t2 in Table2 
on new {X = t1.Column1, Y = 0 } on new {X = t2.Column1, Y = t2.Column2 }
select new {t1, t2}

Using Powershell to stop a service remotely without WMI or remoting

Based on the built-in Powershell examples, this is what Microsoft suggests. Tested and verified:

To stop:

(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StopService()

To start:

(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StartService()

How to get a specific output iterating a hash in Ruby?

Calling sort on a hash converts it into nested arrays and then sorts them by key, so all you need is this:

puts h.sort.map {|k,v| ["#{k}----"] + v}

And if you don't actually need the "----" part, it can be just:

puts h.sort

Installing Apache Maven Plugin for Eclipse

Eclipse > Help > Eclipse Marketplace...

Search for m2e

Install Maven Integration for Eclipse (Juno and newer). [It works for Indigo also]

How to get info on sent PHP curl request

The request is printed in a request.txt with details

$ch = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt_array($ch, array(
CURLOPT_URL            => $url, 
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE        => 1,
CURLOPT_STDERR         => $f,
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);

You can also use curl_getinfo() function.

jQuery Set Cursor Position in Text Area

I had to get this working for contenteditable elements and jQuery and tought someone might want it ready to use:

$.fn.getCaret = function(n) {
    var d = $(this)[0];
    var s, r;
    r = document.createRange();
    r.selectNodeContents(d);
    s = window.getSelection();
    console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
    return s.anchorOffset;
};

$.fn.setCaret = function(n) {
    var d = $(this)[0];
    d.focus();
    var r = document.createRange();
    var s = window.getSelection();
    r.setStart(d.childNodes[0], n);
    r.collapse(true);
    s.removeAllRanges();
    s.addRange(r);
    console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
    return this;
};

Usage $(selector).getCaret() returns the number offset and $(selector).setCaret(num) establishes the offeset and sets focus on element.

Also a small tip, if you run $(selector).setCaret(num) from console it will return the console.log but you won't visualize the focus since it is established at the console window.

Bests ;D

How to beautifully update a JPA entity in Spring Data?

I have encountered this issue!
Luckily, I determine 2 ways and understand some things but the rest is not clear.
Hope someone discuss or support if you know.

  1. Use RepositoryExtendJPA.save(entity).
    Example:
    List<Person> person = this.PersonRepository.findById(0) person.setName("Neo"); This.PersonReository.save(person);
    this block code updated new name for record which has id = 0;
  2. Use @Transactional from javax or spring framework.
    Let put @Transactional upon your class or specified function, both are ok.
    I read at somewhere that this annotation do a "commit" action at the end your function flow. So, every things you modified at entity would be updated to database.

How do I separate an integer into separate digits in an array in JavaScript?

I ended up solving it as follows:

_x000D_
_x000D_
const n = 123456789;_x000D_
let toIntArray = (n) => ([...n + ""].map(Number));_x000D_
console.log(toIntArray(n));
_x000D_
_x000D_
_x000D_

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

Try browse the WCF in IIS see if it's alive and works normally,

In my case it's because the physical path of the WCF is misdirected.

How do I toggle an ng-show in AngularJS based on a boolean?

If you have multiple Menus with Submenus, then you can go with the below solution.

HTML

          <ul class="sidebar-menu" id="nav-accordion">
             <li class="sub-menu">
                  <a href="" ng-click="hasSubMenu('dashboard')">
                      <i class="fa fa-book"></i>
                      <span>Dashboard</span>
                      <i class="fa fa-angle-right pull-right"></i>
                  </a>
                  <ul class="sub" ng-show="showDash">
                      <li><a ng-class="{ active: isActive('/dashboard/loan')}" href="#/dashboard/loan">Loan</a></li>
                      <li><a ng-class="{ active: isActive('/dashboard/recovery')}" href="#/dashboard/recovery">Recovery</a></li>
                  </ul>
              </li>
              <li class="sub-menu">
                  <a href="" ng-click="hasSubMenu('customerCare')">
                      <i class="fa fa-book"></i>
                      <span>Customer Care</span>
                      <i class="fa fa-angle-right pull-right"></i>
                  </a>
                  <ul class="sub" ng-show="showCC">
                      <li><a ng-class="{ active: isActive('/customerCare/eligibility')}" href="#/CC/eligibility">Eligibility</a></li>
                      <li><a ng-class="{ active: isActive('/customerCare/transaction')}" href="#/CC/transaction">Transaction</a></li>
                  </ul>
              </li>
          </ul>

There are two functions i have called first is ng-click = hasSubMenu('dashboard'). This function will be used to toggle the menu and it is explained in the code below. The ng-class="{ active: isActive('/customerCare/transaction')} it will add a class active to the current menu item.

Now i have defined some functions in my app:

First, add a dependency $rootScope which is used to declare variables and functions. To learn more about $roootScope refer to the link : https://docs.angularjs.org/api/ng/service/$rootScope

Here is my app file:

 $rootScope.isActive = function (viewLocation) { 
                return viewLocation === $location.path();
        };

The above function is used to add active class to the current menu item.

        $rootScope.showDash = false;
        $rootScope.showCC = false;

        var location = $location.url().split('/');

        if(location[1] == 'customerCare'){
            $rootScope.showCC = true;
        }
        else if(location[1]=='dashboard'){
            $rootScope.showDash = true;
        }

        $rootScope.hasSubMenu = function(menuType){
            if(menuType=='dashboard'){
                $rootScope.showCC = false;
                $rootScope.showDash = $rootScope.showDash === false ? true: false;
            }
            else if(menuType=='customerCare'){
                $rootScope.showDash = false;
                $rootScope.showCC = $rootScope.showCC === false ? true: false;
            }
        }

By default $rootScope.showDash and $rootScope.showCC are set to false. It will set the menus to closed when page is initially loaded. If you have more than two submenus add accordingly.

hasSubMenu() function will work for toggling between the menus. I have added a small condition

if(location[1] == 'customerCare'){
                $rootScope.showCC = true;
            }
            else if(location[1]=='dashboard'){
                $rootScope.showDash = true;
            }

it will remain the submenu open after reloading the page according to selected menu item.

I have defined my pages like:

$routeProvider
        .when('/dasboard/loan', {
            controller: 'LoanController',
            templateUrl: './views/loan/view.html',
            controllerAs: 'vm'
        })

You can use isActive() function only if you have a single menu without submenu. You can modify the code according to your requirement. Hope this will help. Have a great day :)

Check if an array item is set in JS

if (assoc_pagine.indexOf('home') > -1) {
   // we have home element in the assoc_pagine array
}

Mozilla indexOf

Configure cron job to run every 15 minutes on Jenkins

It should be,

*/15 * * * *  your_command_or_whatever

Fitting a Normal distribution to 1D data

To see both the normal distribution and your actual data you should plot your data as a histogram, then draw the probability density function over this. See the example on https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.normal.html for exactly how to do this.

div inside php echo

You can also do this,

<?php 
if ( ($cart->count_product) > 0) { 
  $print .= "<div class='my_class'>"
  $print .= $cart->count_product; 
  $print .= "</div>"
} else { 
   $print = ''; 
} 
echo  $print;
?>

clear cache of browser by command line

You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.


Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255

Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

Remove spaces from a string in VB.NET

2015: Newer LINQ & lambda.

  1. As this is an old Q (and Answer), just thought to update it with newer 2015 methods.
  2. The original "space" can refer to non-space whitespace (ie, tab, newline, paragraph separator, line feed, carriage return, etc, etc).
  3. Also, Trim() only remove the spaces from the front/back of the string, it does not remove spaces inside the string; eg: " Leading and Trailing Spaces " will become "Leading and Trailing Spaces", but the spaces inside are still present.

Function RemoveWhitespace(fullString As String) As String
    Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function

This will remove ALL (white)-space, leading, trailing and within the string.

Purpose of ESI & EDI registers?

SI = Source Index
DI = Destination Index

As others have indicated, they have special uses with the string instructions. For real mode programming, the ES segment register must be used with DI and DS with SI as in

movsb  es:di, ds:si

SI and DI can also be used as general purpose index registers. For example, the C source code

srcp [srcidx++] = argv [j];

compiles into

8B550C         mov    edx,[ebp+0C]
8B0C9A         mov    ecx,[edx+4*ebx]
894CBDAC       mov    [ebp+4*edi-54],ecx
47             inc    edi

where ebp+12 contains argv, ebx is j, and edi has srcidx. Notice the third instruction uses edi mulitplied by 4 and adds ebp offset by 0x54 (the location of srcp); brackets around the address indicate indirection.


Though I can't remember where I saw it, but this confirms most of it, and this (slide 17) others:

AX = accumulator
DX = double word accumulator
CX = counter
BX = base register

They look like general purpose registers, but there are a number of instructions which (unexpectedly?) use one of them—but which one?—implicitly.

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

Just select all of the files you want to compare, then open the context menu (Right-Click on the file) and choose Compare With, Then select each other..

Convert YYYYMMDD to DATE

The error is happening because you (or whoever designed this table) have a bunch of dates in VARCHAR. Why are you (or whoever designed this table) storing dates as strings? Do you (or whoever designed this table) also store salary and prices and distances as strings?

To find the values that are causing issues (so you (or whoever designed this table) can fix them):

SELECT GRADUATION_DATE FROM mydb
  WHERE ISDATE(GRADUATION_DATE) = 0;

Bet you have at least one row. Fix those values, and then FIX THE TABLE. Or ask whoever designed the table to FIX THE TABLE. Really nicely.

ALTER TABLE mydb ALTER COLUMN GRADUATION_DATE DATE;

Now you don't have to worry about the formatting - you can always format as YYYYMMDD or YYYY-MM-DD on the client, or using CONVERT in SQL. When you have a valid date as a string literal, you can use:

SELECT CONVERT(CHAR(10), '20120101', 120);

...but this is better done on the client (if at all).

There's a popular term - garbage in, garbage out. You're never going to be able to convert to a date (never mind convert to a string in a specific format) if your data type choice (or the data type choice of whoever designed the table) inherently allows garbage into your table. Please fix it. Or ask whoever designed the table (again, really nicely) to fix it.

What does this GCC error "... relocation truncated to fit..." mean?

I ran into the exact same issue. After compiling without the -fexceptions build flag, the file compiled with no issue

Get all files and directories in specific path fast

You can use this to get all directories and sub-directories. Then simply loop through to process the files.

string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);

foreach(string f in folders)
{
   //call some function to get all files in folder
}

Updating Python on Mac

Python 2.7 and 3 can co-exist.
Python version shows on terminal is 2.7, but you can invoke it using "python3", see this:

PeiwenMAC:git Peiwen$ python --version
Python 2.7.2
PeiwenMAC:git Peiwen$ python3
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 00:54:21) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

UITableViewCell Selected Background Color on Multiple Selection

Swift 3

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier", for: indexPath)
    cell.selectionStyle = .none
    return cell
}

Swift 2

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier", for: indexPath)
     cell.selectionStyle = .None
     return cell
}

Visual Studio 2010 always thinks project is out of date, but nothing has changed

I don't know if anyone else has this same problem, but my project's properties had "Configuration Properties" -> C/C++ -> "Debug Information Format" set to "None", and when I switched it back to the default "Program Database (/Zi)", that stopped the project from recompiling every time.

Is there a way to detect if a browser window is not currently active?

u can use :

(function () {

    var requiredResolution = 10; // ms
    var checkInterval = 1000; // ms
    var tolerance = 20; // percent


    var counter = 0;
    var expected = checkInterval / requiredResolution;
    //console.log('expected:', expected);

    window.setInterval(function () {
        counter++;
    }, requiredResolution);

    window.setInterval(function () {
        var deviation = 100 * Math.abs(1 - counter / expected);
        // console.log('is:', counter, '(off by', deviation , '%)');
        if (deviation > tolerance) {
            console.warn('Timer resolution not sufficient!');
        }
        counter = 0;
    }, checkInterval);

})();

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

If you don't want use connection pool (you sure, that your app has only one connection), you can do this - if connection falls you must establish new one - call method .openSession() instead .getCurrentSession()

For example:

SessionFactory sf = null;
// get session factory
// ...
//
Session session = null;
try {
        session = sessionFactory.getCurrentSession();
} catch (HibernateException ex) {
        session = sessionFactory.openSession();
}

If you use Mysql, you can set autoReconnect property:

    <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/database?autoReconnect=true</property>

I hope this helps.

Convert Data URI to File then append to FormData

The evolving standard looks to be canvas.toBlob() not canvas.getAsFile() as Mozilla hazarded to guess.

I don't see any browser yet supporting it :(

Thanks for this great thread!

Also, anyone trying the accepted answer should be careful with BlobBuilder as I'm finding support to be limited (and namespaced):

    var bb;
    try {
        bb = new BlobBuilder();
    } catch(e) {
        try {
            bb = new WebKitBlobBuilder();
        } catch(e) {
            bb = new MozBlobBuilder();
        }
    }

Were you using another library's polyfill for BlobBuilder?

Laravel: Get base url

Check this -

<a href="{{url('/abc/xyz')}}">Go</a>

This is working for me and I hope it will work for you.

Java: Reading a file into an array

Here is some example code to help you get started:

package com.acme;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

    public String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}

And an example unit test:

package com.acme;

import java.io.IOException;

import org.junit.Test;

public class FileArrayProviderTest {

    @Test
    public void testFileArrayProvider() throws IOException {
        FileArrayProvider fap = new FileArrayProvider();
        String[] lines = fap
                .readLines("src/main/java/com/acme/FileArrayProvider.java");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Hope this helps.

Unix command-line JSON parser?

I just made jkid which is a small command-line json explorer that I made to easily explore big json objects. Objects can be explored "transversally" and a "preview" option is there to avoid console overflow.

$  echo '{"john":{"size":20, "eyes":"green"}, "bob":{"size":30, "eyes":"brown"}}' > test3.json
$  jkid . eyes test3.json 
object[.]["eyes"]
{
  "bob": "brown", 
  "john": "green"
}

How do I add a new class to an element dynamically?

Since everyone has given you jQuery/JS answers to this, I will provide an additional solution. The answer to your question is still no, but using LESS (a CSS Pre-processor) you can do this easily.

.first-class {
  background-color: yellow;
}
.second-class:hover {
  .first-class;
}

Quite simply, any time you hover over .second-class it will give it all the properties of .first-class. Note that it won't add the class permanently, just on hover. You can learn more about LESS here: Getting Started with LESS

Here is a SASS way to do it as well:

.first-class {
  background-color: yellow;
}
.second-class {
  &:hover {
    @extend .first-class;
  }
}

Understanding ibeacon distancing

It's possible, but it depends on the power output of the beacon you're receiving, other rf sources nearby, obstacles and other environmental factors. Best thing to do is try it out in the environment you're interested in.

Pandas: create two new columns in a dataframe with values calculated from a pre-existing column

I'd just use zip:

In [1]: from pandas import *

In [2]: def calculate(x):
   ...:     return x*2, x*3
   ...: 

In [3]: df = DataFrame({'a': [1,2,3], 'b': [2,3,4]})

In [4]: df
Out[4]: 
   a  b
0  1  2
1  2  3
2  3  4

In [5]: df["A1"], df["A2"] = zip(*df["a"].map(calculate))

In [6]: df
Out[6]: 
   a  b  A1  A2
0  1  2   2   3
1  2  3   4   6
2  3  4   6   9

Multiple selector chaining in jQuery?

$("#Create").find(".myClass").add("#Edit .myClass").plugin({});

Use $.fn.add to concatenate two sets.

How can I override Bootstrap CSS styles?

Using !important is not a good option, as you will most likely want to override your own styles in the future. That leaves us with CSS priorities.

Basically, every selector has its own numerical 'weight':

  • 100 points for IDs
  • 10 points for classes and pseudo-classes
  • 1 point for tag selectors and pseudo-elements
  • Note: If the element has inline styling that automatically wins (1000 points)

Among two selector styles browser will always choose the one with more weight. Order of your stylesheets only matters when priorities are even - that's why it is not easy to override Bootstrap.

Your option is to inspect Bootstrap sources, find out how exactly some specific style is defined, and copy that selector so your element has equal priority. But we kinda loose all Bootstrap sweetness in the process.

The easiest way to overcome this is to assign additional arbitrary ID to one of the root elements on your page, like this: <body id="bootstrap-overrides">

This way, you can just prefix any CSS selector with your ID, instantly adding 100 points of weight to the element, and overriding Bootstrap definitions:

/* Example selector defined in Bootstrap */
.jumbotron h1 { /* 10+1=11 priority scores */
  line-height: 1;
  color: inherit;
}

/* Your initial take at styling */
h1 { /* 1 priority score, not enough to override Bootstrap jumbotron definition */
  line-height: 1;
  color: inherit;
}

/* New way of prioritization */
#bootstrap-overrides h1 { /* 100+1=101 priority score, yay! */
  line-height: 1;
  color: inherit;
}

What does question mark and dot operator ?. mean in C# 6.0?

It's the null conditional operator. It basically means:

"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."

In your example, the point is that if a is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.

In other words, it's like this:

string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
    ...
}

... except that a is only evaluated once.

Note that this can change the type of the expression, too. For example, consider FileInfo.Length. That's a property of type long, but if you use it with the null conditional operator, you end up with an expression of type long?:

FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null

exception.getMessage() output with class name

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

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

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

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

Output:

Error: Just the message

convert month from name to number

$string = "July";
echo $month_number = date("n",strtotime($string));

returns '7' [month number]

Use date("m",strtotime($string)); for the output "08"

For more formats reffer this..
http://php.net/manual/en/function.date.php

Can I set an unlimited length for maxJsonLength in web.config?

In MVC 4 you can do:

protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
    return new JsonResult()
    {
        Data = data,
        ContentType = contentType,
        ContentEncoding = contentEncoding,
        JsonRequestBehavior = behavior,
        MaxJsonLength = Int32.MaxValue
    };
}

in your controller.

Addition:

For anyone puzzled by the parameters you need to specify, a call could look like this:

Json(
    new {
        field1 = true,
        field2 = "value"
        },
    "application/json",
    Encoding.UTF8,
    JsonRequestBehavior.AllowGet
);

How to convert JSON object to an Typescript array?

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

this.data = res.json().results

iterating over and removing from a map

An alternative, more verbose way

List<SomeObject> toRemove = new ArrayList<SomeObject>();
for (SomeObject key: map.keySet()) {
    if (something) {
        toRemove.add(key);
    }
}

for (SomeObject key: toRemove) {
    map.remove(key);
}

How to center an image horizontally and align it to the bottom of the container?

wouldn't

margin-left:auto;
margin-right:auto;

added to the .image_block a img do the trick?
Note that that won't work in IE6 (maybe 7 not sure)
there you will have to do on .image_block the container Div

text-align:center;

position:relative; could be a problem too.

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

Can I serve multiple clients using just Flask app.run() as standalone?

Tips from 2020:

From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:

$ pip install -U flask

If you are using flask run instead of app.run() with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads):

$ flask run --with-threads

It's same as app.run(threaded=True)

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

@Janei: my first comment here is about your sample ;)

I think if you do like this, you want to take 4, then applying the sort on these 4.

var dados =  from d in dc.tbl_News.Take(4) 
                orderby d.idNews descending
                select new 
                {
                    d.idNews,
                    d.titleNews,
                    d.textNews,
                    d.dateNews,
                    d.imgNewsThumb
                };

Different than sorting whole tbl_News by idNews descending and then taking 4

var dados =  (from d in dc.tbl_News
                orderby d.idNews descending
                select new 
                {
                    d.idNews,
                    d.titleNews,
                    d.textNews,
                    d.dateNews,
                    d.imgNewsThumb
                }).Take(4);

no ? results may be different.

C library function to perform sort

qsort() is the function you're looking for. You call it with a pointer to your array of data, the number of elements in that array, the size of each element and a comparison function.

It does its magic and your array is sorted in-place. An example follows:

#include <stdio.h>
#include <stdlib.h>
int comp (const void * elem1, const void * elem2) 
{
    int f = *((int*)elem1);
    int s = *((int*)elem2);
    if (f > s) return  1;
    if (f < s) return -1;
    return 0;
}
int main(int argc, char* argv[]) 
{
    int x[] = {4,5,2,3,1,0,9,8,6,7};

    qsort (x, sizeof(x)/sizeof(*x), sizeof(*x), comp);

    for (int i = 0 ; i < 10 ; i++)
        printf ("%d ", x[i]);

    return 0;
}

How do I get the name of the rows from the index of a data frame?

if you want to get the index values, you can simply do:

dataframe.index

this will output a pandas.core.index

Bin size in Matplotlib (Histogram)

I use quantiles to do bins uniform and fitted to sample:

bins=df['Generosity'].quantile([0,.05,0.1,0.15,0.20,0.25,0.3,0.35,0.40,0.45,0.5,0.55,0.6,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1]).to_list()

plt.hist(df['Generosity'], bins=bins, normed=True, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none')

enter image description here

Is there a limit on number of tcp/ip connections between machines on linux?

Is your server single-threaded? If so, what polling / multiplexing function are you using?

Using select() does not work beyond the hard-coded maximum file descriptor limit set at compile-time, which is hopeless (normally 256, or a few more).

poll() is better but you will end up with the scalability problem with a large number of FDs repopulating the set each time around the loop.

epoll() should work well up to some other limit which you hit.

10k connections should be easy enough to achieve. Use a recent(ish) 2.6 kernel.

How many client machines did you use? Are you sure you didn't hit a client-side limit?

Inserting records into a MySQL table using Java

This should work for any table, instead of hard-coding the columns.

_x000D_
_x000D_
//Source details_x000D_
    String sourceUrl = "jdbc:oracle:thin:@//server:1521/db";_x000D_
    String sourceUserName = "src";_x000D_
    String sourcePassword = "***";_x000D_
_x000D_
    // Destination details_x000D_
    String destinationUserName = "dest";_x000D_
    String destinationPassword = "***";_x000D_
    String destinationUrl = "jdbc:mysql://server:3306/db";_x000D_
_x000D_
    Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);_x000D_
    Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);_x000D_
_x000D_
    PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT *  FROM src_table ");_x000D_
    ResultSet rs = sourceStatement.executeQuery();_x000D_
    rs.setFetchSize(1000); // not needed_x000D_
_x000D_
_x000D_
    ResultSetMetaData meta = rs.getMetaData();_x000D_
_x000D_
_x000D_
_x000D_
    List<String> columns = new ArrayList<>();_x000D_
    for (int i = 1; i <= meta.getColumnCount(); i++)_x000D_
        columns.add(meta.getColumnName(i));_x000D_
_x000D_
    try (PreparedStatement destStatement = destConnection.prepareStatement(_x000D_
            "INSERT INTO dest_table ("_x000D_
                    + columns.stream().collect(Collectors.joining(", "))_x000D_
                    + ") VALUES ("_x000D_
                    + columns.stream().map(c -> "?").collect(Collectors.joining(", "))_x000D_
                    + ")"_x000D_
            )_x000D_
    )_x000D_
    {_x000D_
        int count = 0;_x000D_
        while (rs.next()) {_x000D_
            for (int i = 1; i <= meta.getColumnCount(); i++) {_x000D_
                destStatement.setObject(i, rs.getObject(i));_x000D_
            }_x000D_
            _x000D_
            destStatement.addBatch();_x000D_
            count++;_x000D_
        }_x000D_
        destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed_x000D_
        System.out.println("done " + count);_x000D_
_x000D_
    }
_x000D_
_x000D_
_x000D_

Using CMake to generate Visual Studio C++ project files

As Alex says, it works very well. The only tricky part is to remember to make any changes in the cmake files, rather than from within Visual Studio. So on all platforms, the workflow is similar to if you'd used plain old makefiles.

But it's fairly easy to work with, and I've had no issues with cmake generating invalid files or anything like that, so I wouldn't worry too much.

PHP cURL HTTP CODE return 0

What is the exact contents you are passing into $html_brand?

If it is has an invalid URL syntax, you will very likely get the HTTP code 0.

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

This is probably not a solution to your problem, but a suggestion just in case (I know I ran into a similar problem before but not with a .NET application).

If you are on a 64-bit machine, there are 2 regsvr32.exe files; One is in \Windows\System32 and the other one is in \Windows\SysWOW64.

You cannot register 64-bit COM-objects with the 32-bit version, but you can do it vice versa. I'd try registering your DLL with both regsvr32.exe files explicitly (i.e. typing "C:\Windows\System32\regsvr32.exe /i mydll.dll" and then "C:\Windows\SysWOW64\regsvr32.exe /i mydll.dll") and seeing if that helps...

How do I prevent people from doing XSS in Spring MVC?

When you are trying to prevent XSS, it's important to think of the context. As an example how and what to escape is very different if you are ouputting data inside a variable in a javascript snippet as opposed to outputting data in an HTML tag or an HTML attribute.

I have an example of this here: http://erlend.oftedal.no/blog/?blogid=91

Also checkout the OWASP XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet

So the short answer is, make sure you escape output like suggested by Tendayi Mawushe, but take special care when you are outputting data in HTML attributes or javascript.

Uncaught SyntaxError: Unexpected token < On Chrome

Error with Uncaught SyntaxError: Unexpected token < using @Mario answer but that was only part of my problem. Another problem is, javascript doesn't get any data from PHP file. That was solved using this code, inside PHP file: header("Content-Type: text/javascript; charset=utf-8"); This answer is found on this link, where I opened another question to solve this issue: Can't receive json data from PHP in Chrome and Opera

How to access the last value in a vector?

Combining lindelof's and Gregg Lind's ideas:

last <- function(x) { tail(x, n = 1) }

Working at the prompt, I usually omit the n=, i.e. tail(x, 1).

Unlike last from the pastecs package, head and tail (from utils) work not only on vectors but also on data frames etc., and also can return data "without first/last n elements", e.g.

but.last <- function(x) { head(x, n = -1) }

(Note that you have to use head for this, instead of tail.)

How to repair COMException error 80040154?

WORKAROUND:

The possible workaround is modify your project's platform from 'Any CPU' to 'X86' (in Project's Properties, Build/Platform's Target)

ROOTCAUSE

The VSS Interop is a managed assembly using 32-bit Framework and the dll contains a 32-bit COM object. If you run this COM dll in 64 bit environment, you will get the error message.

Best data type for storing currency values in a MySQL database

For accounting applications it's very common to store the values as integers (some even go so far as to say it's the only way). To get an idea, take the amount of the transactions (let's suppose $100.23) and multiple by 100, 1000, 10000, etc. to get the accuracy you need. So if you only need to store cents and can safely round up or down, just multiply by 100. In my example, that would make 10023 as the integer to store. You'll save space in the database and comparing two integers is much easier than comparing two floats. My $0.02.

Where does Android emulator store SQLite database?

according to Android docs, Monitor was deprecated in Android Studio 3.1 and removed from Android Studio 3.2. To access files, there is a tab in android studio called "Device File Explorer" bottom-right side of developing window which you can access your emulator file system. Just follow

/data/data/package_name/databases

good luck.

Android device File explorer

Plot 3D data in R

If you're working with "real" data for which the grid intervals and sequence cannot be guaranteed to be increasing or unique (hopefully the (x,y,z) combinations are unique at least, even if these triples are duplicated), I would recommend the akima package for interpolating from an irregular grid to a regular one.

Using your definition of data:

library(akima)
im <- with(data,interp(x,y,z))
with(im,image(x,y,z))

enter image description here

And this should work not only with image but similar functions as well.

Note that the default grid to which your data is mapped to by akima::interp is defined by 40 equal intervals spanning the range of x and y values:

> formals(akima::interp)[c("xo","yo")]
$xo
seq(min(x), max(x), length = 40)

$yo
seq(min(y), max(y), length = 40)

But of course, this can be overridden by passing arguments xo and yo to akima::interp.

Ajax using https on an http page

Add the Access-Control-Allow-Origin header from the server

Access-Control-Allow-Origin: https://www.mysite.com

http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing

Installing specific package versions with pip

I believe that if you already have a package it installed, pip will not overwrite it with another version. Use -I to ignore previous versions.

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You need to encode your parameter's values before concatenating them to URL.
Backslash \ is special character which have to be escaped as %5C

Escaping example:

String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);

The result is http://host.com?param=param%5Cwith%5Cbackslash which is properly formatted url string.

Append to the end of a Char array in C++

If your arrays are character arrays(which seems to be the case), You need a strcat().
Your destination array should have enough space to accommodate the appended data though.

In C++, You are much better off using std::string and then you can use std::string::append()

Are there constants in JavaScript?

Mozillas MDN Web Docs contain good examples and explanations about const. Excerpt:

// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;

// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY_FAV = 20;

But it is sad that IE9/10 still does not support const. And the reason it's absurd:

So, what is IE9 doing with const? So far, our decision has been to not support it. It isn’t yet a consensus feature as it has never been available on all browsers.

...

In the end, it seems like the best long term solution for the web is to leave it out and to wait for standardization processes to run their course.

They don't implement it because other browsers didn't implement it correctly?! Too afraid of making it better? Standards definitions or not, a constant is a constant: set once, never changed.

And to all the ideas: Every function can be overwritten (XSS etc.). So there is no difference in var or function(){return}. const is the only real constant.

Update: IE11 supports const:

IE11 includes support for the well-defined and commonly used features of the emerging ECMAScript 6 standard including let, const, Map, Set, and WeakMap, as well as __proto__ for improved interoperability.

MySQL "between" clause not inclusive?

select * from person where DATE(dob) between '2011-01-01' and '2011-01-31'

Surprisingly such conversions are solutions to many problems in MySQL.

Execute jQuery function after another function completes

You should use a callback parameter:

function Typer(callback)
{
    var srcText = 'EXAMPLE ';
    var i = 0;
    var result = srcText[i];
    var interval = setInterval(function() {
        if(i == srcText.length - 1) {
            clearInterval(interval);
            callback();
            return;
        }
        i++;
        result += srcText[i].replace("\n", "<br />");
        $("#message").html(result);
    },
    100);
    return true;


}

function playBGM () {
    alert("Play BGM function");
    $('#bgm').get(0).play();
}

Typer(function () {
    playBGM();
});

// or one-liner: Typer(playBGM);

So, you pass a function as parameter (callback) that will be called in that if before return.

Also, this is a good article about callbacks.

_x000D_
_x000D_
function Typer(callback)_x000D_
{_x000D_
    var srcText = 'EXAMPLE ';_x000D_
    var i = 0;_x000D_
    var result = srcText[i];_x000D_
    var interval = setInterval(function() {_x000D_
        if(i == srcText.length - 1) {_x000D_
            clearInterval(interval);_x000D_
            callback();_x000D_
            return;_x000D_
        }_x000D_
        i++;_x000D_
        result += srcText[i].replace("\n", "<br />");_x000D_
        $("#message").html(result);_x000D_
    },_x000D_
    100);_x000D_
    return true;_x000D_
        _x000D_
    _x000D_
}_x000D_
_x000D_
function playBGM () {_x000D_
    alert("Play BGM function");_x000D_
    $('#bgm').get(0).play();_x000D_
}_x000D_
_x000D_
Typer(function () {_x000D_
    playBGM();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
</div>_x000D_
<audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3">_x000D_
</audio>
_x000D_
_x000D_
_x000D_

JSFIDDLE

Getting multiple selected checkbox values in a string in javascript and PHP

I you are using jQuery you can put the checkboxes in a form and then use something like this:

var formData = jQuery("#" + formId).serialize();

$.ajax({
      type: "POST",
      url: url,
      data: formData,
      success: success
}); 

How to Use Order By for Multiple Columns in Laravel 4?

You can do as @rmobis has specified in his answer, [Adding something more into it]

Using order by twice:

MyTable::orderBy('coloumn1', 'DESC')
    ->orderBy('coloumn2', 'ASC')
    ->get();

and the second way to do it is,

Using raw order by:

MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
    ->get();

Both will produce same query as follow,

SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC

As @rmobis specified in comment of first answer you can pass like an array to order by column like this,

$myTable->orders = array(
    array('column' => 'coloumn1', 'direction' => 'desc'), 
    array('column' => 'coloumn2', 'direction' => 'asc')
);

one more way to do it is iterate in loop,

$query = DB::table('my_tables');

foreach ($request->get('order_by_columns') as $column => $direction) {
    $query->orderBy($column, $direction);
}

$results = $query->get();

Hope it helps :)

What is the difference between OFFLINE and ONLINE index rebuild in SQL Server?

The main differences are:

1) OFFLINE index rebuild is faster than ONLINE rebuild.

2) Extra disk space required during SQL Server online index rebuilds.

3) SQL Server locks acquired with SQL Server online index rebuilds.

  • This schema modification lock blocks all other concurrent access to the table, but it is only held for a very short period of time while the old index is dropped and the statistics updated.

How to force IE to reload javascript?

Paolo's general idea (i.e. effectively changing some part of the request uri) is your best bet. However, I'd suggest using a more static value such as a version number that you update when you have changed your script file so that you can still get the performance gains of caching.

So either something like this:

<script src="/my/js/file.js?version=2.1.3" ></script>

or maybe

<script src="/my/js/file.2.1.3.js" ></script>

I prefer the first option because it means you can maintain the one file instead of having to constantly rename it (which for example maintains consistent version history in your source control). Of course either one (as I've described them) would involve updating your include statements each time, so you may want to come up with a dynamic way of doing it, such as replacing a fixed value with a dynamic one every time you deploy (using Ant or whatever).

Change the column label? e.g.: change column "A" to column "Name"

If you intend to change A, B, C.... you see high above the columns, you can not. You can hide A, B, C...: Button Office(top left) Excel Options(bottom) Advanced(left) Right looking: Display options fot this worksheet: Select the worksheet(eg. Sheet3) Uncheck: Show column and row headers Ok

Error handling in getJSON calls

Here's my addition.

From http://www.learnjavascript.co.uk/jq/reference/ajax/getjson.html and the official source

"The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead."

I did that and here is Luciano's updated code snippet:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function() { alert('getJSON request failed! '); })
.always(function() { alert('getJSON request ended!'); });

And with error description plus showing all json data as a string:

$.getJSON("example.json", function(data) {
  alert(JSON.stringify(data));
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });

If you don't like alerts, substitute them with console.log

$.getJSON("example.json", function(data) {
  console.log(JSON.stringify(data));
})
.done(function() { console.log('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { console.log('getJSON request failed! ' + textStatus); })
.always(function() { console.log('getJSON request ended!'); });

Convert String to Uri

What are you going to do with the URI?

If you're just going to use it with an HttpGet for example, you can just use the string directly when creating the HttpGet instance.

HttpGet get = new HttpGet("http://stackoverflow.com");

Invalid default value for 'dateAdded'

Change the type from datetime to timestamp and it will work! I had the same issue for mysql 5.5.56-MariaDB - MariaDB Server Hope it can help... sorry if depricated

Making a DateTime field in a database automatic?

Yes, here's an example:

CREATE TABLE myTable ( col1 int, createdDate datetime DEFAULT(getdate()), updatedDate datetime DEFAULT(getdate()) )

You can INSERT into the table without indicating the createdDate and updatedDate columns:

INSERT INTO myTable (col1) VALUES (1)

Or use the keyword DEFAULT:

INSERT INTO myTable (col1, createdDate, updatedDate) VALUES (1, DEFAULT, DEFAULT)

Then create a trigger for updating the updatedDate column:

CREATE TRIGGER dbo.updateMyTable 
ON dbo.myTable
FOR UPDATE 
AS 
BEGIN 
    IF NOT UPDATE(updatedDate) 
        UPDATE dbo.myTable SET updatedDate=GETDATE() 
        WHERE col1 IN (SELECT col1 FROM inserted) 
END 
GO

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

Use CSS :before and content property to print the breakpoint state in the <span id="breakpoint-js"> so the JavaScript just have to read this data to turn it as a variable to use within your function.

(run the snippet to see the example)

NOTE: I added a few line of CSS to use the <span> as a red flag in the upper corner of my browser. Just make sure to switch it back to display:none; before pushing your stuff public.

_x000D_
_x000D_
// initialize it with jquery when DOM is ready_x000D_
$(document).on('ready', function() {_x000D_
    getBootstrapBreakpoint();_x000D_
});_x000D_
_x000D_
// get bootstrap grid breakpoints_x000D_
var theBreakpoint = 'xs'; // bootstrap336 default = mobile first_x000D_
function getBootstrapBreakpoint(){_x000D_
   theBreakpoint = window.getComputedStyle(document.querySelector('#breakpoint-js'),':before').getPropertyValue('content').replace(/['"]+/g, '');_x000D_
   console.log('bootstrap grid breakpoint = ' + theBreakpoint);_x000D_
}
_x000D_
#breakpoint-js {_x000D_
  /* display: none; //comment this while developping. Switch back to display:NONE before commit */_x000D_
  /* optional red flag layout */_x000D_
  position: fixed;_x000D_
  z-index: 999;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  color: white;_x000D_
  padding: 5px 10px;_x000D_
  background-color: red;_x000D_
  opacity: .7;_x000D_
  /* end of optional red flag layout */_x000D_
}_x000D_
#breakpoint-js:before {_x000D_
  content: 'xs'; /* default = mobile first */_x000D_
}_x000D_
@media screen and (min-width: 768px) {_x000D_
  #breakpoint-js:before {_x000D_
    content: 'sm';_x000D_
  }_x000D_
}_x000D_
@media screen and (min-width: 992px) {_x000D_
  #breakpoint-js:before {_x000D_
    content: 'md';_x000D_
  }_x000D_
}_x000D_
@media screen and (min-width: 1200px) {_x000D_
  #breakpoint-js:before {_x000D_
    content: 'lg';_x000D_
  }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
  <span id="breakpoint-js"></span>_x000D_
  <div class="page-header">_x000D_
    <h1>Bootstrap grid examples</h1>_x000D_
    <p class="lead">Basic grid layouts to get you familiar with building within the Bootstrap grid system.</p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Getting the index of a particular item in array

FindIndex Extension

static class ArrayExtensions
{
    public static int FindIndex<T>(this T[] array, Predicate<T> match)
    {
        return Array.FindIndex(array, match);
    }
}

Usage

int[] array = { 9,8,7,6,5 };

var index = array.FindIndex(i => i == 7);

Console.WriteLine(index); // Prints "2"

Here's a fiddle with it.


Bonus: IndexOf Extension

I wrote this first not reading the question properly...

static class ArrayExtensions
{
    public static int IndexOf<T>(this T[] array, T value)
    {
        return Array.IndexOf(array, value);
    }   
}

Usage

int[] array = { 9,8,7,6,5 };

var index = array.IndexOf(7);

Console.WriteLine(index); // Prints "2"

Here's a fiddle with it.

How to calculate the sum of the datatable column in asp.net?

Compute Sum of Column in Datatable , Works 100%

lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "").ToString();

if you want to have any conditions, use it like this

   lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "srno=1 or srno in(1,2)").ToString();

How can I initialize a MySQL database with schema in a Docker container?

I've tried Greg's answer with zero success, I must have done something wrong since my database had no data after all the steps: I was using MariaDB's latest image, just in case.

Then I decided to read the entrypoint for the official MariaDB image, and used that to generate a simple docker-compose file:

database:
  image: mariadb
  ports:
     - 3306:3306
  expose:
     - 3306
  volumes:
     - ./docker/mariadb/data:/var/lib/mysql:rw
     - ./database/schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro
  environment:
     MYSQL_ALLOW_EMPTY_PASSWORD: "yes"

Now I'm able to persist my data AND generate a database with my own schema!

Scala check if element is present in a list

In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.

In this case, you don't need to add any wrapper functions around lists.

Removing empty rows of a data file in R

This is similar to some of the above answers, but with this, you can specify if you want to remove rows with a percentage of missing values greater-than or equal-to a given percent (with the argument pct)

drop_rows_all_na <- function(x, pct=1) x[!rowSums(is.na(x)) >= ncol(x)*pct,]

Where x is a dataframe and pct is the threshold of NA-filled data you want to get rid of.

pct = 1 means remove rows that have 100% of its values NA. pct = .5 means remome rows that have at least half its values NA

Failed to find target with hash string 'android-25'

It seems like that it is only me who are so clumsy, because i have yet to found a solution that my case required.

I am developing a multi-modular project, thus base android module configuration is extracted in single gradle script. All the concrete versions of sdks/libs are also extracted in a script.

A script containing versions looked like this:

...

ext.androidVersions = [
    compile_sdk_version     : '27',
    min_sdk_version         : '19',
    target_sdk_version      : '27',
    build_tool_version      : '27.0.3',
    application_id          : 'com.test.test',
]

...

Not accustomed to groovy syntax my eye has not spotted that the values for compile, min and target sdks were not integers but STRINGS! Therefore a compiler rightfully complained about not being able to find an sdk a version of which would match HASH STRING '27'.

So the solution would be to make sdk's versions integers: ...

ext.androidVersions = [
    compile_sdk_version     : 27,
    min_sdk_version         : 19,
    target_sdk_version      : 27,
    build_tool_version      : '27.0.3',
    application_id          : 'com.test.test',
]

...

Best Practices: working with long, multiline strings in PHP?

you can also use:

<?php
ob_start();
echo "some text";
echo "\n";

// you can also use: 
?> 
some text can be also written here, or maybe HTML:
<div>whatever<\div>
<?php
echo "you can basically write whatever you want";
// and then: 
$long_text = ob_get_clean();

SQL Sum Multiple rows into one

Thank you for your responses. Turns out my problem was a database issue with duplicate entries, not with my logic. A quick table sync fixed that and the SUM feature worked as expected. This is all still useful knowledge for the SUM feature and is worth reading if you are having trouble using it.

Reading settings from app.config or web.config in .NET

Just for completeness, there's another option available for web projects only: System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]

The benefit of this is that it doesn't require an extra reference to be added, so it may be preferable for some people.

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

The SQLite command line utility has a .schema TABLENAME command that shows you the create statements.

Failure [INSTALL_FAILED_INVALID_APK]

I had this problem on android Studio because in my Debug build i've added version name suffix -DEBUG and the - was the problem.

Try to only have letters, numbers and dots on your version names and application ids

Ruby array to string conversion

I find this way readable and rubyish:

add_quotes =- > x{"'#{x}'"}

p  ['12','34','35','231'].map(&add_quotes).join(',') => "'12','34','35','231'"

Difference between one-to-many and many-to-one relationship

One-to-Many and Many-to-One are similar in Multiplicity but not Aspect (i.e. Directionality).

The mapping of Associations between entity classes and the Relationships between tables. There are two categories of Relationships:

  1. Multiplicity (ER term: cardinality)
    • One-to-one relationships: Example Husband and Wife
    • One-to-Many relationships: Example Mother and Children
    • Many-to-Many relationships: Example Student and Subject
  2. Directionality : Not affect on mapping but makes difference on how we can access data.
    • Uni-directional relationships: A relationship field or property that refers to the other entity.
    • Bi-directional relationships: Each entity has a relationship field or property that refers to the other entity.

urllib2 and json

This is what worked for me:

import json
import requests
url = 'http://xxx.com'
payload = {'param': '1', 'data': '2', 'field': '4'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data = json.dumps(payload), headers = headers)

How to make use of ng-if , ng-else in angularJS

There is no directive for ng-else

You can use ng-if to achieve if(){..} else{..} in angularJs.

For your current situation,

<div ng-if="data.id == 5">
<!-- If block -->
</div>
<div ng-if="data.id != 5">
<!-- Your Else Block -->
</div>

Linq: GroupBy, Sum and Count

sometimes you need to select some fields by FirstOrDefault() or singleOrDefault() you can use the below query:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new Models.ResultLine
            {
                ProductName = cl.select(x=>x.Name).FirstOrDefault(),
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

Iterate over object attributes in python

in general put a __iter__ method in your class and iterate through the object attributes or put this mixin class in your class.

class IterMixin(object):
    def __iter__(self):
        for attr, value in self.__dict__.iteritems():
            yield attr, value

Your class:

>>> class YourClass(IterMixin): pass
...
>>> yc = YourClass()
>>> yc.one = range(15)
>>> yc.two = 'test'
>>> dict(yc)
{'one': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 'two': 'test'}

SQLite error 'attempt to write a readonly database' during insert?

This can be caused by SELinux. If you don't want to disable SELinux completely, you need to set the db directory fcontext to httpd_sys_rw_content_t.

semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/railsapp/db(/.*)?"
restorecon -v /var/www/railsapp/db

GCD to perform task in main thread

No you don't need to check if you're in the main thread. Here is how you can do this in Swift:

runThisInMainThread { () -> Void in
    runThisInMainThread { () -> Void in
        // No problem
    }
}

func runThisInMainThread(block: dispatch_block_t) {
    dispatch_async(dispatch_get_main_queue(), block)
}

Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions

How to find my Subversion server version number?

To find the version of the subversion REPOSITORY you can:

  1. Look to the repository on the web and on the bottom of the page it will say something like:
    "Powered by Subversion version 1.5.2 (r32768)."
  2. From the command line: <insert curl, grep oneliner here>

If not displayed, view source of the page

<svn version="1.6.13 (r1002816)" href="http://subversion.tigris.org/"> 

Now for the subversion CLIENT:

svn --version

will suffice

Conditionally formatting cells if their value equals any value of another column

Here is the formula

create a new rule in conditional formating based on a formula. Use the following formula and apply it to $A:$A

=NOT(ISERROR(MATCH(A1,$B$1:$B$1000,0)))


enter image description here

here is the example sheet to download if you encounter problems


UPDATE
here is @pnuts's suggestion which works perfect as well:

=MATCH(A1,B:B,0)>0


How to split a long array into smaller arrays, with JavaScript

More compact:

_x000D_
_x000D_
const chunk = (xs, size) =>_x000D_
  xs.map((_, i) =>_x000D_
    (i % size === 0 ? xs.slice(i, i + size) : null)).filter(Boolean);_x000D_
    _x000D_
// Usage:_x000D_
const sampleArray = new Array(33).fill(undefined).map((_, i) => i);_x000D_
_x000D_
console.log(chunk(sampleArray, 5));
_x000D_
_x000D_
_x000D_

Visual C++ executable and missing MSVCR100d.dll

This problem explained in MSDN Library and as I understand installing Microsoft's Redistributable Package can help.

But sometimes the following solution can be used (as developer's side solution):

In your Visual Studio, open Project properties -> Configuration properties -> C/C++ -> Code generation and change option Runtime Library to /MT instead of /MD

Using margin / padding to space <span> from the rest of the <p>

Use div instead of span, or add display: block; to your css style for the span tag.

Doctrine 2 ArrayCollection filter method

The Collection#filter method really does eager load all members. Filtering at the SQL level will be added in doctrine 2.3.

Appending HTML string to the DOM

The idea is to use innerHTML on an intermediary element and then move all of its child nodes to where you really want them via appendChild.

var target = document.getElementById('test');
var str = '<p>Just some <span>text</span> here</p>';

var temp = document.createElement('div');
temp.innerHTML = str;
while (temp.firstChild) {
  target.appendChild(temp.firstChild);
}

This avoids wiping out any event handlers on div#test but still allows you to append a string of HTML.

Remove first 4 characters of a string with PHP

$num = "+918883967576";

$str = substr($num, 3);

echo $str;

Output:8883967576

How can I show line numbers in Eclipse?

Update November 2015:

In Eclipse Mars 4.5.1, line numbers are (annoyingly) turned off by default again. Follow the below instructions to enable it.


Update December 2013:

Lars Vogel just published on his blog:

Line numbers are default in Eclipse SDK Luna (4.4) as of today

(December 10, 2013)

We conducted a user survey if users want to have line numbers activated in text editors in the Eclipse IDE by default.
The response was very clear:

YES : 80.07% (1852 responses)
NO  : 19.93% (461 responses)
Total  : 2313
Skipped:   15

With Bug 421313, Review - Line number should be activated by default, we enabled it for the Eclipse SDK build, I assume other Eclipse packages will follow.


Update August 2014

Line number default length is now 120 (instead of 80) for Eclipse Mars 4.5M1.
See "How to customize Eclipse's text editor code formating".


Original answer (March 2009)

To really have it by default, you can write a script which ensure, before launching eclipse, that:
[workspace]\.metadata\.plugins\org.eclipse.core.runtime\.settings\org.eclipse.ui.editors.prefs does contain:

lineNumberRuler=true

(with [workspace] being the root directory of your eclipse workspace)
Then eclipse will be opened with "line numbers shown 'by default' "


Otherwise, you can also type 'CTRL+1' and then "line", which will give you access to the command "Show line numbers"
(that will switch to option "show line numbers" in the text editors part of the option.

Or you can just type "numb" in Windows Preferences to access to the Text Editor part:

show line number

Picture from "How to display line numbers in Eclipse" of blog "Mkyong.com"

How to select <td> of the <table> with javascript?

There begin to appear some answers that assume you want to get all <td> elements from #table. If so, the simplest cross-browser way how to do this is document.getElementById('table').getElementsByTagName('td'). This works because getElementsByTagName doesn't return only immediate children. No loops are needed.

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

There is one simple answer for this: You have been output something else, like text, or anything related to output from your page before you send your header. This affect why you get that error.

Just check your code for posible output or you can put the header on top of your method so it will be send first.

How to implement my very own URI scheme on Android

Complementing the @DanielLew answer, to get the values of the parameteres you have to do this:

URI example: myapp://path/to/what/i/want?keyOne=valueOne&keyTwo=valueTwo

in your activity:

Intent intent = getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
  Uri uri = intent.getData();
  String valueOne = uri.getQueryParameter("keyOne");
  String valueTwo = uri.getQueryParameter("keyTwo");
}

How to force NSLocalizedString to use a specific language

As said earlier, just do:

[[NSUserDefaults standardUserDefaults] setObject: [NSArray arrayWithObjects:@"el", nil] forKey:@"AppleLanguages"];

But to avoid having to restart the app, put the line in the main method of main.m, just before UIApplicationMain(...).

Android Camera : data intent returns null

Kotlin code that works for me:

 private fun takePhotoFromCamera() {
          val intent = Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(intent, PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA)
      }

And get Result :

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
 if (requestCode == PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA) {
         if (resultCode == Activity.RESULT_OK) {
           val photo: Bitmap? =  MediaStore.Images.Media.getBitmap(this.contentResolver, Uri.parse( data!!.dataString)   )
            // Do something here : set image to an ImageView or save it ..   
              imgV_pic.imageBitmap = photo 
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i(TAG, "Camera  , RESULT_CANCELED ")
        }

    }

}

and don't forget to declare request code:

companion object {
 const val PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA = 300
  }

Automatically add all files in a folder to a target using CMake?

So Why not use powershell to create the list of source files for you. Take a look at this script

param (
    [Parameter(Mandatory=$True)]
    [string]$root 
)

if (-not (Test-Path  -Path $root)) {    
throw "Error directory does not exist"
}

#get the full path of the root
$rootDir = get-item -Path $root
$fp=$rootDir.FullName;


$files = Get-ChildItem -Path $root -Recurse -File | 
         Where-Object { ".cpp",".cxx",".cc",".h" -contains $_.Extension} | 
         Foreach {$_.FullName.replace("${fp}\","").replace("\","/")}

$CMakeExpr = "set(SOURCES "

foreach($file in $files){

    $CMakeExpr+= """$file"" " ;
}
$CMakeExpr+=")"
return $CMakeExpr;

Suppose you have a folder with this structure

C:\Workspace\A
--a.cpp
C:\Workspace\B 
--b.cpp

Now save this file as "generateSourceList.ps1" for example, and run the script as

~>./generateSourceList.ps1 -root "C:\Workspace" > out.txt

out.txt file will contain

set(SOURCE "A/a.cpp" "B/b.cpp")

Why does this code using random strings print "hello world"?

Here is a minor improvement for Denis Tulskiy answer. It cuts the time by half

public static long[] generateSeed(String goal, long start, long finish) {
    char[] input = goal.toCharArray();

    int[] dif = new int[input.length - 1];
    for (int i = 1; i < input.length; i++) {
        dif[i - 1] = input[i] - input[i - 1];
    }

    mainLoop:
    for (long seed = start; seed < finish; seed++) {
        Random random = new Random(seed);
        int lastChar = random.nextInt(27);
        int base = input[0] - lastChar;
        for (int d : dif) {
            int nextChar = random.nextInt(27);
            if (nextChar - lastChar != d) {
                continue mainLoop;
            }
            lastChar = nextChar;
        }
        if(random.nextInt(27) == 0){
            return new long[]{seed, base};
        }
    }

    throw new NoSuchElementException("Sorry :/");
}

Get first key in a (possibly) associative array?

$myArray = array(
    2 => '3th element',
    4 => 'first element',
    1 => 'second element',
    3 => '4th element'
);
echo min(array_keys($myArray)); // return 1

How to check if an object is defined?

You check if it's null in C# like this:

if(MyObject != null) {
  //do something
}

If you want to check against default (tough to understand the question on the info given) check:

if(MyObject != default(MyObject)) {
 //do something
}

Play sound file in a web-page in the background

Though this might be too late to comment but here's the working code for problems such as yours.

<div id="player">
    <audio autoplay hidden>
     <source src="link/to/file/file.mp3" type="audio/mpeg">
                If you're reading this, audio isn't supported. 
    </audio>
</div>

Linux command: How to 'find' only text files?

I prefer xargs

find . -type f | xargs grep -I "needle text"

if your filenames are weird look up using the -0 options:

find . -type f -print0 | xargs -0 grep -I "needle text"

Python JSON serialize a Decimal object

This is what I have, extracted from our class

class CommonJSONEncoder(json.JSONEncoder):

    """
    Common JSON Encoder
    json.dumps(myString, cls=CommonJSONEncoder)
    """

    def default(self, obj):

        if isinstance(obj, decimal.Decimal):
            return {'type{decimal}': str(obj)}

class CommonJSONDecoder(json.JSONDecoder):

    """
    Common JSON Encoder
    json.loads(myString, cls=CommonJSONEncoder)
    """

    @classmethod
    def object_hook(cls, obj):
        for key in obj:
            if isinstance(key, six.string_types):
                if 'type{decimal}' == key:
                    try:
                        return decimal.Decimal(obj[key])
                    except:
                        pass

    def __init__(self, **kwargs):
        kwargs['object_hook'] = self.object_hook
        super(CommonJSONDecoder, self).__init__(**kwargs)

Which passes unittest:

def test_encode_and_decode_decimal(self):
    obj = Decimal('1.11')
    result = json.dumps(obj, cls=CommonJSONEncoder)
    self.assertTrue('type{decimal}' in result)
    new_obj = json.loads(result, cls=CommonJSONDecoder)
    self.assertEqual(new_obj, obj)

    obj = {'test': Decimal('1.11')}
    result = json.dumps(obj, cls=CommonJSONEncoder)
    self.assertTrue('type{decimal}' in result)
    new_obj = json.loads(result, cls=CommonJSONDecoder)
    self.assertEqual(new_obj, obj)

    obj = {'test': {'abc': Decimal('1.11')}}
    result = json.dumps(obj, cls=CommonJSONEncoder)
    self.assertTrue('type{decimal}' in result)
    new_obj = json.loads(result, cls=CommonJSONDecoder)
    self.assertEqual(new_obj, obj)

Regular cast vs. static_cast vs. dynamic_cast

FYI, I believe Bjarne Stroustrup is quoted as saying that C-style casts are to be avoided and that you should use static_cast or dynamic_cast if at all possible.

Barne Stroustrup's C++ style FAQ

Take that advice for what you will. I'm far from being a C++ guru.

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

You can use git log with the pathnames of the respective folders:

git log A B

The log will only show commits made in A and B. I usually throw in --stat to make things a little prettier, which helps for quick commit reviews.

Where is the itoa function in Linux?

Here is a much improved version of Archana's solution. It works for any radix 1-16, and numbers <= 0, and it shouldn't clobber memory.

static char _numberSystem[] = "0123456789ABCDEF";
static char _twosComp[] = "FEDCBA9876543210";

static void safestrrev(char *buffer, const int bufferSize, const int strlen)
{
    int len = strlen;
    if (len > bufferSize)
    {
        len = bufferSize;
    }
    for (int index = 0; index < (len / 2); index++)
    {
        char ch = buffer[index];
        buffer[index] = buffer[len - index - 1];
        buffer[len - index - 1] = ch;
    }
}

static int negateBuffer(char *buffer, const int bufferSize, const int strlen, const int radix)
{
    int len = strlen;
    if (len > bufferSize)
    {
        len = bufferSize;
    }
    if (radix == 10)
    {
        if (len < (bufferSize - 1))
        {
            buffer[len++] = '-';
            buffer[len] = '\0';
        }
    }
    else
    {
        int twosCompIndex = 0;
        for (int index = 0; index < len; index++)
        {
            if ((buffer[index] >= '0') && (buffer[index] <= '9'))
            {
                twosCompIndex = buffer[index] - '0';
            }
            else if ((buffer[index] >= 'A') && (buffer[index] <= 'F'))
            {
                twosCompIndex = buffer[index] - 'A' + 10;
            }
            else if ((buffer[index] >= 'a') && (buffer[index] <= 'f'))
            {
                twosCompIndex = buffer[index] - 'a' + 10;
            }
            twosCompIndex += (16 - radix);
            buffer[index] = _twosComp[twosCompIndex];
        }
        if (len < (bufferSize - 1))
        {
            buffer[len++] = _numberSystem[radix - 1];
            buffer[len] = 0;
        }
    }
    return len;
}

static int twosNegation(const int x, const int radix)
{
    int n = x;
    if (x < 0)
    {
        if (radix == 10)
        {
            n = -x;
        }
        else
        {
            n = ~x;
        }
    }
    return n;
}

static char *safeitoa(const int x, char *buffer, const int bufferSize, const int radix)
{
    int strlen = 0;
    int n = twosNegation(x, radix);
    int nuberSystemIndex = 0;

    if (radix <= 16)
    {
        do
        {
            if (strlen < (bufferSize - 1))
            {
                nuberSystemIndex = (n % radix);
                buffer[strlen++] = _numberSystem[nuberSystemIndex];
                buffer[strlen] = '\0';
                n = n / radix;
            }
            else
            {
                break;
            }
        } while (n != 0);
        if (x < 0)
        {
            strlen = negateBuffer(buffer, bufferSize, strlen, radix);
        }
        safestrrev(buffer, bufferSize, strlen);
        return buffer;
    }
    return NULL;
}

Stop handler.postDelayed()

You can define a boolean and change it to false when you want to stop handler. Like this..

boolean stop = false;

handler.postDelayed(new Runnable() {
    @Override
    public void run() {

        //do your work here..

        if (!stop) {
            handler.postDelayed(this, delay);
        }
    }
}, delay);

ASP.NET MVC: No parameterless constructor defined for this object

I just had a similar problem. The same exception occurs when a Model has no parameterless constructor.

The call stack was figuring a method responsible for creating a new instance of a model.

System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)


Here is a sample:

public class MyController : Controller
{
    public ActionResult Action(MyModel model)
    {

    }
}

public class MyModel
{
    public MyModel(IHelper helper) // MVC cannot call that
    {
        // ...
    }

    public MyModel() // MVC can call that
    {
    }
}

Copy folder recursively, excluding some folders

inspired by @SteveLazaridis's answer, which would fail, here is a POSIX shell function - just copy and paste into a file named cpx in yout $PATH and make it executible (chmod a+x cpr). [Source is now maintained in my GitLab.

#!/bin/sh

# usage: cpx [-n|--dry-run] "from_path" "to_path" "newline_separated_exclude_list"
# limitations: only excludes from "from_path", not it's subdirectories

cpx() {
# run in subshell to avoid collisions
  (_CopyWithExclude "$@")
}

_CopyWithExclude() {
  case "$1" in
    -n|--dry-run) { DryRun='echo'; shift; } ;;
  esac

  from="$1"
  to="$2"
  exclude="$3"

  $DryRun mkdir -p "$to"

  if [ -z "$exclude" ]; then
      cp "$from" "$to"
      return
  fi

  ls -A1 "$from" \
    | while IFS= read -r f; do
        unset excluded
        if [ -n "$exclude" ]; then
          for x in $(printf "$exclude"); do
          if [ "$f" = "$x" ]; then
              excluded=1
              break
          fi
          done
        fi
        f="${f#$from/}"
        if [ -z "$excluded" ]; then
          $DryRun cp -R "$f" "$to"
        else
          [ -n "$DryRun" ] && echo "skip '$f'"
        fi
      done
}

# Do not execute if being sourced
[ "${0#*cpx}" != "$0" ] && cpx "$@"

Example usage

EXCLUDE="
.git
my_secret_stuff
"
cpr "$HOME/my_stuff" "/media/usb" "$EXCLUDE"

Cleanest way to toggle a boolean variable in Java?

This answer came up when searching for "java invert boolean function". The example below will prevent certain static analysis tools from failing builds due to branching logic. This is useful if you need to invert a boolean and haven't built out comprehensive unit tests ;)

Boolean.valueOf(aBool).equals(false)

or alternatively:

Boolean.FALSE.equals(aBool)

or

Boolean.FALSE::equals

Minimum Hardware requirements for Android development

Have a look at the android SDK system requirements Here

I'm guessing some extra RAM would help your developing experience...Also the emulator does take some time to start on even the speediest systems.

What's the best way to check if a String represents an integer in Java?

Did a quick benchmark. Exceptions aren't actually that expensivve, unless you start popping back multiple methods and the JVM has to do a lot of work to get the execution stack in place. When staying in the same method, they aren't bad performers.

 public void RunTests()
 {
     String str = "1234567890";

     long startTime = System.currentTimeMillis();
     for(int i = 0; i < 100000; i++)
         IsInt_ByException(str);
     long endTime = System.currentTimeMillis();
     System.out.print("ByException: ");
     System.out.println(endTime - startTime);

     startTime = System.currentTimeMillis();
     for(int i = 0; i < 100000; i++)
         IsInt_ByRegex(str);
     endTime = System.currentTimeMillis();
     System.out.print("ByRegex: ");
     System.out.println(endTime - startTime);

     startTime = System.currentTimeMillis();
     for(int i = 0; i < 100000; i++)
         IsInt_ByJonas(str);
     endTime = System.currentTimeMillis();
     System.out.print("ByJonas: ");
     System.out.println(endTime - startTime);
 }

 private boolean IsInt_ByException(String str)
 {
     try
     {
         Integer.parseInt(str);
         return true;
     }
     catch(NumberFormatException nfe)
     {
         return false;
     }
 }

 private boolean IsInt_ByRegex(String str)
 {
     return str.matches("^-?\\d+$");
 }

 public boolean IsInt_ByJonas(String str)
 {
     if (str == null) {
             return false;
     }
     int length = str.length();
     if (length == 0) {
             return false;
     }
     int i = 0;
     if (str.charAt(0) == '-') {
             if (length == 1) {
                     return false;
             }
             i = 1;
     }
     for (; i < length; i++) {
             char c = str.charAt(i);
             if (c <= '/' || c >= ':') {
                     return false;
             }
     }
     return true;
 }

Output:

ByException: 31

ByRegex: 453 (note: re-compiling the pattern every time)

ByJonas: 16

I do agree that Jonas K's solution is the most robust too. Looks like he wins :)

Center a button in a Linear layout

This is working for me.

android:layout_alignParentEnd="true"

Multi-dimensional associative arrays in JavaScript

Get the value for an array of associative arrays's property when the property name is an integer:

Starting with an Associative Array where the property names are integers:

var categories = [
    {"1":"Category 1"},
    {"2":"Category 2"},
    {"3":"Category 3"},
    {"4":"Category 4"}
];

Push items to the array:

categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});

Loop through array and do something with the property value.

for (var i = 0; i < categories.length; i++) {
    for (var categoryid in categories[i]) {
        var category = categories[i][categoryid];
        // log progress to the console
        console.log(categoryid + " : " + category);
        //  ... do something
    }
}

Console output should look like this:

1 : Category 1
2 : Category 2
3 : Category 3
4 : Category 4
2300 : Category 2300
2301 : Category 2301

As you can see, you can get around the associative array limitation and have a property name be an integer.

NOTE: The associative array in my example is the json you would have if you serialized a Dictionary[] object.

Can we have multiple "WITH AS" in single sql - Oracle SQL

Yes you can...

WITH SET1 AS (SELECT SYSDATE FROM DUAL), -- SET1 initialised
     SET2 AS (SELECT * FROM SET1)        -- SET1 accessed
SELECT * FROM SET2;                      -- SET2 projected

10/29/2013 10:43:26 AM

Follow the order in which it should be initialized in Common Table Expressions

Delete commits from a branch in Git

git reset --hard commitId

git push <origin> <branch> --force

PS: CommitId refers the one which you want to revert back to

Converting Hexadecimal String to Decimal Integer

My way:

private static int hexToDec(String hex) {
    return Integer.parseInt(hex, 16);
}

Number of visitors on a specific page

As Blexy already answered, go to "Behavior > Site Content > All Pages".

Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:

                                                     sidebar

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

What issues should be considered when overriding equals and hashCode in Java?

There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate, if you didn't think this was unreasonably complicated already!

Lazy loaded objects are subclasses

If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store. These proxies are implemented as subclasses of your own class. This means thatthis.getClass() == o.getClass() will return false. For example:

Person saved = new Person("John Doe");
Long key = dao.save(saved);
dao.flush();
Person retrieved = dao.retrieve(key);
saved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy

If you're dealing with an ORM, using o instanceof Person is the only thing that will behave correctly.

Lazy loaded objects have null-fields

ORMs usually use the getters to force loading of lazy loaded objects. This means that person.name will be null if person is lazy loaded, even if person.getName() forces loading and returns "John Doe". In my experience, this crops up more often in hashCode() and equals().

If you're dealing with an ORM, make sure to always use getters, and never field references in hashCode() and equals().

Saving an object will change its state

Persistent objects often use a id field to hold the key of the object. This field will be automatically updated when an object is first saved. Don't use an id field in hashCode(). But you can use it in equals().

A pattern I often use is

if (this.getId() == null) {
    return this == other;
}
else {
    return this.getId().equals(other.getId());
}

But: you cannot include getId() in hashCode(). If you do, when an object is persisted, its hashCode changes. If the object is in a HashSet, you'll "never" find it again.

In my Person example, I probably would use getName() for hashCode and getId() plus getName() (just for paranoia) for equals(). It's okay if there are some risk of "collisions" for hashCode(), but never okay for equals().

hashCode() should use the non-changing subset of properties from equals()

List all environment variables from the command line

You can use SET in cmd

To show the current variable, just SET is enough

To show certain variable such as 'PATH', use SET PATH.

For help, type set /?.

How do I read all classes from a Java package in the classpath?

use dependency maven:

groupId: net.sf.extcos
artifactId: extcos
version: 0.4b

then use this code :

ComponentScanner scanner = new ComponentScanner();
        Set classes = scanner.getClasses(new ComponentQuery() {
            @Override
            protected void query() {
                select().from("com.leyton").returning(allExtending(DynamicForm.class));
            }
        });

How to iterate over a TreeMap?

Just to point out the generic way to iterate over any map:

 private <K, V> void iterateOverMap(Map<K, V> map) {
    for (Map.Entry<K, V> entry : map.entrySet()) {
        System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
    }
    }

Working with INTERVAL and CURDATE in MySQL

You need DATE_ADD/DATE_SUB:

AND v.date > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH))
AND v.date < (DATE_SUB(CURDATE(), INTERVAL 1 MONTH))

should work.

How to import a Python class that is in a directory above?

from ..subpkg2 import mod

Per the Python docs: When inside a package hierarchy, use two dots, as the import statement doc says:

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. The specification for relative imports is contained within PEP 328.

PEP 328 deals with absolute/relative imports.

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

Test if element is present using Selenium WebDriver?

Giving my snippet of code. So, the below method checks if a random web element 'Create New Application' button exists on a page or not. Note that I have used the wait period as 0 seconds.

public boolean isCreateNewApplicationButtonVisible(){
    WebDriverWait zeroWait = new WebDriverWait(driver, 0);
    ExpectedCondition<WebElement> c = ExpectedConditions.presenceOfElementLocated(By.xpath("//input[@value='Create New Application']"));
    try {
        zeroWait.until(c);
        logger.debug("Create New Application button is visible");
        return true;
    } catch (TimeoutException e) {
        logger.debug("Create New Application button is not visible");
        return false;
    }
}

Line Break in XML?

In XML a line break is a normal character. You can do this:

<xml>
  <text>some text
with
three lines</text>
</xml>

and the contents of <text> will be

some text
with
three lines

If this does not work for you, you are doing something wrong. Special "workarounds" like encoding the line break are unnecessary. Stuff like \n won't work, on the other hand, because XML has no escape sequences*.


* Note that &#xA; is the character entity that represents a line break in serialized XML. "XML has no escape sequences" means the situation when you interact with a DOM document, setting node values through the DOM API.

This is where neither &#xA; nor things like \n will work, but an actual newline character will. How this character ends up in the serialized document (i.e. "file") is up to the API and should not concern you.


Since you seem to wonder where your line breaks go in HTML: Take a look into your source code, there they are. HTML ignores line breaks in source code. Use <br> tags to force line breaks on screen.

Here is a JavaScript function that inserts <br> into a multi-line string:

function nl2br(s) { return s.split(/\r?\n/).join("<br>"); }

Alternatively you can force line breaks at new line characters with CSS:

div.lines {
    white-space: pre-line;
}

How to resolve 'unrecognized selector sent to instance'?

For me, what caused this error was that I accidentally had the same message being sent twice to the same class member. When I right clicked on the button in the gui, I could see the method name twice, and I just deleted one. Newbie mistake in my case for sure, but wanted to get it out there for other newbies to consider.

Downloading Java JDK on Linux via wget is shown license page instead

download jdk 8u221

$ wget -c --content-disposition "https://javadl.oracle.com/webapps/download/AutoDL?BundleId=239835_230deb18db3e4014bb8e3e8324f81b43"
$ old=$(ls -hat | grep jre | head -n1)
$ mv $old $(echo $old | awk -F"?" '{print $1}')

my blog 044-wget??jdk8u221

How do I find out what License has been applied to my SQL Server installation?

SQL Server does not track licensing. Customers are responsible for tracking the assignment of licenses to servers, following the rules in the Licensing Guide.

disable editing default value of text input

I don't think all the other answerers understood the question correctly. The question requires disabling editing part of the text. One solution I can think of is simulating a textbox with a fixed prefix which is not part of the textarea or input.

An example of this approach is:

<div style="border:1px solid gray; color:#999999; font-family:arial; font-size:10pt; width:200px; white-space:nowrap;">Default Notes<br/>
<textarea style="border:0px solid black;" cols="39" rows="5"></textarea></div>

The other approach, which I end up using is using JS and JQuery to simulate "Disable" feature. Example with pseudo-code (cannot be specific cause of legal issue):

  // disable existing notes by preventing keystroke
  document.getElementById("txtNotes").addEventListener('keydown', function (e) {
    if (cursorLocation < defaultNoteLength ) {
            e.preventDefault();
  });

    // disable existing notes by preventing right click
    document.addEventListener('contextmenu', function (e) {
        if (cursorLocation < defaultNoteLength )
            e.preventDefault();
    });

Thanks, Carsten, for mentioning that this question is old, but I found that the solution might help other people in the future.

How to delete migration files in Rails 3

Run below commands from app's home directory:

  1. rake db:migrate:down VERSION="20140311142212" (here version is the timestamp prepended by rails when migration was created. This action will revert DB changes due to this migration)

  2. Run "rails destroy migration migration_name" (migration_name is the one use chose while creating migration. Remove "timestamp_" from your migration file name to get it)

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

2 Steps to fix this.. 1, connect to internet. 2, Click on clean project. this will fix it :)

How do you kill a Thread in Java?

'Killing a thread' is not the right phrase to use. Here is one way we can implement graceful completion/exit of the thread on will:

Runnable which I used:

class TaskThread implements Runnable {

    boolean shouldStop;

    public TaskThread(boolean shouldStop) {
        this.shouldStop = shouldStop;
    }

    @Override
    public void run() {

        System.out.println("Thread has started");

        while (!shouldStop) {
            // do something
        }

        System.out.println("Thread has ended");

    }

    public void stop() {
        shouldStop = true;
    }

}

The triggering class:

public class ThreadStop {

    public static void main(String[] args) {

        System.out.println("Start");

        // Start the thread
        TaskThread task = new TaskThread(false);
        Thread t = new Thread(task);
        t.start();

        // Stop the thread
        task.stop();

        System.out.println("End");

    }

}

Insert Update trigger how to determine if insert or update

Quick solution MySQL

By the way: I'm using MySQL PDO.

(1) In an auto increment table just get the highest value (my column name = id) from the incremented column once every script run first:

$select = "
    SELECT  MAX(id) AS maxid
    FROM    [tablename]
    LIMIT   1
";

(2) Run the MySQL query as you normaly would, and cast the result to integer, e.g.:

$iMaxId = (int) $result[0]->maxid;

(3) After the "INSERT INTO ... ON DUPLICATE KEY UPDATE" query get the last inserted id your prefered way, e.g.:

$iLastInsertId = (int) $db->lastInsertId();

(4) Compare and react: If the lastInsertId is higher than the highest in the table, it's probably an INSERT, right? And vice versa.

if ($iLastInsertId > $iMaxObjektId) {
    // IT'S AN INSERT
}
else {
    // IT'S AN UPDATE
}

I know it's quick and maybe dirty. And it's an old post. But, hey, I was searching for a solution a for long time, and maybe somebody finds my way somewhat useful anyway. All the best!

How to include quotes in a string

Escape them with backslashes.

"I want to learn \"C#\""

How to get share counts using graph API

You should not use graph api. If you either call:

or

both will return:

{
  "id": "http://www.apple.com",
  "shares": 1146997
}

But the number shown is the sum of:

  • number of likes of this URL
  • number of shares of this URL (this includes copy/pasting a link back to Facebook)
  • number of likes and comments on stories on Facebook about this URL
  • number of inbox messages containing this URL as an attachment.

So you must use FQL.
Look at this answer: How to fetch facebook likes, share, comments count from an article

How to turn on line numbers in IDLE?

There's a set of useful extensions to IDLE called IDLEX that works with MacOS and Windows http://idlex.sourceforge.net/

It includes line numbering and I find it quite handy & free.

Otherwise there are a bunch of other IDEs some of which are free: https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

why are there two different kinds of for loops in java?

There is an excellent summary of this feature in the article The For-Each Loop. It shows by example how using the for-each style can produce clearer code that is easier to read and write.

Refresh/reload the content in Div using jquery/ajax

$(document).ready(function() {
var pageRefresh = 5000; //5 s
    setInterval(function() {
        refresh();
    }, pageRefresh);
});

// Functions

function refresh() {
    $('#div1').load(location.href + " #div1");
    $('#div2').load(location.href + " #div2");
}

What does set -e mean in a bash script?

From help set :

  -e  Exit immediately if a command exits with a non-zero status.

But it's considered bad practice by some (bash FAQ and irc freenode #bash FAQ authors). It's recommended to use:

trap 'do_something' ERR

to run do_something function when errors occur.

See http://mywiki.wooledge.org/BashFAQ/105

Check if table exists and if it doesn't exist, create it in SQL Server 2008

If I am not wrong, this should work:

    if not exists (Select 1 from tableName)
create table ...

how much memory can be accessed by a 32 bit machine?

Yes, a 32-bit architecture is limited to addressing a maximum of 4 gigabytes of memory. Depending on the operating system, this number can be cut down even further due to reserved address space.

This limitation can be removed on certain 32-bit architectures via the use of PAE (Physical Address Extension), but it must be supported by the processor. PAE eanbles the processor to access more than 4 GB of memory, but it does not change the amount of virtual address space available to a single process—each process would still be limited to a maximum of 4 GB of address space.

And yes, theoretically a 64-bit architecture can address 16.8 million terabytes of memory, or 2^64 bytes. But I don't believe the current popular implementations fully support this; for example, the AMD64 architecture can only address up to 1 terabyte of memory. Additionally, your operating system will also place limitations on the amount of supported, addressable memory. Many versions of Windows (particularly versions designed for home or other non-server use) are arbitrarily limited.

How to turn off INFO logging in Spark?

Programmatic way

spark.sparkContext.setLogLevel("WARN")

Available Options

ERROR
WARN 
INFO 

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

How to connect a Windows Mobile PDA to Windows 10

Install Windows Mobile Device Center for your architecture. (It will install older versions of .NET if needed.) In USB to PC settings on device uncheck Enable advanced network and tap OK. This worked for me on 2 different Windows 10 PCs.

How to print React component on click of a button?

On 6/19/2017 This worked perfect for me.

import React, { Component } from 'react'

class PrintThisComponent extends Component {
  render() {
    return (
      <div>
        <button onClick={() => window.print()}>PRINT</button>
        <p>Click above button opens print preview with these words on page</p>
      </div>
    )
  }
}

export default PrintThisComponent

How do I right align div elements?

If you don't have to support IE9 and below you can use flexbox to solve this: codepen

There's also a few bugs with IE10 and 11 (flexbox support), but they are not present in this example

You can vertically align the <button> and the <form> by wrapping them in a container with flex-direction: column. The source order of the elements will be the order in which they're displayed from top to bottom so I reordered them.

You can then horizontally align the form & button container with the canvas by wrapping them in a container with flex-direction: row. Again the source order of the elements will be the order in which they're displayed from left to right so I reordered them.

Also, this would require that you remove all position and float style rules from the code linked in the question.

Here's a trimmed down version of the HTML in the codepen linked above.

<div id="mainContainer">
  <div>
    <canvas></canvas>
  </div>
  <div id="formContainer">
    <div id="addEventForm"> 
      <form></form>
    </div>
    <div id="button">
      <button></button>
    </div>
  </div>
</div>

And here is the relevant CSS

#mainContainer {
  display: flex;
  flex-direction: row;
} 

#formContainer {
  display: flex;
  flex-direction: column;
}

Failed to decode downloaded font

I also had same problem but i have solved by adding 'Content-Type' : 'application/x-font-ttf' in response header for all .ttf files

C++ where to initialize static const

Anywhere in one compilation unit (usually a .cpp file) would do:

foo.h

class foo {
    static const string s; // Can never be initialized here.
    static const char* cs; // Same with C strings.

    static const int i = 3; // Integral types can be initialized here (*)...
    static const int j; //     ... OR in cpp.
};

foo.cpp

#include "foo.h"
const string foo::s = "foo string";
const char* foo::cs = "foo C string";
// No definition for i. (*)
const int foo::j = 4;

(*) According to the standards you must define i outside of the class definition (like j is) if it is used in code other than just integral constant expressions. See David's comment below for details.

MVC razor form with multiple different submit buttons?

Simplest way is to use the html5 FormAction and FormMethod

<input type="submit" 
           formaction="Save"
           formmethod="post" 
           value="Save" />
    <input type="submit"
           formaction="SaveForLatter"
           formmethod="post" 
           value="Save For Latter" />
    <input type="submit"
           formaction="SaveAndPublish"
           formmethod="post"
           value="Save And Publish" />

[HttpPost]
public ActionResult Save(CustomerViewModel model) {...}

[HttpPost]
public ActionResult SaveForLatter(CustomerViewModel model){...}

[HttpPost]
public ActionResult SaveAndPublish(CustomerViewModel model){...}

There are many other ways which we can use, see this article ASP.Net MVC multiple submit button use in different ways

How To Raise Property Changed events on a Dependency Property?

I question the logic of raising a PropertyChanged event on the second property when it's the first property that's changing. If the second properties value changes then the PropertyChanged event could be raised there.

At any rate, the answer to your question is you should implement INotifyPropertyChange. This interface contains the PropertyChanged event. Implementing INotifyPropertyChanged lets other code know that the class has the PropertyChanged event, so that code can hook up a handler. After implementing INotifyPropertyChange, the code that goes in the if statement of your OnPropertyChanged is:

if (PropertyChanged != null)
    PropertyChanged(new PropertyChangedEventArgs("MySecondProperty"));

Converting serial port data to TCP/IP in a Linux environment

You don't need to write a program to do this in Linux. Just pipe the serial port through netcat:

netcat www.example.com port </dev/ttyS0 >/dev/ttyS0

Just replace the address and port information. Also, you may be using a different serial port (i.e. change the /dev/ttyS0 part). You can use the stty or setserial commands to change the parameters of the serial port (baud rate, parity, stop bits, etc.).

AngularJS not detecting Access-Control-Allow-Origin header?

There's a workaround for those who want to use Chrome. This extension allows you to request any site with AJAX from any source, since it adds 'Access-Control-Allow-Origin: *' header to the response.

As an alternative, you can add this argument to your Chrome launcher: --disable-web-security. Note that I'd only use this for development purposes, not for normal "web surfing". For reference see Run Chromium with Flags.

As a final note, by installing the extension mentioned on the first paragraph, you can easily enable/disable CORS.

List of macOS text editors and code editors

Mac UltraEdit is out as of 2011 - http://www.ultraedit.com/products/mac-text-editor.html

Very much a 1.0-ish feel and sluggish (though labeled 2.0.2), has all the great features of the Windows version (column edits, true hex mode, full out macro recording, and plugins for every language under the sun).

what is the difference between const_iterator and iterator?

There is no performance difference.

A const_iterator is an iterator that points to const value (like a const T* pointer); dereferencing it returns a reference to a constant value (const T&) and prevents modification of the referenced value: it enforces const-correctness.

When you have a const reference to the container, you can only get a const_iterator.

Edited: I mentionned “The const_iterator returns constant pointers” which is not accurate, thanks to Brandon for pointing it out.

Edit: For COW objects, getting a non-const iterator (or dereferencing it) will probably trigger the copy. (Some obsolete and now disallowed implementations of std::string use COW.)

How to get user's high resolution profile picture on Twitter?

use this URL : "https://twitter.com/(userName)/profile_image?size=original"

If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient, using TWTRAuthSession.

This is the code snipe for iOS:

if let twitterId = session.userID{
   let twitterClient = TWTRAPIClient(userID: twitterId)
   twitterClient.loadUser(withID: twitterId) {(user, error) in
       if let userName = user?.screenName{
          let url = "https://twitter.com/\(userName)/profile_image?size=original")
       }
   }
}

Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).

EDIT:

Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:

=UDF_Date(C2)

You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.

Addendum:

Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
    
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
    
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
    
        bDate = True
        bValue = True
    
        bChanged = False
    
    
        Dim sVal As String
        Dim dDate As Date
    
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
    
        sVal = CStr(inData.Value)
        dDate = Now()
    
        Set wb = inData.Worksheet.Parent
    
        Set dProps = wb.CustomDocumentProperties
    
    On Error Resume Next
    
        Set pValue = dProps.Item(sName)
    
        If Err.Number <> 0 Then
            bValue = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
        Else
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    
    On Error Resume Next
    
        Set pDate = dProps.Item(sNameDate)
    
        If Err.Number <> 0 Then
            bDate = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
    
        If bChanged Then
            pDate.Value = dDate
        Else
            dDate = pDate.Value
        End If
    
    
        UDF_Date = dDate
     End Function
    

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

How does DateTime.Now.Ticks exactly work?

to convert the current datetime to file name to save files you can use

DateTime.Now.ToFileTime();

this should resolve your objective

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

If you use Mercurial, you can use the built in HTTP server. In the folder you wish to serve up:

hg serve

From the docs:

export the repository via HTTP

    Start a local HTTP repository browser and pull server.

    By default, the server logs accesses to stdout and errors to
    stderr. Use the "-A" and "-E" options to log to files.

options:

 -A --accesslog       name of access log file to write to
 -d --daemon          run server in background
    --daemon-pipefds  used internally by daemon mode
 -E --errorlog        name of error log file to write to
 -p --port            port to listen on (default: 8000)
 -a --address         address to listen on (default: all interfaces)
    --prefix          prefix path to serve from (default: server root)
 -n --name            name to show in web pages (default: working dir)
    --webdir-conf     name of the webdir config file (serve more than one repo)
    --pid-file        name of file to write process ID to
    --stdio           for remote clients
 -t --templates       web templates to use
    --style           template style to use
 -6 --ipv6            use IPv6 in addition to IPv4
    --certificate     SSL certificate file

use "hg -v help serve" to show global options

Linux command to list all available commands and aliases

Add to .bashrc

function ListAllCommands
{
    echo -n $PATH | xargs -d : -I {} find {} -maxdepth 1 \
        -executable -type f -printf '%P\n' | sort -u
}

If you also want aliases, then:

function ListAllCommands
{
    COMMANDS=`echo -n $PATH | xargs -d : -I {} find {} -maxdepth 1 \
        -executable -type f -printf '%P\n'`
    ALIASES=`alias | cut -d '=' -f 1`
    echo "$COMMANDS"$'\n'"$ALIASES" | sort -u
}

Using Python's list index() method on a list of tuples or objects?

I would place this as a comment to Triptych, but I can't comment yet due to lack of rating:

Using the enumerator method to match on sub-indices in a list of tuples. e.g.

li = [(1,2,3,4), (11,22,33,44), (111,222,333,444), ('a','b','c','d'),
        ('aa','bb','cc','dd'), ('aaa','bbb','ccc','ddd')]

# want pos of item having [22,44] in positions 1 and 3:

def getIndexOfTupleWithIndices(li, indices, vals):

    # if index is a tuple of subindices to match against:
    for pos,k in enumerate(li):
        match = True
        for i in indices:
            if k[i] != vals[i]:
                match = False
                break;
        if (match):
            return pos

    # Matches behavior of list.index
    raise ValueError("list.index(x): x not in list")

idx = [1,3]
vals = [22,44]
print getIndexOfTupleWithIndices(li,idx,vals)    # = 1
idx = [0,1]
vals = ['a','b']
print getIndexOfTupleWithIndices(li,idx,vals)    # = 3
idx = [2,1]
vals = ['cc','bb']
print getIndexOfTupleWithIndices(li,idx,vals)    # = 4

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

This workaround worked for me. I edited the serverInfo.properties file as given below:

server.info=Apache Tomcat/8.0.0
server.number=8.0.0.0
server.built=Oct 6 2016 20:15:31 UTC

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

CSS full screen div with text in the middle

There is no pure CSS solution to this classical problem.

If you want to achieve this, you have two solutions:

  • Using a table (ugly, non semantic, but the only way to vertically align things that are not a single line of text)
  • Listening to window.resize and absolute positionning

EDIT: when I say that there is no solution, I take as an hypothesis that you don't know in advance the size of the block to center. If you know it, paislee's solution is very good

Passing data between view controllers

This is a really great tutorial for anyone that wants one. Here is the example code:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"myIdentifer]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        myViewController *destViewController = segue.destinationViewController;
        destViewController.name = [object objectAtIndex:indexPath.row];
    }
}

C++ - Hold the console window open?

Roughly the same kinds of things you've done in C#. Calling getch() is probably the simplest.

Project has no default.properties file! Edit the project properties to set one

Right click on project --> properties --> Android.

Change the checkbox for project build target.

Press apply.

Change it back to your original build target.

Press apply --> ok

Worked for me

How do I get a list of files in a directory in C++?

C++11/Linux version:

#include <dirent.h>

if (auto dir = opendir("some_dir/")) {
    while (auto f = readdir(dir)) {
        if (!f->d_name || f->d_name[0] == '.')
            continue; // Skip everything that starts with a dot

        printf("File: %s\n", f->d_name);
    }
    closedir(dir);
}

How to bind DataTable to Datagrid

You could use DataGrid in WPF

SqlDataAdapter da = new SqlDataAdapter("Select * from Table",con);
DataTable dt = new DataTable("Call Reciept");
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.ItemsSource = dt.DefaultView;

Difference between Eclipse Europa, Helios, Galileo

Each version has some improvements in certain technologies. For users the biggest difference is whether or not to execute certain plugins, because some were made only for a particular version of Eclipse.

Split string with JavaScript

Assuming you're using jQuery..

var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
    var parts = line.split(' ');
    output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');

Regex pattern for checking if a string starts with a certain substring?

For the extension method fans:

public static bool RegexStartsWith(this string str, params string[] patterns)
{
    return patterns.Any(pattern => 
       Regex.Match(str, "^("+pattern+")").Success);
}

Usage

var answer = str.RegexStartsWith("mailto","ftp","joe");
//or
var answer2 = str.RegexStartsWith("mailto|ftp|joe");
//or
bool startsWithWhiteSpace = "  does this start with space or tab?".RegexStartsWith(@"\s");

Gson: Directly convert String to JsonObject (no POJO)

The simplest way is to use the JsonPrimitive class, which derives from JsonElement, as shown below:

JsonElement element = new JsonPrimitive(yourString);
JsonObject result = element.getAsJsonObject();

Where is Java's Array indexOf?

int findIndex(int myElement, int[] someArray){
 int index = 0;
 for(int n: someArray){
   if(myElement == n) return index;
   else index++;
 }
}

Note: you can use this method for arrays of type int, you can also use this algorithm for other types with minor changes

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

The code of Ellbar works! You need only add using.

1 - using Microsoft.AspNet.Identity;

And... the code of Ellbar:

2 - string currentUserId = User.Identity.GetUserId(); ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

With this code (in currentUser), you work the general data of the connected user, if you want extra data... see this link

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

When to use dynamic vs. static libraries

If your working on embedded projects or specialized platforms static libraries are the only way to go, also many times they are less of a hassle to compile into your application. Also having projects and makefile that include everything makes life happier.