Programs & Examples On #Att

AT&T Syntax is an assembly syntax used in UNIX environments, that originates from AT&T Bell Labs. It is descended from the MIPS assembly syntax.

Set adb vendor keys

I had the same problem running Ubuntu 18.04. I tried multiple solutions but my device (OnePlus 5T) was always unauthorized.

Solution

  1. Configure udev rules on Ubuntu. To do this, just follow the official documentation: https://developer.android.com/studio/run/device

    The idVendor of my device (OnePlus) is not listed. To get it, just connect your device and use lsusb:

    Bus 003 Device 008: ID 2a70:4ee7

    In this example, 2a70 is the idVendor.

  2. Remove existing adb keys on Ubuntu:

    rm -v ~/.android/adbkey* ~/.android/adbkey ~/.android/adbkey.pub

  3. 'Revoke USB debugging authorizations' on your device configuration (developer options).

  4. Finally, restart the adb server to create a new key:

    sudo adb kill-server sudo adb devices

After that, I got the authorization prompt on my device and I authorized it.

The point of test %eax %eax

test is a non-destructive and, it doesn't return the result of the operation but it sets the flags register accordingly. To know what it really tests for you need to check the following instruction(s). Often out is used to check a register against 0, possibly coupled with a jz conditional jump.

What does the "@" symbol do in Powershell?

PowerShell will actually treat any comma-separated list as an array:

"server1","server2"

So the @ is optional in those cases. However, for associative arrays, the @ is required:

@{"Key"="Value";"Key2"="Value2"}

Officially, @ is the "array operator." You can read more about it in the documentation that installed along with PowerShell, or in a book like "Windows PowerShell: TFM," which I co-authored.

How to change default language for SQL Server?

If you want to change MSSQL server language, you can use the following QUERY:

EXEC sp_configure 'default language', 'British English';

How do I get the serial key for Visual Studio Express?

I have an improvement on the answer @DewiMorgan gave for VS 2008 express. I have since confirmed it also works on VS 2005 express.
It lets you run the software without it EVER requiring registration, and also makes it so you don't have to manually delete the key every 30 days. It does this by preventing the key from ever being written.

