Programs & Examples On #Uniscribe

Add class to <html> with Javascript?

This should also work:

document.documentElement.className = 'myClass';

Compatibility.

Edit:

IE 10 reckons it's readonly; yet:

It worked!?

Opera works:

Works

I can also confirm it works in:

  • Chrome 26
  • Firefox 19.02
  • Safari 5.1.7

Change color of PNG image via CSS?

You might want to take a look at Icon fonts. http://css-tricks.com/examples/IconFont/

EDIT: I'm using Font-Awesome on my latest project. You can even bootstrap it. Simply put this in your <head>:

<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">

<!-- And if you want to support IE7, add this aswell -->
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome-ie7.min.css" rel="stylesheet">

And then go ahead and add some icon-links like this:

<a class="icon-thumbs-up"></a>

Here's the full cheat sheet

--edit--

Font-Awesome uses different class names in the new version, probably because this makes the CSS files drastically smaller, and to avoid ambiguous css classes. So now you should use:

<a class="fa fa-thumbs-up"></a>

EDIT 2:

Just found out github also uses its own icon font: Octicons It's free to download. They also have some tips on how to create your very own icon fonts.

Detecting installed programs via registry

In addition to all the registry keys mentioned above, you may also have to look at HKEY_CURRENT_USER\Software\Microsoft\Installer\Products for programs installed just for the current user.

Angular EXCEPTION: No provider for Http

All you need to do is to include the following libraries in tour app.module.ts and also include it in your imports:

import { HttpModule } from '@angular/http';

