Programs & Examples On #Dbnull

DBNull is a special value in ADO.Net indicating that the value is NULL in the database.

What is the difference between null and System.DBNull.Value?

DBNull.Value is what the .NET Database providers return to represent a null entry in the database. DBNull.Value is not null and comparissons to null for column values retrieved from a database row will not work, you should always compare to DBNull.Value.

http://msdn.microsoft.com/en-us/library/system.dbnull.value.aspx

DBNull if statement

Ternary operator should do nicely here: condition ? first_expression : second_expression;

strLevel = !Convert.IsDBNull(rsData["usr.ursrdaystime"]) ? Convert.ToString(rsData["usr.ursrdaystime"]) : null

Assign null to a SqlParameter

If you use the conditional(ternary) operator the compiler needs an implicit conversion between both types, otherwise you get an exception.

So you could fix it by casting one of both to System.Object:

planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : (object) AgeItem.AgeIndex;

But since the result is not really pretty and you always have to remember this casting, you could use such an extension method instead:

public static object GetDBNullOrValue<T>(this T val)
{
    bool isDbNull = true;
    Type t = typeof(T);

    if (Nullable.GetUnderlyingType(t) != null)
        isDbNull = EqualityComparer<T>.Default.Equals(default(T), val);
    else if (t.IsValueType)
        isDbNull = false;
    else
        isDbNull = val == null;

    return isDbNull ? DBNull.Value : (object) val;
}

Then you can use this concise code:

planIndexParameter.Value = AgeItem.AgeIndex.GetDBNullOrValue();

handling dbnull data in vb.net

You can also use the Convert.ToString() and Convert.ToInteger() methods to convert items with DB null effectivly.

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

If there is not ISNULL() method, you can use this expression instead:

CASE WHEN fieldname IS NULL THEN 0 ELSE fieldname END

This works the same as ISNULL(fieldname, 0).

Most efficient way to check for DBNull and then assign to a variable?

I always use :

if (row["value"] != DBNull.Value)
  someObject.Member = row["value"];

Found it short and comprehensive.

git - Server host key not cached

Working environment:

  • Windows 10
  • git
  • putty

First: Delete putty known_hosts in registy according to the Regedit.
Then: Executing the command %GIT_SSH% user@hostname in Window's cmd solves the problem.

Hope it helps you all.

Remove item from list based on condition

If you have LINQ:

var itemtoremove = prods.Where(item => item.ID == 1).First();
prods.Remove(itemtoremove)

Is there a better jQuery solution to this.form.submit();?

You can always JQuery-ize your form.submit, but it may just call the same thing:

$("form").submit(); // probably able to affect multiple forms (good or bad)

// or you can address it by ID
$("#yourFormId").submit();

You can also attach functions to the submit event, but that is a different concept.

XML Error: Extra content at the end of the document

I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.

Good Patterns For VBA Error Handling

I use a piece of code that i developed myself and it is pretty good for my codes:

In the beginning of the function or sub, I define:

On error Goto ErrorCatcher:

and then, I handle the possible errors

ErrorCatcher:
Select Case Err.Number

Case 0 'exit the code when no error was raised
    On Error GoTo 0
    Exit Function
Case 1 'Error on definition of object
    'do stuff
Case... 'little description here
    'do stuff
Case Else
    Debug.Print "###ERROR"
    Debug.Print "   • Number  :", Err.Number
    Debug.Print "   • Descrip :", Err.Description
    Debug.Print "   • Source  :", Err.Source
    Debug.Print "   • HelpCont:", Err.HelpContext
    Debug.Print "   • LastDLL :", Err.LastDllError
    Stop
    Err.Clear
    Resume
End Select

How to capitalize the first letter of word in a string using Java?

Here you go (hope this give you the idea):

/*************************************************************************
 *  Compilation:  javac Capitalize.java
 *  Execution:    java Capitalize < input.txt
 * 
 *  Read in a sequence of words from standard input and capitalize each
 *  one (make first letter uppercase; make rest lowercase).
 *
 *  % java Capitalize
 *  now is the time for all good 
 *  Now Is The Time For All Good 
 *  to be or not to be that is the question
 *  To Be Or Not To Be That Is The Question 
 *
 *  Remark: replace sequence of whitespace with a single space.
 *
 *************************************************************************/

public class Capitalize {

    public static String capitalize(String s) {
        if (s.length() == 0) return s;
        return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    }

    public static void main(String[] args) {
        while (!StdIn.isEmpty()) {
            String line = StdIn.readLine();
            String[] words = line.split("\\s");
            for (String s : words) {
                StdOut.print(capitalize(s) + " ");
            }
            StdOut.println();
        }
    }

}

Find if value in column A contains value from column B?

You could try this

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)

-or-

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row "   & MATCH(<single column I value>,<entire column E range>,0))

you could replace <single column I value> and <entire column E range> with named ranged. That'd probably be the easiest.

Just drag that formula all the way down the length of your I column in whatever column you want.

SQL - HAVING vs. WHERE

Didn't see an example of both in one query. So this example might help.

  /**
INTERNATIONAL_ORDERS - table of orders by company by location by day
companyId, country, city, total, date
**/

SELECT country, city, sum(total) totalCityOrders 
FROM INTERNATIONAL_ORDERS with (nolock)
WHERE companyId = 884501253109
GROUP BY country, city
HAVING country = 'MX'
ORDER BY sum(total) DESC

This filters the table first by the companyId, then groups it (by country and city) and additionally filters it down to just city aggregations of Mexico. The companyId was not needed in the aggregation but we were able to use WHERE to filter out just the rows we wanted before using GROUP BY.

Split string into array of character strings

"cat".toCharArray()

But if you need strings

"cat".split("")

Edit: which will return an empty first value.

Get generic type of java.util.List

import org.junit.Assert;
import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class GenericTypeOfCollectionTest {
    public class FormBean {
    }

    public class MyClazz {
        private List<FormBean> list = new ArrayList<FormBean>();
    }

    @Test
    public void testName() throws Exception {
        Field[] fields = MyClazz.class.getFields();
        for (Field field : fields) {
            //1. Check if field is of Collection Type
            if (Collection.class.isAssignableFrom(field.getType())) {
                //2. Get Generic type of your field
                Class fieldGenericType = getFieldGenericType(field);
                //3. Compare with <FromBean>
                Assert.assertTrue("List<FormBean>",
                  FormBean.class.isAssignableFrom(fieldGenericType));
            }
        }
    }

    //Returns generic type of any field
    public Class getFieldGenericType(Field field) {
        if (ParameterizedType.class.isAssignableFrom(field.getGenericType().getClass())) {
            ParameterizedType genericType =
             (ParameterizedType) field.getGenericType();
            return ((Class)
              (genericType.getActualTypeArguments()[0])).getSuperclass();
        }
        //Returns dummy Boolean Class to compare with ValueObject & FormBean
        return new Boolean(false).getClass();
    }
}

Fastest JavaScript summation

Or you could do it the evil way.

var a = [1,2,3,4,5,6,7,8,9];

sum = eval(a.join("+"));

;)

How can I avoid running ActiveRecord callbacks?

Why would you want to be able to do this in development? Surely this will mean you are building your application with invalid data and as such it will behave strangely and not as you expect in production.

If you want to populate your dev db with data a better approach would be to build a rake task that used the faker gem to build valid data and import it into the db creating as many or few records as you desire, but if you are heel bent on it and have a good reason I guess that update_without_callbacks and create_without_callbacks will work fine, but when you are trying to bend rails to your will, ask yourself you have a good reason and if what you are doing is really a good idea.

How to move git repository with all branches from bitbucket to github?

There is the Importing a repository with GitHub Importer

If you have a project hosted on another version control system as Mercurial, you can automatically import it to GitHub using the GitHub Importer tool.

  1. In the upper-right corner of any page, click , and then click Import repository.
  2. Under "Your old repository's clone URL", type the URL of the project you want to import.
  3. Choose your user account or an organization to own the repository, then type a name for the repository on GitHub.
  4. Specify whether the new repository should be public or private.
    • Public repositories are visible to any user on GitHub, so you can benefit from GitHub's collaborative community.
    • Public or private repository radio buttonsPrivate repositories are only available to the repository owner, as well as any collaborators you choose to share with.
  5. Review the information you entered, then click Begin import.

You'll receive an email when the repository has been completely imported.

  1. https://help.github.com/categories/importing-your-projects-to-github
  2. https://help.github.com/articles/importing-a-repository-with-github-importer/

Is it a bad practice to use break in a for loop?

Depends on your use case. There are applications where the runtime of a for loop needs to be constant (e.g. to satisfy some timing constraints, or to hide your data internals from timing based attacks).

In those cases it will even make sense to set a flag and only check the flag value AFTER all the for loop iterations have actually run. Of course, all the for loop iterations need to run code that still takes about the same time.

If you do not care about the run time... use break; and continue; to make the code easier to read.

Could not insert new outlet connection: Could not find any information for the class named

I solved this problem by programmatically creating the Labels and Textfields, and then Command-Dragged from the little empty circles on the left of the code to the components on the Storyboard. To illustrate my point: I wrote @IBOutlet weak var HelloLabel: UILabel!, and then pressed Command and dragged the code into the component on the storyboard.

array of string with unknown size

string[ ] array = {};

// it is not null instead it is empty.

How to change Visual Studio 2012,2013 or 2015 License Key?

To see what's inside these HKCR\Licenses use API Monitor v2

API-Filter find 

    RegQueryValueExW 
        ^-Enable all from Advapi32.dll

    CryptUnprotectData
        ^- Enable all from Crypt32.dll
         + Breakpoint / after Call

sample data that'll come out from CryptUnprotectData:

HKEY_CLASSES_ROOT\Licenses\4D8CFBCB-2F6A-4AD2-BABF-10E28F6F2C8F\07078  [length 0x1C6 (0454.) ]
    00322-20000-00000-AA450                 <- PID2
    7d3cbcbb-90b1-411f-9981-6e28039a9b82    <- Ver
    7C3WXN74-VRMXH-J8X3H-M8F7W-CPQB8        <- PID3

HKEY_CLASSES_ROOT\Licenses\4D8CFBCB-2F6A-4AD2-BABF-10E28F6F2C8F\0bcad  [length 0xbcad (0534.) ]

    0000  00000025 ffffffff 7fffffff   07064. 00000007   07078. 00000007 ffffffff
    0020  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    0040  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    0060  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    0080  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    00a0  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    00c0  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    00e0  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    0100  7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
    0120  7fffffff ffffffff 7fffffff 10.2015. c2a6 11.
    0134                             ^installation date^

Useful here is maybe the Installation timestamp (11.10.2015 here ) Change this would required to call 'CryptProtectData'. Doing so needs some efforts like written a small program OR stop with ollydebug at this place and manually 'crafting' a CryptProtectData call ...

Note: In this example I'm using Microsoft® Visual Studio 2015

-> For a quick'n'dirty sneak into an expired VS I recommend to read this post. However that's just good for occasional use, till you get all the sign up and login crap properly done again ;)

Okay the real meat is here:
%LOCALAPPDATA%\Microsoft\VisualStudio\14.0\Licenses\ ^- This path comes from HKCU\Software\Microsoft\VisualStudio\14.0\Licenses\715f10eb-9e99-11d2-bfc2-00c04f990235\1

1_3jdh3uyw**.crtok**

-after some Base64 decoding:

<ClientRightsContainer 
    xmlns="http://schemas.datacontract.org/2004/07/Microsoft.VisualStudio.Services.Licensing" 
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <CertificateBytes>
        00000000   30 82 06 41 30 82 04 29  A0 03 02 01 02 02 13 5A   0‚ A0‚ )       Z
        00000010   00 00 BC CB 23 AC 52 9C  E8 93 F9 0A 00 01 00 00     ¼Ë#¬Rœè“ù     
        00000020   BC CB 30 0D 06 09 2A 86  48 86 F7 0D 01 01 0B 05   ¼Ë0   *†H†÷     
        00000030   00 30 81 8B 31 0B 30 09  06 03 55 04 06 13 02 55    0 ‹1 0   U    U
        00000040   53 31 13 30 11 06 03 55  04 08 13 0A 57 61 73 68   S1 0   U    Wash
        00000050   69 6E 67 74 6F 6E 31 10  30 0E 06 03 55 04 07 13   ington1 0   U   
        00000060   07 52 65 64 6D 6F 6E 64  31 1E 30 1C 06 03 55 04    Redmond1 0   U 
        00000070   0A 13 15 4D 69 63 72 6F  73 6F 66 74 20 43 6F 72      Microsoft Cor
        00000080   70 6F 72 61 74 69 6F 6E  31 15 30 13 06 03 55 04   poration1 0   U 
        00000090   0B 13 0C 4D 69 63 72 6F  73 6F 66 74 20 49 54 31      Microsoft IT1
        000000A0   1E 30 1C 06 03 55 04 03  13 15 4D 69 63 72 6F 73    0   U    Micros
        000000B0   6F 66 74 20 49 54 20 53  53 4C 20 53 48 41 32 30   oft IT SSL SHA20
        000000C0   1E 17 0D 31 35 30 33 30  35 32 31 32 39 35 36 5A      150305212956Z
        000000D0   17 0D 31 37 30 33 30 34  32 31 32 39 35 36 5A 30     170304212956Z0
        000000E0   25 31 23 30 21 06 03 55  04 03 13 1A 61 70 70 2E   %1#0!  U    app.
        000000F0   76 73 73 70 73 2E 76 69  73 75 61 6C 73 74 75 64   vssps.visualstud
        00000100   69 6F 2E 63 6F 6D 30 82  01 22 30 0D 06 09 2A 86   io.com0‚ "0   *†
        ...
        000002B0   6E 86 36 68 74 74 70 3A  2F 2F 6D 73 63 72 6C 2E   n†6http://mscrl.
        000002C0   6D 69 63 72 6F 73 6F 66  74 2E 63 6F 6D 2F 70 6B   microsoft.com/pk
        000002D0   69 2F 6D 73 63 6F 72 70  2F 63 72 6C 2F 6D 73 69   i/mscorp/crl/msi
        000002E0   74 77 77 77 32 2E 63 72  6C 86 34 68 74 74 70 3A   twww2.crl†4http:
        000002F0   2F 2F 63 72 6C 2E 6D 69  63 72 6F 73 6F 66 74 2E   //crl.microsoft.
        00000300   63 6F 6D 2F 70 6B 69 2F  6D 73 63 6F 72 70 2F 63   com/pki/mscorp/c
        00000310   72 6C 2F 6D 73 69 74 77  77 77 32 2E 63 72 6C 30   rl/msitwww2.crl0
        00000320   70 06 08 2B 06 01 05 05  07 01 01 04 64 30 62 30   p  +        d0b0
        00000330   3C 06 08 2B 06 01 05 05  07 30 02 86 30 68 74 74   <  +     0 †0htt
        00000340   70 3A 2F 2F 77 77 77 2E  6D 69 63 72 6F 73 6F 66   p://www.microsof
        00000350   74 2E 63 6F 6D 2F 70 6B  69 2F 6D 73 63 6F 72 70   t.com/pki/mscorp
        00000360   2F 6D 73 69 74 77 77 77  32 2E 63 72 74 30 22 06   /msitwww2.crt0" 
        00000370   08 2B 06 01 05 05 07 30  01 86 16 68 74 74 70 3A    +     0 † http:
        00000380   2F 2F 6F 63 73 70 2E 6D  73 6F 63 73 70 2E 63 6F   //ocsp.msocsp.co
        00000390   6D 30 4E 06 03 55 1D 20  04 47 30 45 30 43 06 09   m0N  U   G0E0C  
        000003A0   2B 06 01 04 01 82 37 2A  01 30 36 30 34 06 08 2B   +    ‚7* 0604  +
        000003B0   06 01 05 05 07 02 01 16  28 68 74 74 70 3A 2F 2F           (http://
        000003C0   77 77 77 2E 6D 69 63 72  6F 73 6F 66 74 2E 63 6F   www.microsoft.co
        000003D0   6D 2F 70 6B 69 2F 6D 73  63 6F 72 70 2F 63 70 73   m/pki/mscorp/cps
        000003E0   00 30 27 06 09 2B 06 01  04 01 82 37 15 0A 04 1A    0'  +    ‚7    
        000003F0   30 18 30 0A 06 08 2B 06  01 05 05 07 03 01 30 0A   0 0   +       0 
        00000400   06 08 2B 06 01 05 05 07  03 02 30 25 06 03 55 1D     +       0%  U 
        00000410   11 04 1E 30 1C 82 1A 61  70 70 2E 76 73 73 70 73      0 ‚ app.vssps
        00000420   2E 76 69 73 75 61 6C 73  74 75 64 69 6F 2E 63 6F   .visualstudio.co
        00000430   6D 30 0D 06 09 2A 86 48  86 F7 0D 01 01 0B 05 00   m0   *†H†÷      
        ...                                                U
    </CertificateBytes>
    <Token>
    {
        "typ":"JWT",
        "alg":"RS256",
        "x5t":"i7qX-NUrehXBYdQC5PSH-TdvzXA"
    }
    </Token>
</ClientRightsContainer>

Seems M$ is using JSON Web Token (JWT) to wrap in license data. I guess inside CertificateBytes will be somehow the payload - you're email and other details.

So far for the rough overview what's the data inside.

For more wishes get ILSpy + Reflexil (<- to changes/correct little things!) and then 'browser&correct' files like c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE**Microsoft.VisualStudio.Licensing.dll** or check out 'Microsoft.VisualStudio.Services.WebApi.dll'

toBe(true) vs toBeTruthy() vs toBeTrue()

In javascript there are trues and truthys. When something is true it is obviously true or false. When something is truthy it may or may not be a boolean, but the "cast" value of is a boolean.

Examples.

true == true; // (true) true
1 == true; // (true) truthy
"hello" == true;  // (true) truthy
[1, 2, 3] == true; // (true) truthy
[] == false; // (true) truthy
false == false; // (true) true
0 == false; // (true) truthy
"" == false; // (true) truthy
undefined == false; // (true) truthy
null == false; // (true) truthy

This can make things simpler if you want to check if a string is set or an array has any values.

var users = [];

if(users) {
  // this array is populated. do something with the array
}

var name = "";

if(!name) {
  // you forgot to enter your name!
}

And as stated. expect(something).toBe(true) and expect(something).toBeTrue() is the same. But expect(something).toBeTruthy() is not the same as either of those.

How to make button look like a link?

If you don't mind using twitter bootstrap I suggest you simply use the link class.

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">_x000D_
<button type="button" class="btn btn-link">Link</button>
_x000D_
_x000D_
_x000D_

I hope this helps somebody :) Have a nice day!

How do I create a dynamic key to be added to a JavaScript object variable

Associative Arrays in JavaScript don't really work the same as they do in other languages. for each statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push method:

jsArr = []; 

for (var i = 1; i <= 10; i++) { 
    jsArr.push('example ' + 1); 
} 

Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].

How to change background Opacity when bootstrap modal is open

You can download a custom compiled bootstrap 3, just customize the @modal-backdrop-opacity from:

https://getbootstrap.com/docs/3.4/customize/

Customizing bootstrap 4 requires compiling from source, overriding $modal-backdrop-bg as described in:

https://getbootstrap.com/docs/4.4/getting-started/theming/

In the answers to Bootstrap 4 custom build generator / download there is a NodeJS workflow for compiling Bootstrap 4 from source, alone with some non-official Bootstrap 4 customizers.

How to get certain commit from GitHub project

The question title is ambiguous.

How can I strip first and last double quotes?

If you can't assume that all the strings you process have double quotes you can use something like this:

if string.startswith('"') and string.endswith('"'):
    string = string[1:-1]

Edit:

I'm sure that you just used string as the variable name for exemplification here and in your real code it has a useful name, but I feel obliged to warn you that there is a module named string in the standard libraries. It's not loaded automatically, but if you ever use import string make sure your variable doesn't eclipse it.

How to change string into QString?

Moreover, to convert whatever you want, you can use the QVariant class.

for example:

std::string str("hello !");
qDebug() << QVariant(str.c_str()).toString();
int test = 10;
double titi = 5.42;
qDebug() << QVariant(test).toString();
qDebug() << QVariant(titi).toString();
qDebug() << QVariant(titi).toInt();

output

"hello !"
"10"
"5.42"
5

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

How to select the rows with maximum values in each group with dplyr?

You can use top_n

df %>% group_by(A, B) %>% top_n(n=1)

This will rank by the last column (value) and return the top n=1 rows.

Currently, you can't change the this default without causing an error (See https://github.com/hadley/dplyr/issues/426)

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

The view didn't return an HttpResponse object. It returned None instead

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

How do I replace text inside a div element?

Here's an easy jQuery way:

var el = $('#yourid .yourclass');

el.html(el.html().replace(/Old Text/ig, "New Text"));

Adding up BigDecimals using Streams

Original answer

Yes, this is possible:

List<BigDecimal> bdList = new ArrayList<>();
//populate list
BigDecimal result = bdList.stream()
        .reduce(BigDecimal.ZERO, BigDecimal::add);

What it does is:

  1. Obtain a List<BigDecimal>.
  2. Turn it into a Stream<BigDecimal>
  3. Call the reduce method.

    3.1. We supply an identity value for addition, namely BigDecimal.ZERO.

    3.2. We specify the BinaryOperator<BigDecimal>, which adds two BigDecimal's, via a method reference BigDecimal::add.

Updated answer, after edit

I see that you have added new data, therefore the new answer will become:

List<Invoice> invoiceList = new ArrayList<>();
//populate
Function<Invoice, BigDecimal> totalMapper = invoice -> invoice.getUnit_price().multiply(invoice.getQuantity());
BigDecimal result = invoiceList.stream()
        .map(totalMapper)
        .reduce(BigDecimal.ZERO, BigDecimal::add);

It is mostly the same, except that I have added a totalMapper variable, that has a function from Invoice to BigDecimal and returns the total price of that invoice.

Then I obtain a Stream<Invoice>, map it to a Stream<BigDecimal> and then reduce it to a BigDecimal.

Now, from an OOP design point I would advice you to also actually use the total() method, which you have already defined, then it even becomes easier:

List<Invoice> invoiceList = new ArrayList<>();
//populate
BigDecimal result = invoiceList.stream()
        .map(Invoice::total)
        .reduce(BigDecimal.ZERO, BigDecimal::add);

Here we directly use the method reference in the map method.

Convert a python dict to a string and back

If in Chinses

import codecs
fout = codecs.open("xxx.json", "w", "utf-8")
dict_to_json = json.dumps({'text':"??"},ensure_ascii=False,indent=2)
fout.write(dict_to_json + '\n')

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not)

But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver. Just build your JDBC URL like this:

jdbc:sqlserver://localhost;integratedSecurity=true;

And copy the appropriate DLL to Tomcat's bin directory (sqljdbc_auth.dll provided with the driver)

MSDN > Connecting to SQL Server with the JDBC Driver > Building the Connection URL

XML string to XML document

Using Linq to xml

Add a reference to System.Xml.Linq

and use

XDocument.Parse(string xmlString)

Edit: Sample follows, xml data (TestConfig.xml)..

<?xml version="1.0"?>
<Tests>
  <Test TestId="0001" TestType="CMD">
    <Name>Convert number to string</Name>
    <CommandLine>Examp1.EXE</CommandLine>
    <Input>1</Input>
    <Output>One</Output>
  </Test>
  <Test TestId="0002" TestType="CMD">
    <Name>Find succeeding characters</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>abc</Input>
    <Output>def</Output>
  </Test>
  <Test TestId="0003" TestType="GUI">
    <Name>Convert multiple numbers to strings</Name>
    <CommandLine>Examp2.EXE /Verbose</CommandLine>
    <Input>123</Input>
    <Output>One Two Three</Output>
  </Test>
  <Test TestId="0004" TestType="GUI">
    <Name>Find correlated key</Name>
    <CommandLine>Examp3.EXE</CommandLine>
    <Input>a1</Input>
    <Output>b1</Output>
  </Test>
  <Test TestId="0005" TestType="GUI">
    <Name>Count characters</Name>
    <CommandLine>FinalExamp.EXE</CommandLine>
    <Input>This is a test</Input>
    <Output>14</Output>
  </Test>
  <Test TestId="0006" TestType="GUI">
    <Name>Another Test</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>Test Input</Input>
    <Output>10</Output>
  </Test>
</Tests>

C# usage...

XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
    from el in root.Elements("Test")
    where (string)el.Element("CommandLine") == "Examp2.EXE"
    select el;
foreach (XElement el in tests)
    Console.WriteLine((string)el.Attribute("TestId"));

This code produces the following output: 0002 0006

How does Git handle symbolic links?

"Editor's" note: This post may contain outdated information. Please see comments and this question regarding changes in Git since 1.6.1.

Symlinked directories:

It's important to note what happens when there is a directory which is a soft link. Any Git pull with an update removes the link and makes it a normal directory. This is what I learnt hard way. Some insights here and here.

Example

Before

 ls -l
 lrwxrwxrwx 1 admin adm   29 Sep 30 15:28 src/somedir -> /mnt/somedir

git add/commit/push

It remains the same

After git pull AND some updates found

 drwxrwsr-x 2 admin adm 4096 Oct  2 05:54 src/somedir

check if command was successful in a batch file

This likely doesn't work with start, as that starts a new window, but to answer your question:

If the command returns a error level you can check the following ways

By Specific Error Level

commandhere
if %errorlevel%==131 echo do something

By If Any Error

commandhere || echo what to do if error level ISN'T 0

By If No Error

commandhere && echo what to do if error level IS 0

If it does not return a error level but does give output, you can catch it in a variable and determine by the output, example (note the tokens and delims are just examples and would likely fail with any special characters)

By Parsing Full Output

for /f "tokens=* delims=" %%a in ('somecommand') do set output=%%a
if %output%==whateveritwouldsayinerror echo error

Or you could just look for a single phrase in the output like the word Error

By Checking For String

commandhere | find "Error" || echo There was no error!
commandhere | find "Error" && echo There was an error!

And you could even mix together (just remember to escape | with ^| if in a for statement)

Hope this helps.

Using external images for CSS custom cursors

cursor:url('http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif'), auto

NOTE 1: In some cases you should consider setting the offset (anchor):

cursor:url(http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif) 10 3, auto;

in this exmple, we set offsetx to 10 and offsety to 3 (from top left), so the pointer finger will be anchor. fiddle: http://jsfiddle.net/5kxt1j98/ (you can see the difference by moving cursor to top left of container)


NOTE 2: THE MAX CURSOR SIZE IS 128*128, recommended one is below 32*32.

How to line-break from css, without using <br />?

Using &nbsp; instead of spaces will prevent a break.

<span>I&nbsp;DONT&nbsp;WANT&nbsp;TO&nbsp;BREAK&nbsp;THIS&nbsp;LINE&nbsp;UP, but this text can be on any line.</span>

How to include duplicate keys in HashMap?

Map does not supports duplicate keys. you can use collection as value against same key.

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.

Documentation

you can use any kind of List or Set implementation according to your requirement.

If your values might be also duplicate you can go with ArrayList or LinkedList, in case values are unique you can use HashSet or TreeSet etc.


Also In google guava collection library Multimap is available, it is a collection that maps keys to values, similar to Map, but in which each key may be associated with multiple values. You can visualize the contents of a multimap either as a map from keys to nonempty collections of values:

a ? 1, 2
b ? 3  

Example -

ListMultimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("a", "1");
multimap.put("a", "2");
multimap.put("c", "3");

How to make readonly all inputs in some div in Angular2?

Try this in input field:

[readonly]="true"

Hope, this will work.

White space at top of page

Old question, but I just ran into this. Sometimes your files are UTF-8 with a BOM at the start, and your template engine doesn't like that. So when you include your template, you get another (invisible) BOM inserted into your page...

<body>{INVISIBLE BOM HERE}...</body>