(Deleting the correct key can also let you avoid registering VS 2015 "Community Edition," but using permissions to prevent the key being written will make the IDE crash, so I haven't found a great solution for it yet.)

The directions assume Visual C# Express 2008, but this works on all the other visual studio express apps I can find.

  1. Open regedit, head to HKEY_CURRENT_USER\Software\Microsoft\VCSExpress\9.0\Registration.
  2. Delete the value Params. picture of me deleting the value 'Params' in the registry.
  3. Right click on the key 'Registration' in the tree, and click permissions.
  4. Click Advanced...
  5. Go to the permissions tab, and uncheck the box labeled Inherit from parent the permission entries that apply to child objects. Include these with entries explicitly defined here. me unchecking the box
  6. In the dialog that opens, click copy.
    the security dialog that pops up
    Note that in Windows 7 (and 8/8.1, I think), it appears the copy button was renamed to add, as in add inherited permissions as explicit permissions.

    In Windows 10, it appears things changed again. @ravuya says that you might have to manually re-create some of the permissions, as the registry editor no longer offers this exact functionality directly. I don't use Windows very much anymore, so I'll defer to them:

    On Win10, there is a button called "Disable Inheritance" that does the same thing as the checkbox mentioned in step 5. It is necessary to create new permissions just for Registration, instead of inheriting those permissions from an upstream registry key.

  7. Hit OK in the 'Advanced' window.
  8. Back in the first permissions window, click your user, and uncheck Full Control. Me unchecking 'full control'

  9. Do the same thing for the Administrators group. Me unchecking 'full control' for the Administrators group

  10. Hit OK or Apply. Congratulations, you will never again be plagued by the registration nag, and just like WinRAR, your trial will never expire.

You may have to do the same thing for other (non-Visual C#) programs, like Visual Basic express or Visual C++ express.

It has been reported by @IronManMark20 in the comments that simply deleting the registry key works and that Visual Studio does not attempt to re-create the key. I am not sure if I believe this because when I installed VS on a clean windows installation, the key was not created until I ran VS at least once. But for what it's worth, that may be an option as well.

Text Editor which shows \r\n?

With Notepad++, you can show end-of-line characters. It shows CR and LF, instead of "\r" and "\n", but it gets the point across. However, it will still insert the line breaks. But you do get to see the line-ending characters.

To use Notepad++ for this, open the View menu, open the Show Symbols slide out, and select either "Show all characters" or "Show end-of-line characters".

enter image description here

Find all files in a directory with extension .txt in Python

import os

path = 'mypath/path' 
files = os.listdir(path)

files_txt = [i for i in files if i.endswith('.txt')]

Resource files not found from JUnit test cases

This is actually redundant except in cases where you want to override the defaults. All of these settings are implied defaults.

You can verify that by checking your effective POM using this command

mvn help:effective-pom

    <finalName>name</finalName>
    <directory>target</directory>
    <outputDirectory>target/classes</outputDirectory>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
    </testResources>

For example, if i want to point to a different test resource path or resource path you should use this otherwise you don't.

    <resources>
        <resource>
            <directory>/home/josh/desktop/app_resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>/home/josh/desktop/test_resources</directory>
        </testResource>
    </testResources>

Change collations of all columns of all tables in SQL Server

So here I am, once again, not satisfied with the answer. I was tasked to upgrade JIRA 6.4.x to JIRA Software 7.x and I went to that particular problem with the database and column collation.

In SQL Server, if you do not drop constrains such as primary key or foreign key or even indexes, the script provided above as an answer doesn't work at all. It will however change those without those properties. This is really problematic, because I don't want to manually drop all constrains and create them back. That operation could probably ends up with errors. On the other side, creating a script automating the change could take ages to make.

So I found a way to make the migration simply by using SQL Management Studio. Here's the procedure:

  • Rename the database by something else. By example, mine's was "Jira", so I renamed it "JiraTemp".
  • Create a new database named "Jira" and make sure to set the right collation. Simply select the page "Options" and change the collation.
  • Once created, go back to "JiraTemp", right click it, "Tasks -> Generate Scripts...".
    • Select "Script entire database and all database objects".
    • Select "Save to new query window", then select "Advanced"
    • Change the value of "Script for Server Version" for the desired value
    • Enable "Script Object-Level Permissions", "Script Owner" and "Script Full-Text Indexes"
    • Leave everything else as is or personalize it if you wish.
  • Once generated, delete the "CREATE DATABASE" section. Replace "JiraTemp" by "Jira".
  • Run the script. The entire database structure and permissions of the database is now replicated to "Jira".
  • Before we copy the data, we need to disable all constrains. Execute the following command to do so in the database "Jira": EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
  • Now the data needs to be transferred. To do so, simply right click "JiraTemp", then select "Tasks -> Export Data..."
    • Select as data source and destination the OLE DB Provider for SQL Server.
    • Source database is "JiraTemp"
    • Destination database is "Jira"
    • The server name is technically the same for source and destination (except if you've created the database on another server).
    • Select "Copy data from one or another tables or views"
    • Select all tables except views. Then, when still highlighted, click on "Edit Mappings". Check "Enable identity insert"
    • Click OK, Next, then Finish
  • Data transfer can take a while. Once finished, execute the following command to re enable all constrains: exec sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

Once completed, I've restarted JIRA and my database collation was in order. Hope it helps a lot of people!

Is Python strongly typed?

According to this wiki Python article Python is both dynamically and strongly typed (provides a good explanation too).

Perhaps you are thinking about statically typed languages where types can not change during program execution and type checking occurs during compile time to detect possible errors.

This SO question might be of interest: Dynamic type languages versus static type languages and this Wikipedia article on Type Systems provides more information

Catching an exception while using a Python 'with' statement

Differentiating between the possible origins of exceptions raised from a compound with statement

Differentiating between exceptions that occur in a with statement is tricky because they can originate in different places. Exceptions can be raised from either of the following places (or functions called therein):

  • ContextManager.__init__
  • ContextManager.__enter__
  • the body of the with
  • ContextManager.__exit__

For more details see the documentation about Context Manager Types.

If we want to distinguish between these different cases, just wrapping the with into a try .. except is not sufficient. Consider the following example (using ValueError as an example but of course it could be substituted with any other exception type):

try:
    with ContextManager():
        BLOCK
except ValueError as err:
    print(err)

Here the except will catch exceptions originating in all of the four different places and thus does not allow to distinguish between them. If we move the instantiation of the context manager object outside the with, we can distinguish between __init__ and BLOCK / __enter__ / __exit__:

try:
    mgr = ContextManager()
except ValueError as err:
    print('__init__ raised:', err)
else:
    try:
        with mgr:
            try:
                BLOCK
            except TypeError:  # catching another type (which we want to handle here)
                pass
    except ValueError as err:
        # At this point we still cannot distinguish between exceptions raised from
        # __enter__, BLOCK, __exit__ (also BLOCK since we didn't catch ValueError in the body)
        pass

Effectively this just helped with the __init__ part but we can add an extra sentinel variable to check whether the body of the with started to execute (i.e. differentiating between __enter__ and the others):

try:
    mgr = ContextManager()  # __init__ could raise
except ValueError as err:
    print('__init__ raised:', err)
else:
    try:
        entered_body = False
        with mgr:
            entered_body = True  # __enter__ did not raise at this point
            try:
                BLOCK
            except TypeError:  # catching another type (which we want to handle here)
                pass
    except ValueError as err:
        if not entered_body:
            print('__enter__ raised:', err)
        else:
            # At this point we know the exception came either from BLOCK or from __exit__
            pass

The tricky part is to differentiate between exceptions originating from BLOCK and __exit__ because an exception that escapes the body of the with will be passed to __exit__ which can decide how to handle it (see the docs). If however __exit__ raises itself, the original exception will be replaced by the new one. To deal with these cases we can add a general except clause in the body of the with to store any potential exception that would have otherwise escaped unnoticed and compare it with the one caught in the outermost except later on - if they are the same this means the origin was BLOCK or otherwise it was __exit__ (in case __exit__ suppresses the exception by returning a true value the outermost except will simply not be executed).

try:
    mgr = ContextManager()  # __init__ could raise
except ValueError as err:
    print('__init__ raised:', err)
else:
    entered_body = exc_escaped_from_body = False
    try:
        with mgr:
            entered_body = True  # __enter__ did not raise at this point
            try:
                BLOCK
            except TypeError:  # catching another type (which we want to handle here)
                pass
            except Exception as err:  # this exception would normally escape without notice
                # we store this exception to check in the outer `except` clause
                # whether it is the same (otherwise it comes from __exit__)
                exc_escaped_from_body = err
                raise  # re-raise since we didn't intend to handle it, just needed to store it
    except ValueError as err:
        if not entered_body:
            print('__enter__ raised:', err)
        elif err is exc_escaped_from_body:
            print('BLOCK raised:', err)
        else:
            print('__exit__ raised:', err)

Alternative approach using the equivalent form mentioned in PEP 343

PEP 343 -- The "with" Statement specifies an equivalent "non-with" version of the with statement. Here we can readily wrap the various parts with try ... except and thus differentiate between the different potential error sources:

import sys

try:
    mgr = ContextManager()
except ValueError as err:
    print('__init__ raised:', err)
else:
    try:
        value = type(mgr).__enter__(mgr)
    except ValueError as err:
        print('__enter__ raised:', err)
    else:
        exit = type(mgr).__exit__
        exc = True
        try:
            try:
                BLOCK
            except TypeError:
                pass
            except:
                exc = False
                try:
                    exit_val = exit(mgr, *sys.exc_info())
                except ValueError as err:
                    print('__exit__ raised:', err)
                else:
                    if not exit_val:
                        raise
        except ValueError as err:
            print('BLOCK raised:', err)
        finally:
            if exc:
                try:
                    exit(mgr, None, None, None)
                except ValueError as err:
                    print('__exit__ raised:', err)

Usually a simpler approach will do just fine

The need for such special exception handling should be quite rare and normally wrapping the whole with in a try ... except block will be sufficient. Especially if the various error sources are indicated by different (custom) exception types (the context managers need to be designed accordingly) we can readily distinguish between them. For example:

try:
    with ContextManager():
        BLOCK
except InitError:  # raised from __init__
    ...
except AcquireResourceError:  # raised from __enter__
    ...
except ValueError:  # raised from BLOCK
    ...
except ReleaseResourceError:  # raised from __exit__
    ...

Creating random colour in Java?

I know it's a bit late for this answer, but I've not seen anyone else put this.

Like Greg said, you want to use the Random class

Random rand = new Random();

but the difference I'm going to say is simple do this:

Color color = new Color(rand.nextInt(0xFFFFFF));

And it's as simple as that! no need to generate lots of different floats.

How to view the assembly behind the code using Visual C++?

The earlier version of this answer (a "hack" for rextester.com) is mostly redundant now that http://gcc.godbolt.org/ provides CL 19 RC for ARM, x86, and x86-64 (targeting the Windows calling convention, unlike gcc, clang, and icc on that site).

The Godbolt compiler explorer is designed for nicely formatting compiler asm output, removing the "noise" of directives, so I'd highly recommend using it to look at asm for simple functions that take args and return a value (so they won't be optimized away).

For a while, CL was available on http://gcc.beta.godbolt.org/ but not the main site, but now it's on both.


To get MSVC asm output from the http://rextester.com/l/cpp_online_compiler_visual online compiler: Add /FAs to the command line options. Have your program find its own path and work out the path to the .asm and dump it. Or run a disassembler on the .exe.

e.g. http://rextester.com/OKI40941

#include <string>
#include <boost/filesystem.hpp>
#include <Windows.h>

using namespace std;

static string my_exe(void){
    char buf[MAX_PATH];
    DWORD tmp = GetModuleFileNameA( NULL, // self
                                  buf, MAX_PATH);
    return buf;
}

int main() {
    string dircmd = "dir ";
    boost::filesystem::path p( my_exe() );
    //boost::filesystem::path dir = p.parent_path();

    // transform c:\foo\bar\1234\a.exe 
    // into      c:\foo\bar\1234\1234.asm
    p.remove_filename();
    system ( (dircmd + p.string()).c_str() );

    auto subdir = p.end();      // pointing at one-past the end
    subdir--;                   // pointing at the last directory name
    p /= *subdir;               // append the last dir name as a filename
    p.replace_extension(".asm");
    system ( (string("type ") + p.string()).c_str() );
//    std::cout << "Hello, world!\n";
}

... code of functions you want to see the asm for goes here ...

type is the DOS version of cat. I didn't want to include more code that would make it harder to find the functions I wanted to see the asm for. (Although using std::string and boost run counter to those goals! Some C-style string manipulation that makes more assumptions about the string it's processing (and ignores max-length safety / allocation by using a big buffer) on the result of GetModuleFileNameA would be much less total machine code.)

IDK why, but cout << p.string() << endl only shows the basename (i.e. the filename, without the directories), even though printing its length shows it's not just the bare name. (Chromium48 on Ubuntu 15.10). There's probably some backslash-escape processing at some point in cout, or between the program's stdout and the web browser.

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

opencv_core245.lib(dxt.obj) : error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in test.obj I got error like this.
I have opencv_core245.lib and opencv_core245d.lib in Linker->Input->Additional dependenc. Since this two were confilicting I removed first one opencv_core245.lib. Error gone.

Set variable value to array of strings

-- create test table "Accounts"
create table Accounts (
  c_ID int primary key
 ,first_name varchar(100)
 ,last_name varchar(100)
 ,city varchar(100)
 );

insert into Accounts values (101, 'Sebastian', 'Volk', 'Frankfurt' );
insert into Accounts values (102, 'Beate',  'Mueller', 'Hamburg' );
insert into Accounts values (103, 'John',  'Walker', 'Washington' );
insert into Accounts values (104, 'Britney', 'Sears', 'Holywood' );
insert into Accounts values (105, 'Sarah', 'Schmidt', 'Mainz' );
insert into Accounts values (106, 'George', 'Lewis', 'New Jersey' );
insert into Accounts values (107, 'Jian-xin', 'Wang', 'Peking' );
insert into Accounts values (108, 'Katrina', 'Khan', 'Bolywood' );

-- declare table variable
declare @tb_FirstName table(name varchar(100));
insert into  @tb_FirstName values ('John'), ('Sarah'), ('George');

SELECT * 
FROM Accounts
WHERE first_name in (select name from @tb_FirstName);

SELECT * 
FROM Accounts
WHERE first_name not in (select name from @tb_FirstName);
go

drop table Accounts;
go

Stacked Tabs in Bootstrap 3

You should not need to add this back in. This was removed purposefully. The documentation has changed somewhat and the CSS class that is necessary ("nav-stacked") is only mentioned under the pills component, but should work for tabs as well.

This tutorial shows how to use the Bootstrap 3 setup properly to do vertical tabs:
tutsme-webdesign.info/bootstrap-3-toggable-tabs-and-pills

How to sort alphabetically while ignoring case sensitive?

Here is an example to sort an array : Case-insensitive

import java.text.Collator;
import java.util.Arrays;

public class Main {
  public static void main(String args[]) {

    String[] myArray = new String[] { "A", "B", "b" };
    Arrays.sort(myArray, Collator.getInstance());

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

 }

}

/* Output:[A, b, B] */

how to change a selections options based on another select option selected?

Here is an example of what you are trying to do => fiddle

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    $("#type").change(function () {_x000D_
        var val = $(this).val();_x000D_
        if (val == "item1") {_x000D_
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");_x000D_
        } else if (val == "item2") {_x000D_
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");_x000D_
        } else if (val == "item3") {_x000D_
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");_x000D_
        } else if (val == "item0") {_x000D_
            $("#size").html("<option value=''>--select one--</option>");_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<select id="type">_x000D_
    <option value="item0">--Select an Item--</option>_x000D_
    <option value="item1">item1</option>_x000D_
    <option value="item2">item2</option>_x000D_
    <option value="item3">item3</option>_x000D_
</select>_x000D_
_x000D_
<select id="size">_x000D_
    <option value="">-- select one -- </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How can I remove the first line of a text file using bash/sed script?

Try tail:

tail -n +2 "$FILE"

-n x: Just print the last x lines. tail -n 5 would give you the last 5 lines of the input. The + sign kind of inverts the argument and make tail print anything but the first x-1 lines. tail -n +1 would print the whole file, tail -n +2 everything but the first line, etc.

GNU tail is much faster than sed. tail is also available on BSD and the -n +2 flag is consistent across both tools. Check the FreeBSD or OS X man pages for more.

The BSD version can be much slower than sed, though. I wonder how they managed that; tail should just read a file line by line while sed does pretty complex operations involving interpreting a script, applying regular expressions and the like.

Note: You may be tempted to use

# THIS WILL GIVE YOU AN EMPTY FILE!
tail -n +2 "$FILE" > "$FILE"

but this will give you an empty file. The reason is that the redirection (>) happens before tail is invoked by the shell:

  1. Shell truncates file $FILE
  2. Shell creates a new process for tail
  3. Shell redirects stdout of the tail process to $FILE
  4. tail reads from the now empty $FILE

If you want to remove the first line inside the file, you should use:

tail -n +2 "$FILE" > "$FILE.tmp" && mv "$FILE.tmp" "$FILE"

The && will make sure that the file doesn't get overwritten when there is a problem.

Adding a 'share by email' link to website

Easiest: http://www.addthis.com/

Best? Well. probably not, But If you don't want to design something bespoke this is the best there is...

Controlling mouse with Python

As of 2021, you can use mouse:

import mouse
mouse.move("500", "500")
mouse.left_click()

Features

  • Global event hook on all mice devices (captures events regardless of focus).
  • Listen and sends mouse events.
  • Works with Windows and Linux (requires sudo).
  • Pure Python, no C modules to be compiled.
  • Zero dependencies. Trivial to install and deploy, just copy the files.
  • Python 2 and 3
  • Includes high level API (e.g. record and play).
  • Events automatically captured in separate thread, doesn't block main program.
  • Tested and documented.

visual c++: #include files from other projects in the same solution

#include has nothing to do with projects - it just tells the preprocessor "put the contents of the header file here". If you give it a path that points to the correct location (can be a relative path, like ../your_file.h) it will be included correctly.

You will, however, have to learn about libraries (static/dynamic libraries) in order to make such projects link properly - but that's another question.

Dealing with "Xerces hell" in Java/Maven?

I guess there is one question you need to answer:

Does there exist a xerces*.jar that everything in your application can live with?

If not you are basically screwed and would have to use something like OSGI, which allows you to have different versions of a library loaded at the same time. Be warned that it basically replaces jar version issues with classloader issues ...

If there exists such a version you could make your repository return that version for all kinds of dependencies. It's an ugly hack and would end up with the same xerces implementation in your classpath multiple times but better than having multiple different versions of xerces.

You could exclude every dependency to xerces and add one to the version you want to use.

I wonder if you can write some kind of version resolution strategy as a plugin for maven. This would probably the nicest solution but if at all feasible needs some research and coding.

For the version contained in your runtime environment, you'll have to make sure it either gets removed from the application classpath or the application jars get considered first for classloading before the lib folder of the server get considered.

So to wrap it up: It's a mess and that won't change.

make html text input field grow as I type?

Here is an example with only CSS and Content Editable:

jsFiddle Example

CSS

span 
{
    border: solid 1px black;
}
div 
{
    max-width: 200px;   
}

HTML

<div>
    <span contenteditable="true">sdfsd</span>
</div>

Important note regarding contenteditable

Making an HTML element contenteditable lets users paste copied HTML elements inside of this element. This may not be ideal for your use case, so keep that in mind when choosing to use it.

':app:lintVitalRelease' error when generating signed apk

    lintOptions {
      checkReleaseBuilds false
      abortOnError false
    }

The above code can fix the problem by ignoring it, but it may result in crashing the app as well.

The good answer is in the following link:

Error when generate signed apk

How to get a string after a specific substring?

I'm surprised nobody mentioned partition.

def substring_after(s, delim):
    return s.partition(delim)[2]

IMHO, this solution is more readable than @arshajii's. Other than that, I think @arshajii's is the best for being the fastest -- it does not create any unnecessary copies/substrings.

How to find path of active app.config file?

Strictly speaking, there is no single configuration file. Excluding ASP.NET1 there can be three configuration files using the inbuilt (System.Configuration) support. In addition to the machine config: app.exe.config, user roaming, and user local.

To get the "global" configuration (exe.config):

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
                    .FilePath

Use different ConfigurationUserLevel values for per-use roaming and non-roaming configuration files.


1 Which has a completely different model where the content of a child folders (IIS-virtual or file system) web.config can (depending on the setting) add to or override the parent's web.config.

VBA Public Array : how to?

Try this:

Dim colHeader(12)
colHeader = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")

Unfortunately the code found online was VB.NET not VBA.

Int division: Why is the result of 1/3 == 0?

(1/3) means Integer division, thats why you can not get decimal value from this division. To solve this problem use:

public static void main(String[] args) {
        double g = 1.0 / 3;
        System.out.printf("%.2f", g);
    }

How to use If Statement in Where Clause in SQL?

You have to use CASE Statement/Expression

Select * from Customer
WHERE  (I.IsClose=@ISClose OR @ISClose is NULL)  
AND    
    (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
AND 
     CASE @Value
         WHEN 2 THEN (CASE I.RecurringCharge WHEN @Total or @Total is NULL) 
         WHEN 3 THEN (CASE WHEN I.RecurringCharge like 
                               '%'+cast(@Total as varchar(50))+'%' 
                     or @Total is NULL )
     END

Simple way to transpose columns and rows in SQL?

I'd like to point out few more solutions to transposing columns and rows in SQL.

The first one is - using CURSOR. Although the general consensus in the professional community is to stay away from SQL Server Cursors, there are still instances whereby the use of cursors is recommended. Anyway, Cursors present us with another option to transpose rows into columns.

  • Vertical expansion

    Similar to the PIVOT, the cursor has the dynamic capability to append more rows as your dataset expands to include more policy numbers.

  • Horizontal expansion

    Unlike the PIVOT, the cursor excels in this area as it is able to expand to include newly added document, without altering the script.

  • Performance breakdown

    The major limitation of transposing rows into columns using CURSOR is a disadvantage that is linked to using cursors in general – they come at significant performance cost. This is because the Cursor generates a separate query for each FETCH NEXT operation.

Another solution of transposing rows into columns is by using XML.

The XML solution to transposing rows into columns is basically an optimal version of the PIVOT in that it addresses the dynamic column limitation.

The XML version of the script addresses this limitation by using a combination of XML Path, dynamic T-SQL and some built-in functions (i.e. STUFF, QUOTENAME).

  • Vertical expansion

    Similar to the PIVOT and the Cursor, newly added policies are able to be retrieved in the XML version of the script without altering the original script.

  • Horizontal expansion

    Unlike the PIVOT, newly added documents can be displayed without altering the script.

  • Performance breakdown

    In terms of IO, the statistics of the XML version of the script is almost similar to the PIVOT – the only difference is that the XML has a second scan of dtTranspose table but this time from a logical read – data cache.

You can find some more about these solutions (including some actual T-SQL exmaples) in this article: https://www.sqlshack.com/multiple-options-to-transposing-rows-into-columns/

Select single item from a list

List<string> items = new List<string>();

items.Find(p => p == "blah");

or

items.Find(p => p.Contains("b"));

but this allows you to define what you are looking for via a match predicate...

I guess if you are talking linqToSql then:

example looking for Account...

DataContext dc = new DataContext();

Account item = dc.Accounts.FirstOrDefault(p => p.id == 5);

If you need to make sure that there is only 1 item (throws exception when more than 1)

DataContext dc = new DataContext();

Account item = dc.Accounts.SingleOrDefault(p => p.id == 5);

CSS to prevent child element from inheriting parent styles

Unfortunately, you're out of luck here.

There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).

You will have to revert style changes manually:

div { color: green; }

form div { color: red; }

form div div.content { color: green; }

If you have access to the markup, you can add several classes to style precisely what you need:

form div.sub { color: red; }

form div div.content { /* remains green */ }

Edit: The CSS Working Group is up to something:

div.content {
  all: revert;
}

No idea, when or if ever this will be implemented by browsers.

Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)

Edit 3: default was renamed to revert.

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

I had the same problem and tried most of the solutions suggested above, but none worked for me. Eventually, I rebuild my entire com.springframework (maven) repository (by simply deleting .m2/org/springworkframework directory).

It worked for me.

how to force maven to update local repo

Click settings and search for "Repositories", then select the local repo and click "Update". That's all. This action meets my need.

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

The easiest way to do is export your database to .sql, open it on Notepad++ and "Search and Replace" the utf8mb4_unicode_ci to utf8_unicode_ci and also replace utf8mb4 to utf8. Also don't forget to change the database collation to utf8_unicode_ci (Operations > Collation).

Moment JS - check if a date is today or in the future

If you only need to know which one is bigger, you can also compare them directly:

var SpecialToDate = '31/01/2014'; // DD/MM/YYYY

var SpecialTo = moment(SpecialToDate, "DD/MM/YYYY");
if (moment() > SpecialTo) {
    alert('date is today or in future');
} else {
    alert('date is in the past');
}

Hope this helps!

How to redirect to a 404 in Rails?

<%= render file: 'public/404', status: 404, formats: [:html] %>

just add this to the page you want to render to the 404 error page and you are done.

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

For the async Method ("ExecuteSqlCommandAsync") you can use it like this:

var sql = @"Update [User] SET FirstName = @FirstName WHERE Id = @Id";

await ctx.Database.ExecuteSqlCommandAsync(
    sql,
    parameters: new[]{
        new SqlParameter("@FirstName", firstname),
        new SqlParameter("@Id", id)
    });

How can I get the value of a registry key from within a batch script?

set regVar_LocalPrjPath="LocalPrjPath"
set regVar_Path="HKEY_CURRENT_USER\Software\xyz\KeyPath"

:: ### Retrieve VAR1 ###
FOR /F "skip=2 tokens=2,*" %%A IN ('reg.exe query %regVar_Path% /v %regVar_LocalPrjPath%') DO set "VAR1=%%B"

Static methods in Python?

Perhaps the simplest option is just to put those functions outside of the class:

class Dog(object):
    def __init__(self, name):
        self.name = name

    def bark(self):
        if self.name == "Doggy":
            return barking_sound()
        else:
            return "yip yip"

def barking_sound():
    return "woof woof"

Using this method, functions which modify or use internal object state (have side effects) can be kept in the class, and the reusable utility functions can be moved outside.

Let's say this file is called dogs.py. To use these, you'd call dogs.barking_sound() instead of dogs.Dog.barking_sound.

If you really need a static method to be part of the class, you can use the staticmethod decorator.

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

How do I add FTP support to Eclipse?

As none of the other solutions mentioned satisfied me, I wrote a script that uses WinSCP to sync local directories in a project to a FTP(S)/SFTP/SCP Server when eclipse's autobuild feature is triggered. Obviously, this is a Windows-only solution.

Maybe someone finds this useful: http://rays-blog.de/2012/05/05/94/use-winscp-to-upload-files-using-eclipses-autobuild-feature/

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

I received same error despite jar being in lib directory & added to deployment assembly in Eclipse.

So I doubted two things ,

1.Some Weblogic cache issue - as this app was deployed before & I was trying to redeploy after some changes

2.Jar itself is corrupt due to partial download etc

So I re downloaded the jar & deleted everything in directory - ..\Oracle_Home\user_projects\domains\base_domain\lib and redeployed again & all went well.

jQuery's .click - pass parameters to user function

For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.

It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click() function as the first parameter, followed by the event handler function.

Here's some code to illustrate what I mean:

// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);
}

I know it's late in the game for this question, but the previous answers led me to this solution, so I hope it helps someone sometime!

How can I include css files using node, express, and ejs?

I have used the following steps to resolve this problem

  1. create new folder (static) and move all js and css file into this folder.
  2. then add app.use('/static', express.static('static'))
  3. add css like < link rel="stylesheet" type="text/css" href="/static/style.css"/>
  4. restart server to view impact after changes.

Installing Node.js (and npm) on Windows 10

I had the same problem, what helped we was turning of my anti virus protection for like 10 minutes while node installed and it worked like a charm.

How do you specify a different port number in SQL Management Studio?

You'll need the SQL Server Configuration Manager. Go to Sql Native Client Configuration, Select Client Protocols, Right Click on TCP/IP and set your default port there.

Animate the transition between fragments

If you can afford to tie yourself to just Lollipop and later, this seems to do the trick:

import android.transition.Slide;
import android.util.Log;
import android.view.Gravity;
.
.
.
f = new MyFragment();
f.setEnterTransition(new Slide(Gravity.END));
f.setExitTransition(new Slide(Gravity.START));
getFragmentManager()
    .beginTransaction()
    .replace(R.id.content, f, FRAG_TAG)  // FRAG_TAG is the tag for your fragment
    .commit();

Kotlin version:

f = MyFragment().apply {
    enterTransition = Slide(Gravity.END)
    exitTransition = Slide(Gravity.START)
}
fragmentManager
    .beginTransaction()
    .replace(R.id.content, f, FRAG_TAG)  // FRAG_TAG is the tag for your fragment
    .commit();

Hope this helps.

How to create a zip file in Java

To write a ZIP file, you use a ZipOutputStream. For each entry that you want to place into the ZIP file, you create a ZipEntry object. You pass the file name to the ZipEntry constructor; it sets the other parameters such as file date and decompression method. You can override these settings if you like. Then, you call the putNextEntry method of the ZipOutputStream to begin writing a new file. Send the file data to the ZIP stream. When you are done, call closeEntry. Repeat for all the files you want to store. Here is a code skeleton:

FileOutputStream fout = new FileOutputStream("test.zip");
ZipOutputStream zout = new ZipOutputStream(fout);
for all files
{
    ZipEntry ze = new ZipEntry(filename);
    zout.putNextEntry(ze);
    send data to zout;
    zout.closeEntry();
}
zout.close();

How do you create a UIImage View Programmatically - Swift

First create UIImageView then add image in UIImageView .

    var imageView : UIImageView
    imageView  = UIImageView(frame:CGRectMake(10, 50, 100, 300));
    imageView.image = UIImage(named:"image.jpg")
    self.view.addSubview(imageView)

matplotlib: plot multiple columns of pandas data frame on the bar chart

Although the accepted answer works fine, since v0.21.0rc1 it gives a warning

UserWarning: Pandas doesn't allow columns to be created via a new attribute name

Instead, one can do

df[["X", "A", "B", "C"]].plot(x="X", kind="bar")

Plotting time-series with Date labels on x-axis

You can rotate the dates by hacking axis notations with text()

Lines <- "Date            Visits
11/1/2010   696537
11/2/2010   718748
11/3/2010   799355
11/4/2010   805800
11/5/2010   701262
11/6/2010   531579
11/7/2010   690068
11/8/2010   756947
11/9/2010   718757
11/10/2010  701768
11/11/2010  820113
11/12/2010  645259"

dm <- read.table(textConnection(Lines), header = TRUE)
dm$Date <- as.Date(dm$Date, "%m/%d/%Y")
plot(Visits ~ Date, dm, xaxt = "n", type = "l")
axis(1,at=NULL, labels=F)
text(x = dm$Date, par("usr")[3]*.97, labels = paste(dm$Date,' '), srt = 45, pos = 1, xpd = TRUE,cex=.7)

ES6 Class Multiple inheritance

use extent with custom function to handle multiple inheritance with es6

_x000D_
_x000D_
var aggregation = (baseClass, ...mixins) => {_x000D_
    let base = class _Combined extends baseClass {_x000D_
        constructor (...args) {_x000D_
            super(...args)_x000D_
            mixins.forEach((mixin) => {_x000D_
                mixin.prototype.initializer.call(this)_x000D_
            })_x000D_
        }_x000D_
    }_x000D_
    let copyProps = (target, source) => {_x000D_
        Object.getOwnPropertyNames(source)_x000D_
            .concat(Object.getOwnPropertySymbols(source))_x000D_
            .forEach((prop) => {_x000D_
            if (prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))_x000D_
                return_x000D_
            Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop))_x000D_
        })_x000D_
    }_x000D_
    mixins.forEach((mixin) => {_x000D_
        copyProps(base.prototype, mixin.prototype)_x000D_
        copyProps(base, mixin)_x000D_
    })_x000D_
    return base_x000D_
}_x000D_
_x000D_
class Colored {_x000D_
    initializer ()     { this._color = "white" }_x000D_
    get color ()       { return this._color }_x000D_
    set color (v)      { this._color = v }_x000D_
}_x000D_
_x000D_
class ZCoord {_x000D_
    initializer ()     { this._z = 0 }_x000D_
    get z ()           { return this._z }_x000D_
    set z (v)          { this._z = v }_x000D_
}_x000D_
_x000D_
class Shape {_x000D_
    constructor (x, y) { this._x = x; this._y = y }_x000D_
    get x ()           { return this._x }_x000D_
    set x (v)          { this._x = v }_x000D_
    get y ()           { return this._y }_x000D_
    set y (v)          { this._y = v }_x000D_
}_x000D_
_x000D_
class Rectangle extends aggregation(Shape, Colored, ZCoord) {}_x000D_
_x000D_
var rect = new Rectangle(7, 42)_x000D_
rect.z     = 1000_x000D_
rect.color = "red"_x000D_
console.log(rect.x, rect.y, rect.z, rect.color)
_x000D_
_x000D_
_x000D_