@NgModule({
  imports:    [ HttpModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

How do I work with dynamic multi-dimensional arrays in C?

With dynamic allocation, using malloc:

int** x;

x = malloc(dimension1_max * sizeof(*x));
for (int i = 0; i < dimension1_max; i++) {
  x[i] = malloc(dimension2_max * sizeof(x[0]));
}

//Writing values
x[0..(dimension1_max-1)][0..(dimension2_max-1)] = Value; 
[...]

for (int i = 0; i < dimension1_max; i++) {
  free(x[i]);
}
free(x);

This allocates an 2D array of size dimension1_max * dimension2_max. So, for example, if you want a 640*480 array (f.e. pixels of an image), use dimension1_max = 640, dimension2_max = 480. You can then access the array using x[d1][d2] where d1 = 0..639, d2 = 0..479.

But a search on SO or Google also reveals other possibilities, for example in this SO question

Note that your array won't allocate a contiguous region of memory (640*480 bytes) in that case which could give problems with functions that assume this. So to get the array satisfy the condition, replace the malloc block above with this:

int** x;
int* temp;

x = malloc(dimension1_max * sizeof(*x));
temp = malloc(dimension1_max * dimension2_max * sizeof(x[0]));
for (int i = 0; i < dimension1_max; i++) {
  x[i] = temp + (i * dimension2_max);
}

[...]

free(temp);
free(x);

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

When I had an error Access Error: 404 -- Not Found I fixed it by doing the following:

  1. Open command prompt and type "netstat -aon" (without the quotes)
  2. Search for port 8080 and look at its PID number/code.
  3. Open Task Manager (CTRL+ALT+DELETE), go to Services tab, and find the service with the exact PID number. Then right click it and stop the process.

Is there a kind of Firebug or JavaScript console debug for Android?

I sometimes print debugging output to the browser window. Using jQuery, you could send output messages to a display area on your page:

<div id='display'></div>

$('#display').text('array length: ' + myArray.length);

Or if you want to watch JavaScript variables without adding a display area to your page:

function debug(txt) {
    $('body').append("<div style='width:300px;background:orange;padding:3px;font-size:13px'>" + txt + "</div>");
}

Creating NSData from NSString in Swift

In swift 5

let data = Data(YourString.utf8)

ORA-12154 could not resolve the connect identifier specified

This is an old question but Oracle's latest installers are no improvement, so I recently found myself back in this swamp, thrashing around for several days ...

My scenario was SQL Server 2016 RTM. 32-bit Oracle 12c Open Client + ODAC was eventually working fine for Visual Studio Report Designer and Integration Services designer, and also SSIS packages run through SQL Server Agent (with 32-bit option). 64-bit was working fine for Report Portal when defining and Testing an Data Source, but running the reports always gave the dreaded "ORA-12154" error.

My final solution was to switch to an EZCONNECT connection string - this avoids the TNSNAMES mess altogether. Here's a link to a detailed description, but it's basically just: host:port/sid

http://www.oracledistilled.com/oracle-database/oracle-net/using-easy-connect-ezconnect-naming-method-to-connect-to-oracle-databases/

In case it helps anyone in the future (or I get stuck on this again), here are my Oracle install steps (the full horror):

Install Oracle drivers: Oracle Client 12c (32-bit) plus ODAC.

a. Download and unzip the following files from http://www.oracle.com/technetwork/database/enterprise-edition/downloads/database12c-win64-download-2297732.html and http://www.oracle.com/technetwork/database/windows/downloads/utilsoft-087491.html ):

i. winnt_12102_client32.zip

ii. ODAC112040Xcopy_32bit.zip

b. Run winnt_12102_client32\client32\setup.exe. For the Installation Type, choose Admin. For the installation location enter C:\Oracle\Oracle12. Accept other defaults.

c. Start a Command Prompt “As Administrator” and change directory (cd) to your ODAC112040Xcopy_32bit folder.

d. Enter the command: install.bat all C:\Oracle\Oracle12 odac

e. Copy the tnsnames.ora file from another machine to these folders: *

i. C:\Oracle\Oracle12\network\admin *

ii. C:\Oracle\Oracle12\product\12.1.0\client_1\network\admin *

Install Oracle Client 12c (x64) plus ODAC

a. Download and unzip the following files from http://www.oracle.com/technetwork/database/enterprise-edition/downloads/database12c-win64-download-2297732.html and http://www.oracle.com/technetwork/database/windows/downloads/index-090165.html ):

i. winx64_12102_client.zip

ii. ODAC121024Xcopy_x64.zip

b. Run winx64_12102_client\client\setup.exe. For the Installation Type, choose Admin. For the installation location enter C:\Oracle\Oracle12_x64. Accept other defaults.

c. Start a Command Prompt “As Administrator” and change directory (cd) to the C:\Software\Oracle Client\ODAC121024Xcopy_x64 folder.

d. Enter the command: install.bat all C:\Oracle\Oracle12_x64 odac

e. Copy the tnsnames.ora file from another machine to these folders: *

i. C:\Oracle\Oracle12_x64\network\admin *

ii. C:\Oracle\Oracle12_x64\product\12.1.0\client_1\network\admin *

* If you are going with the EZCONNECT method, then these steps are not required.

The ODAC installs are tricky and obscure - thanks to Dan English who gave me the method (detailed above) for that.

A simple scenario using wait() and notify() in java

The wait() and notify() methods are designed to provide a mechanism to allow a thread to block until a specific condition is met. For this I assume you're wanting to write a blocking queue implementation, where you have some fixed size backing-store of elements.

The first thing you have to do is to identify the conditions that you want the methods to wait for. In this case, you will want the put() method to block until there is free space in the store, and you will want the take() method to block until there is some element to return.

public class BlockingQueue<T> {

    private Queue<T> queue = new LinkedList<T>();
    private int capacity;

    public BlockingQueue(int capacity) {
        this.capacity = capacity;
    }

    public synchronized void put(T element) throws InterruptedException {
        while(queue.size() == capacity) {
            wait();
        }

        queue.add(element);
        notify(); // notifyAll() for multiple producer/consumer threads
    }

    public synchronized T take() throws InterruptedException {
        while(queue.isEmpty()) {
            wait();
        }

        T item = queue.remove();
        notify(); // notifyAll() for multiple producer/consumer threads
        return item;
    }
}

There are a few things to note about the way in which you must use the wait and notify mechanisms.

Firstly, you need to ensure that any calls to wait() or notify() are within a synchronized region of code (with the wait() and notify() calls being synchronized on the same object). The reason for this (other than the standard thread safety concerns) is due to something known as a missed signal.

An example of this, is that a thread may call put() when the queue happens to be full, it then checks the condition, sees that the queue is full, however before it can block another thread is scheduled. This second thread then take()'s an element from the queue, and notifies the waiting threads that the queue is no longer full. Because the first thread has already checked the condition however, it will simply call wait() after being re-scheduled, even though it could make progress.

By synchronizing on a shared object, you can ensure that this problem does not occur, as the second thread's take() call will not be able to make progress until the first thread has actually blocked.

Secondly, you need to put the condition you are checking in a while loop, rather than an if statement, due to a problem known as spurious wake-ups. This is where a waiting thread can sometimes be re-activated without notify() being called. Putting this check in a while loop will ensure that if a spurious wake-up occurs, the condition will be re-checked, and the thread will call wait() again.


As some of the other answers have mentioned, Java 1.5 introduced a new concurrency library (in the java.util.concurrent package) which was designed to provide a higher level abstraction over the wait/notify mechanism. Using these new features, you could rewrite the original example like so:

public class BlockingQueue<T> {

    private Queue<T> queue = new LinkedList<T>();
    private int capacity;
    private Lock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    public BlockingQueue(int capacity) {
        this.capacity = capacity;
    }

    public void put(T element) throws InterruptedException {
        lock.lock();
        try {
            while(queue.size() == capacity) {
                notFull.await();
            }

            queue.add(element);
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public T take() throws InterruptedException {
        lock.lock();
        try {
            while(queue.isEmpty()) {
                notEmpty.await();
            }

            T item = queue.remove();
            notFull.signal();
            return item;
        } finally {
            lock.unlock();
        }
    }
}

Of course if you actually need a blocking queue, then you should use an implementation of the BlockingQueue interface.

Also, for stuff like this I'd highly recommend Java Concurrency in Practice, as it covers everything you could want to know about concurrency related problems and solutions.

How to sort multidimensional array by column?

below solution worked for me in case of required number is float. Solution:

table=sorted(table,key=lambda x: float(x[5]))
for row in table[:]:
    Ntable.add_row(row)

'

Flask raises TemplateNotFound error even though template file exists

(Please note that the above accepted Answer provided for file/project structure is absolutely correct.)

Also..

In addition to properly setting up the project file structure, we have to tell flask to look in the appropriate level of the directory hierarchy.

for example..

    app = Flask(__name__, template_folder='../templates')
    app = Flask(__name__, template_folder='../templates', static_folder='../static')

Starting with ../ moves one directory backwards and starts there.

Starting with ../../ moves two directories backwards and starts there (and so on...).

Hope this helps

How to get a string between two characters?

You could use apache common library's StringUtils to do this.

import org.apache.commons.lang3.StringUtils;
...
String s = "test string (67)";
s = StringUtils.substringBetween(s, "(", ")");
....

JBoss AS 7: How to clean up tmp?

Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :

-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache 
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440

npm behind a proxy fails with status 403

For those using Jenkins or other CI server: it matters where you define your proxies, especially when they're different in your local development environment and the CI environment. In this case:

  • don't define proxies in project's .npmrc file. Or if you do, be sure to override the settings on CI server.
  • any other proxy settings might cause 403 Forbidden with little hint to the fact that you're using the wrong proxy. Check your gradle.properties or such and fix/override as necessary.

TLDR: define proxies not in the project but on the machine you're working on.

"query function not defined for Select2 undefined error"

It seems that your selector returns an undefined element (Therefore undefined error is returned)

In case the element really exists, you are calling select2 on an input element without supplying anything to select2, where it should fetch the data from. Typically, one calls .select2({data: [{id:"firstid", text:"firsttext"}]).

Select distinct using linq

You should override Equals and GetHashCode meaningfully, in this case to compare the ID:

public class LinqTest
{
    public int id { get; set; }
    public string value { get; set; }

    public override bool Equals(object obj)
    {
        LinqTest obj2 = obj as LinqTest;
        if (obj2 == null) return false;
        return id == obj2.id;
    }

    public override int GetHashCode()
    {
        return id;
    }
}

Now you can use Distinct:

List<LinqTest> uniqueIDs = myList.Distinct().ToList();

Angular Directive refresh on parameter change

What you're trying to do is to monitor the property of attribute in directive. You can watch the property of attribute changes using $observe() as follows:

angular.module('myApp').directive('conversation', function() {
  return {
    restrict: 'E',
    replace: true,
    compile: function(tElement, attr) {
      attr.$observe('typeId', function(data) {
            console.log("Updated data ", data);
      }, true);

    }
  };
});

Keep in mind that I used the 'compile' function in the directive here because you haven't mentioned if you have any models and whether this is performance sensitive.

If you have models, you need to change the 'compile' function to 'link' or use 'controller' and to monitor the property of a model changes, you should use $watch(), and take of the angular {{}} brackets from the property, example:

<conversation style="height:300px" type="convo" type-id="some_prop"></conversation>

And in the directive:

angular.module('myApp').directive('conversation', function() {
  return {
    scope: {
      typeId: '=',
    },
    link: function(scope, elm, attr) {

      scope.$watch('typeId', function(newValue, oldValue) {
          if (newValue !== oldValue) {
            // You actions here
            console.log("I got the new value! ", newValue);
          }
      }, true);

    }
  };
});

How can I color Python logging output?

Install the colorlog package, you can use colors in your log messages immediately:

  • Obtain a logger instance, exactly as you would normally do.
  • Set the logging level. You can also use the constants like DEBUG and INFO from the logging module directly.
  • Set the message formatter to be the ColoredFormatter provided by the colorlog library.
import colorlog

logger = colorlog.getLogger()
logger.setLevel(colorlog.colorlog.logging.DEBUG)

handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter())
logger.addHandler(handler)

logger.debug("Debug message")
logger.info("Information message")
logger.warning("Warning message")
logger.error("Error message")
logger.critical("Critical message")

output: enter image description here


UPDATE: extra info

Just update ColoredFormatter:

handler.setFormatter(colorlog.ColoredFormatter('%(log_color)s [%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S'))

output: enter image description here


Package:

pip install colorlog

output:

Collecting colorlog
  Downloading colorlog-4.6.2-py2.py3-none-any.whl (10.0 kB)
Installing collected packages: colorlog
Successfully installed colorlog-4.6.2

Android WSDL/SOAP service client

Android doesn't come with SOAP library. However, you can download 3rd party library here:
https://github.com/simpligility/ksoap2-android

If you need help using it, you might find this thread helpful:
How to call a .NET Webservice from Android using KSOAP2?

span with onclick event inside a tag

use onmouseup

try something like this

        <html>
        <head>
        <script type="text/javascript">
        function hide(){
        document.getElementById('span_hide').style.display="none";
        }
        </script>
        </head>

        <body>
        <a href="page" style="text-decoration:none;display:block;">
        <span   onmouseup="hide()" id="span_hide">Hide me</span>
        </a>
        </body>
        </html>

EDIT:

          <html>
        <head>
        <script type="text/javascript">
        $(document).ready(function(){
         $("a").click(function () { 
         $(this).fadeTo("fast", .5).removeAttr("href"); 
        });
        });
        function hide(){
        document.getElementById('span_hide').style.display="none";
        }
        </script>
        </head>

        <body>
        <a href="page.html" style="text-decoration:none;display:block;" onclick="return false" >
        <span   onmouseup="hide()" id="span_hide">Hide me</span>
        </a>
        </body>
        </html>

How to check the version of scipy

In [95]: import scipy

In [96]: scipy.__version__
Out[96]: '0.12.0'

In [104]: scipy.version.*version?
scipy.version.full_version
scipy.version.short_version
scipy.version.version

In [105]: scipy.version.full_version
Out[105]: '0.12.0'

In [106]: scipy.version.git_revision
Out[106]: 'cdd6b32233bbecc3e8cbc82531905b74f3ea66eb'

In [107]: scipy.version.release
Out[107]: True

In [108]: scipy.version.short_version
Out[108]: '0.12.0'

In [109]: scipy.version.version
Out[109]: '0.12.0'

See SciPy doveloper documentation for reference.

How do I get indices of N maximum values in a NumPy array?

Use:

from operator import itemgetter
from heapq import nlargest
result = nlargest(N, enumerate(your_list), itemgetter(1))

Now the result list would contain N tuples (index, value) where value is maximized.

How can a web application send push notifications to iOS devices?

Google Chrome now supports the W3C standard for push notifications.

http://www.w3.org/TR/push-api/

How to convert byte[] to InputStream?

Should be easy to find in the javadocs...

byte[] byteArr = new byte[] { 0xC, 0xA, 0xF, 0xE };
InputStream is = new ByteArrayInputStream(byteArr);

How to clear the cache of nginx?

For those who other solutions are not working, check if you're using a DNS service like CloudFlare. In that case activate the "Development Mode" or use the "Purge Cache" tool.

WCF Service Returning "Method Not Allowed"

Your browser is sending an HTTP GET request: Make sure you have the WebGet attribute on the operation in the contract:

[ServiceContract]
public interface IUploadService
{
    [WebGet()]
    [OperationContract]
    string TestGetMethod(); // This method takes no arguments, returns a string. Perfect for testing quickly with a browser.

    [OperationContract]
    void UploadFile(UploadedFile file); // This probably involves an HTTP POST request. Not so easy for a quick browser test.
 }

Installing J2EE into existing eclipse IDE

Go to Help -> Install new softwares-> add -> paste this link in location box http://download.eclipse.org/webtools/repository/luna/ install all new versions..

System.Data.OracleClient requires Oracle client software version 8.1.7

For me, the issue was some plugin in my Visual Studio started forcing my application into x64 64bit mode, so the Oracle driver wasn't being found as I had Oracle 32bit installed.

So if you are having this issue, try running Visual Studio in safemode (devenv /safemode). I could find that it was looking in SYSWOW64 for the ic.dll file by using the ProcMon app by SysInternals/Microsoft.

Update: For me it was the Telerik JustTrace product that was causing the issue, it was probably hooking in and affecting the runtime version somehow to do tracing.

Update2: It's not just JustTrace causing an issue, JustMock is causing the same processor mode issue. JustMock is easier to fix though: Click JustMock-> Disable Profiler and then my web app's oracle driver runs in the correct CPU mode. This might be fixed by Telerik in the future.

Launch Minecraft from command line - username and password as prefix

This answer is going to briefly explain how the native files are handled on the latest launcher.

As of 4/29/2017 the Minecraft launcher for Windows extracts all native files and places them info %APPDATA%\Local\Temp{random folder}. That folder is temporary and is deleted once the javaw.exe process finishes (when Minecraft is closed). The location of that temporary folder must be provided in the launch arguments as the value of

-Djava.library.path=

Also, the latest launcher (2.0.847) does not show you the launch arguments so if you need to check them yourself you can do so under the Task Manager (simply enable the Command Line tab and expand it) or by using the WMIC utility as explained here.

Hope this helps some people who are still interested in doing this in 2017.

No == operator found while comparing structs in C++

C++20 introduced default comparisons, aka the "spaceship" operator<=>, which allows you to request compiler-generated </<=/==/!=/>=/ and/or > operators with the obvious/naive(?) implementation...

auto operator<=>(const MyClass&) const = default;

...but you can customise that for more complicated situations (discussed below). See here for the language proposal, which contains justifications and discussion. This answer remains relevant for C++17 and earlier, and for insight in to when you should customise the implementation of operator<=>....

It may seem a bit unhelpful of C++ not to have already Standardised this earlier, but often structs/classes have some data members to exclude from comparison (e.g. counters, cached results, container capacity, last operation success/error code, cursors), as well as decisions to make about myriad things including but not limited to:

  • which fields to compare first, e.g. comparing a particular int member might eliminate 99% of unequal objects very quickly, while a map<string,string> member might often have identical entries and be relatively expensive to compare - if the values are loaded at runtime, the programmer may have insights the compiler can't possibly
  • in comparing strings: case sensitivity, equivalence of whitespace and separators, escaping conventions...
  • precision when comparing floats/doubles
  • whether NaN floating point values should be considered equal
  • comparing pointers or pointed-to-data (and if the latter, how to know how whether the pointers are to arrays and of how many objects/bytes needing comparison)
  • whether order matters when comparing unsorted containers (e.g. vector, list), and if so whether it's ok to sort them in-place before comparing vs. using extra memory to sort temporaries each time a comparison is done
  • how many array elements currently hold valid values that should be compared (is there a size somewhere or a sentinel?)
  • which member of a union to compare
  • normalisation: for example, date types may allow out-of-range day-of-month or month-of-year, or a rational/fraction object may have 6/8ths while another has 3/4ers, which for performance reasons they correct lazily with a separate normalisation step; you may have to decide whether to trigger a normalisation before comparison
  • what to do when weak pointers aren't valid
  • how to handle members and bases that don't implement operator== themselves (but might have compare() or operator< or str() or getters...)
  • what locks must be taken while reading/comparing data that other threads may want to update

So, it's kind of nice to have an error until you've explicitly thought about what comparison should mean for your specific structure, rather than letting it compile but not give you a meaningful result at run-time.

All that said, it'd be good if C++ let you say bool operator==() const = default; when you'd decided a "naive" member-by-member == test was ok. Same for !=. Given multiple members/bases, "default" <, <=, >, and >= implementations seem hopeless though - cascading on the basis of order of declaration's possible but very unlikely to be what's wanted, given conflicting imperatives for member ordering (bases being necessarily before members, grouping by accessibility, construction/destruction before dependent use). To be more widely useful, C++ would need a new data member/base annotation system to guide choices - that would be a great thing to have in the Standard though, ideally coupled with AST-based user-defined code generation... I expect it'll happen one day.

Typical implementation of equality operators

A plausible implementation

It's likely that a reasonable and efficient implementation would be:

inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return lhs.my_struct2 == rhs.my_struct2 &&
           lhs.an_int     == rhs.an_int;
}

Note that this needs an operator== for MyStruct2 too.

Implications of this implementation, and alternatives, are discussed under the heading Discussion of specifics of your MyStruct1 below.

A consistent approach to ==, <, > <= etc

It's easy to leverage std::tuple's comparison operators to compare your own class instances - just use std::tie to create tuples of references to fields in the desired order of comparison. Generalising my example from here:

inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return std::tie(lhs.my_struct2, lhs.an_int) ==
           std::tie(rhs.my_struct2, rhs.an_int);
}

inline bool operator<(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return std::tie(lhs.my_struct2, lhs.an_int) <
           std::tie(rhs.my_struct2, rhs.an_int);
}

// ...etc...

When you "own" (i.e. can edit, a factor with corporate and 3rd party libs) the class you want to compare, and especially with C++14's preparedness to deduce function return type from the return statement, it's often nicer to add a "tie" member function to the class you want to be able to compare:

auto tie() const { return std::tie(my_struct1, an_int); }

Then the comparisons above simplify to:

inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return lhs.tie() == rhs.tie();
}

If you want a fuller set of comparison operators, I suggest boost operators (search for less_than_comparable). If it's unsuitable for some reason, you may or may not like the idea of support macros (online):

#define TIED_OP(STRUCT, OP, GET_FIELDS) \
    inline bool operator OP(const STRUCT& lhs, const STRUCT& rhs) \
    { \
        return std::tie(GET_FIELDS(lhs)) OP std::tie(GET_FIELDS(rhs)); \
    }

#define TIED_COMPARISONS(STRUCT, GET_FIELDS) \
    TIED_OP(STRUCT, ==, GET_FIELDS) \
    TIED_OP(STRUCT, !=, GET_FIELDS) \
    TIED_OP(STRUCT, <, GET_FIELDS) \
    TIED_OP(STRUCT, <=, GET_FIELDS) \
    TIED_OP(STRUCT, >=, GET_FIELDS) \
    TIED_OP(STRUCT, >, GET_FIELDS)

...that can then be used a la...

#define MY_STRUCT_FIELDS(X) X.my_struct2, X.an_int
TIED_COMPARISONS(MyStruct1, MY_STRUCT_FIELDS)

(C++14 member-tie version here)

Discussion of specifics of your MyStruct1

There are implications to the choice to provide a free-standing versus member operator==()...

Freestanding implementation

You have an interesting decision to make. As your class can be implicitly constructed from a MyStruct2, a free-standing / non-member bool operator==(const MyStruct2& lhs, const MyStruct2& rhs) function would support...

my_MyStruct2 == my_MyStruct1

...by first creating a temporary MyStruct1 from my_myStruct2, then doing the comparison. This would definitely leave MyStruct1::an_int set to the constructor's default parameter value of -1. Depending on whether you include an_int comparison in the implementation of your operator==, a MyStruct1 might or might not compare equal to a MyStruct2 that itself compares equal to the MyStruct1's my_struct_2 member! Further, creating a temporary MyStruct1 can be a very inefficient operation, as it involves copying the existing my_struct2 member to a temporary, only to throw it away after the comparison. (Of course, you could prevent this implicit construction of MyStruct1s for comparison by making that constructor explicit or removing the default value for an_int.)

Member implementation

If you want to avoid implicit construction of a MyStruct1 from a MyStruct2, make the comparison operator a member function:

struct MyStruct1
{
    ...
    bool operator==(const MyStruct1& rhs) const
    {
        return tie() == rhs.tie(); // or another approach as above
    }
};

Note the const keyword - only needed for the member implementation - advises the compiler that comparing objects doesn't modify them, so can be allowed on const objects.

Comparing the visible representations

Sometimes the easiest way to get the kind of comparison you want can be...

    return lhs.to_string() == rhs.to_string();

...which is often very expensive too - those strings painfully created just to be thrown away! For types with floating point values, comparing visible representations means the number of displayed digits determines the tolerance within which nearly-equal values are treated as equal during comparison.

How do I fix 'ImportError: cannot import name IncompleteRead'?

For fixing pip3 (worked on Ubuntu 14.10):

easy_install3 -U pip

How to catch exception correctly from http.request()?

in the latest version of angular4 use

import { Observable } from 'rxjs/Rx'

it will import all the required things.

How do I format a string using a dictionary in python-3.x?

The Python 2 syntax works in Python 3 as well:

>>> class MyClass:
...     def __init__(self):
...         self.title = 'Title'
... 
>>> a = MyClass()
>>> print('The title is %(title)s' % a.__dict__)
The title is Title
>>> 
>>> path = '/path/to/a/file'
>>> print('You put your file here: %(path)s' % locals())
You put your file here: /path/to/a/file

Why use @Scripts.Render("~/bundles/jquery")

You can also use:

@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")

To specify the format of your output in a scenario where you need to use Charset, Type, etc.

Abstraction vs Encapsulation in Java

Abstraction is about identifying commonalities and reducing features that you have to work with at different levels of your code.

e.g. I may have a Vehicle class. A Car would derive from a Vehicle, as would a Motorbike. I can ask each Vehicle for the number of wheels, passengers etc. and that info has been abstracted and identified as common from Cars and Motorbikes.

In my code I can often just deal with Vehicles via common methods go(), stop() etc. When I add a new Vehicle type later (e.g. Scooter) the majority of my code would remain oblivious to this fact, and the implementation of Scooter alone worries about Scooter particularities.

How to prepare a Unity project for git?

On the Unity Editor open your project and:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository (only if Unity ver < 4.5)
  2. Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save Scene and Project from File menu.
  5. Quit Unity and then you can delete the Library and Temp directory in the project directory. You can delete everything but keep the Assets and ProjectSettings directory.

If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:

cd to/your/unity/project/folder

git init

git add *

git commit -m "First commit"

git remote add origin [email protected]:username/project.git

git push -u origin master

You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).

Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.

And here's my own .gitignore recipe for my Unity projects:

# =============== #
# Unity generated #
# =============== #
Temp/
Obj/
UnityGenerated/
Library/
Assets/AssetStoreTools*

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db

How to perform Unwind segue programmatically?

Backwards compatible solution that will work for versions prior to ios6, for those interested:

- (void)unwindToViewControllerOfClass:(Class)vcClass animated:(BOOL)animated {

    for (int i=self.navigationController.viewControllers.count - 1; i >= 0; i--) {
        UIViewController *vc = [self.navigationController.viewControllers objectAtIndex:i];
        if ([vc isKindOfClass:vcClass]) {
            [self.navigationController popToViewController:vc animated:animated];
            return;
        }
    }
}

Finding the 'type' of an input element

To check input type

<!DOCTYPE html>
<html>
<body>

    <input type=number id="txtinp">
    <button onclick=checktype()>Try it</button>

    <script>
        function checktype() 
        {
            alert(document.getElementById("txtinp").type);
        }
    </script>

</body>
</html> 

How do I start a program with arguments when debugging?

I came to this page because I have sensitive information in my command line parameters, and didn't want them stored in the code repository. I was using System Environment variables to hold the values, which could be set on each build or development machine as needed for each purpose. Environment Variable Expansion works great in Shell Batch processes, but not Visual Studio.

Visual Studio Start Options:

Visual Studio Start Options

However, Visual Studio wouldn't return the variable value, but the name of the variable.

Example of Issue:

Example of Error in Visual Studio

My final solution after trying several here on S.O. was to write a quick lookup for the Environment variable in my Argument Processor. I added a check for % in the incoming variable value, and if it's found, lookup the Environment Variable and replace the value. This works in Visual Studio, and in my Build Environment.

foreach (string thisParameter in args)
            {
                if (thisParameter.Contains("="))
                {
                    string parameter = thisParameter.Substring(0, thisParameter.IndexOf("="));
                    string value = thisParameter.Substring(thisParameter.IndexOf("=") + 1);

                    if (value.Contains("%"))
                    {   //Workaround for VS not expanding variables in debug
                        value = Environment.GetEnvironmentVariable(value.Replace("%", ""));
                    }

This allows me to use the same syntax in my sample batch files, and in debugging with Visual Studio. No account information or URLs saved in GIT.

Example Use in Batch

Batch File Example

How can I convert a Unix timestamp to DateTime and vice versa?

Here's what you need:

public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
    // Unix timestamp is seconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
    return dtDateTime;
}

Or, for Java (which is different because the timestamp is in milliseconds, not seconds):

public static DateTime JavaTimeStampToDateTime( double javaTimeStamp )
{
    // Java timestamp is milliseconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime();
    return dtDateTime;
}

How to fix "'System.AggregateException' occurred in mscorlib.dll"

The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.

Task.Factory.StartNew(x=>
   throw new Exception("I didn't account for this");
)

However, if we do this, at least the application does not crash.

Task.Factory.StartNew(x=>
   try {
      throw new Exception("I didn't account for this");
   }
   catch(Exception ex) {
      //Log ex
   }
)

ArrayList insertion and retrieval order

Yes, ArrayList is an ordered collection and it maintains the insertion order.

Check the code below and run it:

public class ListExample {

    public static void main(String[] args) {
        List<String> myList = new ArrayList<String>();
        myList.add("one");
        myList.add("two");
        myList.add("three");
        myList.add("four");
        myList.add("five");
    
        System.out.println("Inserted in 'order': ");
        printList(myList);
        System.out.println("\n");
        System.out.println("Inserted out of 'order': ");

        // Clear the list
        myList.clear();
    
        myList.add("four");
        myList.add("five");
        myList.add("one");
        myList.add("two");
        myList.add("three");
    
        printList(myList);
    }

    private static void printList(List<String> myList) {
        for (String string : myList) {
            System.out.println(string);
        }
    }
}

Produces the following output:

Inserted in 'order': 
one
two
three
four
five


Inserted out of 'order': 
four
five
one
two
three

For detailed information, please refer to documentation: List (Java Platform SE7)

Recursive sub folder search and return files in a list python

Your original solution was very nearly correct, but the variable "root" is dynamically updated as it recursively paths around. os.walk() is a recursive generator. Each tuple set of (root, subFolder, files) is for a specific root the way you have it setup.

i.e.

root = 'C:\\'
subFolder = ['Users', 'ProgramFiles', 'ProgramFiles (x86)', 'Windows', ...]
files = ['foo1.txt', 'foo2.txt', 'foo3.txt', ...]

root = 'C:\\Users\\'
subFolder = ['UserAccount1', 'UserAccount2', ...]
files = ['bar1.txt', 'bar2.txt', 'bar3.txt', ...]

...

I made a slight tweak to your code to print a full list.

import os
for root, subFolder, files in os.walk(PATH):
    for item in files:
        if item.endswith(".txt") :
            fileNamePath = str(os.path.join(root,item))
            print(fileNamePath)

Hope this helps!

EDIT: (based on feeback)

OP misunderstood/mislabeled the subFolder variable, as it is actually all the sub folders in "root". Because of this, OP, you're trying to do os.path.join(str, list, str), which probably doesn't work out like you expected.

To help add clarity, you could try this labeling scheme:

import os
for current_dir_path, current_subdirs, current_files in os.walk(RECURSIVE_ROOT):
    for aFile in current_files:
        if aFile.endswith(".txt") :
            txt_file_path = str(os.path.join(current_dir_path, aFile))
            print(txt_file_path)

Find all packages installed with easy_install/pip?

pip freeze will output a list of installed packages and their versions. It also allows you to write those packages to a file that can later be used to set up a new environment.

https://pip.pypa.io/en/stable/reference/pip_freeze/#pip-freeze

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

Try this:

/**
 * @(#)demo1.java
 *
 *
 * @author 
 * @version 1.00 2012/8/30
 */

import java.util.*;

public class demo1 
{
    Scanner s=new Scanner(System.in);

    String str;
    int key;

    void getdata()
    {
        System.out.println ("plase enter a string");
        str=s.next();
        System.out.println ("plase enter a key");
        key=s.nextInt();
    }

    void display()
    {
        char a;
        int j;
        for ( int i = 0; i < str.length(); ++i )
        {

            char c = str.charAt( i );
            j = (int) c + key;
            a= (char) j;

            System.out.print(a);  
        }

        public static void main(String[] args)
        {
            demo1 obj=new demo1();
            obj.getdata();
            obj.display();
        }
    }
}

Bootstrap 3: Keep selected tab on page refresh

I prefer storing the selected tab in the hashvalue of the window. This also enables sending links to colleagues, who than see "the same" page. The trick is to change the hash of the location when another tab is selected. If you already use # in your page, possibly the hash tag has to be split. In my app, I use ":" as hash value separator.

<ul class="nav nav-tabs" id="myTab">
  <li class="active"><a href="#home">Home</a></li>
  <li><a href="#profile">Profile</a></li>
  <li><a href="#messages">Messages</a></li>
  <li><a href="#settings">Settings</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="home">home</div>
  <div class="tab-pane" id="profile">profile</div>
  <div class="tab-pane" id="messages">messages</div>
  <div class="tab-pane" id="settings">settings</div>
</div>

JavaScript, has to be embedded after the above in a <script>...</script> part.

$('#myTab a').click(function(e) {
  e.preventDefault();
  $(this).tab('show');
});

// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
  var id = $(e.target).attr("href").substr(1);
  window.location.hash = id;
});

// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#myTab a[href="' + hash + '"]').tab('show');

The remote host closed the connection. The error code is 0x800704CD

I too got this same error on my image handler that I wrote. I got it like 30 times a day on site with heavy traffic, managed to reproduce it also. You get this when a user cancels the request (closes the page or his internet connection is interrupted for example), in my case in the following row:

myContext.Response.OutputStream.Write(buffer, 0, bytesRead);

I can’t think of any way to prevent it but maybe you can properly handle this. Ex:

        try
        {
            …
            myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
            …
        }catch (HttpException ex)
        {
            if (ex.Message.StartsWith("The remote host closed the connection."))
                ;//do nothing
            else
                //handle other errors
        }            
        catch (Exception e)
        {
            //handle other errors
        }
        finally
        {//close streams etc..
        }

Get all validation errors from Angular 2 FormGroup

// IF not populated correctly - you could get aggregated FormGroup errors object
let getErrors = (formGroup: FormGroup, errors: any = {}) {
  Object.keys(formGroup.controls).forEach(field => {
    const control = formGroup.get(field);
    if (control instanceof FormControl) {
      errors[field] = control.errors;
    } else if (control instanceof FormGroup) {
      errors[field] = this.getErrors(control);
    }
  });
  return errors;
}

// Calling it:
let formErrors = getErrors(this.form);

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

Setting TIME_WAIT TCP

In Windows, you can change it through the registry:

; Set the TIME_WAIT delay to 30 seconds (0x1E)

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\TCPIP\Parameters]
"TcpTimedWaitDelay"=dword:0000001E

Bigger Glyphicons

_x000D_
_x000D_
<button class="btn btn-default glyphicon glyphicon-plus fa-2x" type="button">_x000D_
</button>_x000D_
_x000D_
<!--fa-2x , fa-3x , fa-4x ... -->_x000D_
<button class="btn btn-default glyphicon glyphicon-plus fa-3x" type="button">_x000D_
</button>
_x000D_
_x000D_
_x000D_

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

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

How to open warning/information/error dialog in Swing?

JOptionPane.showOptionDialog
JOptionPane.showMessageDialog
....

Have a look on this tutorial on how to make dialogs.

What is an unsigned char?

unsigned char is the heart of all bit trickery. In almost ALL compiler for ALL platform an unsigned char is simply a byte and an unsigned integer of (usually) 8 bits that can be treated as a small integer or a pack of bits.

In addiction, as someone else has said, the standard doesn't define the sign of a char. so you have 3 distinct char types: char, signed char, unsigned char.

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

If you trust the host, either add the valid certificate, specify --no-check-certificate or add:

check_certificate = off

into your ~/.wgetrc.

In some rare cases, your system time could be out-of-sync therefore invalidating the certificates.

Difference between multitasking, multithreading and multiprocessing?

Multitasking (Time sharing):

Time shared systems allows many users to share the computer simultaneously.

Return positions of a regex match() in Javascript?

Here is a cool feature I discovered recently, I tried this on the console and it seems to work:

var text = "border-bottom-left-radius";

var newText = text.replace(/-/g,function(match, index){
    return " " + index + " ";
});

Which returned: "border 6 bottom 13 left 18 radius"

So this seems to be what you are looking for.

What is middleware exactly?

There is a common definition in web application development which is (and I'm making this wording up but it seems to fit): A component which is designed to modify an HTTP request and/or response but does not (usually) serve the response in its entirety, designed to be chained together to form a pipeline of behavioral changes during request processing.

Examples of tasks that are commonly implemented by middleware:

  • Gzip response compression
  • HTTP authentication
  • Request logging

The key point here is that none of these is fully responsible for responding to the client. Instead each changes the behavior in some way as part of the pipeline, leaving the actual response to come from something later in the sequence (pipeline).

Usually, the middlewares are run before some sort of "router", which examines the request (often the path) and calls the appropriate code to generate the response.

Personally, I hate the term "middleware" for its genericity but it is in common use.

Here is an additional explanation specifically applicable to Ruby on Rails.

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

This could be solved without VBA by the following technique.

In this example I am counting all the threes (3) in the range A:A of the sheets Page M904, Page M905 and Page M906.

List all the sheet names in a single continuous range like in the following example. Here listed in the range D3:D5.

enter image description here

Then by having the lookup value in cell B2, the result can be found in cell B4 by using the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D3:D5&"'!A:A"), B2))

Is there a way to SELECT and UPDATE rows at the same time?

It'd be easier to do your UPDATE first and then run 'SELECT ID FROM INSERTED'.

Take a look at SQL Tips for more info and examples.

How to get overall CPU usage (e.g. 57%) on Linux

Take a look at cat /proc/stat

grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'

EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.

NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.

Current CPU usage can be potentially calculated with:

awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)

How do I set path while saving a cookie value in JavaScript?

simply: document.cookie="name=value;path=/";

There is a negative point to it

Now, the cookie will be available to all directories on the domain it is set from. If the website is just one of many at that domain, it’s best not to do this because everyone else will also have access to your cookie information.

Importing files from different folder

The code below imports the Python script given by it's path, no matter where it is located, in a Python version-save way:

def import_module_by_path(path):
    name = os.path.splitext(os.path.basename(path))[0]
    if sys.version_info[0] == 2:   
        # Python 2
        import imp
        return imp.load_source(name, path)
    elif sys.version_info[:2] <= (3, 4):  
        # Python 3, version <= 3.4
        from importlib.machinery import SourceFileLoader
        return SourceFileLoader(name, path).load_module()
    else:                            
        # Python 3, after 3.4
        import importlib.util
        spec = importlib.util.spec_from_file_location(name, path)
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
        return mod

This code is not written by me; I found it in the codebase of psutils, in psutils.test.__init__.py (line 1042; permalink to most recent commit as of 09.10.2020).

Usage example:

script = "/home/username/Documents/some_script.py"
some_module = import_module_by_path(script)
print(some_module.foo())

Caveat: The module will be treated as top-level. If it's a submodule of some bigger project, then relative imports from parent packages will fail.

Deserializing JSON data to C# using JSON.NET

Assuming your sample data is correct, your givenname, and other entries wrapped in brackets are arrays in JS... you'll want to use List for those data types. and List for say accountstatusexpmaxdate... I think you example has the dates incorrectly formatted though, so uncertain as to what else is incorrect in your example.

This is an old post, but wanted to make note of the issues.

How to find the nearest parent of a Git branch?

The solutions based on git show-branch -a plus some filters have one downside: git may consider a branch name of a short lived branch.

If you have a few possible parents which you care about, you can ask yourself this similar question (and probably the one the OP wanted to know about):

From a specific subset of all branches, which is the nearest parent of a git branch?

To simplify, I'll consider "a git branch" to refer to HEAD (i.e., the current branch).

Let's imagine that we have the following branches:

HEAD
important/a
important/b
spam/a
spam/b

The solutions based on git show-branch -a + filters, may give that the nearest parent of HEAD is spam/a, but we don't care about that.

If we want to know which of important/a and important/b is the closest parent of HEAD, we could run the following:

for b in $(git branch -a -l "important/*"); do
    d1=$(git rev-list --first-parent ^${b} HEAD |wc -l);
    d2=$(git rev-list --first-parent ^HEAD ${b} |wc -l);
    echo "${b} ${d1} ${d2}";
done \
|sort -n -k2 -k3 \
|head -n1 \
|awk '{print $1}';

What it does:

1.) $(git branch -a -l "important/*"): Print a list of all branches with some pattern ("important/*").

2.) d=$(git rev-list --first-parent ^${b} HEAD |wc -l);: For each of those branches ($b), calculate the distance ($d1) in number of commits, from HEAD to the nearest commit in $b (similar to when you calculate the distance from a point to a line). You may want to consider the distance differently here: you may not want to use --first-parent, or may want distance from tip to the tip of the branches ("${b}"...HEAD), ...

2.2) d2=$(git rev-list --first-parent ^HEAD ${b} |wc -l);: For each of those branches ($b), calculate the distance ($d2) in number of commits from the tip of the branch to the nearest commit in HEAD. We will use this distance to choose between two branches whose distance $d1 was equal.

3.) echo "${b} ${d1} ${d2}";: Print the name of each of the branches, followed by the distances to be able to sort them later (first $d1, and then $d2).

4.) |sort -n -k2 -k3: Sort the previous result, so we get a sorted (by distance) list of all of the branches, followed by their distances (both).

5.) |head -n1: The first result of the previous step will be the branch that has a smaller distance, i.e., the closest parent branch. So just discard all other branches.

6.) |awk '{print $1}';: We only care about the branch name, and not about the distance, so extract the first field, which was the parent's name. Here it is! :)

URL rewriting with PHP

You can essentially do this 2 ways:

The .htaccess route with mod_rewrite

Add a file called .htaccess in your root folder, and add something like this:

RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1

This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:

The PHP route

Put the following in your .htaccess instead: (note the leading slash)

FallbackResource /index.php

This will tell it to run your index.php for all files it cannot normally find in your site. In there you can then for example:

$path = ltrim($_SERVER['REQUEST_URI'], '/');    // Trim leading slash(es)
$elements = explode('/', $path);                // Split path on slashes
if(empty($elements[0])) {                       // No path elements means home
    ShowHomepage();
} else switch(array_shift($elements))             // Pop off first item and switch
{
    case 'Some-text-goes-here':
        ShowPicture($elements); // passes rest of parameters to internal function
        break;
    case 'more':
        ...
    default:
        header('HTTP/1.1 404 Not Found');
        Show404Error();
}

This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess will do fine though.

How to increase space between dotted border dots

This is an old, but still very relevant topic. The current top answer works well, but only for very small dots. As Bhojendra Rauniyar already pointed out in the comments, for larger (>2px) dots, the dots appear square, not round. I found this page searching for spaced dots, not spaced squares (or even dashes, as some answers here use).

Building on this, I used radial-gradient. Also, using the answer from Ukuser32, the dot-properties can easily be repeated for all four borders. Only the corners are not perfect.