This causes a gap at the start of your page, where the browser renders the BOM, but it looks invisible to you (and in the inspector, just shows up as whitespace/quotes.

Save your template files as UTF-8 without BOM, or change your template engine to correctly handle UTF8/BOM documents.

How to use If Statement in Where Clause in SQL?

SELECT *
  FROM Customer
 WHERE (I.IsClose=@ISClose OR @ISClose is NULL)  
   AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
   AND (isnull(@Value,1) <> 2
        OR I.RecurringCharge = @Total
        OR @Total is NULL )    
   AND (isnull(@Value,2) <> 3
        OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
        OR @Total is NULL )

Basically, your condition was

if (@Value=2)
   TEST FOR => (I.RecurringCharge=@Total  or @Total is NULL )    

flipped around,

AND (isnull(@Value,1) <> 2                -- A
        OR I.RecurringCharge = @Total    -- B
        OR @Total is NULL )              -- C

When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2, which is the original intention.

How to spyOn a value property (rather than a method) with Jasmine

I'm using a kendo grid and therefore can't change the implementation to a getter method but I want to test around this (mocking the grid) and not test the grid itself. I was using a spy object but this doesn't support property mocking so I do this:

    this.$scope.ticketsGrid = { 
        showColumn: jasmine.createSpy('showColumn'),
        hideColumn: jasmine.createSpy('hideColumn'),
        select: jasmine.createSpy('select'),
        dataItem: jasmine.createSpy('dataItem'),
        _data: []
    } 

It's a bit long winded but it works a treat

Go build: "Cannot find package" (even though GOPATH is set)

If you have a valid $GOROOT and $GOPATH but are developing outside of them, you might get this error if the package (yours or someone else's) hasn't been downloaded.

If that's the case, try go get -d (-d flag prevents installation) to ensure the package is downloaded before you run, build or install.

File Upload with Angular Material

You can change the style by wrapping the input inside a label and change the input display to none. Then, you can specify the text you want to be displayed inside a span element. Note: here I used bootstrap 4 button style (btn btn-outline-primary). You can use any style you want.

<label class="btn btn-outline-primary">
      <span>Select File</span>
      <input type="file">
</label>

input {
  display: none;
}

What does "connection reset by peer" mean?

This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

This can happen if the other side crashes and then comes back up or if it calls close() on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.

It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.

TypeError: 'int' object is not callable

I got the same error (TypeError: 'int' object is not callable)

def xlim(i,k,s1,s2):
   x=i/(2*k)
   xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x(1-x))
   return xl 
... ... ... ... 

>>> xlim(1,100,0,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in xlim
TypeError: 'int' object is not callable

after reading this post I realized that I forgot a multiplication sign * so

def xlim(i,k,s1,s2):
   x=i/(2*k)
   xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x * (1-x))
   return xl 

xlim(1.0,100.0,0.0,0.0)
0.005

tanks

How can I find out a file's MIME type (Content-Type)?

Use file. Examples:

> file --mime-type image.png
image.png: image/png

> file -b --mime-type image.png
image/png

> file -i FILE_NAME
image.png: image/png; charset=binary

pandas convert some columns into rows

Use set_index with stack for MultiIndex Series, then for DataFrame add reset_index with rename:

df1 = (df.set_index(["location", "name"])
         .stack()
         .reset_index(name='Value')
         .rename(columns={'level_2':'Date'}))
print (df1)
  location  name        Date  Value
0        A  test    Jan-2010     12
1        A  test    Feb-2010     20
2        A  test  March-2010     30
3        B   foo    Jan-2010     18
4        B   foo    Feb-2010     20
5        B   foo  March-2010     25

Are HTTPS headers encrypted?

With SSL the encryption is at the transport level, so it takes place before a request is sent.

So everything in the request is encrypted.

Passing parameter using onclick or a click binding with KnockoutJS

Knockout's documentation also mentions a much cleaner way of passing extra parameters to functions bound using an on-click binding using function.bind like this:

<button data-bind="click: myFunction.bind($data, 'param1', 'param2')">
    Click me
</button>

C# importing class into another class doesn't work

If they are separate class files within the same project, then you do not need to have an 'import' statement. Just use the class straight off. If the files are in separate projects, you need to add a reference to the project first before you can use an 'import' statement on it.

How to make a list of n numbers in Python and randomly select any number?

You don't need to count stuff if you want to pick a random element. Just use random.choice() and pass your iterable:

import random
items = ['foo', 'bar', 'baz']
print random.choice(items)

If you really have to count them, use random.randint(1, count+1).

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

Remove the '#' and do

Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
                         System.Globalization.NumberStyles.AllowHexSpecifier));

change cursor to finger pointer

Add an href attribute to make it a valid link & return false; in the event handler to prevent it from causing a navigation;

<a href="#" class="menu_links" onclick="displayData(11,1,0,'A'); return false;" onmouseover=""> A </a>

(Or make displayData() return false and ..="return displayData(..)

The developers of this app have not set up this app properly for Facebook Login?

Okay - sandbox is off, domain has to be correct because 99% of the users can reach the app, and "all its live features available to the general public" is set to yes.

Labeling file upload button

You get your browser's language for your button. There's no way to change it programmatically.

javascript filter array multiple conditions

const data = [{
    realName: 'Sean Bean',
    characterName: 'Eddard “Ned” Stark'
}, {
    realName: 'Kit Harington',
    characterName: 'Jon Snow'
}, {
    realName: 'Peter Dinklage',
    characterName: 'Tyrion Lannister'
}, {
    realName: 'Lena Headey',
    characterName: 'Cersei Lannister'
}, {
    realName: 'Michelle Fairley',
    characterName: 'Catelyn Stark'
}, {
    realName: 'Nikolaj Coster-Waldau',
    characterName: 'Jaime Lannister'
}, {
    realName: 'Maisie Williams',
    characterName: 'Arya Stark'
}];

const filterKeys = ['realName', 'characterName'];


const multiFilter = (data = [], filterKeys = [], value = '') => data.filter((item) => filterKeys.some(key => item[key].toString().toLowerCase().includes(value.toLowerCase()) && item[key]));


let filteredData = multiFilter(data, filterKeys, 'stark');

console.info(filteredData);
/* [{
  "realName": "Sean Bean",
  "characterName": "Eddard “Ned” Stark"
}, {
  "realName": "Michelle Fairley",
  "characterName": "Catelyn Stark"
}, {
  "realName": "Maisie Williams",
  "characterName": "Arya Stark"
}]
 */

How to execute Python code from within Visual Studio Code

If you have a project consisting of multiple Python files and you want to start running/debugging with the main program independent of which file is current you create the following launch configuration (change MyMain.py to your main file).

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Main File",
      "type": "python",
      "request": "launch",
      "program": "${workspaceFolder}/MyMain.py",
      "console": "integratedTerminal",
      "cwd": "${workspaceFolder}"
    }
  ]
}

Finding import static statements for Mockito constructs

Here's what I've been doing to cope with the situation.

I use global imports on a new test class.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;

This allows you to code away without getting 'stuck' trying to find the correct package to import.

Convert a PHP object to an associative array

Converting and removing annoying stars:

$array = (array) $object;
foreach($array as $key => $val)
{
    $new_array[str_replace('*_', '', $key)] = $val;
}

Probably, it will be cheaper than using reflections.

NoClassDefFoundError in Java: com/google/common/base/Function

this is for chrome  
System.setProperty("webdriver.chrome.driver","D:\\Testing_offical\\chromedriver.exe");
driver =new ChromeDriver();
this is for fire fox 
System.setProperty("webdriver.gecko.driver",""D:\\Testing_offical\\geckodriver.exe"");
driver =new FirefoxDriver();

pattern :

System.setProperty("webdriver.gecko.driver","**Path of the gecko driver** ");

Note download gecko from here :- http://docs.seleniumhq.org/download/

Div vertical scrollbar show

Always : If you always want vertical scrollbar, use overflow-y: scroll;

jsFiddle:

<div style="overflow-y: scroll;">
......
</div>

When needed: If you only want vertical scrollbar when needed, use overflow-y: auto; (You need to specify a height in this case)

jsFiddle:

<div style="overflow-y: auto; height:150px; ">
....
</div>

Programmatically get own phone number in iOS

No, there's no legal and reliable way to do this.

If you find a way, it will be disabled in the future, as it has happened with every method before.

How to save a BufferedImage as a File

You can save a BufferedImage object using write method of the javax.imageio.ImageIO class. The signature of the method is like this:

public static boolean write(RenderedImage im, String formatName, File output) throws IOException

Here im is the RenderedImage to be written, formatName is the String containing the informal name of the format (e.g. png) and output is the file object to be written to. An example usage of the method for PNG file format is shown below:

ImageIO.write(image, "png", file);

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

If the date String does not include any value for hours, minutes and etc you cannot directly convert this to a LocalDateTime. You can only convert it to a LocalDate, because the string only represent the year,month and date components it would be the correct thing to do.

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf); // 2018-03-06

Anyway you can convert this to LocalDateTime.

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf);
LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(0,0)); // 2018-03-06T00:00

Hidden Features of Xcode

Use xcodebuild command line to do a clean build on the shared build machine:

cd project_directory
xcodebuild -configuration Release -alltargets clean
xcodebuild -configuration Release -alltargets

Postgresql: Scripting psql execution with password

There are several ways to authenticate to PostgreSQL. You may wish to investigate alternatives to password authentication at https://www.postgresql.org/docs/current/static/client-authentication.html.

To answer your question, there are a few ways provide a password for password-based authentication. The obvious way is via the password prompt. Instead of that, you can provide the password in a pgpass file or through the PGPASSWORD environment variable. See these:

There is no option to provide the password as a command line argument because that information is often available to all users, and therefore insecure. However, in Linux/Unix environments you can provide an environment variable for a single command like this:

PGPASSWORD=yourpass psql ...

What is JSONP, and why was it created?

JSONP is really a simple trick to overcome the XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

So - instead of using XMLHttpRequest we have to use script HTML tags, the ones you usually use to load js files, in order for js to get data from another domain. Sounds weird?

Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data';

You will end up with a script segment that looks like this after it loads the data:

<script>
{['some string 1', 'some data', 'whatever data']}
</script>

However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better(and it is):

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data?callback=my_callback';

Notice the my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain js array it'll return this:

my_callback({['some string 1', 'some data', 'whatever data']});

See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data.
That's all there is to know about JSONP: it's a callback and script tags.

NOTE: these are simple examples of JSONP usage, these are not production ready scripts.

Basic JavaScript example (simple Twitter feed using JSONP)

<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>

Basic jQuery example (simple Twitter feed using JSONP)

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>


JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)

How to redirect output of an already running process

Screen

If process is running in a screen session you can use screen's log command to log the output of that window to a file:

Switch to the script's window, C-a H to log.
Now you can :

$ tail -f screenlog.2 | grep whatever

From screen's man page:

log [on|off]

Start/stop writing output of the current window to a file "screenlog.n" in the window's default directory, where n is the number of the current window. This filename can be changed with the 'logfile' command. If no parameter is given, the state of logging is toggled. The session log is appended to the previous contents of the file if it already exists. The current contents and the contents of the scrollback history are not included in the session log. Default is 'off'.

I'm sure tmux has something similar as well.

Row count on the Filtered data

If you try to count the number of rows in the already autofiltered range like this:

Rowz = rnData.SpecialCells(xlCellTypeVisible).Rows.Count

It will only count the number of rows in the first contiguous visible area of the autofiltered range. E.g. if the autofilter range is rows 1 through 10 and rows 3, 5, 6, 7, and 9 are filtered, four rows are visible (rows 2, 4, 8, and 10), but it would return 2 because the first contiguous visible range is rows 1 (the header row) and 2.

A more accurate alternative is this (assuming that ws contains the worksheet with the filtered data):

Rowz = ws.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1

We have to subtract 1 to remove the header row. We need to include the header row in our counted range because SpecialCells will throw an error if no cells are found, which we want to avoid.

The Cells property will give you an accurate count even if the Range has multiple Areas, unlike the Rows property. So we just take the first column of the autofilter range and count the number of visible cells.

How to convert a std::string to const char* or char*?

Just see this:

string str1("stackoverflow");
const char * str2 = str1.c_str();

However, note that this will return a const char *.

For a char *, use strcpy to copy it into another char array.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

I think by positioning views on action bar you will reach what you want.On action bar's layout when layout params set to match parent it does not match full width that's why I did it programmatically where I succeed.By setting width (it works like layout_weight="value") we can set our view wherever we want:

    actionBar = getSupportActionBar(); 
    actionBar.setDisplayShowCustomEnabled(true); 

    LayoutInflater ll = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout linearLayout = (LinearLayout) ll.inflate(R.layout.custom_actionbar, null);
    //inner layout within above linear layout
    LinearLayout inner = (LinearLayout) linearLayout.findViewById(R.id.inner_linear_ractionbar);
    inner.setMinimumWidth(getWidth() * 2 / 10);
    // we will set our textview to center and display there some text
    TextView t = (TextView) linearLayout.findViewById(R.id.center_text);
    t.setWidth(getWidth() * 6 / 10);


    Button b = (Button) linearLayout.findViewById(R.id.edit_button);
    b.setWidth(getWidth() *3/ 20);

    ImageButton imageButton = (ImageButton) linearLayout.findViewById(R.id.action_bar_delete_item);
    imageButton.setMinimumWidth(deviceUtils.getWidth() / 20);

and here is getWidth() method:

 public int getWidth() { 
    DisplayMetrics dm = new DisplayMetrics();
     mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    return dm.widthPixels; 
   }

How to check not in array element

you can check using php in_array() built in function

<?php
  $os = array("Mac", "NT", "Irix", "Linux");
  if (in_array("Irix", $os)) {
    echo "Got Irix";
 }
 if (in_array("mac", $os)) {
  echo "Got mac";
}
?>

and you can also check using this

<?php
  $search_array = array('first' => 1, 'second' => 4);
  if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
   }
   ?>

in_array() is fine if you're only checking but if you need to check that a value exists and return the associated key, array_search is a better option.

$data = array(
0 => 'Key1',
1 => 'Key2'
);

$key = array_search('Key2', $data);

if ($key) {
 echo 'Key is ' . $key;
} else {
 echo 'Key not found';
}

for more details http://php.net/manual/en/function.in-array.php

Jquery Hide table rows

this might work for you...

$('.trhideclass1').hide();

 

<tr class="trhideclass1">
  <td>Label</td>
  <td>InputFile</td>
</tr>

How to close a web page on a button click, a hyperlink or a link button click?

public class Form1 : Form
{
public Form1()
{
    InitializeComponents(); // or whatever that method is called :)
    this.button.Click += new RoutedEventHandler(buttonClick);
}

private void buttonClick(object sender, EventArgs e)
{
    this.Close();
}
}

Spring Boot Multiple Datasource

Update 2018-01-07 with Spring Boot 1.5.8.RELEASE

If you want to know how to config it, how to use it, and how to control transaction. I may have answers for you.

You can see the runnable example and some explanation in https://www.surasint.com/spring-boot-with-multiple-databases-example/

I copied some code here.

First you have to set application.properties like this

#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

database2.datasource.url=jdbc:mysql://localhost/testdb2
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.jdbc.Driver

Then define them as providers (@Bean) like this:

@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
    return DataSourceBuilder.create().build();
}

@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
    return DataSourceBuilder.create().build();
}

Note that I have @Bean(name="datasource1") and @Bean(name="datasource2"), then you can use it when we need datasource as @Qualifier("datasource1") and @Qualifier("datasource2") , for example

@Qualifier("datasource1")
@Autowired
private DataSource dataSource;

If you do care about transaction, you have to define DataSourceTransactionManager for both of them, like this:

@Bean(name="tm1")
@Autowired
@Primary
DataSourceTransactionManager tm1(@Qualifier ("datasource1") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

@Bean(name="tm2")
@Autowired
DataSourceTransactionManager tm2(@Qualifier ("datasource2") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

Then you can use it like

@Transactional //this will use the first datasource because it is @primary

or

@Transactional("tm2")

This should be enough. See example and detail in the link above.

php convert datetime to UTC

alternatively you can try this:

<?php echo (new DateTime("now", new DateTimeZone('Asia/Singapore')))->format("Y-m-d H:i:s e"); ?>

this will output :

2017-10-25 17:13:20 Asia/Singapore

you can use this inside the value attribute of a text input box if you only want to display a read-only date.

remove the 'e' if you do not wish to show your region/country.

Difference between logger.info and logger.debug

  1. INFO is used to log the information your program is working as expected.
  2. DEBUG is used to find the reason in case your program is not working as expected or an exception has occurred. it's in the interest of the developer.

How do I redirect with JavaScript?

Compared to window.location="url"; it is much easyer to do just location="url"; I always use that

How to view the current heap size that an application is using?

You can do it by MXBeans

public class Check {
    public static void main(String[] args) {
        MemoryMXBean memBean = ManagementFactory.getMemoryMXBean() ;
        MemoryUsage heapMemoryUsage = memBean.getHeapMemoryUsage();

        System.out.println(heapMemoryUsage.getMax()); // max memory allowed for jvm -Xmx flag (-1 if isn't specified)
        System.out.println(heapMemoryUsage.getCommitted()); // given memory to JVM by OS ( may fail to reach getMax, if there isn't more memory)
        System.out.println(heapMemoryUsage.getUsed()); // used now by your heap
        System.out.println(heapMemoryUsage.getInit()); // -Xms flag

        // |------------------ max ------------------------| allowed to be occupied by you from OS (less than xmX due to empty survival space)
        // |------------------ committed -------|          | now taken from OS
        // |------------------ used --|                    | used by your heap

    }
}

But remember it is equivalent to Runtime.getRuntime() (took depicted schema from here)

memoryMxBean.getHeapMemoryUsage().getUsed()      <=> runtime.totalMemory() - runtime.freeMemory()
memoryMxBean.getHeapMemoryUsage().getCommitted() <=> runtime.totalMemory()
memoryMxBean.getHeapMemoryUsage().getMax()       <=> runtime.maxMemory()

from javaDoc

init - represents the initial amount of memory (in bytes) that the Java virtual machine requests from the operating system for memory management during startup. The Java virtual machine may request additional memory from the operating system and may also release memory to the system over time. The value of init may be undefined.

used - represents the amount of memory currently used (in bytes).

committed - represents the amount of memory (in bytes) that is guaranteed to be available for use by the Java virtual machine. The amount of committed memory may change over time (increase or decrease). The Java virtual machine may release memory to the system and committed could be less than init. committed will always be greater than or equal to used.

max - represents the maximum amount of memory (in bytes) that can be used for memory management. Its value may be undefined. The maximum amount of memory may change over time if defined. The amount of used and committed memory will always be less than or equal to max if max is defined. A memory allocation may fail if it attempts to increase the used memory such that used > committed even if used <= max would still be true (for example, when the system is low on virtual memory).

    +----------------------------------------------+
    +////////////////           |                  +
    +////////////////           |                  +
    +----------------------------------------------+

    |--------|
       init
    |---------------|
           used
    |---------------------------|
              committed
    |----------------------------------------------|
                        max

As additional note, maxMemory is less than -Xmx because there is necessity at least in one empty survival space, which can't be used for heap allocation.

also it is worth to to take a look at here and especially here

What is the difference between g++ and gcc?

gcc and g ++ are both GNU compiler. They both compile c and c++. The difference is for *.c files gcc treats it as a c program, and g++ sees it as a c ++ program. *.cpp files are considered to be c ++ programs. c++ is a super set of c and the syntax is more strict, so be careful about the suffix.

How to show particular image as thumbnail while implementing share on Facebook?

This blog post seems to have your answer: http://blog.capstrat.com/articles/facebook-share-thumbnail-image/

Specifically, use a tag like the following:

<link rel="image_src" 
      type="image/jpeg" 
      href="http://www.domain.com/path/icon-facebook.gif" />

The name of the image must be the same as in the example.

Click "Making Sure the Preview Works"

Note: Tags can be correct but Facebook only scrapes every 24 hours, according to their documentation. Use the Facebook Lint page to get the image into Facebook.

http://developers.facebook.com/tools/lint/

Save the plots into a PDF

For multiple plots in a single pdf file you can use PdfPages

In the plotGraph function you should return the figure and than call savefig of the figure object.

------ plotting module ------

def plotGraph(X,Y):
      fig = plt.figure()
      ### Plotting arrangements ###
      return fig

------ plotting module ------

----- mainModule ----

from matplotlib.backends.backend_pdf import PdfPages

plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)

pp = PdfPages('foo.pdf')
pp.savefig(plot1)
pp.savefig(plot2)
pp.savefig(plot3)
pp.close()

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008

DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681); 

SET @y = REPLICATE(@y,92681);

SELECT LEN(@y) 

Returns

8589767761

I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory

Running

select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid

Returned

internal_objects_alloc_page_co 
------------------------------ 
2144456    

so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.

Addition

I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647); 
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/


DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823); 
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/


DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test

How to detect when an @Input() value changes in Angular?

I just want to add that there is another Lifecycle hook called DoCheck that is useful if the @Input value is not a primitive value.

I have an Array as an Input so this does not fire the OnChanges event when the content changes (because the checking that Angular does is 'simple' and not deep so the Array is still an Array, even though the content on the Array has changed).

I then implement some custom checking code to decide if I want to update my view with the changed Array.

Uploading an Excel sheet and importing the data into SQL Server database

 protected void btnUpload_Click(object sender, EventArgs e)
    {
        divStatusMsg.Style.Add("display", "none");
        divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
        divStatusMsg.InnerText = "";
        ViewState["Fuletypeidlist"] = "0";
        grdExcel.DataSource = null;
        grdExcel.DataBind();

        if (Page.IsValid)
        {
            bool logval = true;
            if (logval == true)
            {
                String img_1 = fuUploadExcelName.PostedFile.FileName;
                String img_2 = System.IO.Path.GetFileName(img_1);
                string extn = System.IO.Path.GetExtension(img_1);

                string frstfilenamepart = "";
                frstfilenamepart = "DateExcel" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
                UploadExcelName.Value = frstfilenamepart + extn;
                fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/DateExcel/") + "/" + UploadExcelName.Value);
                string PathName = Server.MapPath("~/Emp/DateExcel/") + "\\" + UploadExcelName.Value;
                GetExcelSheetForEmp(PathName, UploadExcelName.Value);
               
                if ((grdExcel.HeaderRow.Cells[0].Text.ToString() == "CODE") && grdExcel.HeaderRow.Cells[1].Text.ToString() == "SAL")
                {
                    GetExcelSheetForEmployeeCode(PathName);
                }
                else
                {
                    divStatusMsg.Style.Add("display", "");
                    divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
                    divStatusMsg.InnerText = "ERROR !!...Please Upload Excel Sheet in header Defined Format ";
                }

            }
        }


    }

    private void GetExcelSheetForEmployeeCode(string filename)
    {
        int count = 0;
        int selectedcheckbox = 0;
        string empcodeexcel = "";
        string empcodegrid = "";
        string excelFile = "Employee/DateExcel" + filename;
        OleDbConnection objConn = null;
        System.Data.DataTable dt = null;
        try
        {
            DataSet ds = new DataSet();
            String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + filename;
            // Create connection. 
            objConn = new OleDbConnection(connString);
            // Opens connection with the database. 
            if (objConn.State == ConnectionState.Closed)
            {
                objConn.Open();
            }
            // Get the data table containing the schema guid, and also sheet names. 
            dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (dt == null)
            {
                return;
            }
            String[] excelSheets = new String[dt.Rows.Count];
            int i = 0;
            // Add the sheet name to the string array. 
            // And respective data will be put into dataset table 
            foreach (DataRow row in dt.Rows)
            {
                if (i == 0)
                {
                    excelSheets[i] = row["TABLE_NAME"].ToString();
                    OleDbCommand cmd = new OleDbCommand("SELECT DISTINCT * FROM [" + excelSheets[i] + "]", objConn);
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    oleda.SelectCommand = cmd;
                    oleda.Fill(ds, "TABLE");
                    if (ds.Tables[0].ToString() != null)
                    {
                        for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                        {
                            for (int k = 0; k < GrdEmplist.Rows.Count; k++)
                            {
                                empcodeexcel = ds.Tables[0].Rows[j][0].ToString();
                                date.Value = ds.Tables[0].Rows[j][1].ToString();

                                Label lbl_EmpCode = (Label)GrdEmplist.Rows[k].FindControl("lblGrdCode");
                                empcodegrid = lbl_Code.Text;
                                CheckBox chk = (CheckBox)GrdEmplist.Rows[k].FindControl("chkSingle");
                                TextBox txt_Sal = (TextBox)GrdEmplist.Rows[k].FindControl("txtSal");


                                if ((empcodegrid == empcodeexcel) && (date.Value != ""))
                                {
                                    chk.Checked = true;
                                    txt_Sal.Text = date.Value;
                                    selectedcheckbox = selectedcheckbox + 1;
                                    lblSelectedRecord.InnerText = selectedcheckbox.ToString();
                                    count++;
                                }
                                if (chk.Checked == true)
                                {

                                }
                            }

                        }

                    }
                }
                i++;
            }

        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message.ToString(), 0);
        }
        finally
        {
            // Clean up. 
            if (objConn != null)
            {
                objConn.Close();
                objConn.Dispose();
            }
            if (dt != null)
            {
                dt.Dispose();
            }
        }
    }

    private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
    {
        string excelFile = "DateExcel/" + PathName;
        OleDbConnection objConn = null;
        System.Data.DataTable dt = null;
        try
        {

            DataSet dss = new DataSet();
            String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
            objConn = new OleDbConnection(connString);
            objConn.Open();
            dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (dt == null)
            {
                return;
            }
            String[] excelSheets = new String[dt.Rows.Count];
            int i = 0;
            foreach (DataRow row in dt.Rows)
            {
                if (i == 0)
                {
                    excelSheets[i] = row["TABLE_NAME"].ToString();
                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    oleda.SelectCommand = cmd;
                    oleda.Fill(dss, "TABLE");

                }
                i++;
            }
            grdExcel.DataSource = dss.Tables[0].DefaultView;
            grdExcel.DataBind();
            lblTotalRec.InnerText = Convert.ToString(grdExcel.Rows.Count);

        }

        catch (Exception ex)
        {
            ViewState["Fuletypeidlist"] = "0";
            grdExcel.DataSource = null;
            grdExcel.DataBind();
        }
        finally
        {
            if (objConn != null)
            {
                objConn.Close();
                objConn.Dispose();
            }
            if (dt != null)
            {
                dt.Dispose();
            }
        }

    }

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

I can see that your using AppServ, mod_rewrite is disabled by default on that WAMP package (just googled it)

Solution:

Find: C:/AppServ/Apache/conf/httpd.conf file.

and un-comment this line #LoadModule rewrite_module modules/mod_rewrite.so

Restart apache... Simplez

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Another possible cause of similar issue could be wrong processorArchitecture in the cx_freeze manifest, trying to load x86 common controls dll in x64 process - should be fixed by this patch:

https://bitbucket.org/anthony_tuininga/cx_freeze/pull-request/71/changed-x86-in-windows-manifest-to/diff

How do you set your pythonpath in an already-created virtualenv?

I modified my activate script to source the file .virtualenvrc, if it exists in the current directory, and to save/restore PYTHONPATH on activate/deactivate.

You can find the patched activate script here.. It's a drop-in replacement for the activate script created by virtualenv 1.11.6.

Then I added something like this to my .virtualenvrc:

export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/some/library/path"

Loading existing .html file with android WebView

ok, that was my very stupid mistake. I post the answer here just in case someone has the same problem.

The correct path for files stored in assets folder is file:///android_asset/* (with no "s" for assets folder which i was always thinking it must have a "s").

And, mWebView.loadUrl("file:///android_asset/myfile.html"); works under all API levels.

I still not figure out why mWebView.loadUrl("file:///android_res/raw/myfile.html"); works only on API level 8. But it doesn't matter now.

Tomcat in Intellij Idea Community Edition

Well the question is already answered, however what I am writing here is just my observation so other fellows in the community can save some of their time. I tried running a spring-mvc project using the embedded tom-cat in Intellij communit edition.

First try I did was using the Gradle tom-cat plugin, however the problem that I faced there is the tomcat server just starts once, after that from the second start the build complains saying that a container is already running. There are so many open thread on the web about this, for some it works and for most of the people (almost 90% of the web threads that I broke my head with, faced the same problem of container not getting started the second time. The resolution is not there.

After wasting a lot lot of my time, I finally decided to switch to maven tom-cat plugin and do the same spring-mvc setup with maven that I did with gradle and VOILA! it worked in the first short.

So long story short, if you are setting up spring-mvc project in intellij community edition, please consider maven tomcat plugin.

Hope this helps somebody's hours of exploration across various web forums.

What's the easiest way to install a missing Perl module?

Lots of recommendation for CPAN.pm, which is great, but if you're using Perl 5.10 then you've also got access to CPANPLUS.pm which is like CPAN.pm but better.

And, of course, it's available on CPAN for people still using older versions of Perl. Why not try:

$ cpan CPANPLUS

How can I force users to access my page over HTTPS instead of HTTP?

You should force the client to request HTTPS always with HTTP Strict Transport Security (HSTS) headers:

// Use HTTP Strict Transport Security to force client to use secure connections only
$use_sts = true;

// iis sets HTTPS to 'off' for non-SSL requests
if ($use_sts && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
    header('Strict-Transport-Security: max-age=31536000');
} elseif ($use_sts) {
    header('Location: https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], true, 301);
    // we are in cleartext at the moment, prevent further execution and output
    die();
}

Please note that HSTS is supported in most modern browsers, but not universal. Thus the logic above manually redirects the user regardless of support if they end up on HTTP, and then sets the HSTS header so that further client requests should be redirected by the browser if possible.

Why am I getting Unknown error in line 1 of pom.xml?

You must to upgrade the m2e connector. It's a known bug, but there is a solution:

  1. Into Eclipse click "Help" > "Install new Software..."

  2. Appears a window. In the "Install" window:

    2a. Into the input box "Work with", enter next site location and press Enter https://download.eclipse.org/m2e-wtp/releases/1.4/

    2b. Appears a lot of information into "Name" input Box. Select all the items

    2c. Click "Next" Button.

Finish the installation and restart Eclipse.

Specify the date format in XMLGregorianCalendar

Yeah Got it...

Date dob=null;
DateFormat df=new SimpleDateFormat("dd/MM/yyyy");
dob=df.parse( "13/06/1983" );
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dob);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);

This will give it in correct format.

How can I write a regex which matches non greedy?

The other answers here presuppose that you have a regex engine which supports non-greedy matching, which is an extension introduced in Perl 5 and widely copied to other modern languages; but it is by no means ubiquitous.