ls command: how can I get a recursive full-path listing, one line per file?

I knew the file name but wanted the directory as well.

find $PWD | fgrep filename

worked perfectly in Mac OS 10.12.1

how to call a function from another function in Jquery

wrap you shared code into another function:

<script>
  function myFun () {
      //do something
  }

  $(document).ready(function(){
    //Load City by State
    $(document).on('change', '#billing_state_id', function() {
       myFun ();
    });   
    $(document).on('click', '#click_me', function() {
       //do something
       myFun();
    });   
  });
</script>

For..In loops in JavaScript - key value pairs

If you are using Lodash, you can use _.forEach

_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  console.log(key + ": " + value);
});
// => Logs 'a: 1' then 'b: 2' (iteration order is not guaranteed).

Handle Guzzle exception and get HTTP body

if put 'http_errors' => false in guzzle request options, then it would stop throw exception while get 4xx or 5xx error, like this: $client->get(url, ['http_errors' => false]). then you parse the response, not matter it's ok or error, it would be in the response for more info

write newline into a file

You could print through a PrintStream.

PrintStream ps = new PrintStream(fop);
ps.println(nodeValue);
ps.close();

How to escape a JSON string containing newline characters using JavaScript?

Take your JSON and .stringify() it. Then use the .replace() method and replace all occurrences of \n with \\n.

EDIT:

As far as I know of, there are no well-known JS libraries for escaping all special characters in a string. But, you could chain the .replace() method and replace all of the special characters like this:

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.replace(/\\n/g, "\\n")
                                      .replace(/\\'/g, "\\'")
                                      .replace(/\\"/g, '\\"')
                                      .replace(/\\&/g, "\\&")
                                      .replace(/\\r/g, "\\r")
                                      .replace(/\\t/g, "\\t")
                                      .replace(/\\b/g, "\\b")
                                      .replace(/\\f/g, "\\f");
// myEscapedJSONString is now ready to be POST'ed to the server. 

But that's pretty nasty, isn't it? Enter the beauty of functions, in that they allow you to break code into pieces and keep the main flow of your script clean, and free of 8 chained .replace() calls. So let's put that functionality into a function called, escapeSpecialChars(). Let's go ahead and attach it to the prototype chain of the String object, so we can call escapeSpecialChars() directly on String objects.

Like so:

String.prototype.escapeSpecialChars = function() {
    return this.replace(/\\n/g, "\\n")
               .replace(/\\'/g, "\\'")
               .replace(/\\"/g, '\\"')
               .replace(/\\&/g, "\\&")
               .replace(/\\r/g, "\\r")
               .replace(/\\t/g, "\\t")
               .replace(/\\b/g, "\\b")
               .replace(/\\f/g, "\\f");
};

Once we have defined that function, the main body of our code is as simple as this:

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.escapeSpecialChars();
// myEscapedJSONString is now ready to be POST'ed to the server

What is the use of the JavaScript 'bind' method?

The simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value.

x = 9;
var module = {
    x: 81,
    getX: function () {
        return this.x;
    }
};

module.getX(); // 81

var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object

// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81

Please refer this link for more information

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

How to center a "position: absolute" element

If you want to center an absolute element

#div {
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    width:300px; /* Assign a value */
    height:500px; /* Assign a value */
    margin:auto;
}

If you want a container to be centered left to right, but not with top to bottom

#div {
    position:absolute;
    left:0;
    right:0;
    width:300px; /* Assign a value */
    height:500px; /* Assign a value */
    margin:auto;
}

If you want a container to be centered top to bottom, regardless of being left to right

#div {
    position:absolute;
    top:0;
    bottom:0;
    width:300px; /* Assign a value */
    height:500px; /* Assign a value */
    margin:auto;
}

Update as of December 15, 2015

Well I learnt this another new trick few months ago. Assuming that you have a relative parent element.

Here goes your absolute element.

.absolute-element { 
    position:absolute; 
    top:50%; 
    left:50%; 
    transform:translate(-50%, -50%); 
    width:50%; /* You can specify ANY width values here */ 
}

With this, I think it's a better answer than my old solution. Since you don't have to specify width AND height. This one it adapts the content of the element itself.

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

Select where count of one field is greater than one

SELECT username, numb from(
Select username, count(username) as numb from customers GROUP BY username ) as my_table
WHERE numb > 3

String Concatenation in EL

Since Expression Language 3.0, it is valid to use += operator for string concatenation.

${(empty value)? "none" : value += " enabled"}  // valid as of EL 3.0

Quoting EL 3.0 Specification.

String Concatenation Operator

To evaluate

A += B 
  • Coerce A and B to String.
  • Return the concatenated string of A and B.

How do I enter a multi-line comment in Perl?

I found it. Perl has multi-line comments:

#!/usr/bin/perl

use strict;

use warnings;

=for comment

Example of multiline comment.

Example of multiline comment.

=cut

print "Multi Line Comment Example \n";

Pass Multiple Parameters to jQuery ajax call

Its all about data which you pass; has to properly formatted string. If you are passing empty data then data: {} will work. However with multiple parameters it has to be properly formatted e.g.

var dataParam = '{' + '"data1Variable": "' + data1Value+ '", "data2Variable": "' + data2Value+ '"' +  '}';

....

data : dataParam

...

Best way to understand is have error handler with proper message parameter, so as to know the detailed errors.

Comparing two dictionaries and checking how many (key, value) pairs are equal

I'm new to python but I ended up doing something similar to @mouad

unmatched_item = set(dict_1.items()) ^ set(dict_2.items())
len(unmatched_item) # should be 0

The XOR operator (^) should eliminate all elements of the dict when they are the same in both dicts.

Python PDF library

Reportlab. There is an open source version, and a paid version which adds the Report Markup Language (an alternative method of defining your document).

How can I create a dynamically sized array of structs?

If you want to grow the array dynamically, you should use malloc() to dynamically allocate some fixed amount of memory, and then use realloc() whenever you run out. A common technique is to use an exponential growth function such that you allocate some small fixed amount and then make the array grow by duplicating the allocated amount.

Some example code would be:

size = 64; i = 0;
x = malloc(sizeof(words)*size); /* enough space for 64 words */
while (read_words()) {
    if (++i > size) {
        size *= 2;
        x = realloc(sizeof(words) * size);
    }
}
/* done with x */
free(x);

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

Download whatever configuration script that your browser is using.

the script would have various host:port configuration. based on the domain you want to connect , one of the host:port is selected by the borwser.

in the eclipse network setting you can try to put on of the host ports and see if that works.

worked for me.

the config script looks like,

if (isPlainHostName(host))
    return "DIRECT";
else if (dnsDomainIs(host, "<***sample host name *******>"))
    return "PROXY ***some ip*****; DIRECT";
else if (dnsDomainIs(host, "address.com")
        || dnsDomainIs(host, "adress2..com")
        || dnsDomainIs(host, "address3.com")
        || dnsDomainIs(host, "address4.com")        
    return "PROXY <***some proxyhost****>:8080";

you would need to look for the host port in the return statement.

Properties order in Margin

There are three unique situations:

  • 4 numbers, e.g. Margin="a,b,c,d".
  • 2 numbers, e.g. Margin="a,b".
  • 1 number, e.g. Margin="a".

4 Numbers

If there are 4 numbers, then its left, top, right, bottom (a clockwise circle starting from the middle left margin). First number is always the "West" like "WPF":

<object Margin="left,top,right,bottom"/>

Example: if we use Margin="10,20,30,40" it generates:

enter image description here

2 Numbers

If there are 2 numbers, then the first is left & right margin thickness, the second is top & bottom margin thickness. First number is always the "West" like "WPF":

<object Margin="a,b"/> // Equivalent to Margin="a,b,a,b".

Example: if we use Margin="10,30", the left & right margin are both 10, and the top & bottom are both 30.

enter image description here

1 Number

If there is 1 number, then the number is repeated (its essentially a border thickness).

<object Margin="a"/> // Equivalent to Margin="a,a,a,a".

Example: if we use Margin="20" it generates:

enter image description here

Update 2020-05-27

Have been working on a large-scale WPF application for the past 5 years with over 100 screens. Part of a team of 5 WPF/C#/Java devs. We eventually settled on either using 1 number (for border thickness) or 4 numbers. We never use 2. It is consistent, and seems to be a good way to reduce cognitive load when developing.


The rule:

All width numbers start on the left (the "West" like "WPF") and go clockwise (if two numbers, only go clockwise twice, then mirror the rest).

How to unescape HTML character entities in Java?

The following library can also be used for HTML escaping in Java: unbescape.

HTML can be unescaped this way:

final String unescapedText = HtmlEscape.unescapeHtml(escapedText); 

JavaScript equivalent of PHP’s die

you can try with :

return 0;

that work in case of stop process.

VBA Excel Provide current Date in Text box

Actually, it is less complicated than it seems.

Sub 
  today_1()
  ActiveCell.FormulaR1C1 = "=TODAY()"
  ActiveCell.Value = Date
End Sub

In Python try until no error

Maybe something like this:

connected = False

while not connected:
    try:
        try_connect()
        connected = True
    except ...:
        pass

Can you have multiple $(document).ready(function(){ ... }); sections?

Yes you can.

Multiple document ready sections are particularly useful if you have other modules haging off the same page that use it. With the old window.onload=func declaration, every time you specified a function to be called, it replaced the old.

Now all functions specified are queued/stacked (can someone confirm?) regardless of which document ready section they are specified in.

Read Numeric Data from a Text File in C++

It can depend, especially on whether your file will have the same number of items on each row or not. If it will, then you probably want a 2D matrix class of some sort, usually something like this:

class array2D { 
    std::vector<double> data;
    size_t columns;
public:
    array2D(size_t x, size_t y) : columns(x), data(x*y) {}

    double &operator(size_t x, size_t y) {
       return data[y*columns+x];
    }
};

Note that as it's written, this assumes you know the size you'll need up-front. That can be avoided, but the code gets a little larger and more complex.

In any case, to read the numbers and maintain the original structure, you'd typically read a line at a time into a string, then use a stringstream to read numbers from the line. This lets you store the data from each line into a separate row in your array.

If you don't know the size ahead of time or (especially) if different rows might not all contain the same number of numbers:

11 12 13
23 34 56 78

You might want to use a std::vector<std::vector<double> > instead. This does impose some overhead, but if different rows may have different sizes, it's an easy way to do the job.

std::vector<std::vector<double> > numbers;

std::string temp;

while (std::getline(infile, temp)) {
    std::istringstream buffer(temp);
    std::vector<double> line((std::istream_iterator<double>(buffer)),
                             std::istream_iterator<double>());

    numbers.push_back(line);
}

...or, with a modern (C++11) compiler, you can use brackets for line's initialization:

    std::vector<double> line{std::istream_iterator<double>(buffer),
                             std::istream_iterator<double>()};

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

And so I see from other answers that there are several ways of dealing with it. But I don't believe this. It has to be reduced into one way. I love IDE but, but if I follow the IDE steps provided from different answers I know this is not the fundamental algebra. My error looked like:

* What went wrong:
Execution failed for task ':compileJava'.
> Could not target platform: 'Java SE 11' using tool chain: 'JDK 8 (1.8)'.

And the way to solve it scientifically is:

vi build.gradle

To change from:

java {
    sourceCompatibility = JavaVersion.toVersion('11')
    targetCompatibility = JavaVersion.toVersion('11')
}

to become:

java {
    sourceCompatibility = JavaVersion.toVersion('8')
    targetCompatibility = JavaVersion.toVersion('8')
}

The scientific method is that method that is open for argumentation and deals on common denominators.

Find row where values for column is maximal in a pandas DataFrame

The direct ".argmax()" solution does not work for me.

The previous example provided by @ely

>>> import pandas
>>> import numpy as np
>>> df = pandas.DataFrame(np.random.randn(5,3),columns=['A','B','C'])
>>> df
      A         B         C
0  1.232853 -1.979459 -0.573626
1  0.140767  0.394940  1.068890
2  0.742023  1.343977 -0.579745
3  2.125299 -0.649328 -0.211692
4 -0.187253  1.908618 -1.862934
>>> df['A'].argmax()
3
>>> df['B'].argmax()
4
>>> df['C'].argmax()
1

returns the following message :

FutureWarning: 'argmax' is deprecated, use 'idxmax' instead. The behavior of 'argmax' 
will be corrected to return the positional maximum in the future.
Use 'series.values.argmax' to get the position of the maximum now.

So that my solution is :

df['A'].values.argmax()

In Python, how do you convert seconds since epoch to a `datetime` object?

datetime.datetime.fromtimestamp will do, if you know the time zone, you could produce the same output as with time.gmtime

>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)

or

>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)

What is the difference between git pull and git fetch + git rebase?

TLDR:

git pull is like running git fetch then git merge
git pull --rebase is like git fetch then git rebase

In reply to your first statement,

git pull is like a git fetch + git merge.

"In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD" More precisely, git pull runs git fetch with the given parameters and then calls git merge to merge the retrieved branch heads into the current branch"

(Ref: https://git-scm.com/docs/git-pull)


For your second statement/question:

'But what is the difference between git pull VS git fetch + git rebase'

Again, from same source:
git pull --rebase

"With --rebase, it runs git rebase instead of git merge."


Now, if you wanted to ask

'the difference between merge and rebase'

that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)

How to sum columns in a dataTable?

Try this:

            DataTable dt = new DataTable();
            int sum = 0;
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    sum += (int)dr[dc];
                }
            } 

What causing this "Invalid length for a Base-64 char array"

This is because of a huge view state, In my case I got lucky since I was not using the viewstate. I just added enableviewstate="false" on the form tag and view state went from 35k to 100 chars

Returning value from called function in a shell script

A Bash function can't return a string directly like you want it to. You can do three things:

  1. Echo a string
  2. Return an exit status, which is a number, not a string
  3. Share a variable

This is also true for some other shells.

Here's how to do each of those options:

1. Echo strings

lockdir="somedir"
testlock(){
    retval=""
    if mkdir "$lockdir"
    then # Directory did not exist, but it was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval="true"
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval="false"
    fi
    echo "$retval"
}

retval=$( testlock )
if [ "$retval" == "true" ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

2. Return exit status

lockdir="somedir"
testlock(){
    if mkdir "$lockdir"
    then # Directory did not exist, but was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval=0
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval=1
    fi
    return "$retval"
}

testlock
retval=$?
if [ "$retval" == 0 ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

3. Share variable

lockdir="somedir"
retval=-1
testlock(){
    if mkdir "$lockdir"
    then # Directory did not exist, but it was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval=0
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval=1
    fi
}

testlock
if [ "$retval" == 0 ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

Locating child nodes of WebElements in selenium

I also found myself in a similar position a couple of weeks ago. You can also do this by creating a custom ElementLocatorFactory (or simply passing in divA into the DefaultElementLocatorFactory) to see if it's a child of the first div - you would then call the appropriate PageFactory initElements method.

In this case if you did the following:

PageFactory.initElements(new DefaultElementLocatorFactory(divA), pageObjectInstance));
// The Page Object instance would then need a WebElement 
// annotated with something like the xpath above or @FindBy(tagName = "input")

Determining the current foreground application from a background task or service

In order to determine the foreground application, you can use for detecting the foreground app, you can use https://github.com/ricvalerio/foregroundappchecker. It uses different methods depending on the android version of the device.

As for the service, the repo also provides the code you need for it. Essentially, let android studio create the service for you, and then onCreate add the snippet that uses the appChecker. You will need to request permission however.

Running Bash commands in Python

To run the command without a shell, pass the command as a list and implement the redirection in Python using [subprocess]:

#!/usr/bin/env python
import subprocess

with open('test.nt', 'wb', 0) as file:
    subprocess.check_call("cwm --rdf test.rdf --ntriples".split(),
                          stdout=file)

Note: no > test.nt at the end. stdout=file implements the redirection.


To run the command using the shell in Python, pass the command as a string and enable shell=True:

#!/usr/bin/env python
import subprocess

subprocess.check_call("cwm --rdf test.rdf --ntriples > test.nt",
                      shell=True)

Here's the shell is responsible for the output redirection (> test.nt is in the command).


To run a bash command that uses bashisms, specify the bash executable explicitly e.g., to emulate bash process substitution:

#!/usr/bin/env python
import subprocess

subprocess.check_call('program <(command) <(another-command)',
                      shell=True, executable='/bin/bash')

How to fix Python Numpy/Pandas installation?

You probably have another Numpy version installed on your system, try to query your numpy version and retrieve it if your distribution does not support it.
aka debian/unbuntu/Mint version can query mostly from dpkg package manger : dpkg --get-selections | egrep -i "numpy", you can see actual Numpy version.

  • Some having apt can either asking to removing it by doing this: apt-get remove numpy.

  • Some having distribution like Fedora, RedHat and any compatible release under RedHat model can use rpm as well to query the installation.

  • This is happening by telling to Numpy installer to install itself in current /usr/local/lib/python[VERSION]/dist-packages over Linux env and c:[...]\python[VERSION]\site-packages for windows. Having probably One version of Numpy installed in /usr/local/python[VERSION]/dist-packages, this one will be instantiated first.

  • .pth file hold information about path location of specific python module, but erasing a component from packages may corrupt it...

Be careful, and you will have to remove the package and all it's dependency... really painful in some case.

Visiting lunchad.net may save you time sometimes they had new versions from some packages.

Creating Roles in Asp.net Identity MVC 5

Here is the complete article describing how to create role, modify roles, delete roles and manage roles using ASP.NET Identity. This also contains User interface, controller methods etc.

http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc

Hope this helpls

Thanks

What's the difference between Invoke() and BeginInvoke()

The difference between Control.Invoke() and Control.BeginInvoke() is,

  • BeginInvoke() will schedule the asynchronous action on the GUI thread. When the asynchronous action is scheduled, your code continues. Some time later (you don't know exactly when) your asynchronous action will be executed
  • Invoke() will execute your asynchronous action (on the GUI thread) and wait until your action has completed.

A logical conclusion is that a delegate you pass to Invoke() can have out-parameters or a return-value, while a delegate you pass to BeginInvoke() cannot (you have to use EndInvoke to retrieve the results).

How to close an iframe within iframe itself

Use this to remove iframe from parent within iframe itself

frameElement.parentNode.removeChild(frameElement)

It works with same origin only(not allowed with cross origin)

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

Finally, Works!

Put smtpClient.UseDefaultCredentials = false; after smtpClient.Credentials = credentials; then problem resolved!

            SmtpClient smtpClient = new SmtpClient(smtpServerName);                          
            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smtpUName, smtpUNamePwd);

            smtpClient.Credentials = credentials;
            smtpClient.UseDefaultCredentials = false;  <-- Set This Line After Credentials

            smtpClient.Send(mailMsg);
            smtpClient = null;
            mailMsg.Dispose();

How good is Java's UUID.randomUUID?

Many of the answers discuss how many UUIDs would have to be generated to reach a 50% chance of a collision. But a 50%, 25%, or even 1% chance of collision is worthless for an application where collision must be (virtually) impossible.

Do programmers routinely dismiss as "impossible" other events that can and do occur?

When we write data to a disk or memory and read it back again, we take for granted that the data are correct. We rely on the device's error correction to detect any corruption. But the chance of undetected errors is actually around 2-50.

Wouldn't it make sense to apply a similar standard to random UUIDs? If you do, you will find that an "impossible" collision is possible in a collection of around 100 billion random UUIDs (236.5).

This is an astronomical number, but applications like itemized billing in a national healthcare system, or logging high frequency sensor data on a large array of devices could definitely bump into these limits. If you are writing the next Hitchhiker's Guide to the Galaxy, don't try to assign UUIDs to each article!

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

I had this issue and it took me for a while to figure out how to fix that.

My case is slightly different. My MySQL server is of version 5.1.x. And somehow I upgraded my MySQL-python from 1.2.3 to 1.2.5. And I kept getting this issue since then event I added the following soft link.

libmysqlclient.18.dylib -> /usr/local/mysql/lib/libmysqlclient.18.dylib

It turns out that for MySQL 5.1.x there is no libmysqlclient.18.dylib, but only libmysqlclient.16.dylib. You can fix this issue either by downgrade your MySQL-python to 1.2.3 or upgrade your MySQL server to 5.6.x (I haven't tried 5.5.x.)

I downgraded the library to 1.2.3 since upgrading MySQL is not an option for me.

Creating a list of objects in Python

To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.

instancelist = [ MyClass() for i in range(29)]

and then access the instances through the index of the list.

instancelist[5].attr1 = 'whamma'

correct way to use super (argument passing)

If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs, and then pop them right after you use them (unless you need them in upper classes).

class First(object):
    def __init__(self, *args, **kwargs):
        self.first_arg = kwargs.pop('first_arg')
        super(First, self).__init__(*args, **kwargs)

class Second(First):
    def __init__(self, *args, **kwargs):
        self.second_arg = kwargs.pop('second_arg')
        super(Second, self).__init__(*args, **kwargs)

class Third(Second):
    def __init__(self, *args, **kwargs):
        self.third_arg = kwargs.pop('third_arg')
        super(Third, self).__init__(*args, **kwargs)

This is the simplest way to solve those kind of problems.

third = Third(first_arg=1, second_arg=2, third_arg=3)

Why is jquery's .ajax() method not sending my session cookie?

Adding my scenario and solution in case it helps someone else. I encountered similar case when using RESTful APIs. My Web server hosting HTML/Script/CSS files and Application Server exposing APIs were hosted on same domain. However the path was different.

web server - mydomain/webpages/abc.html

used abc.js which set cookie named mycookie

app server - mydomain/webapis/servicename.

to which api calls were made

I was expecting the cookie in mydomain/webapis/servicename and tried reading it but it was not being sent. After reading comment from the answer, I checked in browser's development tool that mycookie's path was set to "/webpages" and hence not available in service call to

mydomain/webapis/servicename

So While setting cookie from jquery, this is what I did -

$.cookie("mycookie","mayvalue",{**path:'/'**});

Correct way to read a text file into a buffer in C?

Have you considered mmap()? You can read from the file directly as if it were already in memory.

http://beej.us/guide/bgipc/output/html/multipage/mmap.html

How to serve .html files with Spring

Java configuration for html files (in this case index.html):

@Configuration
@EnableWebMvc
public class DispatcherConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/index.html").addResourceLocations("/index.html");
    }

}

How to convert JSONObjects to JSONArray?

Even shorter and with json-functions:

JSONObject songsObject = json.getJSONObject("songs");
JSONArray songsArray = songsObject.toJSONArray(songsObject.names());

Apply CSS styles to an element depending on its child elements

As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.

It'd be wonderful if you could do something like div[div.a] or div:containing[div.a] as you said, but this isn't possible.

You may want to consider looking at jQuery. Its selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a CSS class to the parent all in one line.

If you use jQuery, something along the lines of this would may work (untested but the theory is there):

$('div:has(div.a)').css('border', '1px solid red');

or

$('div:has(div.a)').addClass('redBorder');

combined with a CSS class:

.redBorder
{
    border: 1px solid red;
}

Here's the documentation for the jQuery "has" selector.

java: run a function after a specific number of seconds

ScheduledThreadPoolExecutor has this ability, but it's quite heavyweight.

Timer also has this ability but opens several thread even if used only once.

Here's a simple implementation with a test (signature close to Android's Handler.postDelayed()):