_x000D_
_x000D_
div {_x000D_
    padding: 1em;_x000D_
    background-image:_x000D_
        radial-gradient(circle at 2.5px, #000 1.25px, rgba(255,255,255,0) 2.5px),_x000D_
        radial-gradient(circle, #000 1.25px, rgba(255,255,255,0) 2.5px),_x000D_
        radial-gradient(circle at 2.5px, #000 1.25px, rgba(255,255,255,0) 2.5px),_x000D_
        radial-gradient(circle, #000 1.25px, rgba(255,255,255,0) 2.5px);_x000D_
    background-position: top, right, bottom, left;_x000D_
    background-size: 15px 5px, 5px 15px;_x000D_
    background-repeat: repeat-x, repeat-y;_x000D_
}
_x000D_
<div>Some content with round, spaced dots as border</div>
_x000D_
_x000D_
_x000D_

The radial-gradient expects:

  • the shape and optional position
  • two or more stops: a color and radius

Here, I wanted a 5 pixel diameter (2.5px radius) dot, with 2 times the diameter (10px) between the dots, adding up to 15px. The background-size should match these.

The two stops are defined such that the dot is nice and smooth: solid black for half the radius and than a gradient to the full radius.

Jquery post, response in new window

Use the write()-Method of the Popup's document to put your markup there:

$.post(url, function (data) {
    var w = window.open('about:blank');
    w.document.open();
    w.document.write(data);
    w.document.close();
});

Plot width settings in ipython notebook

If you're not in an ipython notebook (like the OP), you can also just declare the size when you declare the figure:

width = 12
height = 12
plt.figure(figsize=(width, height))

Scanner vs. StringTokenizer vs. String.Split

They're essentially horses for courses.

  • Scanner is designed for cases where you need to parse a string, pulling out data of different types. It's very flexible, but arguably doesn't give you the simplest API for simply getting an array of strings delimited by a particular expression.
  • String.split() and Pattern.split() give you an easy syntax for doing the latter, but that's essentially all that they do. If you want to parse the resulting strings, or change the delimiter halfway through depending on a particular token, they won't help you with that.
  • StringTokenizer is even more restrictive than String.split(), and also a bit fiddlier to use. It is essentially designed for pulling out tokens delimited by fixed substrings. Because of this restriction, it's about twice as fast as String.split(). (See my comparison of String.split() and StringTokenizer.) It also predates the regular expressions API, of which String.split() is a part.

You'll note from my timings that String.split() can still tokenize thousands of strings in a few milliseconds on a typical machine. In addition, it has the advantage over StringTokenizer that it gives you the output as a string array, which is usually what you want. Using an Enumeration, as provided by StringTokenizer, is too "syntactically fussy" most of the time. From this point of view, StringTokenizer is a bit of a waste of space nowadays, and you may as well just use String.split().

Sticky and NON-Sticky sessions

When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.

However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.

Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.

If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.

To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.

As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html

How to update values in a specific row in a Python Pandas DataFrame?

In SQL, I would have do it in one shot as

update table1 set col1 = new_value where col1 = old_value

but in Python Pandas, we could just do this:

data = [['ram', 10], ['sam', 15], ['tam', 15]] 
kids = pd.DataFrame(data, columns = ['Name', 'Age']) 
kids

which will generate the following output :

    Name    Age
0   ram     10
1   sam     15
2   tam     15

now we can run:

kids.loc[kids.Age == 15,'Age'] = 17
kids

which will show the following output

Name    Age
0   ram     10
1   sam     17
2   tam     17

which should be equivalent to the following SQL

update kids set age = 17 where age = 15

Parsing JSON Array within JSON Object

mainJSON.getJSONArray("source") returns a JSONArray, hence you can remove the new JSONArray.

The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)

Try this:

JSONArray jsonMainArr = mainJSON.getJSONArray("source"); 

How to get element-wise matrix multiplication (Hadamard product) in numpy?

Try this:

a = np.matrix([[1,2], [3,4]])
b = np.matrix([[5,6], [7,8]])

#This would result a 'numpy.ndarray'
result = np.array(a) * np.array(b)

Here, np.array(a) returns a 2D array of type ndarray and multiplication of two ndarray would result element wise multiplication. So the result would be:

result = [[5, 12], [21, 32]]

If you wanna get a matrix, the do it with this:

result = np.mat(result)

Using Helvetica Neue in a Website

I'd recommend this article on CSS Tricks by Chris Coyier entitled Better Helvetica:

http://css-tricks.com/snippets/css/better-helvetica/

He basically recommends the following declaration for covering all the bases:

body {
    font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; 
    font-weight: 300;
}

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

12 is a compile-time constant which can not be changed unlike the data referenced by int&. What you can do is

const int& z = 12;

Font.createFont(..) set color and size (java.awt.Font)

Well, once you have your font, you can invoke deriveFont. For example,

helvetica = helvetica.deriveFont(Font.BOLD, 12f);

Changes the font's style to bold and its size to 12 points.

JavaScript: Get image dimensions

if you have image file from your input form. you can use like this

let images = new Image();
images.onload = () => {
 console.log("Image Size", images.width, images.height)
}
images.onerror = () => result(true);

let fileReader = new FileReader();
fileReader.onload = () => images.src = fileReader.result;
fileReader.onerror = () => result(false);
if (fileTarget) {
   fileReader.readAsDataURL(fileTarget);
}

How to remove the hash from window.location (URL) with JavaScript without page refresh?

(Too many answers are redundant and outdated.) The best solution now is this:

history.replaceState(null, null, ' ');

How to add multiple jar files in classpath in linux

Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do

$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java

To run do

$java -cp .:a.jar:b.jar:c.jar HelloWorld

How to create a HTTP server in Android?

If you are using kotlin,consider these library. It's build for kotlin language.

AndroidHttpServer is a simple demo using ServerSocket to handle http request

https://github.com/weeChanc/AndroidHttpServer

https://github.com/ktorio/ktor

AndroidHttpServer is very small , but the feature is less as well.

Ktor is a very nice library,and the usage is simple too

HTML5 Canvas Rotate Image

As @markE mention in his answer

the alternative is to untranslate & unrotate after drawing

It is much faster than context save and restore.

Here is an example

// translate and rotate
this.context.translate(x,y);
this.context.rotate(radians);
this.context.translate(-x,-y);

this.context.drawImage(...);    

// untranslate and unrotate
this.context.translate(x, y);
this.context.rotate(-radians);
this.context.translate(-x,-y);

How to create custom spinner like border around the spinner with down triangle on the right side?

It's super easy you can just add this to your Adapter -> getDropDownView

getDropDownView:

convertView.setBackground(getContext().getResources().getDrawable(R.drawable.bg_spinner_dropdown));

bg_spinner_dropdown:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/white" />
    <corners
        android:bottomLeftRadius=enter code here"25dp"
        android:bottomRightRadius="25dp"
        android:topLeftRadius="25dp"
        android:topRightRadius="25dp" />
</shape>

Virtual Memory Usage from Java under Linux, too much memory used

This has been a long-standing complaint with Java, but it's largely meaningless, and usually based on looking at the wrong information. The usual phrasing is something like "Hello World on Java takes 10 megabytes! Why does it need that?" Well, here's a way to make Hello World on a 64-bit JVM claim to take over 4 gigabytes ... at least by one form of measurement.

java -Xms1024m -Xmx4096m com.example.Hello

Different Ways to Measure Memory

On Linux, the top command gives you several different numbers for memory. Here's what it says about the Hello World example:

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 2120 kgregory  20   0 4373m  15m 7152 S    0  0.2   0:00.10 java
  • VIRT is the virtual memory space: the sum of everything in the virtual memory map (see below). It is largely meaningless, except when it isn't (see below).
  • RES is the resident set size: the number of pages that are currently resident in RAM. In almost all cases, this is the only number that you should use when saying "too big." But it's still not a very good number, especially when talking about Java.
  • SHR is the amount of resident memory that is shared with other processes. For a Java process, this is typically limited to shared libraries and memory-mapped JARfiles. In this example, I only had one Java process running, so I suspect that the 7k is a result of libraries used by the OS.
  • SWAP isn't turned on by default, and isn't shown here. It indicates the amount of virtual memory that is currently resident on disk, whether or not it's actually in the swap space. The OS is very good about keeping active pages in RAM, and the only cures for swapping are (1) buy more memory, or (2) reduce the number of processes, so it's best to ignore this number.

The situation for Windows Task Manager is a bit more complicated. Under Windows XP, there are "Memory Usage" and "Virtual Memory Size" columns, but the official documentation is silent on what they mean. Windows Vista and Windows 7 add more columns, and they're actually documented. Of these, the "Working Set" measurement is the most useful; it roughly corresponds to the sum of RES and SHR on Linux.

Understanding the Virtual Memory Map

The virtual memory consumed by a process is the total of everything that's in the process memory map. This includes data (eg, the Java heap), but also all of the shared libraries and memory-mapped files used by the program. On Linux, you can use the pmap command to see all of the things mapped into the process space (from here on out I'm only going to refer to Linux, because it's what I use; I'm sure there are equivalent tools for Windows). Here's an excerpt from the memory map of the "Hello World" program; the entire memory map is over 100 lines long, and it's not unusual to have a thousand-line list.

0000000040000000     36K r-x--  /usr/local/java/jdk-1.6-x64/bin/java
0000000040108000      8K rwx--  /usr/local/java/jdk-1.6-x64/bin/java
0000000040eba000    676K rwx--    [ anon ]
00000006fae00000  21248K rwx--    [ anon ]
00000006fc2c0000  62720K rwx--    [ anon ]
0000000700000000 699072K rwx--    [ anon ]
000000072aab0000 2097152K rwx--    [ anon ]
00000007aaab0000 349504K rwx--    [ anon ]
00000007c0000000 1048576K rwx--    [ anon ]
...
00007fa1ed00d000   1652K r-xs-  /usr/local/java/jdk-1.6-x64/jre/lib/rt.jar
...
00007fa1ed1d3000   1024K rwx--    [ anon ]
00007fa1ed2d3000      4K -----    [ anon ]
00007fa1ed2d4000   1024K rwx--    [ anon ]
00007fa1ed3d4000      4K -----    [ anon ]
...
00007fa1f20d3000    164K r-x--  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
00007fa1f20fc000   1020K -----  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
00007fa1f21fb000     28K rwx--  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
...
00007fa1f34aa000   1576K r-x--  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3634000   2044K -----  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3833000     16K r-x--  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3837000      4K rwx--  /lib/x86_64-linux-gnu/libc-2.13.so
...

A quick explanation of the format: each row starts with the virtual memory address of the segment. This is followed by the segment size, permissions, and the source of the segment. This last item is either a file or "anon", which indicates a block of memory allocated via mmap.

Starting from the top, we have

  • The JVM loader (ie, the program that gets run when you type java). This is very small; all it does is load in the shared libraries where the real JVM code is stored.
  • A bunch of anon blocks holding the Java heap and internal data. This is a Sun JVM, so the heap is broken into multiple generations, each of which is its own memory block. Note that the JVM allocates virtual memory space based on the -Xmx value; this allows it to have a contiguous heap. The -Xms value is used internally to say how much of the heap is "in use" when the program starts, and to trigger garbage collection as that limit is approached.
  • A memory-mapped JARfile, in this case the file that holds the "JDK classes." When you memory-map a JAR, you can access the files within it very efficiently (versus reading it from the start each time). The Sun JVM will memory-map all JARs on the classpath; if your application code needs to access a JAR, you can also memory-map it.
  • Per-thread data for two threads. The 1M block is the thread stack. I didn't have a good explanation for the 4k block, but @ericsoe identified it as a "guard block": it does not have read/write permissions, so will cause a segment fault if accessed, and the JVM catches that and translates it to a StackOverFlowError. For a real app, you will see dozens if not hundreds of these entries repeated through the memory map.
  • One of the shared libraries that holds the actual JVM code. There are several of these.
  • The shared library for the C standard library. This is just one of many things that the JVM loads that are not strictly part of Java.

The shared libraries are particularly interesting: each shared library has at least two segments: a read-only segment containing the library code, and a read-write segment that contains global per-process data for the library (I don't know what the segment with no permissions is; I've only seen it on x64 Linux). The read-only portion of the library can be shared between all processes that use the library; for example, libc has 1.5M of virtual memory space that can be shared.

When is Virtual Memory Size Important?

The virtual memory map contains a lot of stuff. Some of it is read-only, some of it is shared, and some of it is allocated but never touched (eg, almost all of the 4Gb of heap in this example). But the operating system is smart enough to only load what it needs, so the virtual memory size is largely irrelevant.

Where virtual memory size is important is if you're running on a 32-bit operating system, where you can only allocate 2Gb (or, in some cases, 3Gb) of process address space. In that case you're dealing with a scarce resource, and might have to make tradeoffs, such as reducing your heap size in order to memory-map a large file or create lots of threads.

But, given that 64-bit machines are ubiquitous, I don't think it will be long before Virtual Memory Size is a completely irrelevant statistic.

When is Resident Set Size Important?

Resident Set size is that portion of the virtual memory space that is actually in RAM. If your RSS grows to be a significant portion of your total physical memory, it might be time to start worrying. If your RSS grows to take up all your physical memory, and your system starts swapping, it's well past time to start worrying.

But RSS is also misleading, especially on a lightly loaded machine. The operating system doesn't expend a lot of effort to reclaiming the pages used by a process. There's little benefit to be gained by doing so, and the potential for an expensive page fault if the process touches the page in the future. As a result, the RSS statistic may include lots of pages that aren't in active use.

Bottom Line

Unless you're swapping, don't get overly concerned about what the various memory statistics are telling you. With the caveat that an ever-growing RSS may indicate some sort of memory leak.

With a Java program, it's far more important to pay attention to what's happening in the heap. The total amount of space consumed is important, and there are some steps that you can take to reduce that. More important is the amount of time that you spend in garbage collection, and which parts of the heap are getting collected.

Accessing the disk (ie, a database) is expensive, and memory is cheap. If you can trade one for the other, do so.

Responsive Bootstrap Jumbotron Background Image

The simplest way is to set the background-size CSS property to cover:

.jumbotron {
  background-image: url("../img/jumbotron_bg.jpg");
  background-size: cover;
}

Program "make" not found in PATH

If you are using GNU MCU Eclipse on Windows, make sure Windows Build Tools are installed, then check the installation path and fill the "Global Build Tools Path" inside Eclipse Window/Preferences... :

Global Build Tools Path

IN vs OR in the SQL WHERE Clause

I think oracle is smart enough to convert the less efficient one (whichever that is) into the other. So I think the answer should rather depend on the readability of each (where I think that IN clearly wins)

Find the differences between 2 Excel worksheets?

COUNTIF works well for quick difference-checking. And it's easier to remember and simpler to work with than VLOOKUP.

=COUNTIF([Book1]Sheet1!$A:$A, A1) 

will give you a column showing 1 if there's match and zero if there's no match (with the bonus of showing >1 for duplicates within the list itself).

Get current AUTO_INCREMENT value for any table

You can get all of the table data by using this query:

SHOW TABLE STATUS FROM `DatabaseName` WHERE `name` LIKE 'TableName' ;

You can get exactly this information by using this query:

SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND   TABLE_NAME   = 'TableName';

Prevent double submission of forms in jQuery

My solution:

// jQuery plugin to prevent double submission of forms
$.fn.preventDoubleSubmission = function () {
    var $form = $(this);

    $form.find('[type="submit"]').click(function () {
        $(this).prop('disabled', true);
        $form.submit();
    });

    // Keep chainability
    return this;
};

How do I redirect to another webpage?

Write the below code after the PHP, HTML or jQuery section. If in the middle of the PHP or HTML section, then use the <script> tag.

location.href = "http://google.com"

How to test enum types?

you can test if have exactly some values, by example:

for(MyBoolean b : MyBoolean.values()) {
    switch(b) {
    case TRUE:
        break;
    case FALSE:
        break;
    default:
        throw new IllegalArgumentException(b.toString());
}

for(String s : new String[]{"TRUE", "FALSE" }) {
    MyBoolean.valueOf(s);
}

If someone removes or adds a value, some of test fails.

Android - running a method periodically using postDelayed() call

final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        //Do something after 100ms
        Toast.makeText(c, "check", Toast.LENGTH_SHORT).show();  
        handler.postDelayed(this, 2000);
      }
    }, 1500);

How do I output an ISO 8601 formatted string in JavaScript?

If you don't need to support IE7, the following is a great, concise hack:

JSON.parse(JSON.stringify(new Date()))

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

File SongsTableSeeder.php should be in database/seeds directory or in its subdirectory.

You need to run:

composer dump-autoload

and then:

php artisan db:seed

or:

php artisan db:seed --class=SongsTableSeeder

How can I test an AngularJS service from the console?

Angularjs Dependency Injection framework is responsible for injecting the dependancies of you app module to your controllers. This is possible through its injector.

You need to first identify the ng-app and get the associated injector. The below query works to find your ng-app in the DOM and retrieve the injector.

angular.element('*[ng-app]').injector()

In chrome, however, you can point to target ng-app as shown below. and use the $0 hack and issue angular.element($0).injector()

Once you have the injector, get any dependency injected service as below

injector = angular.element($0).injector();
injector.get('$mdToast');

enter image description here

How using try catch for exception handling is best practice

An exception is a blocking error.

First of all, the best practice should be don't throw exceptions for any kind of error, unless it's a blocking error.

If the error is blocking, then throw the exception. Once the exception is already thrown, there's no need to hide it because it's exceptional; let the user know about it (you should reformat the whole exception to something useful to the user in the UI).

Your job as software developer is to endeavour to prevent an exceptional case where some parameter or runtime situation may end in an exception. That is, exceptions mustn't be muted, but these must be avoided.

For example, if you know that some integer input could come with an invalid format, use int.TryParse instead of int.Parse. There is a lot of cases where you can do this instead of just saying "if it fails, simply throw an exception".

Throwing exceptions is expensive.

If, after all, an exception is thrown, instead of writing the exception to the log once it has been thrown, one of best practices is catching it in a first-chance exception handler. For example:

  • ASP.NET: Global.asax Application_Error
  • Others: AppDomain.FirstChanceException event.

My stance is that local try/catches are better suited for handling special cases where you may translate an exception into another, or when you want to "mute" it for a very, very, very, very, very special case (a library bug throwing an unrelated exception that you need to mute in order to workaround the whole bug).

For the rest of the cases:

  • Try to avoid exceptions.
  • If this isn't possible: first-chance exception handlers.
  • Or use a PostSharp aspect (AOP).

Answering to @thewhiteambit on some comment...

@thewhiteambit said:

Exceptions are not Fatal-Errors, they are Exceptions! Sometimes they are not even Errors, but to consider them Fatal-Errors is completely false understanding of what Exceptions are.

First of all, how an exception can't be even an error?

  • No database connection => exception.
  • Invalid string format to parse to some type => exception
  • Trying to parse JSON and while input isn't actually JSON => exception
  • Argument null while object was expected => exception
  • Some library has a bug => throws an unexpected exception
  • There's a socket connection and it gets disconnected. Then you try to send a message => exception
  • ...

We might list 1k cases of when an exception is thrown, and after all, any of the possible cases will be an error.

An exception is an error, because at the end of the day it is an object which collects diagnostic information -- it has a message and it happens when something goes wrong.

No one would throw an exception when there's no exceptional case. Exceptions should be blocking errors because once they're thrown, if you don't try to fall into the use try/catch and exceptions to implement control flow they mean your application/service will stop the operation that entered into an exceptional case.

Also, I suggest everyone to check the fail-fast paradigm published by Martin Fowler (and written by Jim Shore). This is how I always understood how to handle exceptions, even before I got to this document some time ago.

[...] consider them Fatal-Errors is completely false understanding of what exceptions are.

Usually exceptions cut some operation flow and they're handled to convert them to human-understandable errors. Thus, it seems like an exception actually is a better paradigm to handle error cases and work on them to avoid an application/service complete crash and notify the user/consumer that something went wrong.

More answers about @thewhiteambit concerns