Many older or more conservative languages and editors only support traditional regular expressions, which have no mechanism for controlling greediness of the repetition operator * - it always matches the longest possible string.

The trick then is to limit what it's allowed to match in the first place. Instead of .* you seem to be looking for

[^>]*

which still matches as many of something as possible; but the something is not just . "any character", but instead "any character which isn't >".

Depending on your application, you may or may not want to enable an option to permit "any character" to include newlines.

Even if your regular expression engine supports non-greedy matching, it's better to spell out what you actually mean. If this is what you mean, you should probably say this, instead of rely on non-greedy matching to (hopefully, probably) Do What I Mean.

For example, a regular expression with a trailing context after the wildcard like .*?><br/> will jump over any nested > until it finds the trailing context (here, ><br/>) even if that requires straddling multiple > instances and newlines if you let it, where [^>]*><br/> (or even [^\n>]*><br/> if you have to explicitly disallow newline) obviously can't and won't do that.

Of course, this is still not what you want if you need to cope with <img title="quoted string with > in it" src="other attributes"> and perhaps <img title="nested tags">, but at that point, you should finally give up on using regular expressions for this like we all told you in the first place.

Python "string_escape" vs "unicode_escape"

According to my interpretation of the implementation of unicode-escape and the unicode repr in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string) and unicode_string.encode('unicode-escape') is the inclusion of wrapping quotes and escaping whichever quote was used.

They are both driven by the same function, unicodeescape_string. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.

React: how to update state.item[1] in state using setState?

Sometimes in React, mutating the cloned array can affect the original one, this method will never cause mutation:

    const myNewArray = Object.assign([...myArray], {
        [index]: myNewItem
    });
    setState({ myArray: myNewArray });

Or if you just want to update a property of an item:

    const myNewArray = Object.assign([...myArray], {
        [index]: {
            ...myArray[index],
            prop: myNewValue
        }
    });
    setState({ myArray: myNewArray });

How can I create a memory leak in Java?

You are able to make memory leak with sun.misc.Unsafe class. In fact this service class is used in different standard classes (for example in java.nio classes). You can't create instance of this class directly, but you may use reflection to do that.

Code doesn't compile in Eclipse IDE - compile it using command javac (during compilation you'll get warnings)

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import sun.misc.Unsafe;


public class TestUnsafe {

    public static void main(String[] args) throws Exception{
        Class unsafeClass = Class.forName("sun.misc.Unsafe");
        Field f = unsafeClass.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        Unsafe unsafe = (Unsafe) f.get(null);
        System.out.print("4..3..2..1...");
        try
        {
            for(;;)
                unsafe.allocateMemory(1024*1024);
        } catch(Error e) {
            System.out.println("Boom :)");
            e.printStackTrace();
        }
    }

}

Checking for a null int value from a Java ResultSet

You can call this method using the resultSet and the column name having Number type. It will either return the Integer value, or null. There will be no zeros returned for empty value in the database

private Integer getIntWithNullCheck(ResultSet rset, String columnName) {
    try {
        Integer value = rset.getInt(columnName);
        return rset.wasNull() ? null : value;
    } catch (Exception e) {
        return null;
    }
}

How to run a .awk file?

Put the part from BEGIN....END{} inside a file and name it like my.awk.

And then execute it like below:

awk -f my.awk life.csv >output.txt

Also I see a field separator as ,. You can add that in the begin block of the .awk file as FS=","

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

Does Python have a ternary conditional operator?

One of the alternatives to Python's conditional expression

"yes" if boolean else "no"

is the following:

{True:"yes", False:"no"}[boolean]

which has the following nice extension:

{True:"yes", False:"no", None:"maybe"}[boolean_or_none]

The shortest alternative remains:

("no", "yes")[boolean]

but there is no alternative to

yes() if boolean else no()

if you want to avoid the evaluation of yes() and no(), because in

(no(), yes())[boolean]  # bad

both no() and yes() are evaluated.

NuGet: 'X' already has a dependency defined for 'Y'

The only solution that worked for me was to uninstall nuget completely from Visual Studio 2013 and then install it again with the obligatory restart of VS in between.

What does 'IISReset' do?

It operates on the whole IIS process tree, as opposed to just your application pools.

C:\>iisreset /?

IISRESET.EXE (c) Microsoft Corp. 1998-1999

Usage:
iisreset [computername]

    /RESTART            Stop and then restart all Internet services.
    /START              Start all Internet services.
    /STOP               Stop all Internet services.
    /REBOOT             Reboot the computer.
    /REBOOTONERROR      Reboot the computer if an error occurs when starting,
                        stopping, or restarting Internet services.
    /NOFORCE            Do not forcefully terminate Internet services if
                        attempting to stop them gracefully fails.
    /TIMEOUT:val        Specify the timeout value ( in seconds ) to wait for
                        a successful stop of Internet services. On expiration
                        of this timeout the computer can be rebooted if
                        the /REBOOTONERROR parameter is specified.
                        The default value is 20s for restart, 60s for stop,
                        and 0s for reboot.
    /STATUS             Display the status of all Internet services.
    /ENABLE             Enable restarting of Internet Services
                        on the local system.
    /DISABLE            Disable restarting of Internet Services
                        on the local system.

How do I iterate through each element in an n-dimensional matrix in MATLAB?

As pointed out in a few other answers, you can iterate over all elements in a matrix A (of any dimension) using a linear index from 1 to numel(A) in a single for loop. There are also a couple of functions you can use: arrayfun and cellfun.

Let's first assume you have a function that you want to apply to each element of A (called my_func). You first create a function handle to this function:

fcn = @my_func;

If A is a matrix (of type double, single, etc.) of arbitrary dimension, you can use arrayfun to apply my_func to each element:

outArgs = arrayfun(fcn, A);

If A is a cell array of arbitrary dimension, you can use cellfun to apply my_func to each cell:

outArgs = cellfun(fcn, A);

The function my_func has to accept A as an input. If there are any outputs from my_func, these are placed in outArgs, which will be the same size/dimension as A.

One caveat on outputs... if my_func returns outputs of different sizes and types when it operates on different elements of A, then outArgs will have to be made into a cell array. This is done by calling either arrayfun or cellfun with an additional parameter/value pair:

outArgs = arrayfun(fcn, A, 'UniformOutput', false);
outArgs = cellfun(fcn, A, 'UniformOutput', false);

C# elegant way to check if a property's property is null

You could do this:

class ObjectAType
{
    public int PropertyC
    {
        get
        {
            if (PropertyA == null)
                return 0;
            if (PropertyA.PropertyB == null)
                return 0;
            return PropertyA.PropertyB.PropertyC;
        }
    }
}



if (ObjectA != null)
{
    int value = ObjectA.PropertyC;
    ...
}

Or even better might be this:

private static int GetPropertyC(ObjectAType objectA)
{
    if (objectA == null)
        return 0;
    if (objectA.PropertyA == null)
        return 0;
    if (objectA.PropertyA.PropertyB == null)
        return 0;
    return objectA.PropertyA.PropertyB.PropertyC;
}


int value = GetPropertyC(ObjectA);

Set cursor position on contentEditable <div>

After playing around I've modified eyelidlessness' answer above and made it a jQuery plugin so you can just do one of these:

var html = "The quick brown fox";
$div.html(html);

// Select at the text "quick":
$div.setContentEditableSelection(4, 5);

// Select at the beginning of the contenteditable div:
$div.setContentEditableSelection(0);

// Select at the end of the contenteditable div:
$div.setContentEditableSelection(html.length);

Excuse the long code post, but it may help someone:

$.fn.setContentEditableSelection = function(position, length) {
    if (typeof(length) == "undefined") {
        length = 0;
    }

    return this.each(function() {
        var $this = $(this);
        var editable = this;
        var selection;
        var range;

        var html = $this.html();
        html = html.substring(0, position) +
            '<a id="cursorStart"></a>' +
            html.substring(position, position + length) +
            '<a id="cursorEnd"></a>' +
            html.substring(position + length, html.length);
        console.log(html);
        $this.html(html);

        // Populates selection and range variables
        var captureSelection = function(e) {
            // Don't capture selection outside editable region
            var isOrContainsAnchor = false,
                isOrContainsFocus = false,
                sel = window.getSelection(),
                parentAnchor = sel.anchorNode,
                parentFocus = sel.focusNode;

            while (parentAnchor && parentAnchor != document.documentElement) {
                if (parentAnchor == editable) {
                    isOrContainsAnchor = true;
                }
                parentAnchor = parentAnchor.parentNode;
            }

            while (parentFocus && parentFocus != document.documentElement) {
                if (parentFocus == editable) {
                    isOrContainsFocus = true;
                }
                parentFocus = parentFocus.parentNode;
            }

            if (!isOrContainsAnchor || !isOrContainsFocus) {
                return;
            }

            selection = window.getSelection();

            // Get range (standards)
            if (selection.getRangeAt !== undefined) {
                range = selection.getRangeAt(0);

                // Get range (Safari 2)
            } else if (
                document.createRange &&
                selection.anchorNode &&
                selection.anchorOffset &&
                selection.focusNode &&
                selection.focusOffset
            ) {
                range = document.createRange();
                range.setStart(selection.anchorNode, selection.anchorOffset);
                range.setEnd(selection.focusNode, selection.focusOffset);
            } else {
                // Failure here, not handled by the rest of the script.
                // Probably IE or some older browser
            }
        };

        // Slight delay will avoid the initial selection
        // (at start or of contents depending on browser) being mistaken
        setTimeout(function() {
            var cursorStart = document.getElementById('cursorStart');
            var cursorEnd = document.getElementById('cursorEnd');

            // Don't do anything if user is creating a new selection
            if (editable.className.match(/\sselecting(\s|$)/)) {
                if (cursorStart) {
                    cursorStart.parentNode.removeChild(cursorStart);
                }
                if (cursorEnd) {
                    cursorEnd.parentNode.removeChild(cursorEnd);
                }
            } else if (cursorStart) {
                captureSelection();
                range = document.createRange();

                if (cursorEnd) {
                    range.setStartAfter(cursorStart);
                    range.setEndBefore(cursorEnd);

                    // Delete cursor markers
                    cursorStart.parentNode.removeChild(cursorStart);
                    cursorEnd.parentNode.removeChild(cursorEnd);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);
                } else {
                    range.selectNode(cursorStart);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);

                    // Delete cursor marker
                    document.execCommand('delete', false, null);
                }
            }

            // Register selection again
            captureSelection();
        }, 10);
    });
};

Using PHP variables inside HTML tags?

HI Jasper,

you can do this:

<?
sprintf("<a href=\"http://www.whatever.com/%s\">Click Here</a>", $param);
?>

What's the fastest algorithm for sorting a linked list?

You can copy it into an array and then sort it.

  • Copying into array O(n),

  • sorting O(nlgn) (if you use a fast algorithm like merge sort ),

  • copying back to linked list O(n) if necessary,

so it is gonna be O(nlgn).

note that if you do not know the number of elements in the linked list you won't know the size of array. If you are coding in java you can use an Arraylist for example.

Handling very large numbers in Python

The python interpreter will handle it for you, you just have to do your operations (+, -, *, /), and it will work as normal.

The int value is unlimited.

Careful when doing division, by default the quotient is turned into float, but float does not support such large numbers. If you get an error message saying float does not support such large numbers, then it means the quotient is too large to be stored in float you’ll have to use floor division (//).

It ignores any decimal that comes after the decimal point, this way, the result will be int, so you can have a large number result.

>>>10//3
3

>>>10//4
2

CSS Input with width: 100% goes outside parent's bound

Do you want the input fields to be centered? A trick to center elements: specify the width of the element and set the margin to auto, eg:

margin : 0px auto;
width:300px

A link to your updated fiddle:

http://jsfiddle.net/4x2KP/5/

Docker error: invalid reference format: repository name must be lowercase

had a space in the current working directory and usign $(pwd) to map volumes. Doesn't like spaces in directory names.

Sql script to find invalid email addresses

MySQL

SELECT * FROM `emails` WHERE `email`
NOT REGEXP '[-a-z0-9~!$%^&*_=+}{\\\'?]+(\\.[-a-z0-9~!$%^&*_=+}{\\\'?]+)*@([a-z0-9_][-a-z0-9_]*(\\.[-a-z0-9_]+)*\\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,5})?'

Python conversion between coordinates

The existing answers can be simplified:

from numpy import exp, abs, angle

def polar2z(r,theta):
    return r * exp( 1j * theta )

def z2polar(z):
    return ( abs(z), angle(z) )

Or even:

polar2z = lambda r,?: r * exp( 1j * ? )
z2polar = lambda z: ( abs(z), angle(z) )

Note these also work on arrays!

rS, thetaS = z2polar( [z1,z2,z3] )
zS = polar2z( rS, thetaS )

Java Spring Boot: How to map my app root (“/”) to index.html?

It would have worked out of the box if you hadn't used @EnableWebMvc annotation. When you do that you switch off all the things that Spring Boot does for you in WebMvcAutoConfiguration. You could remove that annotation, or you could add back the view controller that you switched off:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("forward:/index.html");
}

Why can't I initialize non-const static member or static array in class?

I think it's to prevent you from mixing declarations and definitions. (Think about the problems that could occur if you include the file in multiple places.)

What does "Table does not support optimize, doing recreate + analyze instead" mean?

That's really an informational message.

Likely, you're doing OPTIMIZE on an InnoDB table (table using the InnoDB storage engine, rather than the MyISAM storage engine).

InnoDB doesn't support the OPTIMIZE the way MyISAM does. It does something different. It creates an empty table, and copies all of the rows from the existing table into it, and essentially deletes the old table and renames the new table, and then runs an ANALYZE to gather statistics. That's the closest that InnoDB can get to doing an OPTIMIZE.

The message you are getting is basically MySQL server repeating what the InnoDB storage engine told MySQL server:

Table does not support optimize is the InnoDB storage engine saying...

"I (the InnoDB storage engine) don't do an OPTIMIZE operation like my friend (the MyISAM storage engine) does."

"doing recreate + analyze instead" is the InnoDB storage engine saying...

"I have decided to perform a different set of operations which will achieve an equivalent result."

How to create a localhost server to run an AngularJS project

"Assuming that you have nodejs installed",

mini-http is a pretty easy command-line tool to create http server,
install the package globally npm install mini-http -g
then using your cmd (terminal) run mini-http -p=3000 in your project directory And boom! you created a server on port 3000 now go check http://localhost:3000

Note: specifying a port is not required you can simply run mini-http or mh to start the server

Facebook Graph API, how to get users email?

You can retrieve the email address from the logged in user's profile. Here is the code snippet

<?php

    $facebook = new Facebook(array(
      'appId'  => $initMe["appId"],
      'secret' => $initMe["appSecret"],
    ));

    $facebook->setAccessToken($initMe["accessToken"]);
    $user = $facebook->getUser();

    if ($user) {
        $user_profile = $facebook->api('/me');
        print_r($user_profile["email"]);
    }