public class JavaUtil {
    public static void postDelayed(final Runnable runnable, final long delayMillis) {
        final long requested = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                // The while is just to ignore interruption.
                while (true) {
                    try {
                        long leftToSleep = requested + delayMillis - System.currentTimeMillis();
                        if (leftToSleep > 0) {
                            Thread.sleep(leftToSleep);
                        }
                        break;
                    } catch (InterruptedException ignored) {
                    }
                }
                runnable.run();
            }
        }).start();
    }
}

Test:

@Test
public void testRunsOnlyOnce() throws InterruptedException {
    long delay = 100;
    int num = 0;
    final AtomicInteger numAtomic = new AtomicInteger(num);
    JavaUtil.postDelayed(new Runnable() {
        @Override
        public void run() {
            numAtomic.incrementAndGet();
        }
    }, delay);
    Assert.assertEquals(num, numAtomic.get());
    Thread.sleep(delay + 10);
    Assert.assertEquals(num + 1, numAtomic.get());
    Thread.sleep(delay * 2);
    Assert.assertEquals(num + 1, numAtomic.get());
}

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

This situation occured if there are object in repository, which creates by current transaction.

Simple scenario:

  1. checkout some directory two times, as DIR1 and DIR2
  2. make 'svn mkdir test' in both
  3. make commit from DIR1
  4. try to make commit DIR2 (without svn up), SVN shall return this error

Same thing when adding same files from two working copies.

How to call a JavaScript function, declared in <head>, in the body when I want to call it

Just drop

<script>
myfunction();
</script>

in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.

check null,empty or undefined angularjs

You can do simple check

if(!a) {
   // do something when `a` is not undefined, null, ''.
}

Display current time in 12 hour format with AM/PM

// hh:mm will print hours in 12hrs clock and mins (e.g. 02:30)
System.out.println(DateTimeFormatter.ofPattern("hh:mm").format(LocalTime.now()));

// HH:mm will print hours in 24hrs clock and mins (e.g. 14:30)
System.out.println(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.now())); 

// hh:mm a will print hours in 12hrs clock, mins and AM/PM (e.g. 02:30 PM)
System.out.println(DateTimeFormatter.ofPattern("hh:mm a").format(LocalTime.now())); 

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

UPDATE 2014-11-14: The solution below is too old, I recommend using flex box layout method. Here is a overview: http://learnlayout.com/flexbox.html


My solution

html

<li class="grid-list-header row-cw row-cw-msg-list ...">
  <div class="col-md-1 col-cw col-cw-name">
  <div class="col-md-1 col-cw col-cw-keyword">
  <div class="col-md-1 col-cw col-cw-reply">
  <div class="col-md-1 col-cw col-cw-action">
</li>

<li class="grid-list-item row-cw row-cw-msg-list ...">
  <div class="col-md-1 col-cw col-cw-name">
  <div class="col-md-1 col-cw col-cw-keyword">
  <div class="col-md-1 col-cw col-cw-reply">
  <div class="col-md-1 col-cw col-cw-action">
</li>

scss

.row-cw {
  position: relative;
}

.col-cw {
  position: absolute;
  top: 0;
}


.ir-msg-list {

  $col-reply-width: 140px;
  $col-action-width: 130px;

  .row-cw-msg-list {
    padding-right: $col-reply-width + $col-action-width;
  }

  .col-cw-name {
    width: 50%;
  }

  .col-cw-keyword {
    width: 50%;
  }

  .col-cw-reply {
    width: $col-reply-width;
    right: $col-action-width;
  }

  .col-cw-action {
    width: $col-action-width;
    right: 0;
  }
}

Without modify too much bootstrap layout code.


Update (not from OP): adding code snippet below to facilitate understanding of this answer. But it doesn't seem to work as expected.

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
.row-cw {_x000D_
  position: relative;_x000D_
  height: 20px;_x000D_
}_x000D_
.col-cw {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  background-color: rgba(150, 150, 150, .5);_x000D_
}_x000D_
.row-cw-msg-list {_x000D_
  padding-right: 270px;_x000D_
}_x000D_
.col-cw-name {_x000D_
  width: 50%;_x000D_
  background-color: rgba(150, 0, 0, .5);_x000D_
}_x000D_
.col-cw-keyword {_x000D_
  width: 50%;_x000D_
  background-color: rgba(0, 150, 0, .5);_x000D_
}_x000D_
.col-cw-reply {_x000D_
  width: 140px;_x000D_
  right: 130px;_x000D_
  background-color: rgba(0, 0, 150, .5);_x000D_
}_x000D_
.col-cw-action {_x000D_
  width: 130px;_x000D_
  right: 0;_x000D_
  background-color: rgba(150, 150, 0, .5);_x000D_
}
_x000D_
<ul class="ir-msg-list">_x000D_
  <li class="grid-list-header row-cw row-cw-msg-list">_x000D_
    <div class="col-md-1 col-cw col-cw-name">name</div>_x000D_
    <div class="col-md-1 col-cw col-cw-keyword">keyword</div>_x000D_
    <div class="col-md-1 col-cw col-cw-reply">reply</div>_x000D_
    <div class="col-md-1 col-cw col-cw-action">action</div>_x000D_
  </li>_x000D_
_x000D_
  <li class="grid-list-item row-cw row-cw-msg-list">_x000D_
    <div class="col-md-1 col-cw col-cw-name">name</div>_x000D_
    <div class="col-md-1 col-cw col-cw-keyword">keyword</div>_x000D_
    <div class="col-md-1 col-cw col-cw-reply">reply</div>_x000D_
    <div class="col-md-1 col-cw col-cw-action">action</div>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How Long Does it Take to Learn Java for a Complete Newbie?

There are different schools of thought regarding how much time you need to become expert in programming. I'm not going to add to it. I suggest if you have absolutely no programming experience, learn C first. Then move to Java. The following site is very good for learning java. http://www.javapassion.com

Adding machineKey to web.config on web-farm sites

Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.

An alternative option is to set it in the machine level web.config, so its not even in the web site folder.

To generate it do it just like the linked article in David's answer.

Vim and Ctags tips and tricks

Another iteration on the SetCscope() function above. That sets cscope pre-path to get matches without being on the dir where "cscope.out" is:

function s:FindFile(file)
    let curdir = getcwd()
    let found = curdir
    while !filereadable(a:file) && found != "/"
        cd ..
        let found = getcwd()
    endwhile
    execute "cd " . curdir
    return found
endfunction

if has('cscope')    
    let $CSCOPE_DIR=s:FindFile("cscope.out")
    let $CSCOPE_DB=$CSCOPE_DIR."/cscope.out"
    if filereadable($CSCOPE_DB)
        cscope add $CSCOPE_DB $CSCOPE_DIR
    endif

    command -nargs=0 Cscope !cscope -ub -R &
endif

How to clear Tkinter Canvas?

Items drawn to the canvas are persistent. create_rectangle returns an item id that you need to keep track of. If you don't remove old items your program will eventually slow down.

From Fredrik Lundh's An Introduction to Tkinter:

Note that items added to the canvas are kept until you remove them. If you want to change the drawing, you can either use methods like coords, itemconfig, and move to modify the items, or use delete to remove them.

Fatal error: Call to undefined function: ldap_connect()

If you are a Windows user, this is a common error when you use XAMPP since LDAP is not enabled by default.

You can follow this steps to make sure LDAP works in your XAMPP:

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

     extension=php_ldap.dll
    
  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin (Note: moving the file is needed only for XAMPP prior to version: 5.6.28)

  • Restart Apache.

  • You can now use functions of the LDAP Module!

If you use Linux:

For php5:

sudo apt-get install php5-ldap

For php7:

sudo apt-get install php7.0-ldap

If you are using the latest version of PHP you can do

sudo apt-get install php-ldap

running the above command should do the trick.

if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap to uncomment, save and restart Apache

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

I ran into the above error when building and running inside Eclipse, where everything seemed to be fine, with the exception of this error. However, I discovered that a Maven build failed and that I needed to include Gson in my pom.xml. After fixing the pom.xml, everything fell into place.

JavaScript string newline character?

Email link function i use "%0D%0A"

function sendMail() {   
var bodydata="Before "+ "%0D%0A";
    bodydata+="After"

var MailMSG = "mailto:[email protected]" 
         + "[email protected]" 
         + "&subject=subject" 
         + "&body=" + bodydata; 
window.location.href = MailMSG; 
} 

[HTML]

<a href="#" onClick="sendMail()">Contact Us</a>

Java - Reading XML file

If using another library is an option, the following may be easier:

package for_so;

import java.io.File;

import rasmus_torkel.xml_basic.read.TagNode;
import rasmus_torkel.xml_basic.read.XmlReadOptions;
import rasmus_torkel.xml_basic.read.impl.XmlReader;

public class Q7704827_SimpleRead
{
    public static void
    main(String[] args)
    {
        String fileName = args[0];

        TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
        String recipient = emailNode.nextTextFieldE("recipient");
        String sender = emailNode.nextTextFieldE("sender");
        String subject = emailNode.nextTextFieldE("subject");
        String description = emailNode.nextTextFieldE("description");
        emailNode.verifyNoMoreChildren();

        System.out.println("recipient =  " + recipient);
        System.out.println("sender =     " + sender);
        System.out.println("subject =    " + subject);
        System.out.println("desciption = " + description);
    }
}