For example in case of a missing Database-Connection the program could exceptionally continue with writing to a local file and send the changes to the Database once it is available again. Your invalid String-To-Number casting could be tried to parse again with language-local interpretation on Exception, like as you try default English language to Parse("1,5") fails and you try it with German interpretation again which is completely fine because we use comma instead of point as separator. You see these Exceptions must not even be blocking, they only need some Exception-handling.

  1. If your app might work offline without persisting data to database, you shouldn't use exceptions, as implementing control flow using try/catch is considered as an anti-pattern. Offline work is a possible use case, so you implement control flow to check if database is accessible or not, you don't wait until it's unreachable.

  2. The parsing thing is also an expected case (not EXCEPTIONAL CASE). If you expect this, you don't use exceptions to do control flow!. You get some metadata from the user to know what his/her culture is and you use formatters for this! .NET supports this and other environments too, and an exception because number formatting must be avoided if you expect a culture-specific usage of your application/service.

An unhandled Exception usually becomes an Error, but Exceptions itself are not codeproject.com/Articles/15921/Not-All-Exceptions-Are-Errors

This article is just an opinion or a point of view of the author.

Since Wikipedia can be also just the opinion of articule author(s), I wouldn't say it's the dogma, but check what Coding by exception article says somewhere in some paragraph:

[...] Using these exceptions to handle specific errors that arise to continue the program is called coding by exception. This anti-pattern can quickly degrade software in performance and maintainability.

It also says somewhere:

Incorrect exception usage

Often coding by exception can lead to further issues in the software with incorrect exception usage. In addition to using exception handling for a unique problem, incorrect exception usage takes this further by executing code even after the exception is raised. This poor programming method resembles the goto method in many software languages but only occurs after a problem in the software is detected.

Honestly, I believe that software can't be developed don't taking use cases seriously. If you know that...

  • Your database can go offline...
  • Some file can be locked...
  • Some formatting might be not supported...
  • Some domain validation might fail...
  • Your app should work in offline mode...
  • whatever use case...

...you won't use exceptions for that. You would support these use cases using regular control flow.

And if some unexpected use case isn't covered, your code will fail fast, because it'll throw an exception. Right, because an exception is an exceptional case.

In the other hand, and finally, sometimes you cover exceptional cases throwing expected exceptions, but you don't throw them to implement control flow. You do it because you want to notify upper layers that you don't support some use case or your code fails to work with some given arguments or environment data/properties.

ImageButton in Android

You don't have to use it using src attribute

Wrong way (The image won't fit the button)

android:src="@drawable/myimage"

Right way is to use background atttribute

<ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/skin" />

where skin is an xml

skin.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- <item android:drawable="@drawable/button_disabled" android:state_enabled="false"/> -->
    <item android:drawable="@drawable/button_pressed" android:state_pressed="true"/>
    <!-- <item android:drawable="@drawable/button_focused" android:state_focused="true"/> -->
    <item android:drawable="@drawable/button_normal"/>

</selector>

using button_pressed.png and button_normal.png

This will also help you in creating your skinned button with 4 states of pressed , normal , disabled and focussed. Make sure to keep same sizes of all pngs

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

I believe fcntl() is a POSIX function. Where as ioctl() is a standard UNIX thing. Here is a list of POSIX io. ioctl() is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl() stuff might only work on certain OS or even certain revs of it's kernel.

JSON string to JS object

You can use eval(jsonString) if you trust the data in the string, otherwise you'll need to parse it properly - check json.org for some code samples.

Drop view if exists

DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS 
SELECT * from {TableName}  
Go

Remove empty elements from an array in Javascript

For removing holes, you should use

arr.filter(() => true)
arr.flat(0) // New in ES2019, check compatibility before using this

For removing hole, null, and, undefined:

arr.filter(x => x != null)

For removing hole, and, falsy (null, undefined, 0, -0, 0n, NaN, "", false, document.all) values:

arr.filter(x => x)

_x000D_
_x000D_
arr = [, null, (void 0), 0, -0, 0n, NaN, false, '', 42];
console.log(arr.filter(() => true)); // [null, (void 0), 0, -0, 0n, NaN, false, '', 42]
console.log(arr.filter(x => x != null)); // [0, -0, 0n, NaN, false, "", 42]
console.log(arr.filter(x => x)); // [42]
_x000D_
_x000D_
_x000D_

Find out free space on tablespace

The following query will help to find out free space of tablespaces in MB:

select tablespace_name , sum(bytes)/1024/1024 from dba_free_space group by tablespacE_name order by 1;

Select box arrow style

http://jsfiddle.net/u3cybk2q/2/ check on windows, iOS and Android (iexplorer patch)

_x000D_
_x000D_
.styled-select select {_x000D_
   background: transparent;_x000D_
   width: 240px;_x000D_
   padding: 5px;_x000D_
   font-size: 16px;_x000D_
   line-height: 1;_x000D_
   border: 0;_x000D_
   border-radius: 0;_x000D_
   height: 34px;_x000D_
   -webkit-appearance: none;_x000D_
}_x000D_
.styled-select {_x000D_
   width: 240px;_x000D_
   height: 34px;_x000D_
   overflow: visible;_x000D_
   background: url(http://nightly.enyojs.com/latest/lib/moonstone/dist/moonstone/images/caret-black-small-down-icon.png) no-repeat right #FFF;_x000D_
   border: 1px solid #ccc;_x000D_
}_x000D_
.styled-select select::-ms-expand {_x000D_
    display: none;_x000D_
}
_x000D_
<div class="styled-select">_x000D_
   <select>_x000D_
      <option>Here is the first option</option>_x000D_
      <option>The second option</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Plot yerr/xerr as shaded region rather than error bars

This is basically the same answer provided by Evert, but extended to show-off some cool options of fill_between

enter image description here

from matplotlib import pyplot as pl
import numpy as np

pl.clf()
pl.hold(1)

x = np.linspace(0, 30, 100)
y = np.sin(x) * 0.5
pl.plot(x, y, '-k')


x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape) +.1
y += np.random.normal(0, 0.1, size=y.shape)

pl.plot(x, y, 'k', color='#CC4F1B')
pl.fill_between(x, y-error, y+error,
    alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848')

y = np.cos(x/6*np.pi)    
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#1B2ACC')
pl.fill_between(x, y-error, y+error,
    alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',
    linewidth=4, linestyle='dashdot', antialiased=True)



y = np.cos(x/6*np.pi)  + np.sin(x/3*np.pi)  
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#3F7F4C')
pl.fill_between(x, y-error, y+error,
    alpha=1, edgecolor='#3F7F4C', facecolor='#7EFF99',
    linewidth=0)



pl.show()

Preventing an image from being draggable or selectable without using JS

You could set the image as a background image. Since it resides in a div, and the div is undraggable, the image will be undraggable:

<div style="background-image: url("image.jpg");">
</div>

How to insert a new line in Linux shell script?

echo $'Create the snapshots\nSnapshot created\n'

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

maybe you forget to add parameter dataType:'json' in your $.ajax

$.ajax({
   type: "POST",
   dataType: "json",
   url: url,
   data: { get_member: id },
   success: function( response ) 
   { 
     //some action here
   },
   error: function( error )
   {
     alert( error );
   }
});

MySQL Install: ERROR: Failed to build gem native extension

I had a similar experience, so here are the things that I tried

Firstly, I tried to install mysql's required packages by running the command below in my terminal

sudo apt-get install build-essential libmysqlclient-dev

Secondly, I tried updating rubygems on my system by running the command below in my terminal

sudo gem update --system

But I was still experiencing the same issue. After much research I realized that I was using an almost out-of-date version of the mysql gem. I simply needed to use the mysql2 gem (mysql2 gem)and not the mysql gem, so I fixed it by running the command below in my terminal

gem install mysql2

This worked fine for me. Before running the last command, ensure that you've ran the first and second commands to be sure that everything is fine on your system.

That's all.

I hope this helps

What difference does .AsNoTracking() make?

AsNoTracking() allows the "unique key per record" requirement in EF to be bypassed (not mentioned explicitly by other answers).

This is extremely helpful when reading a View that does not support a unique key because perhaps some fields are nullable or the nature of the view is not logically indexable.

For these cases the "key" can be set to any non-nullable column but then AsNoTracking() must be used with every query else records (duplicate by key) will be skipped.

How to retrieve the current value of an oracle sequence without increment it?

If your use case is that some backend code inserts a record, then the same code wants to retrieve the last insert id, without counting on any underlying data access library preset function to do this, then, as mentioned by others, you should just craft your SQL query using SEQ_MY_NAME.NEXTVAL for the column you want (usually the primary key), then just run statement SELECT SEQ_MY_NAME.CURRVAL FROM dual from the backend.

Remember, CURRVAL is only callable if NEXTVAL has been priorly invoked, which is all naturally done in the strategy above...

AngularJS Directive Restrict A vs E

One of the pitfalls as I know is IE problem with custom elements. As quoted from the docs:

3) you do not use custom element tags such as (use the attribute version instead)

4) if you do use custom element tags, then you must take these steps to make IE 8 and below happy

<!doctype html>
  <html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="optionalModuleName">
    <head>
      <!--[if lte IE 8]>
        <script>
          document.createElement('ng-include');
          document.createElement('ng-pluralize');
          document.createElement('ng-view');

          // Optionally these for CSS
          document.createElement('ng:include');
          document.createElement('ng:pluralize');
          document.createElement('ng:view');
        </script>
      <![endif]-->
    </head>
    <body>
      ...
    </body>
  </html>

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

HTML Input Type Date, Open Calendar by default

This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.

<input type="date" data-date-inline-picker="true" />

Here is a small demo

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

... Could not load file or assembly 'X' or one of its dependencies ...

Most likely it fails to load another dependency.

you could try to check the dependencies with a dependency walker.

I.e: https://www.dependencywalker.com/

Also check your build configuration (x86 / 64)

Edit: I also had this problem once when I was copying dlls in zip from a "untrusted" network share. The file was locked by Windows and the FileNotFoundException was raised.

See here: Detected DLLs that are from the internet and "blocked" by CASPOL

How to regex in a MySQL query

I think you can use REGEXP instead of LIKE

SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')

Add Custom Headers using HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
{
    const string WEBSERVICE_URL = "<<Web Service URL>>";
    try
    {
        var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
        if (webRequest != null)
        {
            webRequest.Method = "GET";
            webRequest.Timeout = 20000;
            webRequest.ContentType = "application/json";
            webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
            using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                {
                    var jsonResponse = sr.ReadToEnd();
                    Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Long Press in JavaScript?

The Diodeus's answer is awesome, but it prevent you to add a onClick function, it'll never run hold function if you put an onclick. And the Razzak's answer is almost perfect, but it run hold function only on mouseup, and generally, the function runs even if user keep holding.

So, I joined both, and made this:

$(element).on('click', function () {
    if(longpress) { // if detect hold, stop onclick function
        return false;
    };
});

$(element).on('mousedown', function () {
    longpress = false; //longpress is false initially
    pressTimer = window.setTimeout(function(){
    // your code here

    longpress = true; //if run hold function, longpress is true
    },1000)
});

$(element).on('mouseup', function () {
    clearTimeout(pressTimer); //clear time on mouseup
});

Why do I need to do `--set-upstream` all the time?

By the way, the shortcut to pushing the current branch to a remote with the same name:

$ git push -u origin HEAD

Creating SVG graphics using Javascript?

This answer is from 2009. Now a community wiki in case anybody cares to bring it up-to-date.

IE needs a plugin to display SVG. Most common is the one available for download by Adobe; however, Adobe no longer supports or develops it. Firefox, Opera, Chrome, Safari, will all display basic SVG fine but will run into quirks if advanced features are used, as support is incomplete. Firefox has no support for declarative animation.

SVG elements can be created with javascript as follows:

// "circle" may be any tag name
var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
// Set any attributes as desired
shape.setAttribute("cx", 25);
shape.setAttribute("cy", 25);
shape.setAttribute("r",  20);
shape.setAttribute("fill", "green");
// Add to a parent node; document.documentElement should be the root svg element.
// Acquiring a parent element with document.getElementById() would be safest.
document.documentElement.appendChild(shape);

The SVG specification describes the DOM interfaces for all SVG elements. For example, the SVGCircleElement, which is created above, has cx, cy, and r attributes for the center point and radius, which can be directly accessed. These are the SVGAnimatedLength attributes, which have a baseVal property for the normal value, and an animVal property for the animated value. Browsers at the moment are not reliably supporting the animVal property. baseVal is an SVGLength, whose value is set by the value property.

Hence, for script animations, one can also set these DOM properties to control SVG. The following code should be equivalent to the above code:

var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
shape.cx.baseVal.value = 25;
shape.cy.baseVal.value = 25;
shape.r.baseVal.value = 20;
shape.setAttribute("fill", "green");
document.documentElement.appendChild(shape);

No module named Image

You can this query:

pip install image 

I had pillow installed, and still, I got the error that you mentioned. But after I executed the above command, the error vanished. And My program worked perfectly.

PHP Try and Catch for SQL Insert

Elaborating on yasaluyari's answer I would stick with something like this:

We can just modify our mysql_query as follows:

function mysql_catchquery($query,$emsg='Error submitting the query'){
    if ($result=mysql_query($query)) return $result;
    else throw new Exception($emsg);
}

Now we can simply use it like this, some good example:

try {
    mysql_catchquery('CREATE TEMPORARY TABLE a (ID int(6))');
    mysql_catchquery('insert into a values(666),(418),(93)');
    mysql_catchquery('insert into b(ID, name) select a.ID, c.name from a join c on a.ID=c.ID');
    $result=mysql_catchquery('select * from d where ID=7777777');
    while ($tmp=mysql_fetch_assoc($result)) { ... }
} catch (Exception $e) {
    echo $e->getMessage();
}

Note how beautiful it is. Whenever any of the qq fails we gtfo with our errors. And you can also note that we don't need now to store the state of the writing queries into a $result variable for verification, because our function now handles it by itself. And the same way it handles the selects, it just assigns the result to a variable as does the normal function, yet handles the errors within itself.

Also note, we don't need to show the actual errors since they bear huge security risk, especially so with this outdated extension. That is why our default will be just fine most of the time. Yet, if we do want to notify the user for some particular query error, we can always pass the second parameter to display our custom error message.

Get a list of distinct values in List

Notes.Select(x => x.Author).Distinct();

This will return a sequence (IEnumerable<string>) of Author values -- one per unique value.

Convert HH:MM:SS string to seconds only in javascript

This function works for MM:SS as well:

_x000D_
_x000D_
const convertTime = (hms) => {_x000D_
        if (hms.length <3){_x000D_
         return hms_x000D_
        } else if (hms.length <6){_x000D_
          const a = hms.split(':')_x000D_
          return hms = (+a[0]) * 60 + (+a[1])_x000D_
        } else {_x000D_
          const a = hms.split(':')_x000D_
          return hms = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2])_x000D_
        }_x000D_
      }
_x000D_
_x000D_
_x000D_

Java String import

Everything in the java.lang package is implicitly imported (including String) and you do not need to do so yourself. This is simply a feature of the Java language. ArrayList and HashMap are however in the java.util package, which is not implicitly imported.

The package java.lang mostly includes essential features, such a class version of primitives, basic exceptions and the Object class. This being integral to most programs, forcing people to import them is redundant and thus the contents of this package are implicitly imported.

Making an image act like a button

You could use an image submit button:

<input type="image"  id="saveform" src="logg.png " alt="Submit Form" />

Java Compare Two List's object values?

It's not the most efficient solution but the most terse code would be:

boolean equalLists = listA.size() == listB.size() && listA.containsAll(listB);

Update:

@WesleyPorter is right. The solution above will not work if duplicate objects are in the collection.
For a complete solution you need to iterate over a collection so duplicate objects are handled correctly.

private static boolean cmp( List<?> l1, List<?> l2 ) {
    // make a copy of the list so the original list is not changed, and remove() is supported
    ArrayList<?> cp = new ArrayList<>( l1 );
    for ( Object o : l2 ) {
        if ( !cp.remove( o ) ) {
            return false;
        }
    }
    return cp.isEmpty();
}

Update 28-Oct-2014:

@RoeeGavriel is right. The return statement needs to be conditional. The code above is updated.

webpack command not working

npm i webpack -g

installs webpack globally on your system, that makes it available in terminal window.

Getting distance between two points based on latitude/longitude

You can use Uber's H3,point_dist() function to compute the spherical distance between two (lat, lng) points. We can set return unit ('km', 'm', or 'rads'). The default unit is Km.

Example :

import H3

coords_1 = (52.2296756, 21.0122287)
coords_2 = (52.406374, 16.9251681)
distance = h3.point_dist(coords_1,coords_2) #278.4584889328128

Hope this will usefull!

"continue" in cursor.forEach()

Use continue statement instead of return to skip an iteration in JS loops.

Remove large .pack file created by git

I am a little late for the show but in case the above answer didn't solve the query then I found another way. Simply remove the specific large file from .pack. I had this issue where I checked in a large 2GB file accidentally. I followed the steps explained in this link: http://www.ducea.com/2012/02/07/howto-completely-remove-a-file-from-git-history/

Explicitly calling return in a function or not

Question was: Why is not (explicitly) calling return faster or better, and thus preferable?

There is no statement in R documentation making such an assumption.
The main page ?'function' says:

function( arglist ) expr
return(value)

Is it faster without calling return?

Both function() and return() are primitive functions and the function() itself returns last evaluated value even without including return() function.

Calling return() as .Primitive('return') with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary .Primitive('return') call can draw additional resources. Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:

bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return
(function(x) vector(length=x,mode="numeric"))(x)
,repeats)) }