?>

How do you change the width and height of Twitter Bootstrap's tooltips?

I needed to adjust the width of some tooltips. But not an overall setting. So I ended up doing this:

CSS

.large-tooltip .tooltip-inner {
    max-width: 300px;
}
@media screen and (max-width: 300px) {
  .large-tooltip .tooltip-inner {
    max-width: 100%;
  }
}

JQuery

$('[data-toggle="tooltip"]')
    .tooltip()
    .on('shown.bs.tooltip', function(e) {
        /**
         * If the item that triggered the event has class 'large-tooltip'
         * then also add it to the currently open tooltip
         */
        if ($(this).hasClass('large-tooltip')) {
            $('body').find('.tooltip[role="tooltip"].show').addClass('large-tooltip');
        }
    });

Html

<img src="/theimage.jpg" class="large-tooltip" data-toggle="tooltip" data-html="true" title="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." />

Ajax success event not working

I'm using XML to carry the result back from the php on the server to the webpage and I have had the same behaviour.

In my case the reason was , that the closing tag did not match the opening tag.

<?php
....
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
    <result>
        <status>$status</status>
        <OPENING_TAG>$message</CLOSING_TAG>
    </result>";
?>

Implement Stack using Two Queues

Here is some simple pseudo code, push is O(n), pop / peek is O(1):

Qpush = Qinstance()
Qpop = Qinstance()

def stack.push(item):
    Qpush.add(item)
    while Qpop.peek() != null: //transfer Qpop into Qpush
        Qpush.add(Qpop.remove()) 
    swap = Qpush
    Qpush = Qpop
    Qpop = swap

def stack.pop():
    return Qpop.remove()

def stack.peek():
    return Qpop.peek()

How can I specify a [DllImport] path at runtime?

If you need a .dll file that is not on the path or on the application's location, then I don't think you can do just that, because DllImport is an attribute, and attributes are only metadata that is set on types, members and other language elements.

An alternative that can help you accomplish what I think you're trying, is to use the native LoadLibrary through P/Invoke, in order to load a .dll from the path you need, and then use GetProcAddress to get a reference to the function you need from that .dll. Then use these to create a delegate that you can invoke.

To make it easier to use, you can then set this delegate to a field in your class, so that using it looks like calling a member method.

EDIT

Here is a code snippet that works, and shows what I meant.

class Program
{
    static void Main(string[] args)
    {
        var a = new MyClass();
        var result = a.ShowMessage();
    }
}

class FunctionLoader
{
    [DllImport("Kernel32.dll")]
    private static extern IntPtr LoadLibrary(string path);

    [DllImport("Kernel32.dll")]
    private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    public static Delegate LoadFunction<T>(string dllPath, string functionName)
    {
        var hModule = LoadLibrary(dllPath);
        var functionAddress = GetProcAddress(hModule, functionName);
        return Marshal.GetDelegateForFunctionPointer(functionAddress, typeof (T));
    }
}

public class MyClass
{
    static MyClass()
    {
        // Load functions and set them up as delegates
        // This is just an example - you could load the .dll from any path,
        // and you could even determine the file location at runtime.
        MessageBox = (MessageBoxDelegate) 
            FunctionLoader.LoadFunction<MessageBoxDelegate>(
                @"c:\windows\system32\user32.dll", "MessageBoxA");
    }

    private delegate int MessageBoxDelegate(
        IntPtr hwnd, string title, string message, int buttons); 

    /// <summary>
    /// This is the dynamic P/Invoke alternative
    /// </summary>
    static private MessageBoxDelegate MessageBox;

    /// <summary>
    /// Example for a method that uses the "dynamic P/Invoke"
    /// </summary>
    public int ShowMessage()
    {
        // 3 means "yes/no/cancel" buttons, just to show that it works...
        return MessageBox(IntPtr.Zero, "Hello world", "Loaded dynamically", 3);
    }
}

Note: I did not bother to use FreeLibrary, so this code is not complete. In a real application, you should take care to release the loaded modules to avoid a memory leak.

How to validate an Email in PHP?

User data is very important for a good developer, so don't ask again and again for same data, use some logic to correct some basic error in data.

Before validation of Email: First you have to remove all illegal characters from email.

//This will Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

after that validate your email address using this filter_var() function.

filter_var($email, FILTER_VALIDATE_EMAIL)) // To Validate the email

For e.g.

<?php
$email = "[email protected]";

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo $email." is a valid email address";
} else {
    echo $email." is not a valid email address";
}
?>

Allow anonymous authentication for a single folder in web.config?

The first approach to take is to modify your web.config using the <location> configuration tag, and <allow users="?"/> to allow anonymous or <allow users="*"/> for all:

<configuration>
   <location path="Path/To/Public/Folder">
      <system.web>
         <authorization>
            <allow users="?"/>
         </authorization>
      </system.web>
   </location>
</configuration>

If that approach doesn't work then you can take the following approach which requires making a small modification to the IIS applicationHost.config.

First, change the anonymousAuthentication section's overrideModeDefault from "Deny" to "Allow" in C:\Windows\System32\inetsrv\config\applicationHost.config:

<section name="anonymousAuthentication" overrideModeDefault="Allow" />

overrideMode is a security feature of IIS. If override is disallowed at the system level in applicationHost.config then there is nothing you can do in web.config to enable it. If you don't have this level of access on your target system you have to take up that discussion with your hosting provider or system administrator.

Second, after setting overrideModeDefault="Allow" then you can put the following in your web.config:

<location path="Path/To/Public/Folder">
  <system.webServer>
    <security>
      <authentication>
        <anonymousAuthentication enabled="true" />
      </authentication>
    </security>
  </system.webServer>
</location>

Finding an elements XPath using IE Developer tool

If your goal is to find CSS selectors you can use MRI (once MRI is open, click any element to see various selectors for the element):

http://westciv.com/mri/

For Xpath:

http://functionaltestautomation.blogspot.com/2008/12/xpath-in-internet-explorer.html

X11/Xlib.h not found in Ubuntu

Why not try find /usr/include/X11 -name Xlib.h

If there is a hit, you have Xlib.h

If not install it using sudo apt-get install libx11-dev

and you are good to go :)

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

I use these attributes and it works, data-keyboard="false" data-backdrop="static"

Spark specify multiple column conditions for dataframe join

Try this:

val rccJoin=dfRccDeuda.as("dfdeuda")
.join(dfRccCliente.as("dfcliente")
,col("dfdeuda.etarcid")===col("dfcliente.etarcid") 
&& col("dfdeuda.etarcid")===col("dfcliente.etarcid"),"inner")

How to keep console window open

You forgot calling your method:

static void Main(string[] args)
{          
    StringAddString s = new StringAddString();  
    s.AddString();
}

it should stop your console, but the result might not be what you expected, you should change your code a little bit:

Console.WriteLine(string.Join(",", strings2));

Having trouble setting working directory

The command setwd("~/") should set your working directory to your home directory. You might be experiencing problems because the OS you are using does not recognise "~/" as your home directory: this might be because of the OS, or it might be because of not having set that as your home directory elsewhere.

As you have tagged the post using RStudio:

  • In the bottom right window move the tab over to 'files'.
  • Navigate through there to whichever folder you were planning to use as your working directory.
  • Under 'more' click 'set as working directory'

You will now have set the folder as your working directory. Use the command getwd() to get the working directory as it is now set, and save that as a variable string at the top of your script. Then use setwd with that string as the argument, so that each time you run the script you use the same directory.

For example at the top of my script I would have:

work_dir <- "C:/Users/john.smith/Documents"
setwd(work_dir)

Parse RSS with jQuery

Using JFeed

function getFeed(sender, uri) {
    jQuery.getFeed({
        url: 'proxy.php?url=' + uri,
        success: function(feed) {
            jQuery(sender).append('<h2>'
            + '<a href="'
            + feed.link
            + '">'
            + feed.title
            + '</a>'
            + '</h2>');

            var html = '';

            for(var i = 0; i < feed.items.length && i < 5; i++) {

                var item = feed.items[i];

                html += '<h3>'
                + '<a href="'
                + item.link
                + '">'
                + item.title
                + '</a>'
                + '</h3>';

                html += '<div class="updated">'
                + item.updated
                + '</div>';

                html += '<div>'
                + item.description
                + '</div>';
            }

            jQuery(sender).append(html);
        }    
    });
}

<div id="getanewbrowser">
  <script type="text/javascript">
    getFeed($("#getanewbrowser"), 'http://feeds.feedburner.com/getanewbrowser')
  </script>
</div>

Simple way to encode a string according to a password?

Here's an implementation of URL Safe encryption and Decryption using AES(PyCrypto) and base64.

import base64
from Crypto import Random
from Crypto.Cipher import AES

AKEY = b'mysixteenbytekey' # AES key must be either 16, 24, or 32 bytes long

iv = Random.new().read(AES.block_size)

def encode(message):
    obj = AES.new(AKEY, AES.MODE_CFB, iv)
    return base64.urlsafe_b64encode(obj.encrypt(message))

def decode(cipher):
    obj2 = AES.new(AKEY, AES.MODE_CFB, iv)
    return obj2.decrypt(base64.urlsafe_b64decode(cipher))

If you face some issue like this https://bugs.python.org/issue4329 (TypeError: character mapping must return integer, None or unicode) use str(cipher) while decoding as follows:

return obj2.decrypt(base64.urlsafe_b64decode(str(cipher)))

Test:

In [13]: encode(b"Hello World")
Out[13]: b'67jjg-8_RyaJ-28='

In [14]: %timeit encode("Hello World")
100000 loops, best of 3: 13.9 µs per loop

In [15]: decode(b'67jjg-8_RyaJ-28=')
Out[15]: b'Hello World'

In [16]: %timeit decode(b'67jjg-8_RyaJ-28=')
100000 loops, best of 3: 15.2 µs per loop

isolating a sub-string in a string before a symbol in SQL Server 2008

This can achieve using two SQL functions- SUBSTRING and CHARINDEX

You can read strings to a variable as shown in the above answers, or can add it to a SELECT statement as below:

SELECT SUBSTRING('Net Operating Loss - 2007' ,0, CHARINDEX('-','Net Operating Loss - 2007'))

Only allow Numbers in input Tag without Javascript

Of course, you can't fully rely on the client-side (javascript) validation, but that's not a reason to avoid it completely. With or without it, you have to do the server-side validation anyway (since the client can disable javascript). And that's just what you're left with, due to your non-javascript solution constraint.

So, after a submit, if the field value doesn't pass the server-side validation, the client should end up on the very same page, with additional error message specifying the requested value format. You also should provide the value format information beforehands, e.g. as a tool-tip hint (title attribute).

There's most certainly no passive client-side validation mechanism existing in HTML 4 / XHTML.

On the other hand, in HTML 5 you have two options:

  • input of type number:

    <input type="number" min="xxx" max="yyy" title="Format: 3 digits" />
    

    – only validates the range – if user enters a non-number, an empty value is submitted
    – the field visual is enhanced with increment / decrement controls (browser dependent)

  • the pattern attribute:

    <input type="text" pattern="[0-9]{3}" title="Format: 3 digits" />
    <input type="text" pattern="\d{3}" title="Format: 3 digits" />
    

    – this gives you a full contorl over the format (anything you can specify by regular expression)
    – no visual difference / enhancement

But here you still rely on browser capabilities, so do a server-side validation in either case.

Executing <script> injected by innerHTML after AJAX call

I used this code, it is working fine

var arr = MyDiv.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
    eval(arr[n].innerHTML)//run script inside div

Predicate Delegates in C#

What is Predicate Delegate?

1) Predicate is a feature that returns true or false.This concept has come in .net 2.0 framework. 2) It is being used with lambda expression (=>). It takes generic type as an argument. 3) It allows a predicate function to be defined and passed as a parameter to another function. 4) It is a special case of a Func, in that it takes only a single parameter and always returns a bool.

In C# namespace:

namespace System
{   
    public delegate bool Predicate<in T>(T obj);
}

It is defined in the System namespace.

Where should we use Predicate Delegate?

We should use Predicate Delegate in the following cases:

1) For searching items in a generic collection. e.g.

var employeeDetails = employees.Where(o=>o.employeeId == 1237).FirstOrDefault();

2) Basic example that shortens the code and returns true or false:

Predicate<int> isValueOne = x => x == 1;

now, Call above predicate:

Console.WriteLine(isValueOne.Invoke(1)); // -- returns true.

3) An anonymous method can also be assigned to a Predicate delegate type as below:

Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
    bool result = isUpper("Hello Chap!!");

Any best practices about predicates?

Use Func, Lambda Expressions and Delegates instead of Predicates.

How to modify a CSS display property from JavaScript?

I found the solution.

As said in the EDIT of my answer, a <div> is misfunctioning in a <table>. So I wrote this code instead :

<tr id="hidden" style="display:none;">
    <td class="depot_table_left">
        <label for="sexe">Sexe</label>
    </td>
    <td>
        <select type="text" name="sexe">
            <option value="1">Sexe</option>
            <option value="2">Joueur</option>
            <option value="3">Joueuse</option>
        </select>
    </td>
</tr>

And this is working fine.

Thanks everybody ;)

How to make an embedded Youtube video automatically start playing?

This works perfectly for me try this just put ?rel=0&autoplay=1 in the end of link

<iframe width="631" height="466" src="https://www.youtube.com/embed/UUdMixCYeTA?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

R Error in x$ed : $ operator is invalid for atomic vectors

Because $ does not work on atomic vectors. Use [ or [[ instead. From the help file for $:

The default methods work somewhat differently for atomic vectors, matrices/arrays and for recursive (list-like, see is.recursive) objects. $ is only valid for recursive objects, and is only discussed in the section below on recursive objects.

x[["ed"]] will work.

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

INFO: No Spring WebApplicationInitializer types detected on classpath

My silly reason was: Build Automatically was disabled!

When to use a linked list over an array/array list?

I did some benchmarking, and found that the list class is actually faster than LinkedList for random inserting:

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int count = 20000;
            Random rand = new Random(12345);

            Stopwatch watch = Stopwatch.StartNew();
            LinkedList<int> ll = new LinkedList<int>();
            ll.AddLast(0);
            for (int i = 1; i < count; i++)
            {
                ll.AddBefore(ll.Find(rand.Next(i)),i);

            }
            Console.WriteLine("LinkedList/Random Add: {0}ms", watch.ElapsedMilliseconds);

            watch = Stopwatch.StartNew();
            List<int> list = new List<int>();
            list.Add(0);
            for (int i = 1; i < count; i++)
            {
                list.Insert(list.IndexOf(rand.Next(i)), i);

            }
            Console.WriteLine("List/Random Add: {0}ms", watch.ElapsedMilliseconds);

            Console.ReadLine();
        }
    }
}