The library and its documentation are at rasmustorkel.com

Android - SMS Broadcast receiver

The Updated code is :

 private class SMSReceiver extends BroadcastReceiver {
                private Bundle bundle;
                private SmsMessage currentSMS;
                private String message;

                @Override
                public void onReceive(Context context, Intent intent) {

                    if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
                        bundle = intent.getExtras();
                        if (bundle != null) {
                            Object[] pdu_Objects = (Object[]) bundle.get("pdus");
                            if (pdu_Objects != null) {

                                for (Object aObject : pdu_Objects) {

                                    currentSMS = getIncomingMessage(aObject, bundle);

                                    String senderNo = currentSMS.getDisplayOriginatingAddress();

                                    message = currentSMS.getDisplayMessageBody();
                                    Toast.makeText(OtpActivity.this, "senderNum: " + senderNo + " :\n message: " + message, Toast.LENGTH_LONG).show();
                                }
                                this.abortBroadcast();
                                // End of loop
                            }
                        }
                    } // bundle null
                }
            }

        private SmsMessage getIncomingMessage(Object aObject, Bundle bundle) {
            SmsMessage currentSMS;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                String format = bundle.getString("format");
                currentSMS = SmsMessage.createFromPdu((byte[]) aObject, format);
            } else {
                currentSMS = SmsMessage.createFromPdu((byte[]) aObject);
            }
    return currentSMS;
}

older code was :

Object [] pdus = (Object[]) myBundle.get("pdus");

    messages = new SmsMessage[pdus.length];

    for (int i = 0; i < messages.length; i++)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String format = myBundle.getString("format");
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
        }
        else {
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
        }
        strMessage += "SMS From: " + messages[i].getOriginatingAddress();
        strMessage += " : ";
        strMessage += messages[i].getMessageBody();
        strMessage += "\n";
    } 

The simple SYntax of code is :

private class SMSReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
            SmsMessage[] smsMessages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
            for (SmsMessage message : smsMessages) {
                // Do whatever you want to do with SMS.
            }
        }
    }
}

Calculate the center point of multiple latitude/longitude coordinate pairs

I used a formula that I got from www.geomidpoint.com and wrote the following C++ implementation. The array and geocoords are my own classes whose functionality should be self-explanatory.

/*
 * midpoints calculated using formula from www.geomidpoint.com
 */
   geocoords geocoords::calcmidpoint( array<geocoords>& points )
   {
      if( points.empty() ) return geocoords();

      float cart_x = 0,
            cart_y = 0,
            cart_z = 0;

      for( auto& point : points )
      {
         cart_x += cos( point.lat.rad() ) * cos( point.lon.rad() );
         cart_y += cos( point.lat.rad() ) * sin( point.lon.rad() );
         cart_z += sin( point.lat.rad() );
      }

      cart_x /= points.numelems();
      cart_y /= points.numelems();
      cart_z /= points.numelems();

      geocoords mean;

      mean.lat.rad( atan2( cart_z, sqrt( pow( cart_x, 2 ) + pow( cart_y, 2 ))));
      mean.lon.rad( atan2( cart_y, cart_x ));

      return mean;
   }

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

Hello @sahil I update your answer for swift 3

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

Hope it's helpful. Thanks

MySQL Cannot Add Foreign Key Constraint

Check following rules :

  • First checks whether names are given right for table names

  • Second right data type give to foreign key ?

Execute action when back bar button of UINavigationController is pressed

One option would be implementing your own custom back button. You would need to add the following code to your viewDidLoad method:

- (void) viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = newBackButton;
}

- (void) back:(UIBarButtonItem *)sender {
    // Perform your custom actions
    // ...
    // Go back to the previous ViewController
    [self.navigationController popViewControllerAnimated:YES];
}

UPDATE:

Here is the version for Swift:

    override func viewDidLoad {
        super.viewDidLoad()
        self.navigationItem.hidesBackButton = true
        let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Bordered, target: self, action: "back:")
        self.navigationItem.leftBarButtonItem = newBackButton
    }

    func back(sender: UIBarButtonItem) {
        // Perform your custom actions
        // ...
        // Go back to the previous ViewController
        self.navigationController?.popViewControllerAnimated(true)
    }

UPDATE 2:

Here is the version for Swift 3:

    override func viewDidLoad {
        super.viewDidLoad()
        self.navigationItem.hidesBackButton = true
        let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(YourViewController.back(sender:)))
        self.navigationItem.leftBarButtonItem = newBackButton
    }

    func back(sender: UIBarButtonItem) {
        // Perform your custom actions
        // ...
        // Go back to the previous ViewController
        _ = navigationController?.popViewController(animated: true)
    }

How to implement authenticated routes in React Router 4?

Based on the answer of @Tyler McGinnis. I made a different approach using ES6 syntax and nested routes with wrapped components:

import React, { cloneElement, Children } from 'react'
import { Route, Redirect } from 'react-router-dom'

const PrivateRoute = ({ children, authed, ...rest }) =>
  <Route
    {...rest}
    render={(props) => authed ?
      <div>
        {Children.map(children, child => cloneElement(child, { ...child.props }))}
      </div>
      :
      <Redirect to={{ pathname: '/', state: { from: props.location } }} />}
  />

export default PrivateRoute

And using it:

<BrowserRouter>
  <div>
    <PrivateRoute path='/home' authed={auth}>
      <Navigation>
        <Route component={Home} path="/home" />
      </Navigation>
    </PrivateRoute>

    <Route exact path='/' component={PublicHomePage} />
  </div>
</BrowserRouter>

How to print the current time in a Batch-File?

This works with Windows 10, 8.x, 7, and possibly further back:

@echo Started: %date% %time%
.
.
.
@echo Completed: %date% %time%

Entity framework code-first null foreign key

I have the same problem now , I have foreign key and i need put it as nullable, to solve this problem you should put

    modelBuilder.Entity<Country>()
        .HasMany(c => c.Users)
        .WithOptional(c => c.Country)
        .HasForeignKey(c => c.CountryId)
        .WillCascadeOnDelete(false);

in DBContext class I am sorry for answer you very late :)

How to access JSON decoded array in PHP

As you're passing true as the second parameter to json_decode, in the above example you can retrieve data doing something similar to:

$myArray = json_decode($data, true);
echo $myArray[0]['id']; // Fetches the first ID
echo $myArray[0]['c_name']; // Fetches the first c_name
// ...
echo $myArray[2]['id']; // Fetches the third ID
// etc..

If you do NOT pass true as the second parameter to json_decode it would instead return it as an object:

echo $myArray[0]->id;

Python wildcard search in string

Why don't you just use the join function? In a regex findall() or group() you will need a string so:

import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, ' '.join(l)) #Syntax option 1
matches = regex.findall(' '.join(l)) #Syntax option 2

The join() function allows you to transform a list in a string. The single quote before join is what you will put in the middle of each string on list. When you execute this code part (' '.join(l)) you'll receive this:

'this is just a test'

So you can use the findal() function.

I know i am 7 years late, but i recently create an account because I'm studying and other people could have the same question. I hope this help you and others.


Update After @FélixBrunet comments:

import re
regex = re.compile(r'th.s')
l = ['this', 'is', 'just', 'a', 'test','th','s', 'this is']

matches2=[] #declare a list
for i in range(len(l)): #loop with the iterations = list l lenght. This avoid the first item commented by @Felix
if regex.findall(l[i]) != []: #if the position i is not an empty list do the next line. PS: remember regex.findall() command return a list.
    if l[i]== ''.join(regex.findall(l[i])): # If the string of i position of l list = command findall() i position so it'll allow the program do the next line - this avoid the second item commented by @Félix
        matches2.append(''.join(regex.findall(l[i]))) #adds in the list just the string in the matches2 list

print(matches2)

How to compare strings

You could use strcmp():

/* strcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char szKey[] = "apple";
  char szInput[80];
  do {
     printf ("Guess my favourite fruit? ");
     gets (szInput);
  } while (strcmp (szKey,szInput) != 0);
  puts ("Correct answer!");
  return 0;
}

Change text (html) with .animate

$("#test").hide(100, function() {
    $(this).html("......").show(100);
});

Updated:

Another easy way:

$("#test").fadeOut(400, function() {
    $(this).html("......").fadeIn(400);
});

How to add chmod permissions to file in Git?

Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644 or 755 (spelled (100644 and 100755; the 100 part means "regular file"):

diff --git a/path b/path
new file mode 100644

The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask setting, which would normally be 022 to remove write permission from "group" and "other", or 002 to remove write permission only from "other". It might also be 077 if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".


1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664 in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.

The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.

How to add buttons like refresh and search in ToolBar in Android?

Try to do this:

getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);

and if you made your custom toolbar (which i presume you did) then you can use the simplest way possible to do this:

toolbarTitle = (TextView)findViewById(R.id.toolbar_title);
toolbarSubTitle = (TextView)findViewById(R.id.toolbar_subtitle);
toolbarTitle.setText("Title");
toolbarSubTitle.setText("Subtitle");

Same goes for any other views you put in your toolbar. Hope it helps.

how to make a html iframe 100% width and height?

Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.

I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

How does HttpContext.Current.User.Identity.Name know which usernames exist?

For windows authentication

select your project.

Press F4

Disable "Anonymous Authentication" and enable "Windows Authentication"

enter image description here

AND/OR in Python?

For the updated question, you can replace what you want with something like:

someList = filter(lambda x: x not in ("a", "á", "à", "ã", "â"), someList)

filter evaluates every element of the list by passing it to the lambda provided. In this lambda we check if the element is not one of the characters provided, because these should stay in the list.

Alternatively, if the items in someList should be unique, you can make someList a set and do something like this:

someList = list(set(someList)-set(("a", "á", "à", "ã", "â")))

This essentially takes the difference between the sets, which does what you want, but also makes sure every element occurs only once, which is different from a list. Note you could store someList as a set from the beginning in this case, it will optimize things a bit.

Java integer to byte array

public static byte[] intToBytes(int x) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bos);
    out.writeInt(x);
    out.close();
    byte[] int_bytes = bos.toByteArray();
    bos.close();
    return int_bytes;
}

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

how to get list of port which are in use on the server

There are a lot of options and tools. If you just want a list of listening ports and their owner processes try.

netstat -bano

How to detect duplicate values in PHP array?

function array_not_unique( $a = array() )
{
  return array_diff_key( $a , array_unique( $a ) );
}

How to import CSV file data into a PostgreSQL table?

You can also use pgfutter, or, even better, pgcsv.

These tools create the table columns from you, based on the CSV header.

pgfutter is quite buggy, I'd recommend pgcsv.

Here's how to do it with pgcsv:

sudo pip install pgcsv
pgcsv --db 'postgresql://localhost/postgres?user=postgres&password=...' my_table my_file.csv

How can I view the Git history in Visual Studio Code?

Git Graph seems like a decent extension. After installing, you can open the graph view from the bottom status bar.

C# how to wait for a webpage to finish loading before continuing

yuna and bnl code failed in the case below;

failing example:

1st one waits for completed.but, 2nd one with the invokemember("submit") didnt . invoke works. but ReadyState.Complete acts like its Completed before its REALLY completed:

wb.Navigate(url);
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
   Application.DoEvents();
}
MessageBox.Show("ok this waits Complete");

//navigates to new page
wb.Document.GetElementById("formId").InvokeMember("submit");
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
   Application.DoEvents();
}
MessageBox.Show("webBrowser havent navigated  yet. it gave me previous page's html.");  
var html = wb.Document.GetElementsByTagName("HTML")[0].OuterHtml;

how to fix this unwanted situation:

usage

    public myForm1 {

        myForm1_load() { }

        // func to make browser wait is inside the Extended class More tidy.
        WebBrowserEX wbEX = new WebBrowserEX();

        button1_click(){
            wbEX.Navigate("site1.com");
            wbEX.waitWebBrowserToComplete(wb);

            wbEX.Document.GetElementById("input1").SetAttribute("Value", "hello");
            //submit does navigation
            wbEX.Document.GetElementById("formid").InvokeMember("submit");
            wbEX.waitWebBrowserToComplete(wb);
            // this actually waits for document Compelete. worked for me.

            var processedHtml = wbEX.Document.GetElementsByTagName("HTML")[0].OuterHtml;
            var rawHtml = wbEX.DocumentText;
         }
     }

//put this  extended class in your code.
//(ie right below form class, or seperate cs file doesnt matter)
public class WebBrowserEX : WebBrowser
{
   //ctor
   WebBrowserEX()
   {
     //wired aumatically here. we dont need to worry our sweet brain.
     this.DocumentCompleted += (o, e) => { webbrowserDocumentCompleted = true;};
   }
     //instead of checking  readState, get state from DocumentCompleted Event 
     // via bool value
     bool webbrowserDocumentCompleted = false;
     public void waitWebBrowserToComplete()
     {
       while (!webbrowserDocumentCompleted )
       { Application.DoEvents();  }
       webbrowserDocumentCompleted = false;
     }

 }

How can I list all foreign keys referencing a given table in SQL Server?

Mysql server has information_schema.REFERENTIAL_CONSTRAINTS table FYI, you can filter it by table name or referenced table name.

Swift double to string

In swift 3:

var a: Double = 1.5
var b: String = String(a)

"relocation R_X86_64_32S against " linking Error

Add -fPIC at the end of CMAKE_CXX_FLAGS and CMAKE_C_FLAG

Example:

set( CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} -Wall --std=c++11 -O3 -fPIC" )
set( CMAKE_C_FLAGS  "${CMAKE_C_FLAGS} -Wall -O3 -fPIC" )

This solved my issue.

Execute cmd command from VBScript

Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "cmd cd /d C:dir_test\file_test & sanity_check_env.bat arg1"

How can I hash a password in Java?

As of 2020, the most reliable password hashing algorithm in use, most likely to optimise its strength given any hardware, is Argon2id or Argon2i but not its Spring implementation.

The PBKDF2 standard includes the the CPU-greedy/computationally-expensive feature of the block cipher BCRYPT algo, and add its stream cipher capability. PBKDF2 was overwhelmed by the memory exponentially-greedy SCRYPT then by the side-channel-attack-resistant Argon2

Argon2 provides the necessary calibration tool to find optimized strength parameters given a target hashing time and the hardware used.

  • Argon2i is specialized in memory greedy hashing
  • Argon2d is specialized in CPU greedy hashing
  • Argon2id use both methods.

Memory greedy hashing would help against GPU use for cracking.

Spring security/Bouncy Castle implementation is not optimized and relatively week given what attacker could use. cf: Spring doc Argon2 and Scrypt

The currently implementation uses Bouncy castle which does not exploit parallelism/optimizations that password crackers will, so there is an unnecessary asymmetry between attacker and defender.

The most credible implementation in use for java is mkammerer's one,

a wrapper jar/library of the official native implementation written in C.

It is well written and simple to use.

The embedded version provides native builds for Linux, windows and OSX.

As an example, it is used by jpmorganchase in its tessera security project used to secure Quorum, its Ethereum cryptocurency implementation.

Here is an example:

    final char[] password = "a4e9y2tr0ngAnd7on6P১M°RD".toCharArray();
    byte[] salt = new byte[128];
    new SecureRandom().nextBytes(salt);
    final Argon2Advanced argon2 = Argon2Factory.createAdvanced(Argon2Factory.Argon2Types.ARGON2id);
    byte[] hash = argon2.rawHash(10, 1048576, 4, password, salt);

(see tessera)

Declare the lib in your POM:

<dependency>
    <groupId>de.mkammerer</groupId>
    <artifactId>argon2-jvm</artifactId>
    <version>2.7</version>
</dependency>

or with gradle:

compile 'de.mkammerer:argon2-jvm:2.7'

Calibration may be performed using de.mkammerer.argon2.Argon2Helper#findIterations

SCRYPT and Pbkdf2 algorithm might also be calibrated by writing some simple benchmark, but current minimal safe iterations values, will require higher hashing times.

How do I decode a base64 encoded string?

Simple:

byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);

Can anyone explain python's relative imports?

Checking it out in python3:

python -V
Python 3.6.5

Example1:

.
+-- parent.py
+-- start.py
+-- sub
    +-- relative.py

- start.py
import sub.relative

- parent.py
print('Hello from parent.py')

- sub/relative.py
from .. import parent

If we run it like this(just to make sure PYTHONPATH is empty):

PYTHONPATH='' python3 start.py

Output:

Traceback (most recent call last):
  File "start.py", line 1, in <module>
    import sub.relative
  File "/python-import-examples/so-example-v1/sub/relative.py", line 1, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/relative.py

- sub/relative.py
import parent

If we run it like this:

PYTHONPATH='' python3 start.py

Output:

Hello from parent.py

Example2:

.
+-- parent.py
+-- sub
    +-- relative.py
    +-- start.py

- parent.py
print('Hello from parent.py')

- sub/relative.py
print('Hello from relative.py')

- sub/start.py
import relative
from .. import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 2, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/start.py:

- sub/start.py
import relative
import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 3, in <module>
    import parent
ModuleNotFoundError: No module named 'parent'

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

Also it's better to use import from root folder, i.e.:

- sub/start.py
import sub.relative
import parent

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

AngularJS - Create a directive that uses ng-model

This is a little late answer, but I found this awesome post about NgModelController, which I think is exactly what you were looking for.

TL;DR - you can use require: 'ngModel' and then add NgModelController to your linking function:

link: function(scope, iElement, iAttrs, ngModelCtrl) {
  //TODO
}

This way, no hacks needed - you are using Angular's built-in ng-model

.htaccess mod_rewrite - how to exclude directory from rewrite rule

What you could also do is put a .htaccess file containing

RewriteEngine Off

In the folders you want to exclude from being rewritten (by the rules in a .htaccess file that's higher up in the tree). Simple but effective.

Graphviz: How to go from .dot to a graph?

dot -Tps input.dot > output.eps
dot -Tpng input.dot > output.png

PostScript output seems always there. I am not sure if dot has PNG output by default. This may depend on how you have built it.

private constructor

It's common when you want to implement a singleton. The class can have a static "factory method" that checks if the class has already been instantiated, and calls the constructor if it hasn't.

Bootstrap modal: close current, open new

$("#buttonid").click(function(){
    $('#modal_id_you_want_to_hid').modal('hide')
});

// same as above button id
$("#buttonid").click(function(){
$('#Modal_id_You_Want_to_Show').modal({backdrop: 'static', keyboard: false})});

How to communicate between iframe and the parent site?

You can also use

postMessage(message, '*');

Changing SQL Server collation to case insensitive from case sensitive?

You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.

Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.

You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.

You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.

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

In hibernate you need not bother about how to create table in SQL and you need not to remember connection ,prepared statement like that data is persisted in a database. So, basically it makes a developer's life easy.

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

How do I POST urlencoded form data with $http without jQuery?

Here is the way it should be (and please no backend changes ... certainly not ... if your front stack does not support application/x-www-form-urlencoded, then throw it away ... hopefully AngularJS does !

$http({
     method: 'POST',
     url: 'api_endpoint',
     headers: {'Content-Type': 'application/x-www-form-urlencoded'},
     data: 'username='+$scope.username+'&password='+$scope.password
 }).then(function(response) {
    // on success
 }, function(response) {
    // on error
 });

Works like a charm with AngularJS 1.5

People, let give u some advice:

  • use promises .then(success, error) when dealing with $http, forget about .sucess and .error callbacks (as they are being deprecated)

  • From the angularjs site here "You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go."

If your data model is more complex that just a username and a password, you can still do that (as suggested above)

$http({
     method: 'POST',
     url: 'api_endpoint',
     headers: {'Content-Type': 'application/x-www-form-urlencoded'},
     data: json_formatted_data,
     transformRequest: function(data, headers) {
          return transform_json_to_urlcoded(data); // iterate over fields and chain key=value separated with &, using encodeURIComponent javascript function
     }
}).then(function(response) {
  // on succes
}, function(response) {
  // on error
});

Document for the encodeURIComponent can be found here

Locking pattern for proper use of .NET MemoryCache

I assume this code has concurrency issues:

Actually, it's quite possibly fine, though with a possible improvement.

Now, in general the pattern where we have multiple threads setting a shared value on first use, to not lock on the value being obtained and set can be:

  1. Disastrous - other code will assume only one instance exists.
  2. Disastrous - the code that obtains the instance is not can only tolerate one (or perhaps a certain small number) concurrent operations.
  3. Disastrous - the means of storage is not thread-safe (e.g. have two threads adding to a dictionary and you can get all sorts of nasty errors).
  4. Sub-optimal - the overall performance is worse than if locking had ensured only one thread did the work of obtaining the value.
  5. Optimal - the cost of having multiple threads do redundant work is less than the cost of preventing it, especially since that can only happen during a relatively brief period.

However, considering here that MemoryCache may evict entries then:

  1. If it's disastrous to have more than one instance then MemoryCache is the wrong approach.
  2. If you must prevent simultaneous creation, you should do so at the point of creation.
  3. MemoryCache is thread-safe in terms of access to that object, so that is not a concern here.

Both of these possibilities have to be thought about of course, though the only time having two instances of the same string existing can be a problem is if you're doing very particular optimisations that don't apply here*.

So, we're left with the possibilities:

  1. It is cheaper to avoid the cost of duplicate calls to SomeHeavyAndExpensiveCalculation().
  2. It is cheaper not to avoid the cost of duplicate calls to SomeHeavyAndExpensiveCalculation().

And working that out can be difficult (indeed, the sort of thing where it's worth profiling rather than assuming you can work it out). It's worth considering here though that most obvious ways of locking on insert will prevent all additions to the cache, including those that are unrelated.

This means that if we had 50 threads trying to set 50 different values, then we'll have to make all 50 threads wait on each other, even though they weren't even going to do the same calculation.

As such, you're probably better off with the code you have, than with code that avoids the race-condition, and if the race-condition is a problem, you quite likely either need to handle that somewhere else, or need a different caching strategy than one that expels old entries†.

The one thing I would change is I'd replace the call to Set() with one to AddOrGetExisting(). From the above it should be clear that it probably isn't necessary, but it would allow the newly obtained item to be collected, reducing overall memory use and allowing a higher ratio of low generation to high generation collections.

So yeah, you could use double-locking to prevent concurrency, but either the concurrency isn't actually a problem, or your storing the values in the wrong way, or double-locking on the store would not be the best way to solve it.

*If you know only one each of a set of strings exists, you can optimise equality comparisons, which is about the only time having two copies of a string can be incorrect rather than just sub-optimal, but you'd want to be doing very different types of caching for that to make sense. E.g. the sort XmlReader does internally.

†Quite likely either one that stores indefinitely, or one that makes use of weak references so it will only expel entries if there are no existing uses.

Progress Bar with HTML and CSS

http://jsfiddle.net/cwZSW/1406/

_x000D_
_x000D_
#progress {_x000D_
    background: #333;_x000D_
    border-radius: 13px;_x000D_
    height: 20px;_x000D_
    width: 300px;_x000D_
    padding: 3px;_x000D_
}_x000D_
_x000D_
#progress:after {_x000D_
    content: '';_x000D_
    display: block;_x000D_
    background: orange;_x000D_
    width: 50%;_x000D_
    height: 100%;_x000D_
    border-radius: 9px;_x000D_
}
_x000D_
<div id="progress"></div>
_x000D_
_x000D_
_x000D_

Use superscripts in R axis labels

The other option in this particular case would be to type the degree symbol: °

R seems to handle it fine. Type Option-k on a Mac to get it. Not sure about other platforms.

How to tar certain file types in all subdirectories?

This will handle paths with spaces:

find ./ -type f -name "*.php" -o -name "*.html" -exec tar uvf myarchives.tar {} +

Suppress console output in PowerShell

Try redirecting the output like this:

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose >$null 2>&1

pthread function from a class

You'll have to give pthread_create a function that matches the signature it's looking for. What you're passing won't work.

You can implement whatever static function you like to do this, and it can reference an instance of c and execute what you want in the thread. pthread_create is designed to take not only a function pointer, but a pointer to "context". In this case you just pass it a pointer to an instance of c.

For instance:

static void* execute_print(void* ctx) {
    c* cptr = (c*)ctx;
    cptr->print();
    return NULL;
}


void func() {

    ...

    pthread_create(&t1, NULL, execute_print, &c[0]);

    ...
}

Eclipse error: "Editor does not contain a main type"

private int user_movie_matrix[][];Th. should be `private int user_movie_matrix[][];.

private int user_movie_matrix[][]; should be private static int user_movie_matrix[][];

cfiltering(numberOfUsers, numberOfMovies); should be new cfiltering(numberOfUsers, numberOfMovies);

Whether or not the code works as intended after these changes is beyond the scope of this answer; there were several syntax/scoping errors.

POST an array from an HTML form without javascript

check this one out.

<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">

<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">

<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">

<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">

it should end up like this in the $_POST[] array (PHP format for easy visualization)

$_POST[] = array(
    'firstname'=>'value',
    'lastname'=>'value',
    'email'=>'value',
    'address'=>'value',
    'tree' => array(
        'tree1'=>array(
            'fruit'=>'value',
            'height'=>'value'
        ),
        'tree2'=>array(
            'fruit'=>'value',
            'height'=>'value'
        ),
        'tree3'=>array(
            'fruit'=>'value',
            'height'=>'value'
        )
    )
)

What causes a java.lang.StackOverflowError

I was having the same issue

Role.java

 @ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY,cascade = CascadeType.ALL)
 Set<BusinessUnitMaster> businessUnits =new HashSet<>();

BusinessUnitMaster.java

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(
        name = "BusinessUnitRoles",
        joinColumns = {@JoinColumn(name = "unit_id", referencedColumnName = "record_id")},
        inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "record_id")}
)
private Set<Role> roles=new HashSet<>();

the problem is that when you create BusinessUnitMaster and Role you have to save the object for both sides for RoleService.java

roleRepository.save(role);

for BusinessUnitMasterService.java

businessUnitMasterRepository.save(businessUnitMaster);

How to sort by dates excel?

For example 8/12/1976. Copy your date column. Highlight the copied column and click Data> Text to Columns> Delimited> Next. In the delimiters column check "Other" and input / and then click Next and Finish. You'll have 3 columns and the first column will be 1/8. Highlight it and click the comma in the Number section and it will give you the month as 8.00, so then reduce it by clicking the comma in Home/Numbers and you'll now have 8 in the first column, 18 in the second column and 1976 in the third column. In the first empty cell to the right use the concatenate function and leave out the year column. If your month is column A, day is column B and year is column C, it will look like this: =concatenate(A2,"/",B2) and hit enter. It will look like 8/18, however, when you click on the cell you'll see the concatenate formula. Highlight the cell(s), then copy and paste special values. Now you can sort by date. It's really quick when you get the hang of it.

How to log SQL statements in Spring Boot?

use this code in the file application.properties:

#Enable logging for config troubeshooting
logging.level.org.hibernate.SQL=DEBUG
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

What is the purpose of the "role" attribute in HTML?

Is this role attribute necessary?

Answer: Yes.

  • The role attribute is necessary to support Accessible Rich Internet Applications (WAI-ARIA) to define roles in XML-based languages, when the languages do not define their own role attribute.
  • Although this is the reason the role attribute is published by the Protocols and Formats Working Group, the attribute has more general use cases as well.

It provides you:

  • Accessibility
  • Device adaptation
  • Server-side processing
  • Complex data description,...etc.

Replace multiple characters in a C# string

This is the shortest way:

myString = Regex.Replace(myString, @"[;,\t\r ]|[\n]{2}", "\n");

Insert, on duplicate update in PostgreSQL?

For merging small sets, using the above function is fine. However, if you are merging large amounts of data, I'd suggest looking into http://mbk.projects.postgresql.org

The current best practice that I'm aware of is:

  1. COPY new/updated data into temp table (sure, or you can do INSERT if the cost is ok)
  2. Acquire Lock [optional] (advisory is preferable to table locks, IMO)
  3. Merge. (the fun part)

Cannot execute script: Insufficient memory to continue the execution of the program

If you need to connect to LocalDB during development, you can use:

sqlcmd -S "(localdb)\MSSQLLocalDB" -d dbname -i file.sql

React fetch data in server before render

In React, props are used for component parameters not for handling data. There is a separate construct for that called state. Whenever you update state the component basically re-renders itself according to the new values.

var BookList = React.createClass({
  // Fetches the book list from the server
  getBookList: function() {
    superagent.get('http://localhost:3100/api/books')
      .accept('json')
      .end(function(err, res) {
        if (err) throw err;

        this.setBookListState(res);
      });
  },
  // Custom function we'll use to update the component state
  setBookListState: function(books) {
    this.setState({
      books: books.data
    });
  },
  // React exposes this function to allow you to set the default state
  // of your component
  getInitialState: function() {
    return {
      books: []
    };
  },
  // React exposes this function, which you can think of as the
  // constructor of your component. Call for your data here.
  componentDidMount: function() {
    this.getBookList();
  },
  render: function() {
    var books = this.state.books.map(function(book) {
      return (
        <li key={book.key}>{book.name}</li>
      );
    });

    return (
      <div>
        <ul>
          {books}
        </ul>
      </div>
    );
  }
});

What are the correct version numbers for C#?

  • C# 1.0 with Visual Studio.NET

  • C# 2.0 with Visual Studio 2005

  • C# 3.0 with Visual Studio 2008

  • C# 4.0 with Visual Studio 2010

  • C# 5.0 with Visual Studio 2012

  • C# 6.0 with Visual Studio 2015

  • C# 7.0 with Visual Studio 2017

  • C# 8.0 with Visual Studio 2019

Using the Web.Config to set up my SQL database connection string?

Here's a great overview on MSDN that covers how to do this.

In your web.config, add a connection string entry:

<connectionStrings>
  <add 
    name="MyConnectionString" 
    connectionString="Data Source=sergio-desktop\sqlexpress;Initial 
    Catalog=MyDatabase;User ID=userName;Password=password"
    providerName="System.Data.SqlClient"
  />
</connectionStrings>

Let's break down the component parts here:

Data Source is your server. In your case, a named SQL instance on sergio-desktop.

Initial Catalog is the default database queries should be executed against. For normal uses, this will be the database name.

For the authentication, we have a few options.

User ID and Password means using SQL credentials, not Windows, but still very simple - just go into your Security section of your SQL Server and create a new Login. Give it a username and password, and give it rights to your database. All the basic dialogs are very self-explanatory.

You can also use integrated security, which means your .NET application will try to connect to SQL using the credentials of the worker process. Check here for more info on that.

Finally, in code, you can get to your connection string by using:

ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString

Save Javascript objects in sessionStorage

Could you not 'stringify' your object...then use sessionStorage.setItem() to store that string representation of your object...then when you need it sessionStorage.getItem() and then use $.parseJSON() to get it back out?

Working example http://jsfiddle.net/pKXMa/

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

You should first take a look at this. This explains what happens when you import a package. For convenience:

The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package.

So PyCharm respects this by showing a warning message, so that the author can decide which of the modules get imported when * from the package is imported. Thus this seems to be useful feature of PyCharm (and in no way can it be called a bug, I presume). You can easily remove this warning by adding the names of the modules to be imported when your package is imported in the __all__ variable which is list, like this

__init__.py

from . import MyModule1, MyModule2, MyModule3
__all__ = [MyModule1, MyModule2, MyModule3]

After you add this, you can ctrl+click on these module names used in any other part of your project to directly jump to the declaration, which I often find very useful.

How to run a PowerShell script

If you only have PowerShell 1.0, this seems to do the trick well enough:

powershell -command - < c:\mypath\myscript.ps1

It pipes the script file to the PowerShell command line.

Proper usage of Java -D command-line parameters

That should be:

java -Dtest="true" -jar myApplication.jar

Then the following will return the value:

System.getProperty("test");

The value could be null, though, so guard against an exception using a Boolean:

boolean b = Boolean.parseBoolean( System.getProperty( "test" ) );

Note that the getBoolean method delegates the system property value, simplifying the code to:

if( Boolean.getBoolean( "test" ) ) {
   // ...
}

How to insert a character in a string at a certain position?

  public static void main(String[] args) {
    char ch='m';
    String str="Hello",k=String.valueOf(ch),b,c;

    System.out.println(str);

    int index=3;
    b=str.substring(0,index-1 );
    c=str.substring(index-1,str.length());
    str=b+k+c;
}

UNIX export command

When you execute a program the child program inherits its environment variables from the parent. For instance if $HOME is set to /root in the parent then the child's $HOME variable is also set to /root.

This only applies to environment variable that are marked for export. If you set a variable at the command-line like

$ FOO="bar"

That variable will not be visible in child processes. Not unless you export it:

$ export FOO

You can combine these two statements into a single one in bash (but not in old-school sh):

$ export FOO="bar"

Here's a quick example showing the difference between exported and non-exported variables. To understand what's happening know that sh -c creates a child shell process which inherits the parent shell's environment.

$ FOO=bar
$ sh -c 'echo $FOO'

$ export FOO
$ sh -c 'echo $FOO'
bar

Note: To get help on shell built-in commands use help export. Shell built-ins are commands that are part of your shell rather than independent executables like /bin/ls.

XAMPP permissions on Mac OS X?

You can also simply change Apache Conf file to a different User Name and keep the group:

Apache Conf Applications/Xammp/etc/..

User 'User' = your user name in Mac os x.

Group daemon

sudo chown -R 'User':daemon ~/Sites/wordpress 

sudo chmod -R g+w ~/Sites/wordpress

How can you find the height of text on an HTML canvas?

EDIT: Are you using canvas transforms? If so, you'll have to track the transformation matrix. The following method should measure the height of text with the initial transform.

EDIT #2: Oddly the code below does not produce correct answers when I run it on this StackOverflow page; it's entirely possible that the presence of some style rules could break this function.

The canvas uses fonts as defined by CSS, so in theory we can just add an appropriately styled chunk of text to the document and measure its height. I think this is significantly easier than rendering text and then checking pixel data and it should also respect ascenders and descenders. Check out the following:

var determineFontHeight = function(fontStyle) {
  var body = document.getElementsByTagName("body")[0];
  var dummy = document.createElement("div");
  var dummyText = document.createTextNode("M");
  dummy.appendChild(dummyText);
  dummy.setAttribute("style", fontStyle);
  body.appendChild(dummy);
  var result = dummy.offsetHeight;
  body.removeChild(dummy);
  return result;
};

//A little test...
var exampleFamilies = ["Helvetica", "Verdana", "Times New Roman", "Courier New"];
var exampleSizes = [8, 10, 12, 16, 24, 36, 48, 96];
for(var i = 0; i < exampleFamilies.length; i++) {
  var family = exampleFamilies[i];
  for(var j = 0; j < exampleSizes.length; j++) {
    var size = exampleSizes[j] + "pt";
    var style = "font-family: " + family + "; font-size: " + size + ";";
    var pixelHeight = determineFontHeight(style);
    console.log(family + " " + size + " ==> " + pixelHeight + " pixels high.");
  }
}

You'll have to make sure you get the font style correct on the DOM element that you measure the height of but that's pretty straightforward; really you should use something like

var canvas = /* ... */
var context = canvas.getContext("2d");
var canvasFont = " ... ";
var fontHeight = determineFontHeight("font: " + canvasFont + ";");
context.font = canvasFont;
/*
  do your stuff with your font and its height here.
*/