bench_ret2 <- function(x,repeats) { system.time(rep(
# with explicit return
(function(x) return(vector(length=x,mode="numeric")))(x)
,repeats)) }

maxlen <- 1000
reps <- 10000
along <- seq(from=1,to=maxlen,by=5)
ret <- sapply(along,FUN=bench_ret2,repeats=reps)
nor <- sapply(along,FUN=bench_nor2,repeats=reps)
res <- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",])

# res object is then visualized
# R version 2.15

Function elapsed time comparison

The picture above may slightly difffer on your platform. Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.

Is it better without calling return?

Return is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.

# here without calling .Primitive('return')
> (function() {10;20;30;40})()
[1] 40
# here with .Primitive('return')
> (function() {10;20;30;40;return(40)})()
[1] 40
# here return terminates flow
> (function() {10;20;return();30;40})()
NULL
> (function() {10;20;return(25);30;40})()
[1] 25
> 

It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.

R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.

Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.

It is not clear if it is better or not as standard user or analyst using R can not see the real difference.

My opinion is that the question should be: Is there any danger in using explicit return coming from R implementation?

Or, maybe better, user writing function code should always ask: What is the effect in not using explicit return (or placing object to be returned as last leaf of code branch) in the function code?

How do I use brew installed Python as the default Python?

No idea what you mean with default Python. I consider it bad practice to replace the system Python interpreter with a different version. System functionality may depend in some way on the system Python and specific modules or a specific Python version. Instead install your custom Python installations in a safe different place and adjust your $PATH as needed in order to call you Python through a path lookup instead of looking for the default Python.

Adding a leading zero to some values in column in MySQL

Possibly:

select lpad(column, 8, 0) from table;

Edited in response to question from mylesg, in comments below:

ok, seems to make the change on the query- but how do I make it stick (change it) permanently in the table? I tried an UPDATE instead of SELECT

I'm assuming that you used a query similar to:

UPDATE table SET columnName=lpad(nums,8,0);

If that was successful, but the table's values are still without leading-zeroes, then I'd suggest you probably set the column as a numeric type? If that's the case then you'd need to alter the table so that the column is of a text/varchar() type in order to preserve the leading zeroes:

First:

ALTER TABLE `table` CHANGE `numberColumn` `numberColumn` CHAR(8);

Second, run the update:

UPDATE table SET `numberColumn`=LPAD(`numberColum`, 8, '0');

This should, then, preserve the leading-zeroes; the down-side is that the column is no longer strictly of a numeric type; so you may have to enforce more strict validation (depending on your use-case) to ensure that non-numerals aren't entered into that column.

References:

An error occurred while signing: SignTool.exe not found

Now try to publish the ClickOnce application. If you still find the same issue, please check if you installed the Microsoft .NET Framework 4.5 Developer Preview on the system. The Microsoft .NET Framework 4.5 Developer Preview is a prerelease version of the .NET Framework, and should not be used in production scenarios. It is an in-place update to the .NET Framework 4. You would need to uninstall this prerelease product from ARP.

https://blogs.msdn.microsoft.com/vsnetsetup/2013/11/18/an-error-occurred-while-signing-signtool-exe-not-found/

Lastly you might want to install the customer preview instead of being on the developer preview

In AngularJS, what's the difference between ng-pristine and ng-dirty?

Both directives obviously serve the same purpose, and though it seems that the decision of the angular team to include both interfere with the DRY principle and adds to the payload of the page, it still is rather practical to have them both around. It is easier to style your input elements as you have both .ng-pristine and .ng-dirty available for styling in your css files. I guess this was the primary reason for adding both directives.

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

jQuery Core doesn't have anything special, but you can read on jQuery Mobile Events page about different touch events, which also work on other than iOS devices as well.

They are:

  • tap
  • taphold
  • swipe
  • swipeleft
  • swiperight

Notice also, that during scroll events (based on touch on mobile devices) iOS devices freezes DOM manipulation while scrolling.

Java's L number (long) specification

By default any integral primitive data type (byte, short, int, long) will be treated as int type by java compiler. For byte and short, as long as value assigned to them is in their range, there is no problem and no suffix required. If value assigned to byte and short exceeds their range, explicit type casting is required.

Ex:

byte b = 130; // CE: range is exceeding.

to overcome this perform type casting.

byte b = (byte)130; //valid, but chances of losing data is there.

In case of long data type, it can accept the integer value without any hassle. Suppose we assign like

Long l = 2147483647; //which is max value of int

in this case no suffix like L/l is required. By default value 2147483647 is considered by java compiler is int type. Internal type casting is done by compiler and int is auto promoted to Long type.

Long l = 2147483648; //CE: value is treated as int but out of range 

Here we need to put suffix as L to treat the literal 2147483648 as long type by java compiler.

so finally

Long l = 2147483648L;// works fine.

How to add text at the end of each line in Vim?

Another solution, using another great feature:

:'<,'>norm A,

See :help :normal.

How to create enum like type in TypeScript?

Enums in typescript:

Enums are put into the typescript language to define a set of named constants. Using enums can make our life easier. The reason for this is that these constants are often easier to read than the value which the enum represents.

Creating a enum:

enum Direction {
    Up = 1,
    Down,
    Left,
    Right,
}

This example from the typescript docs explains very nicely how enums work. Notice that our first enum value (Up) is initialized with 1. All the following members of the number enum are then auto incremented from this value (i.e. Down = 2, Left = 3, Right = 4). If we didn't initialize the first value with 1 the enum would start at 0 and then auto increment (i.e. Down = 1, Left = 2, Right = 3).

Using an enum:

We can access the values of the enum in the following manner:

Direction.Up;     // first the enum name, then the dot operator followed by the enum value
Direction.Down;

Notice that this way we are much more descriptive in the way we write our code. Enums basically prevent us from using magic numbers (numbers which represent some entity because the programmer has given a meaning to them in a certain context). Magic numbers are bad because of the following reasons:

  1. We need to think harder, we first need to translate the number to an entity before we can reason about our code.
  2. If we review our code after a long while, or other programmers review our code, they don't necessarily know what is meant with these numbers.

Rename master branch for both local and remote Git repositories

git update-ref newref oldref
git update-ref -d oldref newref

Reloading a ViewController

You Must use

-(void)viewWillAppear:(BOOL)animated

and set your entries like you want...

"google is not defined" when using Google Maps V3 in Firefox remotely

Changed the

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API"> 
      function(){
            myMap()
                }
</script>

and made it

<script type="text/javascript">
      function(){
            myMap()
                }
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API"></script>

It worked :)

Git: How configure KDiff3 as merge tool and diff tool

I needed to add the command line parameters or KDiff3 would only open without files and prompt me for base, local and remote. I used the version supplied with TortoiseHg.

Additionally, I needed to resort to the good old DOS 8.3 file names.

[merge]
    tool = kdiff3

[mergetool "kdiff3"]
    cmd = /c/Progra~1/TortoiseHg/lib/kdiff3.exe $BASE $LOCAL $REMOTE -o $MERGED

However, it works correctly now.

What uses are there for "placement new"?

We use it with custom memory pools. Just a sketch:

class Pool {
public:
    Pool() { /* implementation details irrelevant */ };
    virtual ~Pool() { /* ditto */ };

    virtual void *allocate(size_t);
    virtual void deallocate(void *);

    static Pool::misc_pool() { return misc_pool_p; /* global MiscPool for general use */ }
};

class ClusterPool : public Pool { /* ... */ };
class FastPool : public Pool { /* ... */ };
class MapPool : public Pool { /* ... */ };
class MiscPool : public Pool { /* ... */ };

// elsewhere...

void *pnew_new(size_t size)
{
   return Pool::misc_pool()->allocate(size);
}

void *pnew_new(size_t size, Pool *pool_p)
{
   if (!pool_p) {
      return Pool::misc_pool()->allocate(size);
   }
   else {
      return pool_p->allocate(size);
   }
}

void pnew_delete(void *p)
{
   Pool *hp = Pool::find_pool(p);
   // note: if p == 0, then Pool::find_pool(p) will return 0.
   if (hp) {
      hp->deallocate(p);
   }
}

// elsewhere...

class Obj {
public:
   // misc ctors, dtors, etc.

   // just a sampling of new/del operators
   void *operator new(size_t s)             { return pnew_new(s); }
   void *operator new(size_t s, Pool *hp)   { return pnew_new(s, hp); }
   void operator delete(void *dp)           { pnew_delete(dp); }
   void operator delete(void *dp, Pool*)    { pnew_delete(dp); }

   void *operator new[](size_t s)           { return pnew_new(s); }
   void *operator new[](size_t s, Pool* hp) { return pnew_new(s, hp); }
   void operator delete[](void *dp)         { pnew_delete(dp); }
   void operator delete[](void *dp, Pool*)  { pnew_delete(dp); }
};

// elsewhere...

ClusterPool *cp = new ClusterPool(arg1, arg2, ...);

Obj *new_obj = new (cp) Obj(arg_a, arg_b, ...);

Now you can cluster objects together in a single memory arena, select an allocator which is very fast but does no deallocation, use memory mapping, and any other semantic you wish to impose by choosing the pool and passing it as an argument to an object's placement new operator.

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

From Java8 and above, you may use below command:

jcmd JAVA_PROCESS_ID GC.heap_info

You may refer to sum of, total and used memory from the output.

Sample Command And Output: jcmd 9758 GC.heap_info

PSYoungGen  total 1579520K, used 487543K [0x0000000751d80000, 0x00000007c0000000, 0x00000007c0000000)
  eden space 1354240K, 36% used [0x0000000751d80000,0x000000076f99dc40,0x00000007a4800000)
  from space 225280K, 0% used [0x00000007b2400000,0x00000007b2400000,0x00000007c0000000)
  to   space 225280K, 0% used [0x00000007a4800000,0x00000007a4800000,0x00000007b2400000)
ParOldGen       total 3610112K, used 0K [0x0000000675800000, 0x0000000751d80000, 0x0000000751d80000)
  object space 3610112K, 0% used [0x0000000675800000,0x0000000675800000,0x0000000751d80000)
Metaspace       used 16292K, capacity 16582K, committed 16896K, reserved 1064960K
  class space    used 1823K, capacity 1936K, committed 2048K, reserved 1048576K

For more details on jcmd command, visit link here

Does JavaScript guarantee object property order?

In ES2015, it does, but not to what you might think

The order of keys in an object wasn't guaranteed until ES2015. It was implementation-defined.

However, in ES2015 in was specified. Like many things in JavaScript, this was done for compatibility purposes and generally reflected an existing unofficial standard among most JS engines (with you-know-who being an exception).

The order is defined in the spec, under the abstract operation OrdinaryOwnPropertyKeys, which underpins all methods of iterating over an object's own keys. Paraphrased, the order is as follows:

  1. All integer index keys (stuff like "1123", "55", etc) in ascending numeric order.

  2. All string keys which are not integer indices, in order of creation (oldest-first).

  3. All symbol keys, in order of creation (oldest-first).

It's silly to say that the order is unreliable - it is reliable, it's just probably not what you want, and modern browsers implement this order correctly.

Some exceptions include methods of enumerating inherited keys, such as the for .. in loop. The for .. in loop doesn't guarantee order according to the specification.

Writing an mp4 video using python opencv

What worked for me was to make sure the input 'frame' size is equal to output video's size (in this case, (680, 480) ).

http://answers.opencv.org/question/27902/how-to-record-video-using-opencv-and-python/

Here is my working code (Mac OSX Sierra 10.12.6):

cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)

fourcc = cv2.VideoWriter_fourcc(*'MP4V')
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (640,480))

while(True):
    ret, frame = cap.read()
    out.write(frame)
    cv2.imshow('frame', frame)
    c = cv2.waitKey(1)
    if c & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

Note: I installed openh264 as suggested by @10SecTom but I'm not sure if that was relevant to the problem.

Just in case:

brew install openh264

The name 'controlname' does not exist in the current context

I had a similar problem when tweaking with a Repeater after converting it from a DataList.

Problem was that I accidentally united 2 attributes when deleting an unneeded one.

<asp:Repeater runat="server" ID="ClientsRP"DataSourceID="ClientsDS">
    .
    .
    .
</asp:Repeater>

And this prevented the generation of the repeater in the design file.

Transform char array into String

I have search it again and search this question in baidu. Then I find 2 ways:

1,

_x000D_
_x000D_
char ch[]={'a','b','c','d','e','f','g','\0'};_x000D_
string s=ch;_x000D_
cout<<s;
_x000D_
_x000D_
_x000D_

Be aware to that '\0' is necessary for char array ch.

2,

_x000D_
_x000D_
#include<iostream>_x000D_
#include<string>_x000D_
#include<strstream>_x000D_
using namespace std;_x000D_
_x000D_
int main()_x000D_
{_x000D_
 char ch[]={'a','b','g','e','d','\0'};_x000D_
 strstream s;_x000D_
 s<<ch;_x000D_
 string str1;_x000D_
 s>>str1;_x000D_
 cout<<str1<<endl;_x000D_
 return 0;_x000D_
}
_x000D_
_x000D_
_x000D_

In this way, you also need to add the '\0' at the end of char array.

Also, strstream.h file will be abandoned and be replaced by stringstream

How to generate a unique hash code for string input in android...?

For me it worked

   public static long getUniqueLongFromString (String value){
       return  UUID.nameUUIDFromBytes(value.getBytes()).getMostSignificantBits();
    }

C++ queue - simple example

Simply declare it as below if you want to us the STL queue container.

std::queue<myclass*> my_queue;

Sending images using Http Post

I usually do this in the thread handling the json response:

try {
  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual

How to resolve the error on 'react-native start'

I got same problem.

"error Invalid regular expression: /(.\fixtures\.|node_modules[\]react[\]dist[\].|website\node_modules\.|heapCapture\bundle.js|.\tests\.)$/: Unterminated character class."

Change the regular expression in \node_modules\metro-config\src\defaults\blacklist.js

From

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

To

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

This change resolved my error.

Git: How to pull a single file from a server repository in Git?

Try using:

git checkout branchName -- fileName

Ex:

git checkout master -- index.php

converting json to string in python

There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

Why is my CSS style not being applied?

Posting, since it might be useful for someone in the future:

For me, when I got here, the solution was browser cache. Had to hard refresh Chrome (cmd/ctrl+shift+R) to get the new styles applied, it seems the old ones got cached really "deep".

This question/answer might come in handy for someone. And hard refresh tips for different browsers for those who don't use Chrome.

Android Studio: Plugin with id 'android-library' not found

Use

apply plugin: 'com.android.library'

to convert an app module to a library module. More info here: https://developer.android.com/studio/projects/android-library.html

Create a temporary table in a SELECT statement without a separate CREATE TABLE

Use this syntax:

CREATE TEMPORARY TABLE t1 (select * from t2);

Address already in use: JVM_Bind

as the exception says there is already another server running on the same port. you can either kill that service or change glassfish to run on another poet

Table Naming Dilemma: Singular vs. Plural Names

Guidelines are really there as just that. It's not "set in stone" that's why you have the option of being able to ignore them.

I would say that it's more logically intuitive to have pluralized table names. A table is a collection of entity after all. In addition to other alternatives mentioned I commonly see prefixes on table names...

  • tblUser
  • tblThis
  • tblThat
  • tblTheOther

I'm not suggesting this is the way to go, I also see spaces used a LOT in table names which I abhor. I've even come across field names with idiotic characters like ? as if to say this field answers a question.

How to stop a looping thread in Python?

I find it useful to have a class, derived from threading.Thread, to encapsulate my thread functionality. You simply provide your own main loop in an overridden version of run() in this class. Calling start() arranges for the object’s run() method to be invoked in a separate thread.

Inside the main loop, periodically check whether a threading.Event has been set. Such an event is thread-safe.

Inside this class, you have your own join() method that sets the stop event object before calling the join() method of the base class. It can optionally take a time value to pass to the base class's join() method to ensure your thread is terminated in a short amount of time.

import threading
import time

class MyThread(threading.Thread):
    def __init__(self, sleep_time=0.1):
        self._stop_event = threading.Event()
        self._sleep_time = sleep_time
        """call base class constructor"""
        super().__init__()

    def run(self):
        """main control loop"""
        while not self._stop_event.isSet():
            #do work
            print("hi")
            self._stop_event.wait(self._sleep_time)

    def join(self, timeout=None):
        """set stop event and join within a given time period"""
        self._stop_event.set()
        super().join(timeout)


if __name__ == "__main__":
    t = MyThread()
    t.start()

    time.sleep(5)

    t.join(1) #wait 1s max

Having a small sleep inside the main loop before checking the threading.Event is less CPU intensive than looping continuously. You can have a default sleep time (e.g. 0.1s), but you can also pass the value in the constructor.

Query to convert from datetime to date mysql

Use the DATE function:

SELECT DATE(orders.date_purchased) AS date

How to use Javascript to read local text file and read line by line?

Using ES6 the javascript becomes a little cleaner

handleFiles(input) {

    const file = input.target.files[0];
    const reader = new FileReader();

    reader.onload = (event) => {
        const file = event.target.result;
        const allLines = file.split(/\r\n|\n/);
        // Reading line by line
        allLines.forEach((line) => {
            console.log(line);
        });
    };

    reader.onerror = (event) => {
        alert(event.target.error.name);
    };

    reader.readAsText(file);
}

How to analyze disk usage of a Docker container

Posting this as an answer because my comments above got hidden:

List the size of a container:

du -d 2 -h /var/lib/docker/devicemapper | grep `docker inspect -f "{{.Id}}" <container_name>`

List the sizes of a container's volumes:

docker inspect -f "{{.Volumes}}" <container_name> | sed 's/map\[//' | sed 's/]//' | tr ' ' '\n' | sed 's/.*://' | xargs sudo du -d 1 -h

Edit: List all running containers' sizes and volumes:

for d in `docker ps -q`; do
    d_name=`docker inspect -f {{.Name}} $d`
    echo "========================================================="
    echo "$d_name ($d) container size:"
    sudo du -d 2 -h /var/lib/docker/devicemapper | grep `docker inspect -f "{{.Id}}" $d`
    echo "$d_name ($d) volumes:"
    docker inspect -f "{{.Volumes}}" $d | sed 's/map\[//' | sed 's/]//' | tr ' ' '\n' | sed 's/.*://' | xargs sudo du -d 1 -h
done

NOTE: Change 'devicemapper' according to your Docker filesystem (e.g 'aufs')

PHP convert XML to JSON

I guess I'm a bit late to the party but I have written a small function to accomplish this task. It also takes care of attributes, text content and even if multiple nodes with the same node-name are siblings.

Dislaimer: I'm not a PHP native, so please bear with simple mistakes.

function xml2js($xmlnode) {
    $root = (func_num_args() > 1 ? false : true);
    $jsnode = array();

    if (!$root) {
        if (count($xmlnode->attributes()) > 0){
            $jsnode["$"] = array();
            foreach($xmlnode->attributes() as $key => $value)
                $jsnode["$"][$key] = (string)$value;
        }

        $textcontent = trim((string)$xmlnode);
        if (count($textcontent) > 0)
            $jsnode["_"] = $textcontent;

        foreach ($xmlnode->children() as $childxmlnode) {
            $childname = $childxmlnode->getName();
            if (!array_key_exists($childname, $jsnode))
                $jsnode[$childname] = array();
            array_push($jsnode[$childname], xml2js($childxmlnode, true));
        }
        return $jsnode;
    } else {
        $nodename = $xmlnode->getName();
        $jsnode[$nodename] = array();
        array_push($jsnode[$nodename], xml2js($xmlnode, true));
        return json_encode($jsnode);
    }
}   

Usage example:

$xml = simplexml_load_file("myfile.xml");
echo xml2js($xml);

Example Input (myfile.xml):

<family name="Johnson">
    <child name="John" age="5">
        <toy status="old">Trooper</toy>
        <toy status="old">Ultrablock</toy>
        <toy status="new">Bike</toy>
    </child>
</family>

Example output:

{"family":[{"$":{"name":"Johnson"},"child":[{"$":{"name":"John","age":"5"},"toy":[{"$":{"status":"old"},"_":"Trooper"},{"$":{"status":"old"},"_":"Ultrablock"},{"$":{"status":"new"},"_":"Bike"}]}]}]}

Pretty printed:

{
    "family" : [{
            "$" : {
                "name" : "Johnson"
            },
            "child" : [{
                    "$" : {
                        "name" : "John",
                        "age" : "5"
                    },
                    "toy" : [{
                            "$" : {
                                "status" : "old"
                            },
                            "_" : "Trooper"
                        }, {
                            "$" : {
                                "status" : "old"
                            },
                            "_" : "Ultrablock"
                        }, {
                            "$" : {
                                "status" : "new"
                            },
                            "_" : "Bike"
                        }
                    ]
                }
            ]
        }
    ]
}

Quirks to keep in mind: Several tags with the same tagname can be siblings. Other solutions will most likely drop all but the last sibling. To avoid this each and every single node, even if it only has one child, is an array which hold an object for each instance of the tagname. (See multiple "" elements in example)

Even the root element, of which only one should exist in a valid XML document is stored as array with an object of the instance, just to have a consistent data structure.

To be able to distinguish between XML node content and XML attributes each objects attributes are stored in the "$" and the content in the "_" child.

Edit: I forgot to show the output for your example input data

{
    "states" : [{
            "state" : [{
                    "$" : {
                        "id" : "AL"
                    },
                    "name" : [{
                            "_" : "Alabama"
                        }
                    ]
                }, {
                    "$" : {
                        "id" : "AK"
                    },
                    "name" : [{
                            "_" : "Alaska"
                        }
                    ]
                }
            ]
        }
    ]
}

Fix columns in horizontal scrolling

Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery

You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/

All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter

<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">

and run js function

app_handle_listing_horisontal_scroll($('#table-listing'))

How to create folder with PHP code?

Purely basic folder creation

<?php mkdir("testing"); ?> <= this, actually creates a folder called "testing".



Basic file creation

<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>

Use the a or a+ switch to add/append to file.



EDIT:

This version will create a file and folder at the same time and show it on screen after.

<?php

// change the name below for the folder you want
$dir = "new_folder_name";

$file_to_write = 'test.txt';
$content_to_write = "The content";

if( is_dir($dir) === false )
{
    mkdir($dir);
}

$file = fopen($dir . '/' . $file_to_write,"w");

// a different way to write content into
// fwrite($file,"Hello World.");

fwrite($file, $content_to_write);

// closes the file
fclose($file);

// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;

?>

Update Fragment from ViewPager

I faced problem some times so that in this case always avoid FragmentPagerAdapter and use FragmentStatePagerAdapter.

It work for me. I hope it will work for you also.

Python: TypeError: cannot concatenate 'str' and 'int' objects

You can convert int into str using string function:

user = "mohan"

line = str(50)

print(user + "typed" + line + "lines")

Tensorflow: how to save/restore a model?

My environment: Python 3.6, Tensorflow 1.3.0

Though there have been many solutions, most of them is based on tf.train.Saver. When we load a .ckpt saved by Saver, we have to either redefine the tensorflow network or use some weird and hard-remembered name, e.g. 'placehold_0:0','dense/Adam/Weight:0'. Here I recommend to use tf.saved_model, one simplest example given below, your can learn more from Serving a TensorFlow Model:

Save the model:

import tensorflow as tf

# define the tensorflow network and do some trains
x = tf.placeholder("float", name="x")
w = tf.Variable(2.0, name="w")
b = tf.Variable(0.0, name="bias")

h = tf.multiply(x, w)
y = tf.add(h, b, name="y")
sess = tf.Session()
sess.run(tf.global_variables_initializer())

# save the model
export_path =  './savedmodel'
builder = tf.saved_model.builder.SavedModelBuilder(export_path)

tensor_info_x = tf.saved_model.utils.build_tensor_info(x)
tensor_info_y = tf.saved_model.utils.build_tensor_info(y)

prediction_signature = (
  tf.saved_model.signature_def_utils.build_signature_def(
      inputs={'x_input': tensor_info_x},
      outputs={'y_output': tensor_info_y},
      method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))

builder.add_meta_graph_and_variables(
  sess, [tf.saved_model.tag_constants.SERVING],
  signature_def_map={
      tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
          prediction_signature 
  },
  )
builder.save()

Load the model:

import tensorflow as tf
sess=tf.Session() 
signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
input_key = 'x_input'
output_key = 'y_output'

export_path =  './savedmodel'
meta_graph_def = tf.saved_model.loader.load(
           sess,
          [tf.saved_model.tag_constants.SERVING],
          export_path)
signature = meta_graph_def.signature_def

x_tensor_name = signature[signature_key].inputs[input_key].name
y_tensor_name = signature[signature_key].outputs[output_key].name

x = sess.graph.get_tensor_by_name(x_tensor_name)
y = sess.graph.get_tensor_by_name(y_tensor_name)

y_out = sess.run(y, {x: 3.0})

Primitive type 'short' - casting in Java

EDIT: Okay, now we know it's Java...

Section 4.2.2 of the Java Language Specification states:

The Java programming language provides a number of operators that act on integral values:

[...]

  • The numerical operators, which result in a value of type int or long:
  • [...]
  • The additive operators + and - (§15.18)

  • In other words, it's like C# - the addition operator (when applied to integral types) only ever results in int or long, which is why you need to cast to assign to a short variable.

    Original answer (C#)

    In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:

    int operator +(int x, int y);
    uint operator +(uint x, uint y);
    long operator +(long x, long y);
    ulong operator +(ulong x, ulong y);
    float operator +(float x, float y);
    double operator +(double x, double y);
    

    These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:

    decimal operator +(decimal x, decimal y);
    

    (Enumeration addition, string concatenation and delegate combination are also defined there.)

    As you can see, there's no short operator +(short x, short y) operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type "int", hence the need to cast.

    How to SSH into Docker?

    Firstly you need to install a SSH server in the images you wish to ssh-into. You can use a base image for all your container with the ssh server installed. Then you only have to run each container mapping the ssh port (default 22) to one to the host's ports (Remote Server in your image), using -p <hostPort>:<containerPort>. i.e:

    docker run -p 52022:22 container1 
    docker run -p 53022:22 container2
    

    Then, if ports 52022 and 53022 of host's are accessible from outside, you can directly ssh to the containers using the ip of the host (Remote Server) specifying the port in ssh with -p <port>. I.e.:

    ssh -p 52022 myuser@RemoteServer --> SSH to container1

    ssh -p 53022 myuser@RemoteServer --> SSH to container2

    Difference between jQuery’s .hide() and setting CSS to display: none

    They are the same thing. .hide() calls a jQuery function and allows you to add a callback function to it. So, with .hide() you can add an animation for instance.

    .css("display","none") changes the attribute of the element to display:none. It is the same as if you do the following in JavaScript:

    document.getElementById('elementId').style.display = 'none';
    

    The .hide() function obviously takes more time to run as it checks for callback functions, speed, etc...

    How to measure time in milliseconds using ANSI C?

    Implementing a portable solution

    As it was already mentioned here that there is no proper ANSI solution with sufficient precision for the time measurement problem, I want to write about the ways how to get a portable and, if possible, a high-resolution time measurement solution.

    Monotonic clock vs. time stamps

    Generally speaking there are two ways of time measurement:

    • monotonic clock;
    • current (date)time stamp.

    The first one uses a monotonic clock counter (sometimes it is called a tick counter) which counts ticks with a predefined frequency, so if you have a ticks value and the frequency is known, you can easily convert ticks to elapsed time. It is actually not guaranteed that a monotonic clock reflects the current system time in any way, it may also count ticks since a system startup. But it guarantees that a clock is always run up in an increasing fashion regardless of the system state. Usually the frequency is bound to a hardware high-resolution source, that's why it provides a high accuracy (depends on hardware, but most of the modern hardware has no problems with high-resolution clock sources).

    The second way provides a (date)time value based on the current system clock value. It may also have a high resolution, but it has one major drawback: this kind of time value can be affected by different system time adjustments, i.e. time zone change, daylight saving time (DST) change, NTP server update, system hibernation and so on. In some circumstances you can get a negative elapsed time value which can lead to an undefined behavior. Actually this kind of time source is less reliable than the first one.

    So the first rule in time interval measuring is to use a monotonic clock if possible. It usually has a high precision, and it is reliable by design.

    Fallback strategy

    When implementing a portable solution it is worth to consider a fallback strategy: use a monotonic clock if available and fallback to time stamps approach if there is no monotonic clock in the system.

    Windows

    There is a great article called Acquiring high-resolution time stamps on MSDN about time measurement on Windows which describes all the details you may need to know about software and hardware support. To acquire a high precision time stamp on Windows you should:

    • query a timer frequency (ticks per second) with QueryPerformanceFrequency:

      LARGE_INTEGER tcounter;
      LARGE_INTEGER freq;    
      
      if (QueryPerformanceFrequency (&tcounter) != 0)
          freq = tcounter.QuadPart;
      

      The timer frequency is fixed on the system boot so you need to get it only once.

    • query the current ticks value with QueryPerformanceCounter:

      LARGE_INTEGER tcounter;
      LARGE_INTEGER tick_value;
      
      if (QueryPerformanceCounter (&tcounter) != 0)
          tick_value = tcounter.QuadPart;
      
    • scale the ticks to elapsed time, i.e. to microseconds:

      LARGE_INTEGER usecs = (tick_value - prev_tick_value) / (freq / 1000000);
      

    According to Microsoft you should not have any problems with this approach on Windows XP and later versions in most cases. But you can also use two fallback solutions on Windows:

    • GetTickCount provides the number of milliseconds that have elapsed since the system was started. It wraps every 49.7 days, so be careful in measuring longer intervals.
    • GetTickCount64 is a 64-bit version of GetTickCount, but it is available starting from Windows Vista and above.

    OS X (macOS)

    OS X (macOS) has its own Mach absolute time units which represent a monotonic clock. The best way to start is the Apple's article Technical Q&A QA1398: Mach Absolute Time Units which describes (with the code examples) how to use Mach-specific API to get monotonic ticks. There is also a local question about it called clock_gettime alternative in Mac OS X which at the end may leave you a bit confused what to do with the possible value overflow because the counter frequency is used in the form of numerator and denominator. So, a short example how to get elapsed time:

    • get the clock frequency numerator and denominator:

      #include <mach/mach_time.h>
      #include <stdint.h>
      
      static uint64_t freq_num   = 0;
      static uint64_t freq_denom = 0;
      
      void init_clock_frequency ()
      {
          mach_timebase_info_data_t tb;
      
          if (mach_timebase_info (&tb) == KERN_SUCCESS && tb.denom != 0) {
              freq_num   = (uint64_t) tb.numer;
              freq_denom = (uint64_t) tb.denom;
          }
      }
      

      You need to do that only once.

    • query the current tick value with mach_absolute_time:

      uint64_t tick_value = mach_absolute_time ();
      
    • scale the ticks to elapsed time, i.e. to microseconds, using previously queried numerator and denominator:

      uint64_t value_diff = tick_value - prev_tick_value;
      
      /* To prevent overflow */
      value_diff /= 1000;
      
      value_diff *= freq_num;
      value_diff /= freq_denom;
      

      The main idea to prevent an overflow is to scale down the ticks to desired accuracy before using the numerator and denominator. As the initial timer resolution is in nanoseconds, we divide it by 1000 to get microseconds. You can find the same approach used in Chromium's time_mac.c. If you really need a nanosecond accuracy consider reading the How can I use mach_absolute_time without overflowing?.

    Linux and UNIX

    The clock_gettime call is your best way on any POSIX-friendly system. It can query time from different clock sources, and the one we need is CLOCK_MONOTONIC. Not all systems which have clock_gettime support CLOCK_MONOTONIC, so the first thing you need to do is to check its availability:

    • if _POSIX_MONOTONIC_CLOCK is defined to a value >= 0 it means that CLOCK_MONOTONIC is avaiable;
    • if _POSIX_MONOTONIC_CLOCK is defined to 0 it means that you should additionally check if it works at runtime, I suggest to use sysconf:

      #include <unistd.h>
      
      #ifdef _SC_MONOTONIC_CLOCK
      if (sysconf (_SC_MONOTONIC_CLOCK) > 0) {
          /* A monotonic clock presents */
      }
      #endif
      
    • otherwise a monotonic clock is not supported and you should use a fallback strategy (see below).

    Usage of clock_gettime is pretty straight forward:

    • get the time value:

      #include <time.h>
      #include <sys/time.h>
      #include <stdint.h>
      
      uint64_t get_posix_clock_time ()
      {
          struct timespec ts;
      
          if (clock_gettime (CLOCK_MONOTONIC, &ts) == 0)
              return (uint64_t) (ts.tv_sec * 1000000 + ts.tv_nsec / 1000);
          else
              return 0;
      }
      

      I've scaled down the time to microseconds here.

    • calculate the difference with the previous time value received the same way:

      uint64_t prev_time_value, time_value;
      uint64_t time_diff;
      
      /* Initial time */
      prev_time_value = get_posix_clock_time ();
      
      /* Do some work here */
      
      /* Final time */
      time_value = get_posix_clock_time ();
      
      /* Time difference */
      time_diff = time_value - prev_time_value;
      

    The best fallback strategy is to use the gettimeofday call: it is not a monotonic, but it provides quite a good resolution. The idea is the same as with clock_gettime, but to get a time value you should:

    #include <time.h>
    #include <sys/time.h>
    #include <stdint.h>
    
    uint64_t get_gtod_clock_time ()
    {
        struct timeval tv;
    
        if (gettimeofday (&tv, NULL) == 0)
            return (uint64_t) (tv.tv_sec * 1000000 + tv.tv_usec);
        else
            return 0;
    }
    

    Again, the time value is scaled down to microseconds.

    SGI IRIX

    IRIX has the clock_gettime call, but it lacks CLOCK_MONOTONIC. Instead it has its own monotonic clock source defined as CLOCK_SGI_CYCLE which you should use instead of CLOCK_MONOTONIC with clock_gettime.

    Solaris and HP-UX

    Solaris has its own high-resolution timer interface gethrtime which returns the current timer value in nanoseconds. Though the newer versions of Solaris may have clock_gettime, you can stick to gethrtime if you need to support old Solaris versions.

    Usage is simple:

    #include <sys/time.h>
    
    void time_measure_example ()
    {
        hrtime_t prev_time_value, time_value;
        hrtime_t time_diff;
    
        /* Initial time */
        prev_time_value = gethrtime ();
    
        /* Do some work here */
    
        /* Final time */
        time_value = gethrtime ();
    
        /* Time difference */
        time_diff = time_value - prev_time_value;
    }
    

    HP-UX lacks clock_gettime, but it supports gethrtime which you should use in the same way as on Solaris.

    BeOS

    BeOS also has its own high-resolution timer interface system_time which returns the number of microseconds have elapsed since the computer was booted.

    Example usage:

    #include <kernel/OS.h>
    
    void time_measure_example ()
    {
        bigtime_t prev_time_value, time_value;
        bigtime_t time_diff;
    
        /* Initial time */
        prev_time_value = system_time ();
    
        /* Do some work here */
    
        /* Final time */
        time_value = system_time ();
    
        /* Time difference */
        time_diff = time_value - prev_time_value;
    }
    

    OS/2

    OS/2 has its own API to retrieve high-precision time stamps:

    • query a timer frequency (ticks per unit) with DosTmrQueryFreq (for GCC compiler):

      #define INCL_DOSPROFILE
      #define INCL_DOSERRORS
      #include <os2.h>
      #include <stdint.h>
      
      ULONG freq;
      
      DosTmrQueryFreq (&freq);
      
    • query the current ticks value with DosTmrQueryTime:

      QWORD    tcounter;
      unit64_t time_low;
      unit64_t time_high;
      unit64_t timestamp;
      
      if (DosTmrQueryTime (&tcounter) == NO_ERROR) {
          time_low  = (unit64_t) tcounter.ulLo;
          time_high = (unit64_t) tcounter.ulHi;
      
          timestamp = (time_high << 32) | time_low;
      }
      
    • scale the ticks to elapsed time, i.e. to microseconds:

      uint64_t usecs = (prev_timestamp - timestamp) / (freq / 1000000);
      

    Example implementation

    You can take a look at the plibsys library which implements all the described above strategies (see ptimeprofiler*.c for details).

    Express.js - app.listen vs server.listen

    There is one more difference of using the app and listening to http server is when you want to setup for https server

    To setup for https, you need the code below:

    var https = require('https');
    var server = https.createServer(app).listen(config.port, function() {
        console.log('Https App started');
    });
    

    The app from express will return http server only, you cannot set it in express, so you will need to use the https server command

    var express = require('express');
    var app = express();
    app.listen(1234);
    

    How to make nginx to listen to server_name:port

    The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

    netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

    If you want to change the IP nginx binds on, you have to change the listendocs rule.
    So, if you want to set nginx to bind to localhost, you'd change that to:

    listen 127.0.0.1:80;
    

    In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

    CSS text-overflow in a table cell?

    When it's in percentage table width, or you can't set fixed width on table cell. You can apply table-layout: fixed; to make it work.

    _x000D_
    _x000D_
    table {_x000D_
      table-layout: fixed;_x000D_
      width: 100%;_x000D_
    }_x000D_
    td {_x000D_
      text-overflow: ellipsis;_x000D_
      white-space: nowrap;_x000D_
      overflow: hidden;_x000D_
      border: 1px solid red;_x000D_
    }
    _x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</td>_x000D_
        <td>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</td>_x000D_
      </tr>_x000D_
    </table>
    _x000D_
    _x000D_
    _x000D_

    Find file in directory from command line

    I use this script to quickly find files across directories in a project. I have found it works great and takes advantage of Vim's autocomplete by opening up and closing an new buffer for the search. It also smartly completes as much as possible for you so you can usually just type a character or two and open the file across any directory in your project. I started using it specifically because of a Java project and it has saved me a lot of time. You just build the cache once when you start your editing session by typing :FC (directory names). You can also just use . to get the current directory and all subdirectories. After that you just type :FF (or FS to open up a new split) and it will open up a new buffer to select the file you want. After you select the file the temp buffer closes and you are inside the requested file and can start editing. In addition, here is another link on Stack Overflow that may help.

    Android Notification Sound

    Don't depends on builder or notification. Use custom code for vibrate.

    public static void vibrate(Context context, int millis){
        try {
            Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                v.vibrate(VibrationEffect.createOneShot(millis, VibrationEffect.DEFAULT_AMPLITUDE));
            } else {
                v.vibrate(millis);
            }
        }catch(Exception ex){
        }
    }
    

    Find the max of 3 numbers in Java with different data types

    I have a very simple idea:

     int smallest = Math.min(a, Math.min(b, Math.min(c, d)));
    

    Of course, if you have 1000 numbers, it's unusable, but if you have 3 or 4 numbers, its easy and fast.

    Regards, Norbert

    How to find all duplicate from a List<string>?

    I use a method like that to check duplicated entrys in a string:

    public static IEnumerable<string> CheckForDuplicated(IEnumerable<string> listString)
    {
        List<string> duplicateKeys = new List<string>();
        List<string> notDuplicateKeys = new List<string>();
        foreach (var text in listString)
        {
            if (notDuplicateKeys.Contains(text))
            {
                duplicateKeys.Add(text);
            }
            else
            {
                notDuplicateKeys.Add(text);
            }
        }
        return duplicateKeys;
    }
    

    Maybe it's not the most shorted or elegant way, but I think that is very readable.

    How to import a .cer certificate into a java keystore?

    Importing .cer certificate file downloaded from browser (open the url and dig for details) into cacerts keystore in java_home\jre\lib\security worked for me, as opposed to attemps to generate and use my own keystore.

    1. Go to your java_home\jre\lib\security
    2. (Windows) Open admin command line there using cmd and CTRL+SHIFT+ENTER
    3. Run keytool to import certificate:
      • (Replace yourAliasName and path\to\certificate.cer respectively)

     ..\..\bin\keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias yourAliasName -file path\to\certificate.cer
    

    This way you don't have to specify any additional JVM options and the certificate should be recognized by the JRE.

    C++ display stack trace on exception

    It depends which platform.

    On GCC it's pretty trivial, see this post for more details.

    On MSVC then you can use the StackWalker library that handles all of the underlying API calls needed for Windows.

    You'll have to figure out the best way to integrate this functionality into your app, but the amount of code you need to write should be minimal.

    How to add /usr/local/bin in $PATH on Mac

    I tend to find this neat

    sudo mkdir -p /etc/paths.d   # was optional in my case
    echo /usr/local/git/bin  | sudo tee /etc/paths.d/mypath1
    

    Mail multipart/alternative vs multipart/mixed

    Use multipart/mixed with the first part as multipart/alternative and subsequent parts for the attachments. In turn, use text/plain and text/html parts within the multipart/alternative part.

    A capable email client should then recognise the multipart/alternative part and display the text part or html part as necessary. It should also show all of the subsequent parts as attachment parts.

    The important thing to note here is that, in multipart MIME messages, it is perfectly valid to have parts within parts. In theory, that nesting can extend to any depth. Any reasonably capable email client should then be able to recursively process all of the message parts.

    How Do I Make Glyphicons Bigger? (Change Size?)

    I've used bootstrap header classes ("h1", "h2", etc.) for this. This way you get all the style benefits without using the actual tags. Here is an example:

    <div class="h3"><span class="glyphicon glyphicon-tags" aria-hidden="true"></span></div>

    Event system in Python

    PyPI packages

    As of January 2021, these are the event-related packages available on PyPI, ordered by most recent release date.

    There's more

    That's a lot of libraries to choose from, using very different terminology (events, signals, handlers, method dispatch, hooks, ...).

    I'm trying to keep an overview of the above packages, plus the techniques mentioned in the answers here.

    First, some terminology...

    Observer pattern

    The most basic style of event system is the 'bag of handler methods', which is a simple implementation of the Observer pattern.

    Basically, the handler methods (callables) are stored in an array and are each called when the event 'fires'.

    Publish-Subscribe

    The disadvantage of Observer event systems is that you can only register the handlers on the actual Event object (or handlers list). So at registration time the event already needs to exist.

    That's why the second style of event systems exists: the publish-subscribe pattern. Here, the handlers don't register on an event object (or handler list), but on a central dispatcher. Also the notifiers only talk to the dispatcher. What to listen for, or what to publish is determined by 'signal', which is nothing more than a name (string).

    Mediator pattern

    Might be of interest as well: the Mediator pattern.

    Hooks

    A 'hook' system is usally used in the context of application plugins. The application contains fixed integration points (hooks), and each plugin may connect to that hook and perform certain actions.

    Other 'events'

    Note: threading.Event is not an 'event system' in the above sense. It's a thread synchronization system where one thread waits until another thread 'signals' the Event object.

    Network messaging libraries often use the term 'events' too; sometimes these are similar in concept; sometimes not. They can of course traverse thread-, process- and computer boundaries. See e.g. pyzmq, pymq, Twisted, Tornado, gevent, eventlet.

    Weak references

    In Python, holding a reference to a method or object ensures that it won't get deleted by the garbage collector. This can be desirable, but it can also lead to memory leaks: the linked handlers are never cleaned up.

    Some event systems use weak references instead of regular ones to solve this.

    Some words about the various libraries

    Observer-style event systems:

    • zope.event shows the bare bones of how this works (see Lennart's answer). Note: this example does not even support handler arguments.
    • LongPoke's 'callable list' implementation shows that such an event system can be implemented very minimalistically by subclassing list.
    • Felk's variation EventHook also ensures the signatures of callees and callers.
    • spassig's EventHook (Michael Foord's Event Pattern) is a straightforward implementation.
    • Josip's Valued Lessons Event class is basically the same, but uses a set instead of a list to store the bag, and implements __call__ which are both reasonable additions.
    • PyNotify is similar in concept and also provides additional concepts of variables and conditions ('variable changed event'). Homepage is not functional.
    • axel is basically a bag-of-handlers with more features related to threading, error handling, ...
    • python-dispatch requires the even source classes to derive from pydispatch.Dispatcher.
    • buslane is class-based, supports single- or multiple handlers and facilitates extensive type hints.
    • Pithikos' Observer/Event is a lightweight design.

    Publish-subscribe libraries:

    • blinker has some nifty features such as automatic disconnection and filtering based on sender.
    • PyPubSub is a stable package, and promises "advanced features that facilitate debugging and maintaining topics and messages".
    • pymitter is a Python port of Node.js EventEmitter2 and offers namespaces, wildcards and TTL.
    • PyDispatcher seems to emphasize flexibility with regards to many-to-many publication etc. Supports weak references.
    • louie is a reworked PyDispatcher and should work "in a wide variety of contexts".
    • pypydispatcher is based on (you guessed it...) PyDispatcher and also works in PyPy.
    • django.dispatch is a rewritten PyDispatcher "with a more limited interface, but higher performance".
    • pyeventdispatcher is based on PHP's Symfony framework's event-dispatcher.
    • dispatcher was extracted from django.dispatch but is getting fairly old.
    • Cristian Garcia's EventManger is a really short implementation.

    Others:

    • pluggy contains a hook system which is used by pytest plugins.
    • RxPy3 implements the Observable pattern and allows merging events, retry etc.
    • Qt's Signals and Slots are available from PyQt or PySide2. They work as callback when used in the same thread, or as events (using an event loop) between two different threads. Signals and Slots have the limitation that they only work in objects of classes that derive from QObject.

    How do I convert a string to a double in Python?

    >>> x = "2342.34"
    >>> float(x)
    2342.3400000000001
    

    There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).

    How to check a channel is closed or not without reading it?

    it's easier to check first if the channel has elements, that would ensure the channel is alive.

    func isChanClosed(ch chan interface{}) bool {
        if len(ch) == 0 {
            select {
            case _, ok := <-ch:
                return !ok
            }
        }
        return false 
    }
    

    ImportError: No module named enum

    Or run a pip install --upgrade pip enum34

    How to convert SQL Query result to PANDAS Data Structure?

    Here is mine. Just in case if you are using "pymysql":

    import pymysql
    from pandas import DataFrame
    
    host   = 'localhost'
    port   = 3306
    user   = 'yourUserName'
    passwd = 'yourPassword'
    db     = 'yourDatabase'
    
    cnx    = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db)
    cur    = cnx.cursor()
    
    query  = """ SELECT * FROM yourTable LIMIT 10"""
    cur.execute(query)
    
    field_names = [i[0] for i in cur.description]
    get_data = [xx for xx in cur]
    
    cur.close()
    cnx.close()
    
    df = DataFrame(get_data)
    df.columns = field_names
    

    What is "string[] args" in Main class for?

    For passing in command line parameters. For example args[0] will give you the first command line parameter, if there is one.

    Get local IP address in Node.js

    Here's a simplified version in vanilla JavaScript to obtain a single IP address:

    function getServerIp() {
    
      var os = require('os');
      var ifaces = os.networkInterfaces();
      var values = Object.keys(ifaces).map(function(name) {
        return ifaces[name];
      });
      values = [].concat.apply([], values).filter(function(val){
        return val.family == 'IPv4' && val.internal == false;
      });
    
      return values.length ? values[0].address : '0.0.0.0';
    }
    

    How to grab substring before a specified character jQuery or JavaScript

    almost the same thing as David G's answer but without the anonymous function, if you don't feel like including one.

    s = s.substr(0, s.indexOf(',') === -1 ? s.length : s.indexOf(','));
    

    in this case we make use of the fact that the second argument of substr is a length, and that we know our substring is starting at 0.

    the top answer is not a generic solution because of the undesirable behavior if the string doesn't contain the character you are looking for.

    if you want correct behavior in a generic case, use this method or David G's method, not the top answer

    regex and split methods will also work, but may be somewhat slower / overkill for this specific problem.