It takes 900 ms for the linked list and 100ms for the list class.

It creates lists of subsequent integer numbers. Each new integer is inserted after a random number which is already in the list. Maybe the List class uses something better than just an array.

php.ini: which one?

You can find what is the php.ini file used:

  • By add phpinfo() in a php page and display the page (like the picture under)
  • From the shell, enter: php -i

Next, you can find the information in the Loaded Configuration file (so here it's /user/local/etc/php/php.ini)

Sometimes, you have indicated (none), in this case you just have to put your custom php.ini that you can find here: http://git.php.net/?p=php-src.git;a=blob;f=php.ini-production;hb=HEAD

I hope this answer will help.

What is the correct way to read from NetworkStream in .NET

Networking code is notoriously difficult to write, test and debug.

You often have lots of things to consider such as:

  • what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.

  • are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive

  • how does congestion in the real world which causes delays in the stream affect your reading/writing logic

If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).

Here are several different ways to handle the exchange:

  • have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"

  • use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"

  • use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.

  • have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)

Each approach has its pros and cons for "correctness".

The code below uses the "timeout" method, as that seems to be the one you want.

See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream on the TCPClient so you can change the ReadTimeout.

string SendCmd(string cmd, string ip, int port)
{
  var client = new TcpClient(ip, port);
  var data = Encoding.GetEncoding(1252).GetBytes(cmd);
  var stm = client.GetStream();
  // Set a 250 millisecond timeout for reading (instead of Infinite the default)
  stm.ReadTimeout = 250;
  stm.Write(data, 0, data.Length);
  byte[] resp = new byte[2048];
  var memStream = new MemoryStream();
  int bytesread = stm.Read(resp, 0, resp.Length);
  while (bytesread > 0)
  {
      memStream.Write(resp, 0, bytesread);
      bytesread = stm.Read(resp, 0, resp.Length);
  }
  return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}

As a footnote for other variations on this writing network code...when doing a Read where you want to avoid a "block", you can check the DataAvailable flag and then ONLY read what is in the buffer checking the .Length property e.g. stm.Read(resp, 0, stm.Length);

Is it valid to define functions in JSON results?

The problem is that JSON as a data definition language evolved out of JSON as a JavaScript Object Notation. Since Javascript supports eval on JSON, it is legitimate to put JSON code inside JSON (in that use-case). If you're using JSON to pass data remotely, then I would say it is bad practice to put methods in the JSON because you may not have modeled your client-server interaction well. And, further, when wishing to use JSON as a data description language I would say you could get yourself into trouble by embedding methods because some JSON parsers were written with only data description in mind and may not support method definitions in the structure.

Wikipedia JSON entry makes a good case for not including methods in JSON, citing security concerns:

Unless you absolutely trust the source of the text, and you have a need to parse and accept text that is not strictly JSON compliant, you should avoid eval() and use JSON.parse() or another JSON specific parser instead. A JSON parser will recognize only JSON text and will reject other text, which could contain malevolent JavaScript. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

HTML - Arabic Support

i edit the html page with notepad ++ ,set encoding to utf-8 and its work

Setting PATH environment variable in OSX permanently

For a new path to be added to PATH environment variable in MacOS just create a new file under /etc/paths.d directory and add write path to be set in the file. Restart the terminal. You can check with echo $PATH at the prompt to confirm if the path was added to the environment variable.

For example: to add a new path /usr/local/sbin to the PATH variable:

cd /etc/paths.d
sudo vi newfile

Add the path to the newfile and save it.

Restart the terminal and type echo $PATH to confirm

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

This can happen due to a different language in the phone for which your code doesn't have the asset for. For example your preference.xml is placed in xml-en and you are trying to run your app in a phone which has French selected, the app will crash.

Head and tail in one line

Building on the Python 2 solution from @GarethLatty, the following is a way to get a single line equivalent without intermediate variables in Python 2.

t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0]

If you need it to be exception-proof (i.e. supporting empty list), then add:

t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0]

If you want to do it without the semicolon, use:

h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0]

iOS: Multi-line UILabel in Auto Layout

One way to do this... As text length increases try to change (decrease) the fontsize of the label text using

Label.adjustsFontSizeToFitWidth = YES;

Get full URL and query string in Servlet for both HTTP and HTTPS requests

I know this is a Java question, but if you're using Kotlin you can do this quite nicely:

val uri = request.run {
    if (queryString.isNullOrBlank()) requestURI else "$requestURI?$queryString"
}

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

Try this to get value from select element by Element Name

$("select[name=elementnamehere]").val();

How to upload files to server using Putty (ssh)

Use WinSCP for file transfer over SSH, putty is only for SSH commands.

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

How to detect if numpy is installed

I think you also may use this

>> import numpy
>> print numpy.__version__

Update: for python3 use print(numpy.__version__)

Difference between two dates in years, months, days in JavaScript

How precise do you need to be? If you do need to take into account common years and leap years, and the exact difference in days between months then you'll have to write something more advanced but for a basic and rough calculation this should do the trick:

today = new Date()
past = new Date(2010,05,01) // remember this is equivalent to 06 01 2010
//dates in js are counted from 0, so 05 is june

function calcDate(date1,date2) {
    var diff = Math.floor(date1.getTime() - date2.getTime());
    var day = 1000 * 60 * 60 * 24;

    var days = Math.floor(diff/day);
    var months = Math.floor(days/31);
    var years = Math.floor(months/12);

    var message = date2.toDateString();
    message += " was "
    message += days + " days " 
    message += months + " months "
    message += years + " years ago \n"

    return message
    }


a = calcDate(today,past)
console.log(a) // returns Tue Jun 01 2010 was 1143 days 36 months 3 years ago

Keep in mind that this is imprecise, in order to calculate the date with full precision one would have to have a calendar and know if a year is a leap year or not, also the way I'm calculating the number of months is only approximate.

But you can improve it easily.

How can I subset rows in a data frame in R based on a vector of values?

This will give you what you want:

eg2011cleaned <- eg2011[!eg2011$ID %in% bg2011missingFromBeg, ]

The error in your second attempt is because you forgot the ,

In general, for convenience, the specification object[index] subsets columns for a 2d object. If you want to subset rows and keep all columns you have to use the specification object[index_rows, index_columns], while index_cols can be left blank, which will use all columns by default.

However, you still need to include the , to indicate that you want to get a subset of rows instead of a subset of columns.

Named capturing groups in JavaScript regex?

ECMAScript 2018 introduces named capturing groups into JavaScript regexes.

Example:

  const auth = 'Bearer AUTHORIZATION_TOKEN'
  const { groups: { token } } = /Bearer (?<token>[^ $]*)/.exec(auth)
  console.log(token) // "Prints AUTHORIZATION_TOKEN"

If you need to support older browsers, you can do everything with normal (numbered) capturing groups that you can do with named capturing groups, you just need to keep track of the numbers - which may be cumbersome if the order of capturing group in your regex changes.

There are only two "structural" advantages of named capturing groups I can think of:

  1. In some regex flavors (.NET and JGSoft, as far as I know), you can use the same name for different groups in your regex (see here for an example where this matters). But most regex flavors do not support this functionality anyway.

  2. If you need to refer to numbered capturing groups in a situation where they are surrounded by digits, you can get a problem. Let's say you want to add a zero to a digit and therefore want to replace (\d) with $10. In JavaScript, this will work (as long as you have fewer than 10 capturing group in your regex), but Perl will think you're looking for backreference number 10 instead of number 1, followed by a 0. In Perl, you can use ${1}0 in this case.

Other than that, named capturing groups are just "syntactic sugar". It helps to use capturing groups only when you really need them and to use non-capturing groups (?:...) in all other circumstances.

The bigger problem (in my opinion) with JavaScript is that it does not support verbose regexes which would make the creation of readable, complex regular expressions a lot easier.

Steve Levithan's XRegExp library solves these problems.

Facebook Access Token for Pages

See here if you want to grant a Facebook App permanent access to a page (even when you / the app owner are logged out):

http://developers.facebook.com/docs/opengraph/using-app-tokens/

"An App Access Token does not expire unless you refresh the application secret through your app settings."

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

Work for me in CentOS:

$ service mysql stop
$ mysqld --skip-grant-tables &
$ mysql -u root mysql

mysql> FLUSH PRIVILEGES;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

$ service mysql restart

Android Stop Emulator from Command Line

If you don't want to have to know the serial name of your device for adb -s emulator-5554 emu kill, then you can just use adb -e emu kill to kill a single emulator. This won't kill anything if you have more than one emulator running at once, but it's useful for automation where you start and stop a single emulator for a test.

Rounding Bigdecimal values with 2 Decimal Places

You may try this:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12345");
    System.out.println(toPrecision(a, 2));
}

private static BigDecimal toPrecision(BigDecimal dec, int precision) {
    String plain = dec.movePointRight(precision).toPlainString();
    return new BigDecimal(plain.substring(0, plain.indexOf("."))).movePointLeft(precision);
}

OUTPUT:

10.12

How do I show/hide a UIBarButtonItem?

Just Set barButton.customView = UIView() and see the Trick

jquery select option click handler

One possible solution is to add a class to every option

<select name="export_type" id="export_type">
    <option class="export_option" value="pdf">PDF</option>
    <option class="export_option" value="xlsx">Excel</option>
    <option class="export_option" value="docx">DocX</option>
</select>

and then use the click handler for this class

$(document).ready(function () {

    $(".export_option").click(function (e) {
        //alert('click');
    });

});

UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome. Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.

Scheduled run of stored procedure on SQL server

Using Management Studio - you may create a Job (unter SQL Server Agent) One Job may include several Steps from T-SQL scripts up to SSIS Packages

Jeb was faster ;)

How to create a jQuery function (a new jQuery method or plugin)?

From the Docs:

(function( $ ){
   $.fn.myfunction = function() {
      alert('hello world');
      return this;
   }; 
})( jQuery );

Then you do

$('#my_div').myfunction();

How can I convert a VBScript to an executable (EXE) file?

You can do this with PureBasic and MsScriptControl

All you need to do is pasting the MsScriptControl to the Purebasic editor and add something like this below

InitScriptControl()
SCtr_AddCode("MsgBox 1")

Excel - extracting data based on another list

I couldn't get the first method to work, and I know this is an old topic, but this is what I ended up doing for a solution:

=IF(ISNA(MATCH(A1,B:B,0)),"Not Matched", A1)

Basically, MATCH A1 to Column B exactly (the 0 stands for match exactly to a value in Column B). ISNA tests for #N/A response which match will return if the no match is found. Finally, if ISNA is true, write "Not Matched" to the selected cell, otherwise write the contents of the matched cell.

How can I see if a Perl hash already has a certain key?

Well, your whole code can be limited to:

foreach $line (@lines){
        $strings{$1}++ if $line =~ m|my regex|;
}

If the value is not there, ++ operator will assume it to be 0 (and then increment to 1). If it is already there - it will simply be incremented.

How to make a gap between two DIV within the same column

#firstDropContainer{
float: left; 
width: 40%; 
margin-right: 1.5em; 

}

#secondDropContainer{
float: left; 
width: 40%;
margin-bottom: 1em;
}



<div id="mainDrop">
    <div id="firstDropContainer"></div>
    <div id="secondDropContainer"></div>
</div>

Note: Adjust the width of the divs based on your req. 

How do I connect to a MySQL Database in Python?

For python 3.3

CyMySQL https://github.com/nakagami/CyMySQL

I have pip installed on my windows 7, just pip install cymysql