Delay/Wait in a test case of Xcode UI testing

Based on @Ted's answer, I've used this extension:

extension XCTestCase {

    // Based on https://stackoverflow.com/a/33855219
    func waitFor<T>(object: T, timeout: TimeInterval = 5, file: String = #file, line: UInt = #line, expectationPredicate: @escaping (T) -> Bool) {
        let predicate = NSPredicate { obj, _ in
            expectationPredicate(obj as! T)
        }
        expectation(for: predicate, evaluatedWith: object, handler: nil)

        waitForExpectations(timeout: timeout) { error in
            if (error != nil) {
                let message = "Failed to fulful expectation block for \(object) after \(timeout) seconds."
                let location = XCTSourceCodeLocation(filePath: file, lineNumber: line)
                let issue = XCTIssue(type: .assertionFailure, compactDescription: message, detailedDescription: nil, sourceCodeContext: .init(location: location), associatedError: nil, attachments: [])
                self.record(issue)
            }
        }
    }

}

You can use it like this

let element = app.staticTexts["Name of your element"]
waitFor(object: element) { $0.exists }

It also allows for waiting for an element to disappear, or any other property to change (by using the appropriate block)

waitFor(object: element) { !$0.exists } // Wait for it to disappear

How can I split a shell command over multiple lines when using an IF statement?

For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.


This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).

How do I adb pull ALL files of a folder present in SD Card

On Android 6 with ADB version 1.0.32, you have to put / behind the folder you want to copy. E.g adb pull "/sdcard/".

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

You want to be able to pass in a Class and get a type-safe instance of that class? Try the following:

public static void main(String [] args) throws Exception {
    String s = instanceOf(String.class);
}

public static <T> T instanceOf (Class<T> clazz) throws Exception {
    return clazz.newInstance();
}

Origin <origin> is not allowed by Access-Control-Allow-Origin

I was facing a problem while calling cross origin resource using ajax from chrome.

I have used node js and local http server to deploy my node js app.

I was getting error response, when I access cross origin resource

I found one solution on that ,

1) I have added below code to my app.js file

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");

2) In my html page called cross origin resource using $.getJSON();

$.getJSON("http://localhost:3000/users", function (data) {
    alert("*******Success*********");
    var response=JSON.stringify(data);
    alert("success="+response);
    document.getElementById("employeeDetails").value=response;
});

auto create database in Entity Framework Core

My answer is very similar to Ricardo's answer, but I feel that my approach is a little more straightforward simply because there is so much going on in his using function that I'm not even sure how exactly it works on a lower level.

So for those who want a simple and clean solution that creates a database for you where you know exactly what is happening under the hood, this is for you:

public Startup(IHostingEnvironment env)
{
    using (var client = new TargetsContext())
    {
        client.Database.EnsureCreated();
    }
}

This pretty much means that within the DbContext that you created (in this case, mine is called TargetsContext), you can use an instance of the DbContext to ensure that the tables defined with in the class are created when Startup.cs is run in your application.

How to convert a Java String to an ASCII byte array?

Convert string to ascii values.

   String test = "ABCD";

   for ( int i = 0; i < test.length(); ++i ) {
   char c = test.charAt( i );
   int j = (int) c;
   System.out.println(j);
   }

How to pass a user / password in ansible command

you can use --extra-vars like this:

$ ansible all --inventory=10.0.1.2, -m ping \
    --extra-vars "ansible_user=root ansible_password=yourpassword"

If you're authenticating to a Linux host that's joined to a Microsoft Active Directory domain, this command line works.

ansible --module-name ping --extra-vars 'ansible_user=domain\user ansible_password=PASSWORD' --inventory 10.10.6.184, all

How do I wait for an asynchronously dispatched block to finish?

I’ve recently come to this issue again and wrote the following category on NSObject:

@implementation NSObject (Testing)

- (void) performSelector: (SEL) selector
    withBlockingCallback: (dispatch_block_t) block
{
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [self performSelector:selector withObject:^{
        if (block) block();
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_release(semaphore);
}

@end

This way I can easily turn asynchronous call with a callback into a synchronous one in tests:

[testedObject performSelector:@selector(longAsyncOpWithCallback:)
    withBlockingCallback:^{
    STAssert…
}];

How to populate a dropdownlist with json data in jquery?

To populate ComboBox with JSON, you can consider using the: jqwidgets combobox, too.

Upload video files via PHP and save them in appropriate folder and have a database entry

"Could you suggest a simpler code main thing is uploading the file Data base entry is secondary"

^--- As per OP's request. ---^

Image and video uploading code (tested with PHP Version 5.4.17)

HTML form

<!DOCTYPE html>

<head>
<title></title>
</head>

<body>

<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

PHP handler (upload_file.php)

Change upload folder to preferred name. Presently saves to upload/

<?php

$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "audio/mp3")
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))

&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))

  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

How can I give access to a private GitHub repository?

If you are the owner it is simple:

  • Go to your repo and click the Settings button.
  • In the left menu click Collaborators
  • Then Add their name.

Then collaborator should visit this example repo link https://github.com/user/repo/invitations

Source: Github Docs.

CSS last-child selector: select last-element of specific class, not last child inside of parent?

What about this solution?

div.commentList > article.comment:not(:last-child):last-of-type
{
    color:red; /*or whatever...*/
}

How to remove constraints from my MySQL table?

For those that come here using MariaDB:

Note that MariaDB allows DROP CONSTRAINT statements in general, for example for dropping check constraints:

ALTER TABLE table_name
DROP CONSTRAINT constraint_name;

https://mariadb.com/kb/en/library/alter-table/