(you don't need cython) quick and painless

Node.js heap out of memory

If I remember correctly, there is a strict standard limit for the memory usage in V8 of around 1.7 GB, if you do not increase it manually.

In one of our products we followed this solution in our deploy script:

 node --max-old-space-size=4096 yourFile.js

There would also be a new space command but as I read here: a-tour-of-v8-garbage-collection the new space only collects the newly created short-term data and the old space contains all referenced data structures which should be in your case the best option.

Can I obtain method parameter name using Java reflection?

To add my 2 cents; parameter info is available in a class file "for debugging" when you use javac -g to compile the source. And it is available to APT but you'll need an annotation so no use to you. (Somebody discussed something similar 4-5 years ago here: http://forums.java.net/jive/thread.jspa?messageID=13467&tstart=0 )

Overall in-short you can't get it unless you work on Source files directly (similar to what APT does at compile time).

How to edit Docker container files from the host?

Whilst it is possible, and the other answers explain how, you should avoid editing files in the Union File System if you can.

Your definition of volumes isn't quite right - it's more about bypassing the Union File System than exposing files on the host. For example, if I do:

$ docker run --name="test" -v /volume-test debian echo "test"

The directory /volume-test inside the container will not be part of the Union File System and instead will exist somewhere on the host. I haven't specified where on the host, as I may not care - I'm not exposing host files, just creating a directory that is shareable between containers and the host. You can find out exactly where it is on the host with:

$ docker inspect -f "{{.Volumes}}" test
map[/volume_test:/var/lib/docker/vfs/dir/b7fff1922e25f0df949e650dfa885dbc304d9d213f703250cf5857446d104895]

If you really need to just make a quick edit to a file to test something, either use docker exec to get a shell in the container and edit directly, or use docker cp to copy the file out, edit on the host and copy back in.

Get a file name from a path

The boost filesystem library is also available as the experimental/filesystem library and was merged into ISO C++ for C++17. You can use it like this:

#include <iostream>
#include <experimental/filesystem>

namespace fs = std::experimental::filesystem;

int main () {
    std::cout << fs::path("/foo/bar.txt").filename() << '\n'
}

Output:

"bar.txt"

It also works for std::string objects.

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

If you are using MS Excel 2003 then go to view->Tool bar->Pivot Table From this tool bar we can do refresh by clicking ! this symbol.

Print array elements on separate lines in Bash?

Try doing this :

$ printf '%s\n' "${my_array[@]}"

The difference between $@ and $*:

  • Unquoted, the results are unspecified. In Bash, both expand to separate args and then wordsplit and globbed.

  • Quoted, "$@" expands each element as a separate argument, while "$*" expands to the args merged into one argument: "$1c$2c..." (where c is the first char of IFS).

You almost always want "$@". Same goes for "${arr[@]}".

Always quote them!

Importing JSON into an Eclipse project

Download java-json.jar from here, which contains org.json.JSONArray

http://www.java2s.com/Code/JarDownload/java/java-json.jar.zip

nzip and add to your project's library: Project > Build Path > Configure build path> Select Library tab > Add External Libraries > Select the java-json.jar file.

Android - running a method periodically using postDelayed() call

You should set andrid:allowRetainTaskState="true" to Launch Activity in Manifest.xml. If this Activty is not Launch Activity. you should set android:launchMode="singleTask" at this activity

How to get distinct values from an array of objects in JavaScript?

If like me you prefer a more "functional" without compromising speed, this example uses fast dictionary lookup wrapped inside reduce closure.

var array = 
[
    {"name":"Joe", "age":17}, 
    {"name":"Bob", "age":17}, 
    {"name":"Carl", "age": 35}
]
var uniqueAges = array.reduce((p,c,i,a) => {
    if(!p[0][c.age]) {
        p[1].push(p[0][c.age] = c.age);
    }
    if(i<a.length-1) {
        return p
    } else {
        return p[1]
    }
}, [{},[]])

According to this test my solution is twice as fast as the proposed answer

Is there a way to check for both `null` and `undefined`?

if( value ) {
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ''
  • 0
  • false

typescript includes javascript rules.

How to unlock android phone through ADB

Tested in Nexus 5:

adb shell input keyevent 26 #Pressing the lock button
adb shell input touchscreen swipe 930 880 930 380 #Swipe UP
adb shell input text XXXX #Entering your passcode
adb shell input keyevent 66 #Pressing Enter

Worked for me.

check for null date in CASE statement, where have I gone wrong?

Try:

select
     id,
     StartDate,
CASE WHEN StartDate IS NULL
    THEN 'Awaiting'
    ELSE 'Approved' END AS StartDateStatus
FROM myTable

You code would have been doing a When StartDate = NULL, I think.


NULL is never equal to NULL (as NULL is the absence of a value). NULL is also never not equal to NULL. The syntax noted above is ANSI SQL standard and the converse would be StartDate IS NOT NULL.

You can run the following:

SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison

And this returns:

EqualityCheck = 0
InEqualityCheck = 0
NullComparison = 1

For completeness, in SQL Server you can:

SET ANSI_NULLS OFF;

Which would result in your equals comparisons working differently:

SET ANSI_NULLS OFF

SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison

Which returns:

EqualityCheck = 1
InEqualityCheck = 0
NullComparison = 1

But I would highly recommend against doing this. People subsequently maintaining your code might be compelled to hunt you down and hurt you...

Also, it will no longer work in upcoming versions of SQL server:

https://msdn.microsoft.com/en-GB/library/ms188048.aspx

PHP: How to check if a date is today, yesterday or tomorrow

function getRangeDateString($timestamp) {
    if ($timestamp) {
        $currentTime=strtotime('today');
        // Reset time to 00:00:00
        $timestamp=strtotime(date('Y-m-d 00:00:00',$timestamp));
        $days=round(($timestamp-$currentTime)/86400);
        switch($days) {
            case '0';
                return 'Today';
                break;
            case '-1';
                return 'Yesterday';
                break;
            case '-2';
                return 'Day before yesterday';
                break;
            case '1';
                return 'Tomorrow';
                break;
            case '2';
                return 'Day after tomorrow';
                break;
            default:
                if ($days > 0) {
                    return 'In '.$days.' days';
                } else {
                    return ($days*-1).' days ago';
                }
                break;
        }
    }
}

How to display a content in two-column layout in LaTeX?

Use two minipages.

\begin{minipage}[position]{width}
  text
 \end{minipage}

How does delete[] know it's an array?

Hey ho well it depends of what you allocating with new[] expression when you allocate array of build in types or class / structure and you don't provide your constructor and destructor the operator will treat it as a size "sizeof(object)*numObjects" rather than object array therefore in this case number of allocated objects will not be stored anywhere, however if you allocate object array and you provide constructor and destructor in your object than behavior change, new expression will allocate 4 bytes more and store number of objects in first 4 bytes so the destructor for each one of them can be called and therefore new[] expression will return pointer shifted by 4 bytes forward, than when the memory is returned the delete[] expression will call a function template first, iterate through array of objects and call destructor for each one of them. I've created this simple code witch overloads new[] and delete[] expressions and provides a template function to deallocate memory and call destructor for each object if needed:

// overloaded new expression 
void* operator new[]( size_t size )
{
    // allocate 4 bytes more see comment below 
    int* ptr = (int*)malloc( size + 4 );

    // set value stored at address to 0 
    // and shift pointer by 4 bytes to avoid situation that
    // might arise where two memory blocks 
    // are adjacent and non-zero
    *ptr = 0;
    ++ptr; 

    return ptr;
}
//////////////////////////////////////////

// overloaded delete expression 
void static operator delete[]( void* ptr )
{
    // decrement value of pointer to get the
    // "Real Pointer Value"
    int* realPtr = (int*)ptr;
    --realPtr;

    free( realPtr );
}
//////////////////////////////////////////

// Template used to call destructor if needed 
// and call appropriate delete 
template<class T>
void Deallocate( T* ptr )
{
    int* instanceCount = (int*)ptr;
    --instanceCount;

    if(*instanceCount > 0) // if larger than 0 array is being deleted
    {
        // call destructor for each object
        for(int i = 0; i < *instanceCount; i++)
        {
            ptr[i].~T();
        }
        // call delete passing instance count witch points
        // to begin of array memory 
        ::operator delete[]( instanceCount );
    }
    else
    {
        // single instance deleted call destructor
        // and delete passing ptr
        ptr->~T();
        ::operator delete[]( ptr );
    }
}

// Replace calls to new and delete
#define MyNew ::new
#define MyDelete(ptr) Deallocate(ptr)

// structure with constructor/ destructor
struct StructureOne
{
    StructureOne():
    someInt(0)
    {}
    ~StructureOne() 
    {
        someInt = 0;
    }

    int someInt;
};
//////////////////////////////

// structure without constructor/ destructor
struct StructureTwo
{
    int someInt;
};
//////////////////////////////


void main(void)
{
    const unsigned int numElements = 30;

    StructureOne* structOne = nullptr;
    StructureTwo* structTwo = nullptr;
    int* basicType = nullptr;
    size_t ArraySize = 0;

/**********************************************************************/
    // basic type array 

    // place break point here and in new expression
    // check size and compare it with size passed 
    // in to new expression size will be the same
    ArraySize = sizeof( int ) * numElements;

    // this will be treated as size rather than object array as there is no 
    // constructor and destructor. value assigned to basicType pointer
    // will be the same as value of "++ptr" in new expression
    basicType = MyNew int[numElements];

    // Place break point in template function to see the behavior
    // destructors will not be called and it will be treated as 
    // single instance of size equal to "sizeof( int ) * numElements"
    MyDelete( basicType );

/**********************************************************************/
    // structure without constructor and destructor array 

    // behavior will be the same as with basic type 

    // place break point here and in new expression
    // check size and compare it with size passed 
    // in to new expression size will be the same
    ArraySize = sizeof( StructureTwo ) * numElements;

    // this will be treated as size rather than object array as there is no 
    // constructor and destructor value assigned to structTwo pointer
    // will be the same as value of "++ptr" in new expression
    structTwo = MyNew StructureTwo[numElements]; 

    // Place break point in template function to see the behavior
    // destructors will not be called and it will be treated as 
    // single instance of size equal to "sizeof( StructureTwo ) * numElements"
    MyDelete( structTwo );

/**********************************************************************/
    // structure with constructor and destructor array 

    // place break point check size and compare it with size passed in
    // new expression size in expression will be larger by 4 bytes
    ArraySize = sizeof( StructureOne ) * numElements;

    // value assigned to "structOne pointer" will be different 
    // of "++ptr" in new expression  "shifted by another 4 bytes"
    structOne = MyNew StructureOne[numElements];

    // Place break point in template function to see the behavior
    // destructors will be called for each array object 
    MyDelete( structOne );
}
///////////////////////////////////////////

How can I upgrade specific packages using pip and a requirements file?

First make sure you have checked the most voted answer.


I'm not sure if it's exactly your problem, but in my case, I wasn't able to upgrade Django to 1.2.4 - I was always finishing with 1.2.3 version, so I uninstalled Django with:

<virtualenv>/bin/pip uninstall Django

Then I removed <virtualenv>/build/Django directory and finally I installed the proper version with:

<virtualenv>/bin/pip install Django

mysql command for showing current configuration variables

As an alternative you can also query the information_schema database and retrieve the data from the global_variables (and global_status of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.

For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size in bytes and megabytes:

SELECT
  variable_name,
  variable_value AS innodb_log_buffer_size_bytes,
  ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE  'innodb_log_buffer_size';

As a result you get:

+------------------------+------------------------------+---------------------------+
| variable_name          | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456                    |                       256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)

How do I check if a property exists on a dynamic anonymous type in c#?

Using reflection, this is the function i use :

public static bool doesPropertyExist(dynamic obj, string property)
{
    return ((Type)obj.GetType()).GetProperties().Where(p => p.Name.Equals(property)).Any();
}

then..

if (doesPropertyExist(myDynamicObject, "myProperty")){
    // ...
}

Jquery Chosen plugin - dynamically populate list by Ajax

The chosen answer is outdated, same goes to meltingice /ajax-chosen plugin.

With Select2 plugin got many bugs which is i can't resolve it.

Here my answer for this question.

I integrated my solution with function trigger after user type. Thanks to this answer : https://stackoverflow.com/a/5926782/4319179.

//setup before functions
  var typingTimer;                //timer identifier
  var doneTypingInterval = 2000;  //time in ms (2 seconds)
  var selectID = 'YourSelectId';    //Hold select id
  var selectData = [];           // data for unique id array

  //on keyup, start the countdown
  $('#' + selectID + '_chosen .chosen-choices input').keyup(function(){

      // Change No Result Match text to Searching.
      $('#' + selectID + '_chosen .no-results').html('Searching = "'+ $('#' + selectID + '_chosen .chosen-choices input').val() + '"');


      clearTimeout(typingTimer);  //Refresh Timer on keyup 
      if ($('#' + selectID + '_chosen .chosen-choices input').val()) {

           typingTimer = setTimeout(doneTyping, doneTypingInterval);  //Set timer back if got value on input

      }

  });

  //user is "finished typing," do something
  function doneTyping () {

      var inputData = $('#' + selectID + '_chosen .chosen-choices input').val();  //get input data

      $.ajax({
        url: "YourUrl",
         data: {data: inputData},
        type:'POST',
        dataType: "json",
        beforeSend: function(){
          // Change No Result Match to Getting Data beforesend
          $('#' + selectID + '_chosen .no-results').html('Getting Data = "'+$('#' + selectID + '_chosen .chosen-choices input').val()+'"');
    },
        success: function( data ) { 

          // iterate data before append
          $.map( data, function( item ) {

            // matching data eg: by id or something unique; if data match: <option> not append - else: append <option>
            // This will prevent from select the same thing twice.
            if($.inArray(item.attr_hash,selectData) == -1){

              // if not match then append in select
              $('#' + selectID ).append('<option id="'+item.id+'" data-id = "'+item.id+'">' + item.data + '</option>');

            }            

          });

          // Update chosen again after append <option>
          $('#' + selectID ).trigger("chosen:updated");

        }
      });

  }

  // Chosen event listen on input change eg: after select data / deselect this function will be trigger
  $('#' + selectID ).on('change', function() {

    // get select jquery object
    var domArray = $('#' + selectID ).find('option:selected');

    // empty array data
    selectData = [];

    for (var i = 0, length = domArray.length; i < length; i++ ){

      // Push unique data to array (for matching purpose)
      selectData.push( $(domArray[i]).data('id') );

    }

    // Replace select <option> to only selected option
    $('#' + selectID ).html(domArray);

    // Update chosen again after replace selected <option>
    $('#' + selectID ).trigger("chosen:updated");

  });

How do I add a delay in a JavaScript loop?

In my opinion, the simpler and most elegant way to add a delay in a loop is like this:

names = ['John', 'Ana', 'Mary'];

names.forEach((name, i) => {
 setTimeout(() => {
  console.log(name);
 }, i * 1000);  // one sec interval
});

docker mounting volumes on host

Basically VOLUME and -v option are almost equal. These mean 'mount specific directory on your container'. For example, VOLUME /data and -v /data is exactly same meaning. If you run the image that have VOLUME /data or with -v /data option, /data directory is mounted your container. This directory doesn't belong to your container.

Imagine that You add some files to /data on the container, then commit the container into new image. There isn't any files on data directory because mounted /data directory is belong to original container.

$ docker run -it -v /data --name volume ubuntu:14.04 bash
root@2b5e0f2d37cd:/# cd /data
root@2b5e0f2d37cd:/data# touch 1 2 3 4 5 6 7 8 9
root@2b5e0f2d37cd:/data# cd /tmp
root@2b5e0f2d37cd:/tmp# touch 1 2 3 4 5 6 7 8 9
root@2b5e0f2d37cd:/tmp# exit
exit

$ docker commit volume nacyot/volume  
835cfe3d8d159622507ba3256bb1c0b0d6e7c1419ae32751ad0f925c40378945
nacyot $ docker run -it nacyot/volume
root@dbe335c7e64d:/# cd /data
root@dbe335c7e64d:/data# ls
root@dbe335c7e64d:/data# cd /tmp
root@dbe335c7e64d:/tmp# ls
1  2  3  4  5  6  7  8  9
root@dbe335c7e64d:/tmp# 
root@dbe335c7e64d:/tmp# 

This mounted directory like /data is used to store data that is not belong to your application. And you can predefine the data directory that is not belong to the container by using VOLUME.

A difference between Volume and -v option is that you can use -v option dynamically on starting container. It mean you can mount some directory dynamically. And another difference is that you can mount your host directory on your container by using -v

How to implement DrawerArrowToggle from Android appcompat v7 21 library

If you are using the Support Library provided DrawerLayout as suggested in the Creating a navigation drawer training, you can use the newly added android.support.v7.app.ActionBarDrawerToggle (note: different from the now deprecated android.support.v4.app.ActionBarDrawerToggle):

shows a Hamburger icon when drawer is closed and an arrow when drawer is open. It animates between these two states as the drawer opens.

While the training hasn't been updated to take the deprecation/new class into account, you should be able to use it almost exactly the same code - the only difference in implementing it is the constructor.

How do I write a Python dictionary to a csv file?

You are using DictWriter.writerows() which expects a list of dicts, not a dict. You want DictWriter.writerow() to write a single row.

You will also want to use DictWriter.writeheader() if you want a header for you csv file.

You also might want to check out the with statement for opening files. It's not only more pythonic and readable but handles closing for you, even when exceptions occur.

Example with these changes made:

import csv

my_dict = {"test": 1, "testing": 2}

with open('mycsvfile.csv', 'w') as f:  # You will need 'wb' mode in Python 2.x
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

Which produces:

test,testing
1,2

Select rows which are not present in other table

this can also be tried...

SELECT l.ip, tbl2.ip as ip2, tbl2.hostname
FROM   login_log l 
LEFT   JOIN (SELECT ip_location.ip, ip_location.hostname
             FROM ip_location
             WHERE ip_location.ip is null)tbl2

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass