Programs & Examples On #Exception

An exception is an unusual condition that requires deviation from the program's normal flow. Normally, an exception should not result in total failure, but instead be attended by an exception handler. Exception handling is a built-in construct in many programming languages. Usually, exceptions are handled by unwinding the stack, thus rolling back to a defined state outside the exception's scope, and then invoking a handler block or routine.

python exception message capturing

for the future strugglers, in python 3.8.2(and maybe a few versions before that), the syntax is

except Attribute as e:
    print(e)

What could cause java.lang.reflect.InvocationTargetException?

The exception is thrown if

InvocationTargetException - if the underlying method throws an exception.

So if the method, that has been invoked with reflection API, throws an exception (runtime exception for example), the reflection API will wrap the exception into an InvocationTargetException.

When to catch java.lang.Error?

It might be appropriate to catch error within unit tests that check an assertion is made. If someone disables assertions or otherwise deletes the assertion you would want to know

WPF global exception handler

I use the following code in my WPF apps to show a "Sorry for the inconvenience" dialog box whenever an unhandled exception occurs. It shows the exception message, and asks user whether they want to close the app or ignore the exception and continue (the latter case is convenient when a non-fatal exceptions occur and user can still normally continue to use the app).

In App.xaml add the Startup event handler:

<Application .... Startup="Application_Startup">

In App.xaml.cs code add Startup event handler function that will register the global application event handler:

using System.Windows.Threading;

private void Application_Startup(object sender, StartupEventArgs e)
{
    // Global exception handling  
    Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(AppDispatcherUnhandledException);    
}

void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{    
    \#if DEBUG   // In debug mode do not custom-handle the exception, let Visual Studio handle it

    e.Handled = false;

    \#else

    ShowUnhandledException(e);    

    \#endif     
}

void ShowUnhandledException(DispatcherUnhandledExceptionEventArgs e)
{
    e.Handled = true;

    string errorMessage = string.Format("An application error occurred.\nPlease check whether your data is correct and repeat the action. If this error occurs again there seems to be a more serious malfunction in the application, and you better close it.\n\nError: {0}\n\nDo you want to continue?\n(if you click Yes you will continue with your work, if you click No the application will close)",

    e.Exception.Message + (e.Exception.InnerException != null ? "\n" + 
    e.Exception.InnerException.Message : null));

    if (MessageBox.Show(errorMessage, "Application Error", MessageBoxButton.YesNoCancel, MessageBoxImage.Error) == MessageBoxResult.No)   {
        if (MessageBox.Show("WARNING: The application will close. Any changes will not be saved!\nDo you really want to close it?", "Close the application!", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
    {
        Application.Current.Shutdown();
    } 
}

Custom exception type

Use the throw statement.

JavaScript doesn't care what the exception type is (as Java does). JavaScript just notices, there's an exception and when you catch it, you can "look" what the exception "says".

If you have different exception types you have to throw, I'd suggest to use variables which contain the string/object of the exception i.e. message. Where you need it use "throw myException" and in the catch, compare the caught exception to myException.

Log exception with traceback

You can get the traceback using a logger, at any level (DEBUG, INFO, ...). Note that using logging.exception, the level is ERROR.

# test_app.py
import sys
import logging

logging.basicConfig(level="DEBUG")

def do_something():
    raise ValueError(":(")

try:
    do_something()
except Exception:
    logging.debug("Something went wrong", exc_info=sys.exc_info())
DEBUG:root:Something went wrong
Traceback (most recent call last):
  File "test_app.py", line 10, in <module>
    do_something()
  File "test_app.py", line 7, in do_something
    raise ValueError(":(")
ValueError: :(

EDIT:

This works too (using python 3.6)

logging.debug("Something went wrong", exc_info=True)

How using try catch for exception handling is best practice

The second approach is a good one.

If you don't want to show the error and confuse the user of application by showing runtime exception(i.e. error) which is not related to them, then just log error and the technical team can look for the issue and resolve it.

try
{
  //do some work
}
catch(Exception exception)
{
   WriteException2LogFile(exception);//it will write the or log the error in a text file
}

I recommend that you go for the second approach for your whole application.

IllegalArgumentException or NullPointerException for a null parameter?

You should be using IllegalArgumentException (IAE), not NullPointerException (NPE) for the following reasons:

First, the NPE JavaDoc explicitly lists the cases where NPE is appropriate. Notice that all of them are thrown by the runtime when null is used inappropriately. In contrast, the IAE JavaDoc couldn't be more clear: "Thrown to indicate that a method has been passed an illegal or inappropriate argument." Yup, that's you!

Second, when you see an NPE in a stack trace, what do you assume? Probably that someone dereferenced a null. When you see IAE, you assume the caller of the method at the top of the stack passed in an illegal value. Again, the latter assumption is true, the former is misleading.

Third, since IAE is clearly designed for validating parameters, you have to assume it as the default choice of exception, so why would you choose NPE instead? Certainly not for different behavior -- do you really expect calling code to catch NPE's separately from IAE and do something different as a result? Are you trying to communicate a more specific error message? But you can do that in the exception message text anyway, as you should for all other incorrect parameters.

Fourth, all other incorrect parameter data will be IAE, so why not be consistent? Why is it that an illegal null is so special that it deserves a separate exception from all other types of illegal arguments?

Finally, I accept the argument given by other answers that parts of the Java API use NPE in this manner. However, the Java API is inconsistent with everything from exception types to naming conventions, so I think just blindly copying (your favorite part of) the Java API isn't a good enough argument to trump these other considerations.

slf4j: how to log formatted message, object array, exception

As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.

So, writing (in SLF4J version 1.7.x and later)

 logger.error("one two three: {} {} {}", "a", "b", 
              "c", new Exception("something went wrong"));

or writing (in SLF4J version 1.6.x)

 logger.error("one two three: {} {} {}", new Object[] {"a", "b", 
              "c", new Exception("something went wrong")});

will yield

one two three: a b c
java.lang.Exception: something went wrong
    at Example.main(Example.java:13)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at ...

The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.

How to create a custom exception type in Java?

You can create you own exception by inheriting from java.lang.Exception Here is an example that can help you do that.

What is a good way to handle exceptions when trying to read a file in python?

Here is a read/write example. The with statements insure the close() statement will be called by the file object regardless of whether an exception is thrown. http://effbot.org/zone/python-with-statement.htm

import sys

fIn = 'symbolsIn.csv'
fOut = 'symbolsOut.csv'

try:
   with open(fIn, 'r') as f:
      file_content = f.read()
      print "read file " + fIn
   if not file_content:
      print "no data in file " + fIn
      file_content = "name,phone,address\n"
   with open(fOut, 'w') as dest:
      dest.write(file_content)
      print "wrote file " + fOut
except IOError as e:
   print "I/O error({0}): {1}".format(e.errno, e.strerror)
except: #handle other exceptions such as attribute errors
   print "Unexpected error:", sys.exc_info()[0]
print "done"

Exception: Serialization of 'Closure' is not allowed

As already stated: closures, out of the box, cannot be serialized.

However, using the __sleep(), __wakeup() magic methods and reflection u CAN manually make closures serializable. For more details see extending-php-5-3-closures-with-serialization-and-reflection

This makes use of reflection and the php function eval. Do note this opens up the possibility of CODE injection, so please take notice of WHAT you are serializing.

Getting the exception value in Python

Use repr() and The difference between using repr and str

Using repr:

>>> try:
...     print(x)
... except Exception as e:
...     print(repr(e))
... 
NameError("name 'x' is not defined")

Using str:

>>> try:
...     print(x)
... except Exception as e:
...     print(str(e))
... 
name 'x' is not defined

How can I throw a general exception in Java?

It depends. You can throw a more general exception, or a more specific exception. For simpler methods, more general exceptions are enough. If the method is complex, then, throwing a more specific exception will be reliable.

How do I create a custom Error in JavaScript?

This is implemented nicely in the Cesium DeveloperError:

In it's simplified form:

var NotImplementedError = function(message) {
    this.name = 'NotImplementedError';
    this.message = message;
    this.stack = (new Error()).stack;
}

// Later on...

throw new NotImplementedError();

When should I really use noexcept?

There are many examples of functions that I know will never throw, but for which the compiler cannot determine so on its own. Should I append noexcept to the function declaration in all such cases?

When you say "I know [they] will never throw", you mean by examining the implementation of the function you know that the function will not throw. I think that approach is inside out.

It is better to consider whether a function may throw exceptions to be part of the design of the function: as important as the argument list and whether a method is a mutator (... const). Declaring that "this function never throws exceptions" is a constraint on the implementation. Omitting it does not mean the function might throw exceptions; it means that the current version of the function and all future versions may throw exceptions. It is a constraint that makes the implementation harder. But some methods must have the constraint to be practically useful; most importantly, so they can be called from destructors, but also for implementation of "roll-back" code in methods that provide the strong exception guarantee.

Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

Well after doing some more searching I discovered the error may be related to other issues as invalid keystores, passwords etc.

I then remembered that I had set two VM arguments for when I was testing SSL for my network connectivity.

I removed the following VM arguments to fix the problem:

-Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456

Note: this keystore no longer exists so that's probably why the Exception.

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

try to clear workspace.

rm -rf ' ~/Library/Application\ Support/"your programm name" '

How can I get the line number which threw exception?

Extension Method

static class ExceptionHelpers
{
    public static int LineNumber(this Exception ex)
    {
        int n;
        int i = ex.StackTrace.LastIndexOf(" ");
        if (i > -1)
        {
            string s = ex.StackTrace.Substring(i + 1);
            if (int.TryParse(s, out n))
                return n;
        }
        return -1;
    }
}

Usage

try
{
    throw new Exception("A new error happened");
}
catch (Exception ex)
{
    //If error in exception LineNumber() will be -1
    System.Diagnostics.Debug.WriteLine("[" + ex.LineNumber() + "] " + ex.Message);
}

Is it good practice to make the constructor throw an exception?

You do not need to throw a checked exception. This is a bug within the control of the program, so you want to throw an unchecked exception. Use one of the unchecked exceptions already provided by the Java language, such as IllegalArgumentException, IllegalStateException or NullPointerException.

You may also want to get rid of the setter. You've already provided a way to initiate age through the constructor. Does it need to be updated once instantiated? If not, skip the setter. A good rule, do not make things more public than necessary. Start with private or default, and secure your data with final. Now everyone knows that Person has been constructed properly, and is immutable. It can be used with confidence.

Most likely this is what you really need:

class Person { 

  private final int age;   

  Person(int age) {    

    if (age < 0) 
       throw new IllegalArgumentException("age less than zero: " + age); 

    this.age = age;   
  }

  // setter removed

How do I check if a variable exists?

Like so:

def no(var):
    "give var as a string (quote it like 'var')"
    assert(var not in vars())
    assert(var not in globals())
    assert(var not in vars(__builtins__))
    import keyword
    assert(var not in keyword.kwlist)

Then later:

no('foo')
foo = ....

If your new variable foo is not safe to use, you'll get an AssertionError exception which will point to the line that failed, and then you will know better. Here is the obvious contrived self-reference:

no('no')

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-88-d14ecc6b025a> in <module>
----> 1 no('no')

<ipython-input-86-888a9df72be0> in no(var)
      2     "give var as a string (quote it)"
      3     assert( var not in vars())
----> 4     assert( var not in globals())
      5     assert( var not in vars(__builtins__))
      6     import keyword

AssertionError: 

"NoClassDefFoundError: Could not initialize class" error

You're missing the necessary class definition; typically caused by required JAR not being in classpath.

From J2SE API:

public class NoClassDefFoundError extends LinkageError

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

This always can happen in DataBinding. Try to stay away from adding logic in your bindings, including appending an empty string. You can make your own custom adapter, and use it multiple times.

@BindingAdapter("numericText")
fun numericText(textView: TextView, value: Number?) {
    value?.let {
        textView.text = value.toString()
    }
}

<TextView app:numericText="@{list.size()}" .../>

How to avoid a System.Runtime.InteropServices.COMException?

I came across System.Runtime.InteropServices.COMException while opening a project solution. Sometimes user doesn't have enough priveleges to run some COM Methods. I ran Visual Studio as Administrator and the exception was gone.

How do you assert that a certain exception is thrown in JUnit 4 tests?

JUnit 5 Solution

@Test
void testFooThrowsIndexOutOfBoundsException() {    
  Throwable exception = expectThrows( IndexOutOfBoundsException.class, foo::doStuff );

  assertEquals( "some message", exception.getMessage() );
}

More Infos about JUnit 5 on http://junit.org/junit5/docs/current/user-guide/#writing-tests-assertions

How to throw std::exceptions with variable messages?

The standard exceptions can be constructed from a std::string:

#include <stdexcept>

char const * configfile = "hardcode.cfg";
std::string const anotherfile = get_file();

throw std::runtime_error(std::string("Failed: ") + configfile);
throw std::runtime_error("Error: " + anotherfile);

Note that the base class std::exception can not be constructed thus; you have to use one of the concrete, derived classes.

throwing exceptions out of a destructor

Everyone else has explained why throwing destructors are terrible... what can you do about it? If you're doing an operation that may fail, create a separate public method that performs cleanup and can throw arbitrary exceptions. In most cases, users will ignore that. If users want to monitor the success/failure of the cleanup, they can simply call the explicit cleanup routine.

For example:

class TempFile {
public:
    TempFile(); // throws if the file couldn't be created
    ~TempFile() throw(); // does nothing if close() was already called; never throws
    void close(); // throws if the file couldn't be deleted (e.g. file is open by another process)
    // the rest of the class omitted...
};

Which exception should I raise on bad/illegal argument combinations in Python?

I'm not sure I agree with inheritance from ValueError -- my interpretation of the documentation is that ValueError is only supposed to be raised by builtins... inheriting from it or raising it yourself seems incorrect.

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

-- ValueError documentation

Counting the number of occurences of characters in a string

You should be able to utilize the StringUtils class and the countMatches() method.

public static int countMatches(String str, String sub)

Counts how many times the substring appears in the larger String.

Try the following:

int count = StringUtils.countMatches("a.b.c.d", ".");

How do you test that a Python function throws an exception?

The code in my previous answer can be simplified to:

def test_afunction_throws_exception(self):
    self.assertRaises(ExpectedException, afunction)

And if afunction takes arguments, just pass them into assertRaises like this:

def test_afunction_throws_exception(self):
    self.assertRaises(ExpectedException, afunction, arg1, arg2)

sql try/catch rollback/commit - preventing erroneous commit after rollback

Below might be useful.

Source: https://msdn.microsoft.com/en-us/library/ms175976.aspx

BEGIN TRANSACTION;

BEGIN TRY
    -- your code --
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

Troubleshooting BadImageFormatException

This error "Could not load file or assembly 'example' or one of its dependencies. An attempt was made to load a program with an incorrect format" is typically caused by an incorrect application pool configuration.

  1. Ensure that the AppPool your site is currently running on has "Enable 32-Bit Applications" set to False.
  2. Ensure you are using the correct version for your platform.
  3. If you are getting this error on a web site, ensure that your application pool is set to run in the correct mode (3.0 sites should run in 64 bit mode)
  4. You should also make sure that the reference to that assembly in visual studio is pointing at the correct file in the packages folder.
  5. Ensure you have the correct version of the dll installed in the GAC for 2.0 sites.
  6. This can also be caused by WSODLibs being promoted with the web project.

Why doesn't catching Exception catch RuntimeException?

class Test extends Thread
{
    public void run(){  
        try{  
            Thread.sleep(10000);  
        }catch(InterruptedException e){  
            System.out.println("test1");
            throw new RuntimeException("Thread interrupted..."+e);  
        }  

    }  

    public static void main(String args[]){  
        Test t1=new Test1();  
        t1.start();  
        try{  
            t1.interrupt();  
        }catch(Exception e){
            System.out.println("test2");
            System.out.println("Exception handled "+e);
        }  

    }  
}

Its output doesn't contain test2 , so its not handling runtime exception. @jon skeet, @Jan Zyka

Exception thrown in catch and finally clause

class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}

public class C1 {
    public static void main(String[] args) throws Exception {
        try {
            System.out.print("TryA L1\n");
            q();
            System.out.print("TryB L1\n");
        }
        catch (Exception i) {
            System.out.print("Catch L1\n");                
        }
        finally {
            System.out.print("Finally L1\n");
            throw new MyExc1();
        }
    }

    static void q() throws Exception {
        try {
            System.out.print("TryA L2\n");
            q2();
            System.out.print("TryB L2\n");
        }
        catch (Exception y) {
            System.out.print("Catch L2\n");
            throw new MyExc2();  
        }
        finally {
            System.out.print("Finally L2\n");
            throw new Exception();
        }
    }

    static void q2() throws Exception {
        throw new MyExc1();
    }
}

Order:

TryA L1
TryA L2
Catch L2
Finally L2
Catch L1
Finally L1        
Exception in thread "main" MyExc1 at C1.main(C1.java:30)

https://www.compilejava.net/

C# - Substring: index and length must refer to a location within the string

Try This:

 int positionOfJPG=url.IndexOf(".jpg");
 string newString = url.Substring(18, url.Length - positionOfJPG);

django MultiValueDictKeyError error, how do I deal with it

Use the MultiValueDict's get method. This is also present on standard dicts and is a way to fetch a value while providing a default if it does not exist.

is_private = request.POST.get('is_private', False)

Generally,

my_var = dict.get(<key>, <default>)

Causes of getting a java.lang.VerifyError

I fixed this error on Android by making the project I was importing a library, as described here http://developer.android.com/tools/projects/projects-eclipse.html#SettingUpLibraryProject

Previously, I was just referencing the project (not making it a library) and I was getting this strange VerifyError.

Hope it helps someone.

Stack smashing detected

Another source of stack smashing is (incorrect) use of vfork() instead of fork().

I just debugged a case of this, where the child process was unable to execve() the target executable and returned an error code rather than calling _exit().

Because vfork() had spawned that child, it returned while actually still executing within the parent's process space, not only corrupting the parent's stack, but causing two disparate sets of diagnostics to be printed by "downstream" code.

Changing vfork() to fork() fixed both problems, as did changing the child's return statement to _exit() instead.

But since the child code precedes the execve() call with calls to other routines (to set the uid/gid, in this particular case), it technically does not meet the requirements for vfork(), so changing it to use fork() is correct here.

(Note that the problematic return statement was not actually coded as such -- instead, a macro was invoked, and that macro decided whether to _exit() or return based on a global variable. So it wasn't immediately obvious that the child code was nonconforming for vfork() usage.)

For more information, see:

The difference between fork(), vfork(), exec() and clone()

Eclipse - java.lang.ClassNotFoundException

Well, you can solve this problem basically by creating a new project.

  1. Close the project (save the code in another folder on your computer).
  2. Create a new project (add a new final directory and do not leave the default directory selected).
  3. Remake your previous project adding the code saved before.

This happens because probably you created a project and didn't select a directory/folder or something like that. I hope had helped you!

c++ exception : throwing std::string

Yes. std::exception is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?

boost has an excellent document on good style for exceptions and error handling. It's worth a read.

How to solve java.lang.NoClassDefFoundError?

This error means you didn't add some of dependencies.

Identifying Exception Type in a handler Catch Block

try
{
}
catch (Exception err)
{
    if (err is Web2PDFException)
        DoWhatever();
}

but there is probably a better way of doing whatever it is you want.

How to create custom exceptions in Java?

For a checked exception:

public class MyCustomException extends Exception { }

Technically, anything that extends Throwable can be an thrown, but exceptions are generally extensions of the Exception class so that they're checked exceptions (except RuntimeException or classes based on it, which are not checked), as opposed to the other common type of throwable, Errors which usually are not something designed to be gracefully handled beyond the JVM internals.

You can also make exceptions non-public, but then you can only use them in the package that defines them, as opposed to across packages.

As far as throwing/catching custom exceptions, it works just like the built-in ones - throw via

throw new MyCustomException()

and catch via

catch (MyCustomException e) { }

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

If you want to do this by code, you can add the behavior like this:

serviceHost.Description.Behaviors.Remove(
    typeof(ServiceDebugBehavior));
serviceHost.Description.Behaviors.Add(
    new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });

Catching FULL exception message

I found it!

Simply print out $Error[0] for the last error message.

How to throw an exception in C?

Plain old C doesn't actually support exceptions natively.

You can use alternative error handling strategies, such as:

  • returning an error code
  • returning FALSE and using a last_error variable or function.

See http://en.wikibooks.org/wiki/C_Programming/Error_handling.

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

int len = qs.Length % 4;
            if (len > 0) qs = qs.PadRight(qs.Length + (4 - len), '=');

where qs is any base64 encoded string

Why doesn't list have safe "get" method like dictionary?

For small index values you can implement

my_list.get(index, default)

as

(my_list + [default] * (index + 1))[index]

If you know in advance what index is then this can be simplified, for example if you knew it was 1 then you could do

(my_list + [default, default])[index]

Because lists are forward packed the only fail case we need to worry about is running off the end of the list. This approach pads the end of the list with enough defaults to guarantee that index is covered.

how to print an exception using logger?

Try to log the stack trace like below:

logger.error("Exception :: " , e);

Why am I getting "Thread was being aborted" in ASP.NET?

Nope, ThreadAbortException is thrown by a simple Response.Redirect

How do I get ruby to print a full backtrace instead of a truncated one?

[examine all threads backtraces to find the culprit]
Even fully expanded call stack can still hide the actual offending line of code from you when you use more than one thread!

Example: One thread is iterating ruby Hash, other thread is trying to modify it. BOOM! Exception! And the problem with the stack trace you get while trying to modify 'busy' hash is that it shows you chain of functions down to the place where you're trying to modify hash, but it does NOT show who's currently iterating it in parallel (who owns it)! Here's the way to figure that out by printing stack trace for ALL currently running threads. Here's how you do this:

# This solution was found in comment by @thedarkone on https://github.com/rails/rails/issues/24627
rescue Object => boom

    thread_count = 0
    Thread.list.each do |t|
      thread_count += 1
      err_msg += "--- thread #{thread_count} of total #{Thread.list.size} #{t.object_id} backtrace begin \n"
      # Lets see if we are able to pin down the culprit
      # by collecting backtrace for all existing threads:
      err_msg += t.backtrace.join("\n")
      err_msg += "\n---thread #{thread_count} of total #{Thread.list.size} #{t.object_id} backtrace end \n"
    end

    # and just print it somewhere you like:
    $stderr.puts(err_msg)

    raise # always reraise
end

The above code snippet is useful even just for educational purposes as it can show you (like x-ray) how many threads you actually have (versus how many you thought you have - quite often those two are different numbers ;)

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I found a possible solution here: http://www.made4dotnet.com/Default.aspx?tabid=141&aid=15

Edit:

If you automate Microsoft Excel with Microsoft Visual Basic .NET, Microsoft Visual C# .NET, or Microsoft Visual C++, you may receive the following errors when calling certain methods because the machine has the locale set to something other than US English (locale ID or LCID 1033):

Exception from HRESULT: 0x800A03EC

and/or

Old format or invalid type library

SOLUTION 1:


To get around this error you can set CurrentCulture to en-US when executing code related to Excel and reset back to your originale by using these 2 functions.

//declare a variable to hold the CurrentCulture
System.Globalization.CultureInfo oldCI;
//get the old CurrenCulture and set the new, en-US
void SetNewCurrentCulture()
{
  oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
  System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
//reset Current Culture back to the originale
void ResetCurrentCulture()
{
  System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}

SOLUTION 2:


Another solution that could work, create a 1033 directory under Microsoft Office\Office11 (or your corresponding office-version), copy excel.exe to the 1033 directory, and rename it to xllex.dll.

Although you might solve the problem using one off these solutions, when you call the Excel object model in locales other than US English, the Excel object model can act differently and your code can fail in ways you may not have thought of. For example, you might have code that sets the value of a range to a date:

yourRange.Value2 = "10/10/09"

Depending on the locale this code can act differently resulting in Excel putting into the range any of the following values:

October 10, 2009 September 10, 2009 October 9, 2010

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

Replace

List<String> list=Arrays.asList(split);

to

List<String> list = New ArrayList<>();
list.addAll(Arrays.asList(split));

or

List<String> list = new ArrayList<>(Arrays.asList(split));

or

List<String> list = new ArrayList<String>(Arrays.asList(split));

or (Better for Remove elements)

List<String> list = new LinkedList<>(Arrays.asList(split));

How to get exception message in Python properly

To improve on the answer provided by @artofwarfare, here is what I consider a neater way to check for the message attribute and print it or print the Exception object as a fallback.

try:
    pass 
except Exception as e:
    print getattr(e, 'message', repr(e))

The call to repr is optional, but I find it necessary in some use cases.


Update #1:

Following the comment by @MadPhysicist, here's a proof of why the call to repr might be necessary. Try running the following code in your interpreter:

try:
    raise Exception 
except Exception as e:
    print(getattr(e, 'message', repr(e)))
    print(getattr(e, 'message', str(e)))

Update #2:

Here is a demo with specifics for Python 2.7 and 3.5: https://gist.github.com/takwas/3b7a6edddef783f2abddffda1439f533

How to print an exception in Python?

Python 3: logging

Instead of using the basic print() function, the more flexible logging module can be used to log the exception. The logging module offers a lot extra functionality, e.g. logging messages into a given log file, logging messages with timestamps and additional information about where the logging happened. (For more information check out the official documentation.)

Logging an exception can be done with the module-level function logging.exception() like so:

import logging

try:
    1/0
except BaseException:
    logging.exception("An exception was thrown!")

Output:

ERROR:root:An exception was thrown!
Traceback (most recent call last):
  File ".../Desktop/test.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero 

Notes:

  • the function logging.exception() should only be called from an exception handler

  • the logging module should not be used inside a logging handler to avoid a RecursionError (thanks @PrakharPandey)


Alternative log-levels

It's also possible to log the exception with another log-level by using the keyword argument exc_info=True like so:

logging.debug("An exception was thrown!", exc_info=True)
logging.info("An exception was thrown!", exc_info=True)
logging.warning("An exception was thrown!", exc_info=True)

Cannot delete directory with Directory.Delete(path, true)

Is it possible you have a race condition where another thread or process is adding files to the directory:

The sequence would be:

Deleter process A:

  1. Empty the directory
  2. Delete the (now empty) directory.

If someone else adds a file between 1 & 2, then maybe 2 would throw the exception listed?

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

In my case I ran on this problem while using Edge.js — all the problem was a JavaScript syntax error inside a C# Edge.js function definition.

Exception in thread "main" java.util.NoSuchElementException

You close the second Scanner which closes the underlying InputStream, therefore the first Scanner can no longer read from the same InputStream and a NoSuchElementException results.

The solution: For console apps, use a single Scanner to read from System.in.

Aside: As stated already, be aware that Scanner#nextInt does not consume newline characters. Ensure that these are consumed before attempting to call nextLine again by using Scanner#newLine().

See: Do not create multiple buffered wrappers on a single InputStream

"Exception has been thrown by the target of an invocation" error (mscorlib)

' Get the your application's application domain.
Dim currentDomain As AppDomain = AppDomain.CurrentDomain 

' Define a handler for unhandled exceptions.
AddHandler currentDomain.UnhandledException, AddressOf MYExHandler 

' Define a handler for unhandled exceptions for threads behind forms.
AddHandler Application.ThreadException, AddressOf MYThreadHandler 

Private Sub MYExnHandler(ByVal sender As Object, _
ByVal e As UnhandledExceptionEventArgs) 
Dim EX As Exception 
EX = e.ExceptionObject 
Console.WriteLine(EX.StackTrace) 
End Sub 

Private Sub MYThreadHandler(ByVal sender As Object, _
ByVal e As Threading.ThreadExceptionEventArgs) 
Console.WriteLine(e.Exception.StackTrace) 
End Sub

' This code will throw an exception and will be caught.  
Dim X as Integer = 5
X = X / 0 'throws exception will be caught by subs below

How do I raise an exception in Rails so it behaves like other Rails exceptions?

You don't have to do anything special, it should just be working.

When I have a fresh rails app with this controller:

class FooController < ApplicationController
  def index
    raise "error"
  end
end

and go to http://127.0.0.1:3000/foo/

I am seeing the exception with a stack trace.

You might not see the whole stacktrace in the console log because Rails (since 2.3) filters lines from the stack trace that come from the framework itself.

See config/initializers/backtrace_silencers.rb in your Rails project

What's a good way to extend Error in JavaScript?

The snippet shows it all.

function add(x, y) {
      if (x && y) {
        return x + y;
      } else {
        /**
         * 
         * the error thrown will be instanceof Error class and InvalidArgsError also
         */
        throw new InvalidArgsError();
        // throw new Invalid_Args_Error(); 
      }
    }

    // Declare custom error using using Class
    class Invalid_Args_Error extends Error {
      constructor() {
        super("Invalid arguments");
        Error.captureStackTrace(this);
      }
    }

    // Declare custom error using Function
    function InvalidArgsError(message) {
      this.message = `Invalid arguments`;
      Error.captureStackTrace(this);
    }
    // does the same magic as extends keyword
    Object.setPrototypeOf(InvalidArgsError.prototype, Error.prototype);

    try{
      add(2)
    }catch(e){
      // true
      if(e instanceof Error){
        console.log(e)
      }
      // true
      if(e instanceof InvalidArgsError){
        console.log(e)
      }
    }

Why is "except: pass" a bad programming practice?

?Handling errors is very important in programming. You do need to show the user what went wrong. In very few cases you can ignore the errors. This is it is very bad programming practice.

Globally catch exceptions in a WPF application?

AppDomain.UnhandledException Event

This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.

   public App()
   {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);    
   }

   static void MyHandler(object sender, UnhandledExceptionEventArgs args) 
   {
      Exception e = (Exception) args.ExceptionObject;
      Console.WriteLine("MyHandler caught : " + e.Message);
      Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
   }

If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.

For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. The first application domain in which the UnhandledException event can be raised is "AD1". If that application domain is not the default application domain, the event can also be raised in the default application domain.

Python: How to ignore an exception and proceed?

Try this:

try:
    blah()
except:
    pass

Mockito test a void method throws an exception

If you ever wondered how to do it using the new BDD style of Mockito:

willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));

And for future reference one may need to throw exception and then do nothing:

willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

Use commitAllowingStateLoss() instead of commit().

when you use commit() it will can throw an exception if state loss occurs but commitAllowingStateLoss() saves transaction without state loss so that will doesn't throw an exception if state loss occurs.

Exception.Message vs Exception.ToString()

Well, I'd say it depends what you want to see in the logs, doesn't it? If you're happy with what ex.Message provides, use that. Otherwise, use ex.toString() or even log the stack trace.

Could not autowire field in spring. why?

In spring servlet .xml :

<context:component-scan base-package="net.controller" />

(I assumed that the service impl is in the same package as the service interface "net.service")

I think you have to add the package net.service (or all of net) to the component scan. Currently spring only searches in net.controller for components and as your service impl is in net.service, it will not be instantiated by spring.

How can I safely create a nested directory?

Check os.makedirs: (It makes sure the complete path exists.)
To handle the fact the directory might exist, catch OSError. (If exist_ok is False (the default), an OSError is raised if the target directory already exists.)

import os
try:
    os.makedirs('./path/to/somewhere')
except OSError:
    pass

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

One cause for this crash is that ArrayList object cannot change completely. So, when I remove an item, I have to do this:

mList.clear();
mList.addAll(newDataList);

This fixed the crash for me.

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

Although this may not be the cause of your issue, you'll get the same error if there are two MySQL services running on the same port. You can check on windows by looking at the list of services in the services tab of Task Manager.

Visual Studio: How to break on handled exceptions?

There is an 'exceptions' window in VS2005 ... try Ctrl+Alt+E when debugging and click on the 'Thrown' checkbox for the exception you want to stop on.

Difference between try-catch and throw in java

In my limited experience with the following details.throws is a declaration that declares multiple exceptions that may occur but do not necessarily occur, throw is an action that can throw only one exception, typically a non-runtime exception, try catch is a block that catches exceptions that can be handled when an exception occurs in a method,this exception can be thrown.An exception can be understood as a responsibility that should be taken care of by the behavior that caused the exception, rather than by its upper callers. I hope my answer will help you

java.lang.IllegalAccessError: tried to access method

I was getting similar exception but at class level

e.g. Caused by: java.lang.IllegalAccessError: tried to access class ....

I fixed this by making my class public.

Catch a thread's exception in the caller thread in Python

The concurrent.futures module makes it simple to do work in separate threads (or processes) and handle any resulting exceptions:

import concurrent.futures
import shutil

def copytree_with_dots(src_path, dst_path):
    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
        # Execute the copy on a separate thread,
        # creating a future object to track progress.
        future = executor.submit(shutil.copytree, src_path, dst_path)

        while future.running():
            # Print pretty dots here.
            pass

        # Return the value returned by shutil.copytree(), None.
        # Raise any exceptions raised during the copy process.
        return future.result()

concurrent.futures is included with Python 3.2, and is available as the backported futures module for earlier versions.

Handling exceptions from Java ExecutorService tasks

WARNING: It should be noted that this solution will block the calling thread.


If you want to process exceptions thrown by the task, then it is generally better to use Callable rather than Runnable.

Callable.call() is permitted to throw checked exceptions, and these get propagated back to the calling thread:

Callable task = ...
Future future = executor.submit(task);
try {
   future.get();
} catch (ExecutionException ex) {
   ex.getCause().printStackTrace();
}

If Callable.call() throws an exception, this will be wrapped in an ExecutionException and thrown by Future.get().

This is likely to be much preferable to subclassing ThreadPoolExecutor. It also gives you the opportunity to re-submit the task if the exception is a recoverable one.

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

As pointed out in the other answers, C++ can support finally-like functionality. The implementation of this functionality that is probably closest to being part of the standard language is the one accompanying the C++ Core Guidelines, a set of best practices for using C++ edited by Bjarne Stoustrup and Herb Sutter. An implementation of finally is part of the Guidelines Support Library (GSL). Throughout the Guidelines, use of finally is recommended when dealing with old-style interfaces, and it also has a guideline of its own, titled Use a final_action object to express cleanup if no suitable resource handle is available.

So, not only does C++ support finally, it is actually recommended to use it in a lot of common use-cases.

An example use of the GSL implementation would look like:

#include <gsl/gsl_util.h>

void example()
{
    int handle = get_some_resource();
    auto handle_clean = gsl::finally([&handle] { clean_that_resource(handle); });

    // Do a lot of stuff, return early and throw exceptions.
    // clean_that_resource will always get called.
}

The GSL implementation and usage is very similar to the one in Paolo.Bolzoni's answer. One difference is that the object created by gsl::finally() lacks the disable() call. If you need that functionality (say, to return the resource once it's assembled and no exceptions are bound to happen), you might prefer Paolo's implementation. Otherwise, using GSL is as close to using standardized features as you will get.

What to do on TransactionTooLargeException

This is not a definitive answer, but it may shed some light on the causes of a TransactionTooLargeException and help pinpoint the problem.

Although most answers refer to large amounts of data transferred, I see this exception being thrown incidentally after heavy scrolling and zooming and repeatedly opening an ActionBar spinner menu. The crash happens on tapping the action bar. (this is a custom mapping app)

The only data being passed around seem to be touches from the "Input Dispatcher" to the app. I think this cannot reasonably amount to anywhere near 1 mb in the "Transaction Buffer".

My app is running on a quad core 1.6 GHz device and uses 3 threads for heavylifting, keeping one core free for the UI thread. Furthermore, the app uses android:largeHeap, has 10 mb of unused heap left and has 100 mb of room left to grow the heap. So I wouldn't say it is a resource issue.

The crash is always immediately preceded by these lines:

W/InputDispatcher( 2271): channel ~ Consumer closed input channel or an error occurred.  events=0x9
E/InputDispatcher( 2271): channel ~ Channel is unrecoverably broken and will be disposed!
E/JavaBinder(28182): !!! FAILED BINDER TRANSACTION !!!

Which are not neccesarily printed in that order, but (as far as I checked) happen on the same millisecond.

And the stack trace itself, for clarity, is the same as in the question:

E/AndroidRuntime(28182): java.lang.RuntimeException: Adding window failed
..
E/AndroidRuntime(28182): Caused by: android.os.TransactionTooLargeException

Delving into the source code of android one finds these lines:

frameworks/base/core/jni/android_util_Binder.cpp:

case FAILED_TRANSACTION:
    ALOGE("!!! FAILED BINDER TRANSACTION !!!");
    // TransactionTooLargeException is a checked exception, only throw from certain methods.
    // FIXME: Transaction too large is the most common reason for FAILED_TRANSACTION
    //        but it is not the only one.  The Binder driver can return BR_FAILED_REPLY
    //        for other reasons also, such as if the transaction is malformed or
    //        refers to an FD that has been closed.  We should change the driver
    //        to enable us to distinguish these cases in the future.
    jniThrowException(env, canThrowRemoteException
            ? "android/os/TransactionTooLargeException"
                    : "java/lang/RuntimeException", NULL);

To me it sounds like I'm possibly hitting this undocumented feature, where the transaction fails for other reasons than a Transaction being TooLarge. They should have named it TransactionTooLargeOrAnotherReasonException.

At this time I did not solve the issue, but if I find something useful I will update this answer.

update: it turned out my code leaked some file descriptors, the number of which is maximized in linux (typically 1024), and this seems to have triggered the exception. So it was a resource issue after all. I verified this by opening /dev/zero 1024 times, which resulted in all kinds of weird exceptions in UI related actions, including the exception above, and even some SIGSEGV's. Apparently failure to open a file/socket is not something which is handled/reported very cleanly throughout Android.

PKIX path building failed in Java application

You've imported the certificate into the truststore of the JRE provided in the JDK, but you are running the java.exe of the JRE installed directly.

EDIT

For clarity, and to resolve the morass of misunderstanding in the commentary below, you need to import the certificate into the cacerts file of the JRE you are intending to use, and that will rarely if ever be the one shipping inside the JDK, because clients won't normally have a JDK. Anything in the commentary below that suggests otherwise should be ignored as not expressing my intention here.

A far better solution would be to create your own truststore, starting with a copy of the cacerts file, and specifically tell Java to use that one via the system property javax.net.ssl.trustStore.

You should make building this part of your build process, so as to keep up to date with changes I the cacerts file caused by JDK upgrades.

Collection was modified; enumeration operation may not execute in ArrayList

using ArrayList also you can try like this

ArrayList arraylist = ... // myobject data list

ArrayList temp = (ArrayList)arraylist.Clone();

foreach (var item in temp)
{
      if (...)
         arraylist.Remove(item);
}

Multiple try codes in one block

You'll have to make this separate try blocks:

try:
    code a
except ExplicitException:
    pass

try:
    code b
except ExplicitException:
    try:
        code c
    except ExplicitException:
        try:
            code d
        except ExplicitException:
            pass

This assumes you want to run code c only if code b failed.

If you need to run code c regardless, you need to put the try blocks one after the other:

try:
    code a
except ExplicitException:
    pass

try:
    code b
except ExplicitException:
    pass

try:
    code c
except ExplicitException:
    pass

try:
    code d
except ExplicitException:
    pass

I'm using except ExplicitException here because it is never a good practice to blindly ignore all exceptions. You'll be ignoring MemoryError, KeyboardInterrupt and SystemExit as well otherwise, which you normally do not want to ignore or intercept without some kind of re-raise or conscious reason for handling those.

Connection Java-MySql : Public Key Retrieval is not allowed

This solution worked for MacOS Sierra, and running MySQL version 8.0.11. Please make sure driver you have added in your build path - "add external jar" should match up with SQL version.

String url = "jdbc:mysql://localhost:3306/syscharacterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

All your problems derive from this

byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
return encrypted;

Which are enclosed in a try, catch block, the problem is that in case the program found an exception you are not returning anything. Put it like this (modify it as your program logic stands):

public static byte[] encrypt(String toEncrypt) throws Exception{
    try{
        String plaintext = toEncrypt;
        String key = "01234567890abcde";
        String iv = "fedcba9876543210";

        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);
        byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());

        return encrypted;
    } catch(Exception e){
        return null;            // Always must return something
    }
}

For the second one you must catch the Exception from the encrypt method call, like this (also modify it as your program logic stands):

public void actionPerformed(ActionEvent e)
  .
  .
  .
    try {
        byte[] encrypted = encrypt(concatURL);
        String encryptedString = bytesToHex(encrypted);
        content.removeAll();
        content.add(new JLabel("Concatenated User Input -->" + concatURL));

        content.add(encryptedTextField);
    setContentPane(content);
    } catch (Exception exc) {
        // TODO: handle exception
    }
}

The lessons you must learn from this:

  • A method with a return-type must always return an object of that type, I mean in all possible scenarios
  • All checked exceptions must always be handled

How should I throw a divide by zero exception in Java without actually dividing by zero?

Do this:

if (denominator == 0) throw new ArithmeticException("denominator == 0");

ArithmeticException is the exception which is normally thrown when you divide by 0.

Exception from HRESULT: 0x800A03EC Error

I know this is old but just to pitch in my experience. I just ran into it this morning. Turns our my error has nothing to do with .xls line limit or array index. It is caused by an incorrect formula.

I was exporting from database to Excel a sheet about my customers. Someone fill in the customer name as =90Erickson-King and apparently this is fine as a string-type field in the database, however will result in an error as a formula in Excel. Instead of showing #N/A like when you're using Excel, the program just froze and spilt that 0x800A03EC error a while later.

I corrected this by deleting the equal sign and the dash in the customer's name. After that exporting went well.

I guess this error code is a bit too general as people are seen reporting quite a range of different possible causes.

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

How to save traceback / sys.exc_info() values in a variable?

This is how I do it:

>>> import traceback
>>> try:
...   int('k')
... except:
...   var = traceback.format_exc()
... 
>>> print var
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'k'

You should however take a look at the traceback documentation, as you might find there more suitable methods, depending to how you want to process your variable afterwards...

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

ListenForClients is getting invoked twice (on two different threads) - once from the constructor, once from the explicit method call in Main. When two instances of the TcpListener try to listen on the same port, you get that error.

How to get Exception Error Code in C#

Building on Preet Sangha's solution, the following should safely cover the scenario where you're working with a large solution with the potential for several Inner Exceptions.

 try
 {
     object result = processClass.InvokeMethod("Create", methodArgs);
 }
 catch (Exception e)
 {
     // Here I was hoping to get an error code.
     if (ExceptionContainsErrorCode(e, 10004))
     {
         // Execute desired actions
     }
 }

...

private bool ExceptionContainsErrorCode(Exception e, int ErrorCode)
{
    Win32Exception winEx = e as Win32Exception;
    if (winEx != null && ErrorCode == winEx.ErrorCode) 
        return true;

    if (e.InnerException != null) 
        return ExceptionContainsErrorCode(e.InnerException, ErrorCode);

    return false;
}

This code has been unit tested.

I won't harp too much on the need for coming to appreciate and implement good practice when it comes to Exception Handling by managing each expected Exception Type within their own blocks.

Is there a difference between "throw" and "throw ex"?

Look at here: http://blog-mstechnology.blogspot.de/2010/06/throw-vs-throw-ex.html

Throw:

try 
{
    // do some operation that can fail
}
catch (Exception ex)
{
    // do some local cleanup
    throw;
}

It preserve the Stack information with Exception

This is called as "Rethrow"

If want to throw new exception,

throw new ApplicationException("operation failed!");

Throw Ex:

try
{
    // do some operation that can fail
}
catch (Exception ex)
{
    // do some local cleanup
    throw ex;
}

It Won't Send Stack information with Exception

This is called as "Breaking the Stack"

If want to throw new exception,

throw new ApplicationException("operation failed!",ex);

How to handle AccessViolationException

You can try using AppDomain.UnhandledException and see if that lets you catch it.

**EDIT*

Here is some more information that might be useful (it's a long read).

How to deserialize a JObject to .NET object

Too late, just in case some one is looking for another way:

void Main()
{
    string jsonString = @"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}";

    Product product = new Product();
    //Serializing to Object
    Product obj = JObject.Parse(jsonString).SelectToken("$.Manufacturers[?(@.Name == 'Acme Co' && @.Name != 'Contoso')]").ToObject<Product>();

    Console.WriteLine(obj);
}


public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Java List.add() UnsupportedOperationException

Many of the List implementation support limited support to add/remove, and Arrays.asList(membersArray) is one of that. You need to insert the record in java.util.ArrayList or use the below approach to convert into ArrayList.

With the minimal change in your code, you can do below to convert a list to ArrayList. The first solution is having a minimum change in your solution, but the second one is more optimized, I guess.

    String[] membersArray = request.getParameterValues('members');
    ArrayList<String> membersList = new ArrayList<>(Arrays.asList(membersArray));

OR

    String[] membersArray = request.getParameterValues('members');
    ArrayList<String> membersList = Stream.of(membersArray).collect(Collectors.toCollection(ArrayList::new));

How to return a value from try, catch, and finally?

Here is another example that return's a boolean value using try/catch.

private boolean doSomeThing(int index){
    try {
        if(index%2==0) 
            return true; 
    } catch (Exception e) {
        System.out.println(e.getMessage()); 
    }finally {
        System.out.println("Finally!!! ;) ");
    }
    return false; 
}

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

URLs use forward slashes (/), not backward ones (as windows). Try:

serverURLS = "https://abc.my.domain.com:55555/update";

The reason why you get the error is that the URL class can't parse the host part of the string and therefore, host is null.

How can I catch all the exceptions that will be thrown through reading and writing a file?

You may catch multiple exceptions in single catch block.

try{
  // somecode throwing multiple exceptions;
} catch (Exception1 | Exception2 | Exception3 exception){
  // handle exception.
} 

Official reasons for "Software caused connection abort: socket write error"

I was facing the same problem with wireMock while mocking the rest API calls. Earlier I was defining the server like this:

WireMockServer wireMockServer = null;

But it should be defined like as shown below:

@Rule 
public WireMockRule wireMockRule = new WireMockRule(8089);

ansible : how to pass multiple commands

You can also do like this:

- command: "{{ item }}"
  args:
    chdir: "/src/package/"
  with_items:
    - "./configure"
    - "/usr/bin/make"
    - "/usr/bin/make install"

Hope that might help other

Python URLLib / URLLib2 POST

u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

Doing a 302 will typically cause clients to convert a POST to a GET request.

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

You can add one Section(with zero rows) above, then set the above sectionFooterView as current section's headerView, footerView doesn't float. Hope it gives a help.

How to initialise a string from NSData in Swift

This is how you should initialize the NSString:

Swift 2.X or older

let datastring = NSString(data: fooData, encoding: NSUTF8StringEncoding)

Swift 3 or newer:

let datastring = NSString(data: fooData, encoding: String.Encoding.utf8.rawValue)

This doc explains the syntax.

How to override equals method in Java

@Override
public boolean equals(Object that){
  if(this == that) return true;//if both of them points the same address in memory

  if(!(that instanceof People)) return false; // if "that" is not a People or a childclass

  People thatPeople = (People)that; // than we can cast it to People safely

  return this.name.equals(thatPeople.name) && this.age == thatPeople.age;// if they have the same name and same age, then the 2 objects are equal unless they're pointing to different memory adresses
}

Command to get nth line of STDOUT

From sed1line:

# print line number 52
sed -n '52p'                 # method 1
sed '52!d'                   # method 2
sed '52q;d'                  # method 3, efficient on large files

From awk1line:

# print line number 52
awk 'NR==52'
awk 'NR==52 {print;exit}'          # more efficient on large files

json.dumps vs flask.jsonify

You can do:

flask.jsonify(**data)

or

flask.jsonify(id=str(album.id), title=album.title)

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

I got this error because I declared a variable (above the ConfigureServices method) of type that was my context. I had:

CupcakeContext _ctx

Not sure what I was thinking. I know it's legal to do this if your passing in a parameter to the Configure method.

Batch file to delete folders older than 10 days in Windows 7

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

I could not get Blorgbeard's suggestion to work, but I was able to get it to work with RMDIR instead of RD:

FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"

Since RMDIR won't delete folders that aren't empty so I also ended up using this code to delete the files that were over 10 days and then the folders that were over 10 days old.

FOR /d %%K in ("n:\test*") DO (

FOR /d %%J in ("%%K*") DO (

FORFILES /P %%J /S /M . /D -10 /C "cmd /c del @file"

)

)

FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"

I used this code to purge out the sub folders in the folders within test (example n:\test\abc\123 would get purged when empty, but n:\test\abc would not get purged

ORA-12516, TNS:listener could not find available handler

I fixed this problem with sql command line:

connect system/<password>
alter system set processes=300 scope=spfile;
alter system set sessions=300 scope=spfile;

Restart database.

Can you force a React component to rerender without calling setState?

You could do it a couple of ways:

1. Use the forceUpdate() method:

There are some glitches that may happen when using the forceUpdate() method. One example is that it ignores the shouldComponentUpdate() method and will re-render the view regardless of whether shouldComponentUpdate() returns false. Because of this using forceUpdate() should be avoided when at all possible.

2. Passing this.state to the setState() method

The following line of code overcomes the problem with the previous example:

this.setState(this.state);

Really all this is doing is overwriting the current state with the current state which triggers a re-rendering. This still isn't necessarily the best way to do things, but it does overcome some of the glitches you might encounter using the forceUpdate() method.

Ansible: deploy on multiple hosts in the same time

I played a long time with things like ls -1 | xargs -P to parallelize my playbooks runs. But to get a prettier display, and simplicity I wrote a simple Python tool to do it, ansible-parallel.

It goes like this:

pip install ansible-parallel
ansible-parallel *.yml

To answer precisely to the original question (how to run some tasks first, and the rest in parallel), it can be solved by removing the 3 includes and running:

ansible-playbook say_hi.yml
ansible-parallel load_balancers.yml webservers.yml dbservers.yml

Does Spring @Transactional attribute work on a private method?

Yes, it is possible to use @Transactional on private methods, but as others have mentioned this won't work out of the box. You need to use AspectJ. It took me some time to figure out how to get it working. I will share my results.

I chose to use compile-time weaving instead of load-time weaving because I think it's an overall better option. Also, I'm using Java 8 so you may need to adjust some parameters.

First, add the dependency for aspectjrt.

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.8</version>
</dependency>

Then add the AspectJ plugin to do the actual bytecode weaving in Maven (this may not be a minimal example).

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <version>1.8</version>
    <configuration>
        <complianceLevel>1.8</complianceLevel>
        <source>1.8</source>
        <target>1.8</target>
        <aspectLibraries>
            <aspectLibrary>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
            </aspectLibrary>
        </aspectLibraries>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Finally add this to your config class

@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)

Now you should be able to use @Transactional on private methods.

One caveat to this approach: You will need to configure your IDE to be aware of AspectJ otherwise if you run the app via Eclipse for example it may not work. Make sure you test against a direct Maven build as a sanity check.

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

It looks like a permissions issue - not a Windows 7 issue.

Your ssh key is not authorised - Permission denied (publickey).

You need to create a public ssh key and ask the administrator of the Git repository to add the ssh public key

Information on how to do this: Saving ssh key fails

Add 10 seconds to a Date

The Date() object in javascript is not that smart really.

If you just focus on adding seconds it seems to handle things smoothly but if you try to add X number of seconds then add X number of minute and hours, etc, to the same Date object you end up in trouble. So I simply fell back to only using the setSeconds() method and converting my data into seconds (which worked fine).

If anyone can demonstrate adding time to a global Date() object using all the set methods and have the final time come out correctly I would like to see it but I get the sense that one set method is to be used at a time on a given Date() object and mixing them leads to a mess.

var vTime = new Date();

var iSecondsToAdd = ( iSeconds + (iMinutes * 60) + (iHours * 3600) + (iDays * 86400) );

vTime.setSeconds(iSecondsToAdd);

Here is some more documentation that may help:

How do you modify a CSS style in the code behind file for divs in ASP.NET?

It's an HtmlGenericControl so not sure what the recommended way to do this is, so you could also do:

testSpace.Attributes.Add("style", "text-align: center;");

or

testSpace.Attributes.Add("class", "centerIt");

or

testSpace.Attributes["style"] = "text-align: center;";

or

testSpace.Attributes["class"] = "centerIt";

How do I use LINQ Contains(string[]) instead of Contains(string)

So am I assuming correctly that uid is a Unique Identifier (Guid)? Is this just an example of a possible scenario or are you really trying to find a guid that matches an array of strings?

If this is true you may want to really rethink this whole approach, this seems like a really bad idea. You should probably be trying to match a Guid to a Guid

Guid id = new Guid(uid);
var query = from xx in table
            where xx.uid == id
            select xx;

I honestly can't imagine a scenario where matching a string array using "contains" to the contents of a Guid would be a good idea. For one thing, Contains() will not guarantee the order of numbers in the Guid so you could potentially match multiple items. Not to mention comparing guids this way would be way slower than just doing it directly.

Select multiple rows with the same value(s)

The problem is GROUP BY - if you group results by Locus, you only get one result per locus.

Try:

SELECT * FROM Genes WHERE Locus = '3' AND Chromosome = '10';

If you prefer using HAVING syntax, then GROUP BY id or something that is not repeating in the result set.

C# how to use enum with switch

The correct answer is already given, nevertheless here is the better way (than switch):

private Dictionary<Operator, Func<int, int, double>> operators =
    new Dictionary<Operator, Func<int, int, double>>
    {
        { Operator.PLUS, ( a, b ) => a + b },
        { Operator.MINUS, ( a, b ) => a - b },
        { Operator.MULTIPLY, ( a, b ) => a * b },
        { Operator.DIVIDE ( a, b ) => (double)a / b },
    };

public double Calculate( int left, int right, Operator op )
{
    return operators.ContainsKey( op ) ? operators[ op ]( left, right ) : 0.0;
}

VBA Count cells in column containing specified value

one way;

var = count("find me", Range("A1:A100"))

function count(find as string, lookin as range) As Long
   dim cell As Range
   for each cell in lookin
       if (cell.Value = find) then count = count + 1 '//case sens
   next
end function

How to solve java.lang.OutOfMemoryError trouble in Android

I see only two options:

  1. You have memory leaks in your application.
  2. Devices do not have enough memory when running your application.

Unique random string generation

Michael Kropats solution in VB.net

Private Function RandomString(ByVal length As Integer, Optional ByVal allowedChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") As String
    If length < 0 Then Throw New ArgumentOutOfRangeException("length", "length cannot be less than zero.")
    If String.IsNullOrEmpty(allowedChars) Then Throw New ArgumentException("allowedChars may not be empty.")


    Dim byteSize As Integer = 256
    Dim hash As HashSet(Of Char) = New HashSet(Of Char)(allowedChars)
    'Dim hash As HashSet(Of String) = New HashSet(Of String)(allowedChars)
    Dim allowedCharSet() = hash.ToArray

    If byteSize < allowedCharSet.Length Then Throw New ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize))


    ' Guid.NewGuid and System.Random are not particularly random. By using a
    ' cryptographically-secure random number generator, the caller is always
    ' protected, regardless of use.
    Dim rng = New System.Security.Cryptography.RNGCryptoServiceProvider()
    Dim result = New System.Text.StringBuilder()
    Dim buf = New Byte(128) {}
    While result.Length < length
        rng.GetBytes(buf)
        Dim i
        For i = 0 To buf.Length - 1 Step +1
            If result.Length >= length Then Exit For
            ' Divide the byte into allowedCharSet-sized groups. If the
            ' random value falls into the last group and the last group is
            ' too small to choose from the entire allowedCharSet, ignore
            ' the value in order to avoid biasing the result.
            Dim outOfRangeStart = byteSize - (byteSize Mod allowedCharSet.Length)
            If outOfRangeStart <= buf(i) Then
                Continue For
            End If
            result.Append(allowedCharSet(buf(i) Mod allowedCharSet.Length))
        Next
    End While
    Return result.ToString()
End Function

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

Yes, if you're having problems with StaleElementReferenceExceptions it's because there is a race condition. Consider the following scenario:

WebElement element = driver.findElement(By.id("foo"));
// DOM changes - page is refreshed, or element is removed and re-added
element.click();

Now at the point where you're clicking the element, the element reference is no longer valid. It's close to impossible for WebDriver to make a good guess about all the cases where this might happen - so it throws up its hands and gives control to you, who as the test/app author should know exactly what may or may not happen. What you want to do is explicitly wait until the DOM is in a state where you know things won't change. For example, using a WebDriverWait to wait for a specific element to exist:

// times out after 5 seconds
WebDriverWait wait = new WebDriverWait(driver, 5);
    
// while the following loop runs, the DOM changes - 
// page is refreshed, or element is removed and re-added
wait.until(presenceOfElementLocated(By.id("container-element")));        

// now we're good - let's click the element
driver.findElement(By.id("foo")).click();

The presenceOfElementLocated() method would look something like this:

private static Function<WebDriver,WebElement> presenceOfElementLocated(final By locator) {
    return new Function<WebDriver, WebElement>() {
        @Override
        public WebElement apply(WebDriver driver) {
            return driver.findElement(locator);
        }
    };
}

You're quite right about the current Chrome driver being quite unstable, and you'll be happy to hear that the Selenium trunk has a rewritten Chrome driver, where most of the implementation was done by the Chromium developers as part of their tree.

PS. Alternatively, instead of waiting explicitly like in the example above, you can enable implicit waits - this way WebDriver will always loop up until the specified timeout waiting for the element to become present:

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)

In my experience though, explicitly waiting is always more reliable.

How to get Django and ReactJS to work together?

I don't have experience with Django but the concepts from front-end to back-end and front-end framework to framework are the same.

  1. React will consume your Django REST API. Front-ends and back-ends aren't connected in any way. React will make HTTP requests to your REST API in order to fetch and set data.
  2. React, with the help of Webpack (module bundler) & Babel (transpiler), will bundle and transpile your Javascript into single or multiple files that will be placed in the entry HTML page. Learn Webpack, Babel, Javascript and React and Redux (a state container). I believe you won't use Django templating but instead allow React to render the front-end.
  3. As this page is rendered, React will consume the API to fetch data so React can render it. Your understanding of HTTP requests, Javascript (ES6), Promises, Middleware and React is essential here.

Here are a few things I've found on the web that should help (based on a quick Google search):

Hope this steers you in the right direction! Good luck! Hopefully others who specialize in Django can add to my response.

Image style height and width not taken in outlook mails

I have same problem for image which is not showing correctly in outlook.and I am using px and % for applying height and width for image. but when i removed px and % and using only just whatever the value in html it is worked for me. For example i was using : width="800px" now I'm using widht="800" and problem is resolved for me.

Slicing a dictionary

You should be iterating over the tuple and checking if the key is in the dict not the other way around, if you don't check if the key exists and it is not in the dict you are going to get a key error:

print({k:d[k] for k in l if k in d})

Some timings:

 {k:d[k] for k in set(d).intersection(l)}

In [22]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in l}
   ....: 
100 loops, best of 3: 11.5 ms per loop

In [23]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in set(d).intersection(l)}
   ....: 
10 loops, best of 3: 20.4 ms per loop

In [24]: %%timeit                        
l = xrange(100000)
l = set(l)                              
{key: d[key] for key in d.viewkeys() & l}
   ....: 
10 loops, best of 3: 24.7 ms per

In [25]: %%timeit                        

l = xrange(100000)
{k:d[k] for k in l if k in d}
   ....: 
100 loops, best of 3: 17.9 ms per loop

I don't see how {k:d[k] for k in l} is not readable or elegant and if all elements are in d then it is pretty efficient.

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

  1. Run your app on the simulator, and save screen shots.

  2. Rename those screen shots to 4.7.1 (iPhone 6), 5.5.1 (iPhone 6 plus) and so on.

Execute JavaScript code stored as a string

One can use mathjs

Snippet from above link:

// evaluate expressions
math.evaluate('sqrt(3^2 + 4^2)')        // 5
math.evaluate('sqrt(-4)')               // 2i
math.evaluate('2 inch to cm')           // 5.08 cm
math.evaluate('cos(45 deg)')            // 0.7071067811865476

// provide a scope
let scope = {
    a: 3,
    b: 4
}
math.evaluate('a * b', scope)           // 12
math.evaluate('c = 2.3 + 4.5', scope)   // 6.8
scope.c                                

scope is any object. So if you pass the global scope to the evalute function, you may be able to execute alert() dynamically.

Also mathjs is much better option than eval() because it runs in a sandbox.

A user could try to inject malicious JavaScript code via the expression parser. The expression parser of mathjs offers a sandboxed environment to execute expressions which should make this impossible. It’s possible though that there are unknown security vulnerabilities, so it’s important to be careful, especially when allowing server side execution of arbitrary expressions.

Newer versions of mathjs does not use eval() or Function().

The parser actively prevents access to JavaScripts internal eval and new Function which are the main cause of security attacks. Mathjs versions 4 and newer does not use JavaScript’s eval under the hood. Version 3 and older did use eval for the compile step. This is not directly a security issue but results in a larger possible attack surface.

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Do I need a content-type header for HTTP GET requests?

The accepted answer is wrong. The quote is correct, the assertion that PUT and POST must have it is incorrect. There is no requirement that PUT or POST actually have additional content. Nor is there a prohibition against GET actually having content.

The RFCs say exactly what they mean .. IFF your side (client OR origin server) will be sending additional content, beyond the HTTP headers, it SHOULD specify a Content-Type header. But note it is allowable to omit the Content-Type and still include content (say, by using a Content-Length header).

Angular - res.json() is not a function

HttpClient.get() applies res.json() automatically and returns Observable<HttpResponse<string>>. You no longer need to call this function yourself.

See Difference between HTTP and HTTPClient in angular 4?

Where is android studio building my .apk file?

Take a look at this question.

TL;DR: clean, then build.

./gradlew clean packageDebug 

Maven error "Failure to transfer..."

Please Make sure that settings.XML file in the folder .m2 is valid first Then after clean the repository using below command in cmd

cd %userprofile%\.m2\repository
for /r %i in (*.lastUpdated) do del %i

How to create a .gitignore file

========== In Windows ==========

  1. Open Notepad.
  2. Add the contents of your gitignore file.
  3. Click "Save as" and select "all files".
  4. Save as .gitignore.

======== Easy peasy! No command line required! ========

How to check if the string is empty?

Another easy way could be to define a simple function:

def isStringEmpty(inputString):
    if len(inputString) == 0:
        return True
    else:
        return False

Rename multiple files in a directory in Python

Here is a more general solution:

This code can be used to remove any particular character or set of characters recursively from all filenames within a directory and replace them with any other character, set of characters or no character.

import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk('C:\FolderName')
        for filename in filenames)

for path in paths:
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory
    newname = path.replace('#', '-')
    if newname != path:
        os.rename(path, newname)

How to get the wsdl file from a webservice's URL

to get the WSDL (Web Service Description Language) from a Web Service URL.

Is possible from SOAP Web Services:

http://www.w3schools.com/xml/tempconvert.asmx

to get the WSDL we have only to add ?WSDL , for example:

http://www.w3schools.com/xml/tempconvert.asmx?WSDL

How to start an Android application from the command line?

You can use:

adb shell monkey -p com.package.name -c android.intent.category.LAUNCHER 1

This will start the LAUNCHER Activity of the application using monkeyrunner test tool.

How can I style the border and title bar of a window in WPF?

I suggest you to start from an existing solution and customize it to fit your needs, that's better than starting from scratch!

I was looking for the same thing and I fall on this open source solution, I hope it will help.

How do you express binary literals in Python?

0 in the start here specifies that the base is 8 (not 10), which is pretty easy to see:

>>> int('010101', 0)
4161

If you don't start with a 0, then python assumes the number is base 10.

>>> int('10101', 0)
10101

How do I include the string header?

For using the string header first we must have include string header file as #include <string> and then we can include string header in the following ways in C++:

1)

string header = "--- Demonstrates Unformatted Input ---";

2)

string header("**** Counts words****\n"), prompt("Enter a text and terminate"
" with a period and return:"), line( 60, '-'), text;

How do I pass JavaScript variables to PHP?

Your code has a few things wrong with it.

  • You define a JavaScript function, func_load3(), but do not call it.
  • Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
  • Your form has no means to submit it. It needs a submit button.
  • You do not check whether your form has been submitted.

It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:

<?php
if (isset($_POST['hidden1'])) {
   echo "You submitted {$_POST['hidden1']}";
   die;
}

echo <<<HTML
   <form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
      <input type="submit" name="submit" value="Test this mess!" />
      <input type="hidden" name="hidden1" id="hidden1" />
   </form>

   <script type="text/javascript">
      document.getElementById("hidden1").value = "This is an example";
   </script>
HTML;
?>

Attempt to set a non-property-list object as an NSUserDefaults

The code you posted tries to save an array of custom objects to NSUserDefaults. You can't do that. Implementing the NSCoding methods doesn't help. You can only store things like NSArray, NSDictionary, NSString, NSData, NSNumber, and NSDate in NSUserDefaults.

You need to convert the object to NSData (like you have in some of the code) and store that NSData in NSUserDefaults. You can even store an NSArray of NSData if you need to.

When you read back the array you need to unarchive the NSData to get back your BC_Person objects.

Perhaps you want this:

- (void)savePersonArrayData:(BC_Person *)personObject {
    [mutableDataArray addObject:personObject];

    NSMutableArray *archiveArray = [NSMutableArray arrayWithCapacity:mutableDataArray.count];
    for (BC_Person *personObject in mutableDataArray) { 
        NSData *personEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:personObject];
        [archiveArray addObject:personEncodedObject];
    }

    NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
    [userData setObject:archiveArray forKey:@"personDataArray"];
}

Get a json via Http Request in NodeJS

http sends/receives data as strings... this is just the way things are. You are looking to parse the string as json.

var jsonObject = JSON.parse(data);

How to parse JSON using Node.js?

What is the PHP syntax to check "is not null" or an empty string?

Null OR an empty string?

if (!empty($user)) {}

Use empty().


After realizing that $user ~= $_POST['user'] (thanks matt):

var uservariable='<?php 
    echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';

How to list all tags along with the full message in git?

Mark Longair's answer (using git show) is close to what is desired in the question. However, it also includes the commit pointed at by the tag, along with the full patch for that commit. Since the commit can be somewhat unrelated to the tag (it's only one commit that the tag is attempting to capture), this may be undesirable. I believe the following is a bit nicer:

for t in `git tag -l`; do git cat-file -p `git rev-parse $t`; done

Using Math.round to round to one decimal place?

Your method is right, all you have to do is add a .0 after both the tens and it will fix your problem!

double example = Math.round((187/35) * 10.0) / 10.0;

The output would be:

5.3

How to set an HTTP proxy in Python 2.7?

It looks like get-pip.py has been updated to use the environment variables http_proxy and https_proxy.

Windows:

set http_proxy=http://proxy.myproxy.com
set https_proxy=https://proxy.myproxy.com
python get-pip.py

Linux/OS X:

export http_proxy=http://proxy.myproxy.com
export https_proxy=https://proxy.myproxy.com
sudo -E python get-pip.py

However if this still doesn't work for you, you can always install pip through a proxy using setuptools' easy_install by setting the same environment variables.

Windows:

set http_proxy=http://proxy.myproxy.com
set https_proxy=https://proxy.myproxy.com
easy_install pip

Linux/OS X:

export http_proxy=http://proxy.myproxy.com
export https_proxy=https://proxy.myproxy.com
sudo -E easy_install pip

Then once it's installed, use:

pip install --proxy="user:password@server:port" packagename

From the pip man page:

--proxy
Have pip use a proxy server to access sites. This can be specified using "user:[email protected]:port" notation. If the password is left out, pip will ask for it.

Histogram with Logarithmic Scale and custom breaks

Run the hist() function without making a graph, log-transform the counts, and then draw the figure.

hist.data = hist(my.data, plot=F)
hist.data$counts = log(hist.data$counts, 2)
plot(hist.data)

It should look just like the regular histogram, but the y-axis will be log2 Frequency.

Sort a Custom Class List<T>

One way to do this is with a delegate

List<cTag> week = new List<cTag>();
// add some stuff to the list
// now sort
week.Sort(delegate(cTag c1, cTag c2) { return c1.date.CompareTo(c2.date); });

Why is a "GRANT USAGE" created the first time I grant a user privileges?

As you said, in MySQL USAGE is synonymous with "no privileges". From the MySQL Reference Manual:

The USAGE privilege specifier stands for "no privileges." It is used at the global level with GRANT to modify account attributes such as resource limits or SSL characteristics without affecting existing account privileges.

USAGE is a way to tell MySQL that an account exists without conferring any real privileges to that account. They merely have permission to use the MySQL server, hence USAGE. It corresponds to a row in the `mysql`.`user` table with no privileges set.

The IDENTIFIED BY clause indicates that a password is set for that user. How do we know a user is who they say they are? They identify themselves by sending the correct password for their account.

A user's password is one of those global level account attributes that isn't tied to a specific database or table. It also lives in the `mysql`.`user` table. If the user does not have any other privileges ON *.*, they are granted USAGE ON *.* and their password hash is displayed there. This is often a side effect of a CREATE USER statement. When a user is created in that way, they initially have no privileges so they are merely granted USAGE.

Unable to establish SSL connection, how do I fix my SSL cert?

There are a few possibilities:

  1. Your workstation doesn't have the root CA cert used to sign your server's cert. How exactly you fix that depends on what OS you're running and what release, etc. (I suspect this is not related)
  2. Your cert isn't installed properly. If your SSL cert requires an intermediate cert to be presented and you didn't set that up, you can get these warnings.
  3. Are you sure you've enabled SSL on port 443?

For starters, to eliminate (3), what happens if you telnet to that port?

Assuming it's not (3), then depending on your needs you may be fine with ignoring these errors and just passing --no-certificate-check. You probably want to use a regular browser (which generally will bundle the root certs directly) and see if things are happy.

If you want to manually verify the cert, post more details from the openssl s_client output. Or use openssl x509 -text -in /path/to/cert to print it out to your terminal.

Calling jQuery method from onClick attribute in HTML

you forgot to add this in your function : change to this :

<input type="button" value="ahaha"  onclick="$(this).MessageBox('msg');" />

MSIE and addEventListener Problem in Javascript?

In case you are using JQuery 2.x then please add the following in the

<html>
   <head>
      <meta http-equiv="X-UA-Compatible" content="IE=edge;" />
   </head>
   <body>
    ...
   </body>
</html>

This worked for me.

Dart/Flutter : Converting timestamp

meh, just use https://github.com/andresaraujo/timeago.dart library; it does all the heavy-lifting for you.

EDIT:

From your question, it seems you wanted relative time conversions, and the timeago library enables you to do this in 1 line of code. Converting Dates isn't something I'd choose to implement myself, as there are a lot of edge cases & it gets fugly quickly, especially if you need to support different locales in the future. More code you write = more you have to test.

import 'package:timeago/timeago.dart' as timeago;

final fifteenAgo = DateTime.now().subtract(new Duration(minutes: 15));
print(timeago.format(fifteenAgo)); // 15 minutes ago
print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
print(timeago.format(fifteenAgo, locale: 'es'));

// Add a new locale messages
timeago.setLocaleMessages('fr', timeago.FrMessages());

// Override a locale message
timeago.setLocaleMessages('en', CustomMessages());

print(timeago.format(fifteenAgo)); // 15 min ago
print(timeago.format(fifteenAgo, locale: 'fr')); // environ 15 minutes

to convert epochMS to DateTime, just use...

final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1546553448639);

How to call javascript function from code-behind

One way of doing it is to use the ClientScriptManager:

Page.ClientScript.RegisterStartupScript(
    GetType(), 
    "MyKey", 
    "Myfunction();", 
    true);

Android Design Support Library expandable Floating Action Button(FAB) menu

Another option for the same result with ConstraintSet animation:

fab animation example

1) Put all the animated views in one ConstraintLayout

2) Animate it from code like this (if you want some more effects its up to you..this is only example)

menuItem1 and menuItem2 is the first and second FABs in menu, descriptionItem1 and descriptionItem2 is the description to the left of menu, parentConstraintLayout is the root ConstraintLayout wich contains all the animated views, isMenuOpened is some function to change open/closed flag in the state

I put animation code in extension file but its not necessary.

fun FloatingActionButton.expandMenu(
    menuItem1: View,
    menuItem2: View,
    descriptionItem1: TextView,
    descriptionItem2: TextView,
    parentConstraintLayout: ConstraintLayout,
    isMenuOpened: (Boolean)-> Unit
) {
    val constraintSet = ConstraintSet()
    constraintSet.clone(parentConstraintLayout)

    constraintSet.setVisibility(descriptionItem1.id, View.VISIBLE)
    constraintSet.clear(menuItem1.id, ConstraintSet.TOP)
    constraintSet.connect(menuItem1.id, ConstraintSet.BOTTOM, this.id, ConstraintSet.TOP, 0)
    constraintSet.connect(menuItem1.id, ConstraintSet.START, this.id, ConstraintSet.START, 0)
    constraintSet.connect(menuItem1.id, ConstraintSet.END, this.id, ConstraintSet.END, 0)

    constraintSet.setVisibility(descriptionItem2.id, View.VISIBLE)
    constraintSet.clear(menuItem2.id, ConstraintSet.TOP)
    constraintSet.connect(menuItem2.id, ConstraintSet.BOTTOM, menuItem1.id, ConstraintSet.TOP, 0)
    constraintSet.connect(menuItem2.id, ConstraintSet.START, this.id, ConstraintSet.START, 0)
    constraintSet.connect(menuItem2.id, ConstraintSet.END, this.id, ConstraintSet.END, 0)

    val transition = AutoTransition()
    transition.duration = 150
    transition.interpolator = AccelerateInterpolator()

    transition.addListener(object: Transition.TransitionListener {
        override fun onTransitionEnd(p0: Transition) {
            isMenuOpened(true)
        }
        override fun onTransitionResume(p0: Transition) {}
        override fun onTransitionPause(p0: Transition) {}
        override fun onTransitionCancel(p0: Transition) {}
        override fun onTransitionStart(p0: Transition) {}
    })

    TransitionManager.beginDelayedTransition(parentConstraintLayout, transition)
    constraintSet.applyTo(parentConstraintLayout)
}

Image overlay on responsive sized images bootstrap

When you specify position:absolute it positions itself to the next-highest element with position:relative. In this case, that's the .project div.

If you give the image's immediate parent div a style of position:relative, the overlay will key to that instead of the div which includes the text. For example: http://jsfiddle.net/7gYUU/1/

 <div class="parent">
    <img src="http://placehold.it/500x500" class="img-responsive"/>
    <div class="fa fa-plus project-overlay"></div>
 </div>

.parent {
   position: relative;
}

Does Go have "if x in" construct similar to Python?

Another option is using a map as a set. You use just the keys and having the value be something like a boolean that's always true. Then you can easily check if the map contains the key or not. This is useful if you need the behavior of a set, where if you add a value multiple times it's only in the set once.

Here's a simple example where I add random numbers as keys to a map. If the same number is generated more than once it doesn't matter, it will only appear in the final map once. Then I use a simple if check to see if a key is in the map or not.

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    var MAX int = 10

    m := make(map[int]bool)

    for i := 0; i <= MAX; i++ {
        m[rand.Intn(MAX)] = true
    }

    for i := 0; i <= MAX; i++ {
        if _, ok := m[i]; ok {
            fmt.Printf("%v is in map\n", i)
        } else {
            fmt.Printf("%v is not in map\n", i)
        }
    }
}

Here it is on the go playground

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

It is due to mismatched blacklist file configuration.

To resolve that,

  1. We have to move to the project folder.

  2. Open \node_modules\metro-config\src\defaults\blacklist.js

  3. Replace the following.

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__\/.*/
];

How to execute two mysql queries as one in PHP/MYSQL?

It says on the PHP site that multiple queries are NOT permitted (EDIT: This is only true for the mysql extension. mysqli and PDO allow multiple queries) . So you can't do it in PHP, BUT, why can't you just execute that query in another mysql_query call, (like Jon's example)? It should still give you the correct result if you use the same connection. Also, mysql_num_rows may help also.

Can I have multiple Xcode versions installed?

All the updates for new version of xcode will be available in appstore if you have installed the version from appstore. If you just paste the downloaded version appstore will show install not update. Hence keep the stable version downloaded from appstore in your applications folder.

To try new beta releases i usually put it in separate drive and unzip and install it there. This will avoid confusion while working on stable version.

To avoid confusion you can keep only the stable version in your dock and open the beta version from spotlight(Command + Space). This will place beta temporarily on dock. But it will make sure you don't accidentally edit your client project in beta version.

Most Important:- Working on same project on two different xcode might create some unwanted results. Like there was a bug in interface builder that got introduced in certain version of xcode. Which broke the constraints. It got fixed again in the next one.

Keep track of release notes to know exactly what are additional features and what are known issues.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

Alternative Windows shells, besides CMD.EXE?

Try Clink. It's awesome, especially if you are used to bash keybindings and features.

(As already pointed out - there is a similar question: Is there a better Windows Console Window?)

Formatting numbers (decimal places, thousands separators, etc) with CSS

If it helps...

I use the PHP function number_format() and the Narrow No-break Space (&#8239;). It is often used as an unambiguous thousands separator.

echo number_format(200000, 0, "", "&#8239;");

Because IE8 has some problems to render the Narrow No-break Space, I changed it for a SPAN

echo "<span class='number'>".number_format(200000, 0, "", "<span></span>")."</span>";
.number SPAN{
    padding: 0 1px; 
}

Understanding inplace=True

When inplace=True is passed, the data is renamed in place (it returns nothing), so you'd use:

df.an_operation(inplace=True)

When inplace=False is passed (this is the default value, so isn't necessary), performs the operation and returns a copy of the object, so you'd use:

df = df.an_operation(inplace=False) 

How to open my files in data_folder with pandas using relative path?

Try

import pandas as pd
pd.read_csv("../data_folder/data.csv")

How to check cordova android version of a cordova/phonegap project?

The current platform version of a cordova app can be checked by the following command

cordova platform version android

And can be upgraded using the command

cordova platform update android

You can replace android by any of your platform choice like "ios" or some else.

This only applies to android platform. I have not checked. You can try replacing android in the code segments to try for other platforms.

R dplyr: Drop multiple columns

We can try

iris %>% 
      select_(.dots= setdiff(names(.),drop.cols))

Sequelize OR condition object

Use Sequelize.or:

var condition = {
  where: Sequelize.and(
    { name: 'a project' },
    Sequelize.or(
      { id: [1,2,3] },
      { id: { lt: 10 } }
    )
  )
};

Reference (search for Sequelize.or)

Edit: Also, this has been modified and for the latest method see Morio's answer,

What's the better (cleaner) way to ignore output in PowerShell?

I just did some tests of the four options that I know about.

Measure-Command {$(1..1000) | Out-Null}

TotalMilliseconds : 76.211

Measure-Command {[Void]$(1..1000)}

TotalMilliseconds : 0.217

Measure-Command {$(1..1000) > $null}

TotalMilliseconds : 0.2478

Measure-Command {$null = $(1..1000)}

TotalMilliseconds : 0.2122

## Control, times vary from 0.21 to 0.24
Measure-Command {$(1..1000)}

TotalMilliseconds : 0.2141

So I would suggest that you use anything but Out-Null due to overhead. The next important thing, to me, would be readability. I kind of like redirecting to $null and setting equal to $null myself. I use to prefer casting to [Void], but that may not be as understandable when glancing at code or for new users.

I guess I slightly prefer redirecting output to $null.

Do-Something > $null

Edit

After stej's comment again, I decided to do some more tests with pipelines to better isolate the overhead of trashing the output.

Here are some tests with a simple 1000 object pipeline.

## Control Pipeline
Measure-Command {$(1..1000) | ?{$_ -is [int]}}

TotalMilliseconds : 119.3823

## Out-Null
Measure-Command {$(1..1000) | ?{$_ -is [int]} | Out-Null}

TotalMilliseconds : 190.2193

## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}

TotalMilliseconds : 119.7923

In this case, Out-Null has about a 60% overhead and > $null has about a 0.3% overhead.

Addendum 2017-10-16: I originally overlooked another option with Out-Null, the use of the -inputObject parameter. Using this the overhead seems to disappear, however the syntax is different:

Out-Null -inputObject ($(1..1000) | ?{$_ -is [int]})

And now for some tests with a simple 100 object pipeline.

## Control Pipeline
Measure-Command {$(1..100) | ?{$_ -is [int]}}

TotalMilliseconds : 12.3566

## Out-Null
Measure-Command {$(1..100) | ?{$_ -is [int]} | Out-Null}

TotalMilliseconds : 19.7357

## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}

TotalMilliseconds : 12.8527

Here again Out-Null has about a 60% overhead. While > $null has an overhead of about 4%. The numbers here varied a bit from test to test (I ran each about 5 times and picked the middle ground). But I think it shows a clear reason to not use Out-Null.

How do I check if a string is unicode or ascii?

Note that on Python 3, it's not really fair to say any of:

  • strs are UTFx for any x (eg. UTF8)

  • strs are Unicode

  • strs are ordered collections of Unicode characters

Python's str type is (normally) a sequence of Unicode code points, some of which map to characters.


Even on Python 3, it's not as simple to answer this question as you might imagine.

An obvious way to test for ASCII-compatible strings is by an attempted encode:

"Hello there!".encode("ascii")
#>>> b'Hello there!'

"Hello there... ?!".encode("ascii")
#>>> Traceback (most recent call last):
#>>>   File "", line 4, in <module>
#>>> UnicodeEncodeError: 'ascii' codec can't encode character '\u2603' in position 15: ordinal not in range(128)

The error distinguishes the cases.

In Python 3, there are even some strings that contain invalid Unicode code points:

"Hello there!".encode("utf8")
#>>> b'Hello there!'

"\udcc3".encode("utf8")
#>>> Traceback (most recent call last):
#>>>   File "", line 19, in <module>
#>>> UnicodeEncodeError: 'utf-8' codec can't encode character '\udcc3' in position 0: surrogates not allowed

The same method to distinguish them is used.

Check if key exists in JSON object using jQuery

Use JavaScript's hasOwnProperty() function:

if (json_object.hasOwnProperty('name')) {
    //do struff
}

Dynamically add script tag with src that may include document.write

There is the onload function, that could be called when the script has loaded successfully:

function addScript( src, callback ) {
  var s = document.createElement( 'script' );
  s.setAttribute( 'src', src );
  s.onload=callback;
  document.body.appendChild( s );
}

How to check for DLL dependency?

NDepend was already mentioned by Jesse (if you analyze .NET code) but let's explain exactly how it can help.

Is there a program/script that can scan an executable for DLL dependencies or execute the program in a "clean" DLL-free environment for testing to prevent these oops situations?

In the NDepend Project Properties panel, you can define what application assemblies to analyze (in green) and NDepend will infer Third-Party assemblies used by application ones (in blue). A list of directories where to search application and third-party assemblies is provided.

NDepend Project Properties Application and Third-Party assemblies

If a third-party assembly is not found in these directories, it will be in error mode. For example, if I remove the .NET Fx directory C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319, I can see that .NET Fx third-party assemblies are not resolved:

NDepend Project Properties Application and Third-Party assemblies not resolved

Disclaimer: I work for NDepend

Rails 4 LIKE query - ActiveRecord adds quotes

While string interpolation will work, as your question specifies rails 4, you could be using Arel for this and keeping your app database agnostic.

def self.search(query, page=1)
  query = "%#{query}%"
  name_match = arel_table[:name].matches(query)
  postal_match = arel_table[:postal_code].matches(query)
  where(name_match.or(postal_match)).page(page).per_page(5)
end

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

How to create a pivot query in sql server without aggregate function

SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
    MAX([Value])
    FOR [Period] IN ([2000], [2001], [2002])
) as pvt

Another way,

SELECT ACCOUNT,
      MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
      MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
      MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account

Find non-ASCII characters in varchar columns using SQL Server

This script searches for non-ascii characters in one column. It generates a string of all valid characters, here code point 32 to 127. Then it searches for rows that don't match the list:

declare @str varchar(128)
declare @i int
set @str = ''
set @i = 32
while @i <= 127
    begin
    set @str = @str + '|' + char(@i)
    set @i = @i + 1
    end

select  col1
from    YourTable
where   col1 like '%[^' + @str + ']%' escape '|'

Can't execute jar- file: "no main manifest attribute"

I had a similar issue as you, in below a syntax to create successfully .war File:-

jar {cvf} [jar-file] [manifest-file]

manifest When creating (c) or updating (u) a JAR file, the manifest operand defines the preexisting manifest files with names and values of attributes to be included in MANIFEST.MF in the JAR file. The manifest operand must be specified if the f option is present '[1]'.

In order to create manifest file you need to defined a value for some attributes, you could put asterisk after the (.WAR) file name to avoid creating manifest file:-

jar -cvf foo.war *

To be honest with you I don't know if that is a best practice but it do the work for me :).

Export and Import all MySQL databases at one time

mysqldump -uroot -proot --all-databases > allDB.sql

note: -u"your username" -p"your password"

Newline in string attribute

Code behind solution

private void Button1_Click(object sender, RoutedEventArgs e)
{
    System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();
    myStringBuilder.Append("Orange").AppendLine();
    myStringBuilder.Append("").AppendLine();
    myStringBuilder.Append("Apple").AppendLine();
    myStringBuilder.Append("Banana").AppendLine();
    myStringBuilder.Append("").AppendLine();
    myStringBuilder.Append("Plum").AppendLine();
    TextBox1.Text = myStringBuilder.ToString();
}

Prevent form redirect OR refresh on submit?

It looks like you're missing a return false.

MySQL "Or" Condition

Your question is about the operator precedences in mysql and Alex has shown you how to "override" the precedence with parentheses.

But on a side note, if your column date is of the type Date you can use MySQL's date and time functions to fetch the records of the last seven days, like e.g.

SELECT
  *
FROM
  Drinks
WHERE
  email='$Email'
  AND date >= Now()-Interval 7 day

(or maybe Curdate() instead of Now())

Change background image opacity

You can't use transparency on background-images directly, but you can achieve this effect with something like this:

http://jsfiddle.net/m4TgL/

HTML:

<div class="container">
    <div class="content">//my blog post</div>
</div>?

CSS:

.container {  position: relative; }

.container:before {
    content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1;
    background-image: url('image.jpg');
   opacity: 0.5;
}

.content {
    position: relative; 
    z-index: 2;
}?

How to get label text value form a html page?

For cases where the data element is inside the label like in this example:

<label for="subscription">Subscription period
    <select id='subscription' name='subscription'>
        <option></option>
        <option>1 year</option>
        <option>2 years</option>
        <option>3 years</option>
    </select>
</label>

all the previous answers will give an unexpected result:

"Subscription period


                    1 year
                    2 years
                    3 years

            "

While the expected result would be:

"Subscription period"

So, the correct solution will be like this:

const label = document.getElementById('yourLableId');
const labelText = Array.prototype.filter
    .call(label.childNodes, x => x.nodeName === "#text")
    .map(x => x.textContent)
    .join(" ")
    .trim();

Syntax for a single-line Bash infinite while loop

It's also possible to use sleep command in while's condition. Making one-liner looking more clean imho.

while sleep 2; do echo thinking; done

SQL, Postgres OIDs, What are they and why are they useful?

To remove all OIDs from your database tables, you can use this Linux script:

First, login as PostgreSQL superuser:

sudo su postgres

Now run this script, changing YOUR_DATABASE_NAME with you database name:

for tbl in `psql -qAt -c "select schemaname || '.' || tablename from pg_tables WHERE schemaname <> 'pg_catalog' AND schemaname <> 'information_schema';" YOUR_DATABASE_NAME` ; do  psql -c "alter table $tbl SET WITHOUT OIDS" YOUR_DATABASE_NAME ; done

I used this script to remove all my OIDs, since Npgsql 3.0 doesn't work with this, and it isn't important to PostgreSQL anymore.

How to set Spring profile from system variable?

If i run the command line : java -Dspring.profiles.active=development -jar yourApplication.jar from my webapplication directory it states that the path is incorrect. So i just defined the profile in manualy in the application.properties file like this :

spring.profiles.active=mysql 

or

spring.profiles.active=postgres

or

spring.profiles.active=mongodb

Updating a java map entry

Use

table.put(key, val);

to add a new key/value pair or overwrite an existing key's value.

From the Javadocs:

V put(K key, V value): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

Intellij idea subversion checkout error: `Cannot run program "svn"`

IntelliJ needs the subversion command(svn) added into Subversion settings. Here are the steps: 1. Download and Install subversion. 2. check on the command line prompt on windows(cmd) for the same command - svn.

enter image description here

  1. Validate svn command added to File --> settings --> Version Control --> subversion enter image description here

  2. Exit IntelliJ studio and relaunch

C++ IDE for Linux?

For me Ultimate++ seems to be the best solution to write cross-os program

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

You can easily install 1.8 via PPA. Which can be done by:

$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt-get update
$ sudo apt-get install oracle-java8-installer

Then check the running version:

$ java -version

If you must do it manually there's already an answer for that on AskUbuntu here.

what's the default value of char?

The default value of a char primitive type is '\u0000'(null character) as stated in the Java Language Specification.

The shortcut for 'u0000' is '\0', So the null can be represented either by 'u0000' or '\0'.

The below Java program validates null representations using instance char field 'c'.

public class DefaultValueForchar {  
    char c;
    public static void main(String[] args) {
        char c0 = '\0';
        char cu0000 = '\u0000';
        DefaultValueForchar obj = new DefaultValueForchar();
        System.out.println(obj.c);
        System.out.println(c0);
        System.out.println(cu0000);
        System.out.println(c0==cu0000);
        System.out.println(obj.c==c0);
        System.out.println(obj.c==cu0000);
    }

}

output:

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

Alternate background colors for list items

This is set background color on even and odd li:

  li:nth-child(odd) { background: #ffffff; }
  li:nth-child(even) { background: #80808030; }

Auto refresh page every 30 seconds

There are multiple solutions for this. If you want the page to be refreshed you actually don't need JavaScript, the browser can do it for you if you add this meta tag in your head tag.

<meta http-equiv="refresh" content="30">

The browser will then refresh the page every 30 seconds.

If you really want to do it with JavaScript, then you can refresh the page every 30 seconds with location.reload() (docs) inside a setTimeout():

window.setTimeout(function () {
  window.location.reload();
}, 30000);

If you don't need to refresh the whole page but only a part of it, I guess an Ajax call would be the most efficient way.

Python datetime to string without microsecond component

In Python 3.6:

from datetime import datetime
datetime.now().isoformat(' ', 'seconds')
'2017-01-11 14:41:33'

https://docs.python.org/3.6/library/datetime.html#datetime.datetime.isoformat

How to check if a string "StartsWith" another string?

If you are working with startsWith() and endsWith() then you have to be careful about leading spaces. Here is a complete example:

var str1 = " Your String Value Here.!! "; // Starts & ends with spaces    
if (str1.startsWith("Your")) { }  // returns FALSE due to the leading spaces…
if (str1.endsWith("Here.!!")) { } // returns FALSE due to trailing spaces…

var str2 = str1.trim(); // Removes all spaces (and other white-space) from start and end of `str1`.
if (str2.startsWith("Your")) { }  // returns TRUE
if (str2.endsWith("Here.!!")) { } // returns TRUE

Why is setState in reactjs Async instead of Sync?

Yes, setState() is asynchronous.

From the link: https://reactjs.org/docs/react-component.html#setstate

  • React does not guarantee that the state changes are applied immediately.
  • setState() does not always immediately update the component.
  • Think of setState() as a request rather than an immediate command to update the component.

Because they think
From the link: https://github.com/facebook/react/issues/11527#issuecomment-360199710

... we agree that setState() re-rendering synchronously would be inefficient in many cases

Asynchronous setState() makes life very difficult for those getting started and even experienced unfortunately:
- unexpected rendering issues: delayed rendering or no rendering (based on program logic)
- passing parameters is a big deal
among other issues.

Below example helped:

// call doMyTask1 - here we set state
// then after state is updated...
//     call to doMyTask2 to proceed further in program

constructor(props) {
    // ..

    // This binding is necessary to make `this` work in the callback
    this.doMyTask1 = this.doMyTask1.bind(this);
    this.doMyTask2 = this.doMyTask2.bind(this);
}

function doMyTask1(myparam1) {
    // ..

    this.setState(
        {
            mystate1: 'myvalue1',
            mystate2: 'myvalue2'
            // ...
        },    
        () => {
            this.doMyTask2(myparam1); 
        }
    );
}

function doMyTask2(myparam2) {
    // ..
}

Hope that helps.

open program minimized via command prompt

If the application is already open (even in background), it will be restored by "start" command. Exit the program if running then /max or /min will work

How to pre-populate the sms body text via an html link

I know this is an old thread but stumbled upon it and found that some parts are no longer relevant.

I've found that if you want to just per-populate the text without adding a phone number, you can do the following:

sms:?&body=/* message body here */

How to get the anchor from the URL using jQuery?

jQuery style:

$(location).attr('hash');

What is the most efficient string concatenation method in python?

''.join(sequenceofstrings) is what usually works best -- simplest and fastest.

How to find the logs on android studio?

The path to the log files in Windows has been moved.

They appear to be under C:\Program Files\Android\Android Studio\caches\trunk-system\log\idea.log in Android Studio 4.1.1

Remove empty lines in a text file via grep

with awk, just check for number of fields. no need regex

$ more file
hello

world

foo

bar

$ awk 'NF' file
hello
world
foo
bar

Abstract Class vs Interface in C++

I assume that with interface you mean a C++ class with only pure virtual methods (i.e. without any code), instead with abstract class you mean a C++ class with virtual methods that can be overridden, and some code, but at least one pure virtual method that makes the class not instantiable. e.g.:

class MyInterface
{
public:
  // Empty virtual destructor for proper cleanup
  virtual ~MyInterface() {}

  virtual void Method1() = 0;
  virtual void Method2() = 0;
};


class MyAbstractClass
{
public:
  virtual ~MyAbstractClass();

  virtual void Method1();
  virtual void Method2();
  void Method3();

  virtual void Method4() = 0; // make MyAbstractClass not instantiable
};

In Windows programming, interfaces are fundamental in COM. In fact, a COM component exports only interfaces (i.e. pointers to v-tables, i.e. pointers to set of function pointers). This helps defining an ABI (Application Binary Interface) that makes it possible to e.g. build a COM component in C++ and use it in Visual Basic, or build a COM component in C and use it in C++, or build a COM component with Visual C++ version X and use it with Visual C++ version Y. In other words, with interfaces you have high decoupling between client code and server code.

Moreover, when you want to build DLL's with a C++ object-oriented interface (instead of pure C DLL's), as described in this article, it's better to export interfaces (the "mature approach") instead of C++ classes (this is basically what COM does, but without the burden of COM infrastructure).

I'd use an interface if I want to define a set of rules using which a component can be programmed, without specifying a concrete particular behavior. Classes that implement this interface will provide some concrete behavior themselves.

Instead, I'd use an abstract class when I want to provide some default infrastructure code and behavior, and make it possible to client code to derive from this abstract class, overriding the pure virtual methods with some custom code, and complete this behavior with custom code. Think for example of an infrastructure for an OpenGL application. You can define an abstract class that initializes OpenGL, sets up the window environment, etc. and then you can derive from this class and implement custom code for e.g. the rendering process and handling user input:

// Abstract class for an OpenGL app.
// Creates rendering window, initializes OpenGL; 
// client code must derive from it 
// and implement rendering and user input.
class OpenGLApp
{
public:
  OpenGLApp();
  virtual ~OpenGLApp();
  ...

  // Run the app    
  void Run();


  // <---- This behavior must be implemented by the client ---->

  // Rendering
  virtual void Render() = 0;

  // Handle user input
  // (returns false to quit, true to continue looping)
  virtual bool HandleInput() = 0;

  // <--------------------------------------------------------->


private:
  //
  // Some infrastructure code
  //
  ... 
  void CreateRenderingWindow();
  void CreateOpenGLContext();
  void SwapBuffers();
};


class MyOpenGLDemo : public OpenGLApp
{
public:
  MyOpenGLDemo();
  virtual ~MyOpenGLDemo();

  // Rendering
  virtual void Render();  // implements rendering code

  // Handle user input
  virtual bool HandleInput(); // implements user input handling


  //  ... some other stuff
};

How to prevent form from submitting multiple times from client side?

This allow submit every 2 seconds. In case of front validation.

$(document).ready(function() {
    $('form[debounce]').submit(function(e) {
        const submiting = !!$(this).data('submiting');

        if(!submiting) {
            $(this).data('submiting', true);

            setTimeout(() => {
                $(this).data('submiting', false);
            }, 2000);

            return true;
        }

        e.preventDefault();
        return false;
    });
})

HTML Image not displaying, while the src url works

change the name of the image folder to img and then use the HTML code

How to upper case every first letter of word in a string?

import org.apache.commons.lang.WordUtils;

public class CapitalizeFirstLetterInString {
    public static void main(String[] args) {
        // only the first letter of each word is capitalized.
        String wordStr = WordUtils.capitalize("this is first WORD capital test.");
        //Capitalize method capitalizes only first character of a String
        System.out.println("wordStr= " + wordStr);

        wordStr = WordUtils.capitalizeFully("this is first WORD capital test.");
        // This method capitalizes first character of a String and make rest of the characters lowercase
        System.out.println("wordStr = " + wordStr );
    }
}

Output :

This Is First WORD Capital Test.

This Is First Word Capital Test.

How to create folder with PHP code?

In answer to the question in how to write to a file in PHP you can use the following as an example:

    $fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
    if ($fp) {
        fwrite ($fp, $text); //$text is what you are writing to the file
        fclose ($fp);
        $writeSuccess = "Yes";
        #echo ("File written");
    }
    else {
    $writeSuccess = "No";
    #echo ("File was not written");
    }

What is the difference between method overloading and overriding?

Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.

void foo(int a)
void foo(int a, float b)

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class Parent {
    void foo(double d) {
        // do something
    }
}

class Child extends Parent {

    @Override
    void foo(double d){
        // this method is overridden.  
    }
}

How can we draw a vertical line in the webpage?

That's no struts related problem but rather plain HMTL/CSS.

I'm not HTML or CSS expert, but I guess you could use a div with a border on the left or right side only.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

I believe I have encountered the same quandary. I started encountering the problem when I changed to:

</system.web>
<httpRuntime targetFramework="4.5"/>

Which gives the error message you describe above.

adding:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />

Solves the issue, but then it makes your validation controls/scripts throw Javascript runtime errors. If you change to:

</system.web>
<httpRuntime targetFramework="4.0"/>

You should be OK, but you’ll have to make sure the rest of your code does/ behaves as desired. You might also have to forgo some new features only available in 4.5 onward.

P.S. It is highly recommended that you read the following before implementing this solution. Especially, if you use Async functionality:

https://blogs.msdn.microsoft.com/webdev/2012/11/19/all-about-httpruntime-targetframework/

UPDATE April 2017: After some some experimentation and testing I have come up with a combination that works:

<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
<httpRuntime targetFramework="4.5.1" />

with:

jQuery version 1.11.3

Java String to SHA1

Convert byte array to hex string.

public static String toSHA1(byte[] convertme) {
    final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA-1");
    }
    catch(NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    byte[] buf = md.digest(convertme);
    char[] chars = new char[2 * buf.length];
    for (int i = 0; i < buf.length; ++i) {
        chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
        chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
    }
    return new String(chars);
}

Selecting a Record With MAX Value

Note: An incorrect revision of this answer was edited out. Please review all answers.

A subselect in the WHERE clause to retrieve the greatest BALANCE aggregated over all rows. If multiple ID values share that balance value, all would be returned.

SELECT 
  ID,
  BALANCE
FROM CUSTOMERS
WHERE BALANCE = (SELECT MAX(BALANCE) FROM CUSTOMERS)

SQL Server Restore Error - Access is Denied

Another scenario could be the existence of multiple database paths. First, make note of the path where new databases are currently being stored. So if you create a new empty database and then do Tasks/Restore, make sure that the path the restore is trying to use is the same directory that the empty database was created in. Even if the restore path is legal, you will still get the access denied error if it is not the current path you are working with. Very easy to spot when the path is not legal, much harder to spot when the path is legal, but not the current path.

Check if a varchar is a number (TSQL)

Damien_The_Unbeliever noted that his was only good for digits

Wade73 added a bit to handle decimal points

neizan made an additional tweak as did notwhereuareat

Unfortunately, none appear to handle negative values and they appear to have issues with a comma in the value...

Here's my tweak to pick up negative values and those with commas

declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar) 
values 
(N'1234')
, (N'000005')
, (N'1,000')
, (N'293.8457')
, (N'x')
, (N'+')
, (N'293.8457.')
, (N'......')
, (N'.')
, (N'-375.4')
, (N'-00003')
, (N'-2,000')
, (N'3-3')
, (N'3000-')
;

-- This shows that Neizan's answer allows "." to slip through.
select * from (
select 
    MyVar
    , case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber 
from 
    @MyTable
) t order by IsNumber;

-- Notice the addition of "and MyVar not like '.'".
select * from (
select 
    MyVar
    , case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' and MyVar not like '.' then 1 else 0 end as IsNumber 
from 
    @MyTable
) t 
order by IsNumber;

--Trying to tweak for negative values and the comma
--Modified when comparison
select * from (
select 
    MyVar
    , case 
        when MyVar not like N'%[^0-9.,-]%' and MyVar not like '.' and isnumeric(MyVar) = 1 then 1
        else 0 
    end as IsNumber 
from 
    @MyTable
) t 
order by IsNumber;

Bootstrap with jQuery Validation Plugin

DARK_DIESEL's answer worked great for me; here's the code for anyone who wants the equivalent using glyphicons:

jQuery.validator.setDefaults({
    highlight: function (element, errorClass, validClass) {
        if (element.type === "radio") {
            this.findByName(element.name).addClass(errorClass).removeClass(validClass);
        } else {
            $(element).closest('.form-group').removeClass('has-success has-feedback').addClass('has-error has-feedback');
            $(element).closest('.form-group').find('span.glyphicon').remove();
            $(element).closest('.form-group').append('<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>');
        }
    },
    unhighlight: function (element, errorClass, validClass) {
        if (element.type === "radio") {
            this.findByName(element.name).removeClass(errorClass).addClass(validClass);
        } else {
            $(element).closest('.form-group').removeClass('has-error has-feedback').addClass('has-success has-feedback');
            $(element).closest('.form-group').find('span.glyphicon').remove();
            $(element).closest('.form-group').append('<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>');
        }
    }
});

How to create EditText accepts Alphabets only in android?

Allow only Alphabets in EditText android:

InputFilter letterFilter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            String filtered = "";
            for (int i = start; i < end; i++) {
                char character = source.charAt(i);
                if (!Character.isWhitespace(character)&&Character.isLetter(character)) {
                    filtered += character;
                }
            }

            return filtered;
        }

    };
editText.setFilters(new InputFilter[]{letterFilter}); 

What's the difference between fill_parent and wrap_content?

Either attribute can be applied to View's (visual control) horizontal or vertical size. It's used to set a View or Layouts size based on either it's contents or the size of it's parent layout rather than explicitly specifying a dimension.

fill_parent (deprecated and renamed MATCH_PARENT in API Level 8 and higher)

Setting the layout of a widget to fill_parent will force it to expand to take up as much space as is available within the layout element it's been placed in. It's roughly equivalent of setting the dockstyle of a Windows Form Control to Fill.

Setting a top level layout or control to fill_parent will force it to take up the whole screen.

wrap_content

Setting a View's size to wrap_content will force it to expand only far enough to contain the values (or child controls) it contains. For controls -- like text boxes (TextView) or images (ImageView) -- this will wrap the text or image being shown. For layout elements it will resize the layout to fit the controls / layouts added as its children.

It's roughly the equivalent of setting a Windows Form Control's Autosize property to True.

Online Documentation

There's some details in the Android code documentation here.

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This happens when you index a row/column with a number that is larger than the dimensions of your dataframe. For instance, getting the eleventh column when you have only three.

import pandas as pd

df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
                   'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
                   'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})

You have 5 rows and three columns:

    Name      City      Car
0   Mark    Lisbon    Tesla
1  Laura  Montreal     Audi
2   Adam    Lisbon  Porsche
3  Roger    Berlin     Ford
4   Anna   Glasgow    Honda

Let's try to index the eleventh column (it doesn't exist):

df.iloc[:, 10] # there is obviously no 11th column

IndexError: single positional indexer is out-of-bounds

If you are a beginner with Python, remember that df.iloc[:, 10] would refer to the eleventh column.

How to install Maven 3 on Ubuntu 18.04/17.04/16.10/16.04 LTS/15.10/15.04/14.10/14.04 LTS/13.10/13.04 by using apt-get?

It's best to use miske's answer.

Properly installing natecarlson's repository

If you really want to use natecarlson's repository, the instructions just below can do any of the following:

  1. set it up from scratch
  2. repair it if apt-get update gives a 404 error after add-apt-repository
  3. repair it if apt-get update gives a NO_PUBKEY error after manually adding it to /etc/apt/sources.list

Open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!

Removing natecarlson's repository

If you installed natecarlson's repository (either using add-apt-repository or manually added to /etc/apt/sources.list) and you don't want it anymore, open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!

PDF to image using Java

jPDFImages is not free but a commercial library which converts PDF pages to images in JPEG, TIFF or PNG format. The output image size is customizable.

keycode and charcode

The property event.which is added when using jQuery to avoid browser differences. See docs.

The which property will be undefined if you are not using jQuery.

What is the best way to programmatically detect porn images?

Add an offensive link and store the md5 (or other hash) of the offending image so that it can automatically tagged in the future.

How cool would it be if somebody had a large public database of image md5 along with descriptive tags running as a webservice? Alot of porn isn't original work (in that the person who has it now, didn't probably make it) and the popular images tend to float around different places, so this could really make a difference.

Environment variables for java installation

In Windows 7, right-click on Computer -> Properties -> Advanced system settings; then in the Advanced tab, click Environment Variables... -> System variables -> New....

Give the new system variable the name JAVA_HOME and the value C:\Program Files\Java\jdk1.7.0_79 (depending on your JDK installation path it varies).

Then select the Path system variable and click Edit.... Keep the variable name as Path, and append C:\Program Files\Java\jdk1.7.0_79\bin; or %JAVA_HOME%\bin; (both mean the same) to the variable value.

Once you are done with above changes, try below steps. If you don't see similar results, restart the computer and try again. If it still doesn't work you may need to reinstall JDK.

Open a Windows command prompt (Windows key + R -> enter cmd -> OK), and check the following:

java -version

You will see something like this:

java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)

Then check the following:

javac -version

You will see something like this:

javac 1.7.0_79

SQL: Select columns with NULL values only

If you need to list all rows where all the column values are NULL, then i'd use the COLLATE function. This takes a list of values and returns the first non-null value. If you add all the column names to the list, then use IS NULL, you should get all the rows containing only nulls.

SELECT * FROM MyTable WHERE COLLATE(Col1, Col2, Col3, Col4......) IS NULL

You shouldn't really have any tables with ALL the columns null, as this means you don't have a primary key (not allowed to be null). Not having a primary key is something to be avoided; this breaks the first normal form.

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

This issue should be fixed in the newest version of Homebrew. Try reinstalling it, which is described on the Homebrew home page.

Bad Request - Invalid Hostname IIS7

For Visual Studio 2017 and Visual Studio 2015, IIS Express settings is stored in the hidden .vs directory and the path is something like this .vs\config\applicationhost.config, add binding like below will work

<bindings>
    <binding protocol="http" bindingInformation="*:8802:localhost" />
    <binding protocol="http" bindingInformation="*:8802:127.0.0.1" />
</bindings>

Syntax: https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.administration.binding.bindinginformation?view=iis-dotnet

How do I link to a library with Code::Blocks?

The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)

To link with gdi32:

enter image description here

This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a has no advantage over gdi32 other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib for MSVC).

For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).

a = open("file", "r"); a.readline() output without \n

That would be:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

Where to download visual studio express 2005?

For somebody like me who lands onto this page from Google ages after this question had been posted, you can find VS2005 here: http://apdubey.blogspot.com/2009/04/microsoft-visual-studio-2005-express.html

EDIT: In case that blog dies, here are the links from the blog.

All the bellow files are more them 400MB.

Visual Web Developer 2005 Express Edition
449,848 KB
.IMG File | .ISO File

Visual Basic 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C# 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C++ 2005 Express Edition
474,686 KB
.IMG File | .ISO File

Visual J# 2005 Express Edition
448,702 KB
.IMG File | .ISO File

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

import React, {Component} from 'react';
import {StyleSheet, View} from 'react-native';


export default class App extends Component {
  render() {
    return (
       <View>// you need to wrap the two Views an another View
          <View style={styles.box1}></View>
          <View style={styles.box2}></View>
       </View> 
    );
  }
}

const styles = StyleSheet.create({
  box1:{
    height:100,
    width:100,
    backgroundColor:'red'
  },
  box2:{
    height:100,
    width:100,
    backgroundColor:'green',
    position: 'absolute',
    top:10,
    left:30

  },
});

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

Insert an element at a specific index in a list and return the updated list

Most performance efficient approach

You may also insert the element using the slice indexing in the list. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]

For inserting multiple elements together at a given index, all you need to do is to use a list of multiple elements that you want to insert. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2   # Index starting from which multiple elements will be inserted

# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]

>>> a[insert_at:insert_at] = insert_elements
>>> a   # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]

To know more about slice indexing, you can refer: Understanding slice notation.

Note: In Python 3.x, difference of performance between slice indexing and list.index(...) is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.


Alternative using list comprehension (but very slow in terms of performance):

As an alternative, it can be achieved using list comprehension with enumerate too. (But please don't do it this way. It is just for illustration):

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]

Performance comparison of all solutions

Here's the timeit comparison of all the answers with list of 1000 elements on Python 3.9.1 and Python 2.7.16. Answers are listed in the order of performance for both the Python versions.

Python 3.9.1

  1. My answer using sliced insertion - Fastest ( 2.25 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 5: 2.25 µsec per loop
    
  2. Rushy Panchal's answer with most votes using list.insert(...)- Second (2.33 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 5: 2.33 µsec per loop
    
  3. ATOzTOA's accepted answer based on merge of sliced lists - Third (5.01 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    50000 loops, best of 5: 5.01 µsec per loop
    
  4. My answer with List Comprehension and enumerate - Fourth (very slow with 135 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    2000 loops, best of 5: 135 µsec per loop
    

Python 2.7.16

  1. My answer using sliced insertion - Fastest (2.09 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 3: 2.09 µsec per loop
    
  2. Rushy Panchal's answer with most votes using list.insert(...)- Second (2.36 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 3: 2.36 µsec per loop
    
  3. ATOzTOA's accepted answer based on merge of sliced lists - Third (4.44 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    100000 loops, best of 3: 4.44 µsec per loop
    
  4. My answer with List Comprehension and enumerate - Fourth (very slow with 103 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    10000 loops, best of 3: 103 µsec per loop
    

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

Absolute path routing

There are 2 methods for navigation, .navigate() and .navigateByUrl()

You can use the method .navigateByUrl() for absolute path routing:

import {Router} from '@angular/router';

constructor(private router: Router) {}

navigateToLogin() {
   this.router.navigateByUrl('/login');
}

You put the absolute path to the URL of the component you want to navigate to.

Note: Always specify the complete absolute path when calling router's navigateByUrl method. Absolute paths must start with a leading /

// Absolute route - Goes up to root level    
this.router.navigate(['/root/child/child']);

// Absolute route - Goes up to root level with route params   
this.router.navigate(['/root/child', crisis.id]);

Relative path routing

If you want to use relative path routing, use the .navigate() method.

NOTE: It's a little unintuitive how the routing works, particularly parent, sibling, and child routes:

// Parent route - Goes up one level 
// (notice the how it seems like you're going up 2 levels)
this.router.navigate(['../../parent'], { relativeTo: this.route });

// Sibling route - Stays at the current level and moves laterally, 
// (looks like up to parent then down to sibling)
this.router.navigate(['../sibling'], { relativeTo: this.route });

// Child route - Moves down one level
this.router.navigate(['./child'], { relativeTo: this.route });

// Moves laterally, and also add route parameters
// if you are at the root and crisis.id = 15, will result in '/sibling/15'
this.router.navigate(['../sibling', crisis.id], { relativeTo: this.route });

// Moves laterally, and also add multiple route parameters
// will result in '/sibling;id=15;foo=foo'. 
// Note: this does not produce query string URL notation with ? and & ... instead it
// produces a matrix URL notation, an alternative way to pass parameters in a URL.
this.router.navigate(['../sibling', { id: crisis.id, foo: 'foo' }], { relativeTo: this.route });

Or if you just need to navigate within the current route path, but to a different route parameter:

// If crisis.id has a value of '15'
// This will take you from `/hero` to `/hero/15`
this.router.navigate([crisis.id], { relativeTo: this.route });

Link parameters array

A link parameters array holds the following ingredients for router navigation:

  • The path of the route to the destination component. ['/hero']
  • Required and optional route parameters that go into the route URL. ['/hero', hero.id] or ['/hero', { id: hero.id, foo: baa }]

Directory-like syntax

The router supports directory-like syntax in a link parameters list to help guide route name lookup:

./ or no leading slash is relative to the current level.

../ to go up one level in the route path.

You can combine relative navigation syntax with an ancestor path. If you must navigate to a sibling route, you could use the ../<sibling> convention to go up one level, then over and down the sibling route path.

Important notes about relative nagivation

To navigate a relative path with the Router.navigate method, you must supply the ActivatedRoute to give the router knowledge of where you are in the current route tree.

After the link parameters array, add an object with a relativeTo property set to the ActivatedRoute. The router then calculates the target URL based on the active route's location.

From official Angular Router Documentation

Pass props in Link react-router

Route:

<Route state={this.state} exact path="/customers/:id" render={(props) => <PageCustomer {...props} state={this.state} />} />

And then can access params in your PageCustomer component like this: this.props.match.params.id.

For example an api call in PageCustomer component:

axios({
   method: 'get',
   url: '/api/customers/' + this.props.match.params.id,
   data: {},
   headers: {'X-Requested-With': 'XMLHttpRequest'}
 })

How to replace negative numbers in Pandas Data Frame by zero

With lambda function

df['column'] = df['column'].apply(lambda x : x if x > 0 else 0)

github markdown colspan

Compromise minimum solution:

| One    | Two | Three | Four    | Five  | Six 
| -
| Span <td colspan=3>triple  <td colspan=2>double

So you can omit closing </td> for speed, ?r can leave for consistency.

Result from http://markdown-here.com/livedemo.html : markdown table with colspan

Works in Jupyter Markdown.

Update:

As of 2019 year all pipes in the second line are compulsory in Jupyter Markdown.

| One    | Two | Three | Four    | Five  | Six
|-|-|-|-|-|-
| Span <td colspan=3>triple  <td colspan=2>double

minimally:

One    | Two | Three | Four    | Five  | Six
-|||||-
Span <td colspan=3>triple  <td colspan=2>double

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

Use java.sql.Timestamp.toString if you want to get fractional seconds in text representation. The difference betwen Timestamp from DB and Java Date is that DB precision is nanoseconds while Java Date precision is milliseconds.

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

Where can I find a list of escape characters required for my JSON ajax return type?

From the spec:

All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus [backslash] (U+005C), and the control characters U+0000 to U+001F

Just because e.g. Bell (U+0007) doesn't have a single-character escape code does not mean that you don't need to escape it. Use the Unicode escape sequence \u0007.

Default interface methods are only supported starting with Android N

You can resolve this issue by downgrading Source Compatibility and Target Compatibility Java Version to 1.8 in Latest Android Studio Version 3.4.1

  1. Open Module Settings (Project Structure) Winodw by right clicking on app folder or Command + Down Arrow on Mac enter image description here

  2. Go to Modules -> Properties enter image description here

  3. Change Source Compatibility and Target Compatibility Version to 1.8 enter image description here

  4. Click on Apply or OK Thats it. It will solve your issue.

Also you can manually add in build.gradle (Module: app)

android {
...

compileOptions {
        sourceCompatibility = '1.8'
        targetCompatibility = '1.8'
    }

...
}

"java.lang.OutOfMemoryError: PermGen space" in Maven build

When you say you increased MAVEN_OPTS, what values did you increase? Did you increase the MaxPermSize, as in example:

export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=128m"

(or on Windows:)

set MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=128m

You can also specify these JVM options in each maven project separately.

how to implement a long click listener on a listview

If your ListView row item refers to a separate XML file, be sure to add android:longClickable="true" to that layout file in addition to setting setOnItemLongClickListener() to your ListView.

How to open link in new tab on html?

target="_blank" attribute will do the job. Just don't forget to add rel="noopener noreferrer" to solve the potential vulnerability. More on that here: https://dev.to/ben/the-targetblank-vulnerability-by-example

<a href="https://www.google.com/" target="_blank" rel="noopener noreferrer">Searcher</a>

What are native methods in Java and where should they be used?

I like to know where does we use Native Methods

Ideally, not at all. In reality some functionality is not available in Java and you have to call some C code.

The methods are implemented in C code.

How do I check if string contains substring?

I know that best way is str.indexOf(s) !== -1; http://hayageek.com/javascript-string-contains/

I suggest another way(str.replace(s1, "") !== str):

_x000D_
_x000D_
var str = "Hello World!", s1 = "ello", s2 = "elloo";_x000D_
alert(str.replace(s1, "") !== str);_x000D_
alert(str.replace(s2, "") !== str);
_x000D_
_x000D_
_x000D_

Installing Python 2.7 on Windows 8

GUI Option:

  1. Open System Properties

    a. Type it in the Start Menu

    b. Use the keyboard shortcut Win+Pause)

    c. From Windows Explorer address bar go to

    %windir%\System32\SystemPropertiesProtection.exe

    d. Write SystemPropertiesProtection in run window and press Enter

  2. Switch to the Advanced tab

  3. Click Environment Variables
  4. Select PATH in the System variables section
  5. Click Edit
  6. Add python's path to the end of the list (the paths are separated by semicolons).

For example:

C:\Windows;C:\Windows\System32;C:\Python27

Command Line Option:

  1. Run Command Prompt as administrator
  2. Check existing paths under PATH variable (the paths are separated by semicolons). If your python folder already listed then no need to add again. Default python folder is C:\Python27

    C:\Windows\system32>path or C:\Windows\system32>echo %PATH%

  3. Append python path using setx command. The /M option sets the variable at SYSTEM scope.

The default behavior is to set it for the USER.

C:\Windows\system32>setx /M PATH "%PATH%;C:\Python27"

Unix epoch time to Java Date object

How about just:

Date expiry = new Date(Long.parseLong(date));

EDIT: as per rde6173's answer and taking a closer look at the input specified in the question , "1081157732" appears to be a seconds-based epoch value so you'd want to multiply the long from parseLong() by 1000 to convert to milliseconds, which is what Java's Date constructor uses, so:

Date expiry = new Date(Long.parseLong(date) * 1000);

How to remove unused imports from Eclipse

Not to reorganize imports (not to unfold .* and not to reorder lines) to have least VCS changeset
you can use custom eclipse clenup as this answer suggests

Batch file to copy files from one folder to another folder

xcopy.exe is definitely your friend here. It's built into Windows, so its cost is nothing.

Just xcopy /s c:\source d:\target

You'd probably want to tweak a few things; some of the options we also add include these:

  • /s/e - recursive copy, including copying empty directories.
  • /v - add this to verify the copy against the original. slower, but for the paranoid.
  • /h - copy system and hidden files.
  • /k - copy read-only attributes along with files. otherwise, all files become read-write.
  • /x - if you care about permissions, you might want /o or /x.
  • /y - don't prompt before overwriting existing files.
  • /z - if you think the copy might fail and you want to restart it, use this. It places a marker on each file as it copies, so you can rerun the xcopy command to pick up from where it left off.

If you think the xcopy might fail partway through (like when you are copying over a flaky network connection), or that you have to stop it and want to continue it later, you can use xcopy /s/z c:\source d:\target.

Hope this helps.

tr:hover not working

I had the same problem. I found that if I use a DOCTYPE like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

it didn't work. But if I use:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">

it did work.

How to read a .properties file which contains keys that have a period character using Shell script

I found using while IFS='=' read -r to be a bit slow (I don't know why, maybe someone could briefly explain in a comment or point to a SO answer?). I also found @Nicolai answer very neat as a one-liner, but very inefficient as it will scan the entire properties file over and over again for every single call of prop.

I found a solution that answers the question, performs well and it is a one-liner (bit verbose line though).

The solution does sourcing but massages the contents before sourcing:

#!/usr/bin/env bash

source <(grep -v '^ *#' ./app.properties | grep '[^ ] *=' | awk '{split($0,a,"="); print gensub(/\./, "_", "g", a[1]) "=" a[2]}')

echo $db_uat_user

Explanation:

grep -v '^ *#': discard comment lines grep '[^ ] *=': discards lines without = split($0,a,"="): splits line at = and stores into array a, i.e. a[1] is the key, a[2] is the value gensub(/\./, "_", "g", a[1]): replaces . with _ print gensub... "=" a[2]} concatenates the result of gensub above with = and value.

Edit: As others pointed out, there are some incompatibilities issues (awk) and also it does not validate the contents to see if every line of the property file is actually a kv pair. But the goal here is to show the general idea for a solution that is both fast and clean. Sourcing seems to be the way to go as it loads the properties once that can be used multiple times.

Multiplying Two Columns in SQL Server

Syntax:

SELECT <Expression>[Arithmetic_Operator]<expression>...
 FROM [Table_Name] 
 WHERE [expression];
  1. Expression : Expression made up of a single constant, variable, scalar function, or column name and can also be the pieces of a SQL query that compare values against other values or perform arithmetic calculations.
  2. Arithmetic_Operator : Plus(+), minus(-), multiply(*), and divide(/).
  3. Table_Name : Name of the table.

Lumen: get URL parameter in a Blade view

Laravel 5.6:

{{ Request::query('parameter') }}

How to support placeholder attribute in IE8 and 9

For others landing here. This is what worked for me:

//jquery polyfill for showing place holders in IE9
$('[placeholder]').focus(function() {
    var input = $(this);
    if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
    }
}).blur(function() {
    var input = $(this);
    if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
    }
}).blur();

$('[placeholder]').parents('form').submit(function() {
    $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
        }
    })
});

Just add this in you script.js file. Courtesy of http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

  1. Put mysql-connector-java-5.0.8-bin.jar in $CATALINA_HOME/lib

  2. Check for typo in connection url, example
    "jdbc:mysql://localhost:3306/report" ('report' here is the db name)

  3. Make sure to use machine name(example : localhost instead of ip address(127.0.0.1))

/usr/bin/ld: cannot find

When you make the call to gcc it should say

g++ -Wall -I/home/alwin/Development/Calculator/ -L/opt/lib main.cpp -lcalc -o calculator

not -libcalc.so 

I have a similar problem with auto-generated makes.

You can create a soft link from your compile directory to the library directory. Then the library becomes "local".

cd /compile/directory

ln -s  /path/to/libcalc.so libcalc.so

How do you tell if caps lock is on using JavaScript?

We use getModifierState to check for caps lock, it's only a member of a mouse or keyboard event so we cannot use an onfocus. The most common two ways that the password field will gain focus is with a click in or a tab. We use onclick to check for a mouse click within the input, and we use onkeyup to detect a tab from the previous input field. If the password field is the only field on the page and is auto-focused then the event will not happen until the first key is released, which is ok but not ideal, you really want caps lock tool tips to display once the password field gains focus, but for most cases this solution works like a charm.

HTML

<input type="password" id="password" onclick="checkCapsLock(event)" onkeyup="checkCapsLock(event)" />

JS

function checkCapsLock(e) {
  if (e.getModifierState("CapsLock")) {
    console.log("Caps");
  }
}

https://codepen.io/anon/pen/KxJwjq

Git push error pre-receive hook declined

Despite the question is specific to gitlab, but similar errors can happen on github, depending how it is set up (usually Github Enterprise).

You need to familiarize yourself with the following concepts:

  • pre-receive hooks
  • organization webhooks
  • Webhooks

Webhooks are more commonly understood than other two items.

The Pre-receive hooks

are scripts that run on the GitHub Enterprise server to enforce policy. When a push occurs, each script runs in an isolated environment to determine whether the push is accepted or rejected.

Organization webhooks:

Webhook events are also sent from your repository to your "organization webhooks". more info.

These are set up in your github enterprise. They are specific to the version of the github enterprise. You may have no visibility because of your access limitations (developer, maintainer, admin, etc).

How to detect the currently pressed key?

Most of these answers are either far too complicated or don't seem to work for me (e.g. System.Windows.Input doesn't seem to exist). Then I found some sample code which works fine: http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state

In case the page disappears in the future I am posting the relevant source code below:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace MouseKeyboardStateTest
{
  public abstract class Keyboard
  {
    [Flags]
    private enum KeyStates
    {
      None = 0,
      Down = 1,
      Toggled = 2
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    private static extern short GetKeyState(int keyCode);

    private static KeyStates GetKeyState(Keys key)
    {
      KeyStates state = KeyStates.None;

      short retVal = GetKeyState((int)key);

      //If the high-order bit is 1, the key is down
      //otherwise, it is up.
      if ((retVal & 0x8000) == 0x8000)
        state |= KeyStates.Down;

      //If the low-order bit is 1, the key is toggled.
      if ((retVal & 1) == 1)
        state |= KeyStates.Toggled;

      return state;
    }

    public static bool IsKeyDown(Keys key)
    { 
      return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
    }

    public static bool IsKeyToggled(Keys key)
    { 
      return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
    }
  }
}

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

The problem is still your pg_hba.conf file (/etc/postgresql/9.1/main/pg_hba.conf*).

This line:

local   all             postgres                                peer

Should be:

local   all             postgres                                md5

* If you can't find this file, running locate pg_hba.conf should show you where the file is.

After altering this file, don't forget to restart your PostgreSQL server. If you're on Linux, that would be sudo service postgresql restart.

These are brief descriptions of both options according to the official PostgreSQL docs on authentication methods.

Peer authentication

The peer authentication method works by obtaining the client's operating system user name from the kernel and using it as the allowed database user name (with optional user name mapping). This method is only supported on local connections.

Password authentication

The password-based authentication methods are md5 and password. These methods operate similarly except for the way that the password is sent across the connection, namely MD5-hashed and clear-text respectively.

If you are at all concerned about password "sniffing" attacks then md5 is preferred. Plain password should always be avoided if possible. However, md5 cannot be used with the db_user_namespace feature. If the connection is protected by SSL encryption then password can be used safely (though SSL certificate authentication might be a better choice if one is depending on using SSL).

Sample location for pg_hba.conf:
/etc/postgresql/9.1/main/pg_hba.conf

python dict to numpy structured array

I would prefer storing keys and values on separate arrays. This i often more practical. Structures of arrays are perfect replacement to array of structures. As most of the time you have to process only a subset of your data (in this cases keys or values, operation only with only one of the two arrays would be more efficient than operating with half of the two arrays together.

But in case this way is not possible, I would suggest to use arrays sorted by column instead of by row. In this way you would have the same benefit as having two arrays, but packed only in one.

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

names = 0
values = 1
array = np.empty(shape=(2, len(result)), dtype=float)
array[names] = result.keys()
array[values] = result.values()

But my favorite is this (simpler):

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

arrays = {'names': np.array(result.keys(), dtype=float),
          'values': np.array(result.values(), dtype=float)}

Is there a unique Android device ID?

The unique device ID of an Android OS device as String, using TelephonyManager and ANDROID_ID, is obtained by:

String deviceId;
final TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (mTelephony.getDeviceId() != null) {
    deviceId = mTelephony.getDeviceId();
}
else {
    deviceId = Secure.getString(
                   getApplicationContext().getContentResolver(),
                   Secure.ANDROID_ID);
}

But I strongly recommend a method suggested by Google, see Identifying App Installations.

How to reference image resources in XAML?

One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.

Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UI="clr-namespace:UI.Images" 

Set your Image source like this:

<Image Source={Binding {x:Static UI:Resources.Search}} /> where 'Search' is name of the resource.

How to redirect to another page in node.js

@Nazar Medeiros - Your solution uses passport with Express. I am not using passport, just express-jwt. I might be doing something wrong, but when a user logs in, the token needs to return to the client side. From what I have found so far, this means we have to return a json with the token and therefor cannot call redirect. Is there something I am missing there?

To get around this, I simply return the token, store it in my cookies and then make a ajax GET request (with the valid token). When that ajax call returns I replace the body's html with the returned HTML. This is probably not the right way to do it, but I can't find a better way. Here is my JQuery JavaScript code.

function loginUser(){
  $.post("/users/login", {
    username: $( '#login_input_username' ).val(),
   password: $( '#login_input_password' ).val()
 }).done(function(res){
    document.cookie = "token = " + res.token;
    redirectToHome();
  })
}

function redirectToHome(){
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": "/home",
    "type": "GET",
    "headers": {
      "authorization": "Bearer " + getCookie('token'),
      "cache-control": "no-cache"
    }
  }

  $.ajax(settings).done(function (response) {
    $('body').replaceWith(response);
  });
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

illegal use of break statement; javascript

break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return to break the execution flow of the current function and return to the caller.

function loop() {
    if (isPlaying) {
        jet1.draw();
        drawAllEnemies();
        requestAnimFrame(loop);
        if (game == 1) {
           return
        }
    }
}

Note: This does not cover the logic behind the if condition or when to return from the method, for that we need to have more context regarding the drawAllEnemies and requestAnimFrame method as well as how game value is updated

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

In my case, this message comes from forgotten dependency injection in main module

Why am I getting a FileNotFoundError?

A good start would be validating the input. In other words, you can make sure that the user has indeed typed a correct path for a real existing file, like this:

import os
fileName = input("Please enter the name of the file you'd like to use.")
while not os.path.isfile(fileName):
    fileName = input("Whoops! No such file! Please enter the name of the file you'd like to use.")

This is with a little help from the built in module os, That is a part of the Standard Python Library.

Get content uri from file path in android

// This code works for images on 2.2, not sure if any other media types

   //Your file path - Example here is "/sdcard/cats.jpg"
   final String filePathThis = imagePaths.get(position).toString();

   MediaScannerConnectionClient mediaScannerClient = new
   MediaScannerConnectionClient() {
    private MediaScannerConnection msc = null;
    {
        msc = new MediaScannerConnection(getApplicationContext(), this);
        msc.connect();
    }

    public void onMediaScannerConnected(){
        msc.scanFile(filePathThis, null);
    }


    public void onScanCompleted(String path, Uri uri) {
        //This is where you get your content uri
            Log.d(TAG, uri.toString());
        msc.disconnect();
    }
   };

ComboBox.SelectedText doesn't give me the SelectedText

If you bind your Combobox to something like KeyValuePair, with properties in the constructor like so...:

 DataSource = dataSource,
 DisplayMember = "Value",
 ValueMember = "Key"

so dataSource is of type KeyValuePair...

You end up with having to do this...

  string v = ((KeyValuePair)((ComboBox)c).SelectedItem).Value;

(I had a Dynamic form - where c was of type Control - so had to cast it to ComboBox)

How to sort a data frame by date

In case you want to sort dates with descending order the minus sign doesn't work with Dates.

out <- DF[rev(order(as.Date(DF$end))),]

However you can have the same effect with a general purpose function: rev(). Therefore, you mix rev and order like:

#init data
DF <- data.frame(ID=c('ID3', 'ID2','ID1'), end=c('4/1/09 12:00', '6/1/10 14:20', '1/1/11 11:10')
#change order
out <- DF[rev(order(as.Date(DF$end))),]

Hope it helped.

Functional programming vs Object Oriented programming

Object Oriented Programming offers:

  1. Encapsulation, to
    • control mutation of internal state
    • limit coupling to internal representation
  2. Subtyping, allowing:
    • substitution of compatible types (polymorphism)
    • a crude means of sharing implementation between classes (implementation inheritance)

Functional Programming, in Haskell or even in Scala, can allow substitution through more general mechanism of type classes. Mutable internal state is either discouraged or forbidden. Encapsulation of internal representation can also be achieved. See Haskell vs OOP for a good comparison.

Norman's assertion that "Adding a new kind of thing to a functional program may require editing many function definitions to add a new case." depends on how well the functional code has employed type classes. If Pattern Matching on a particular Abstract Data Type is spread throughout a codebase, you will indeed suffer from this problem, but it is perhaps a poor design to start with.

EDITED Removed reference to implicit conversions when discussing type classes. In Scala, type classes are encoded with implicit parameters, not conversions, although implicit conversions are another means to acheiving substitution of compatible types.

how to compare the Java Byte[] array?

If you're trying to use the array as a generic HashMap key, that's not going to work. Consider creating a custom wrapper object that holds the array, and whose equals(...) and hashcode(...) method returns the results from the java.util.Arrays methods. For example...

import java.util.Arrays;

public class MyByteArray {
   private byte[] data;

   // ... constructors, getters methods, setter methods, etc...


   @Override
   public int hashCode() {
      return Arrays.hashCode(data);
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      MyByteArray other = (MyByteArray) obj;
      if (!Arrays.equals(data, other.data))
         return false;
      return true;
   }


}

Objects of this wrapper class will work fine as a key for your HashMap<MyByteArray, OtherType> and will allow for clean use of equals(...) and hashCode(...) methods.

How to build a Debian/Ubuntu package from source?

First, the title question: Assuming the debian directory is already there, be in the source directory (the directory containing the debian directory) and invoke dpkg-buildpackage. I like to run it with these options:

dpkg-buildpackage -us -uc -nc

which mean don't sign the result and don't clean.

How can I check if I have listed all the dependencies correctly?

Getting the dependencies is a black art. The "official" way is to check build depends is if the package builds with only the base system, the "build-essential" packages, and the build dependencies you have specified. Don't know a general answer for regular Dependencies, just wade in :)

How I can I prevent the update system installing the older version in the repo on an update? How I can prevent the system installing a newer version (when its out), overwriting my custom package?

My knowledge might be out of date on this one, but to address both: Use dpkg --set-selections. Assuming nullidentd was the package you wanted to stay put, run as root

echo 'nullidentd hold' | dpkg --set-selections

Alternately, since you are building from source, you can use an epoch to set the version number artificially high and never be bothered again. To use an epoch, add a new entry to the debian/changelog file, and put a 99: in front of the version number. Given my nullidentd example, the first line of your updated changelog would read:

nullidentd (99:1.0-4) unstable; urgency=low

Bernard's link is good, especially if you have to create the debian directory yourself - also helpful are the developers reference and the general resource page. Adam's link also looks good but I'm not familiar with it.

PHP - Fatal error: Unsupported operand types

$total_ratings is an array, which you can't use for a division.

From above:

$total_ratings = mysqli_fetch_array($result);

If statement in aspx page

<div>
    <% 
        if (true)
        {
    %>
    <div>
        Show true content
    </div>
    <%
        }
        else
        {
    %>
    <div>
        Show false content
    </div>
    <%
        }
    %>
</div>

List files committed for a revision

To just get the list of the changed files with the paths, use

svn diff --summarize -r<rev-of-commit>:<rev-of-commit - 1>

For example:

svn diff --summarize -r42:41

should result in something like

M       path/to/modifiedfile
A       path/to/newfile

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

How to check the gradle version in Android Studio?

I'm not sure if this is what you ask, but you can check gradle version of your project here in android studio:

(left pane must be in project view, not android for this path) app->gradle->wrapper->gradle-wrapper.properties

it has a line like this, indicating the gradle version:

distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-all.zip

There is also a table at the end of this page that shows gradle and gradle plug-in versions supported by each android studio version. (you can check your android studio by checking help->about as you may already know)

Limit file format when using <input type="file">?

As mentioned in previous answers we cannot restrict user to select files for only given file formats. But it's really handy to use the accept tag on file attribute in html.

As for validation, we have to do it at the server side. We can also do it at client side in js but its not a foolproof solution. We must validate at server side.

For these requirements I really prefer struts2 Java web application development framework. With its built-in file upload feature, uploading files to struts2 based web apps is a piece of cake. Just mention the file formats that we would like to accept in our application and all the rest is taken care of by the core of framework itself. You can check it out at struts official site.

How to display the current time and date in C#

labelName.Text = DateTime.Now.ToString("dddd , MMM dd yyyy,hh:mm:ss");

Output:

][1

How to compare strings in sql ignoring case?

If you are matching the full value of the field use

WHERE UPPER(fieldName) = 'ANGEL'

EDIT: From your comment you want to use:

SELECT 
    RPAD(a.name, 10,'=') "Nombre del Cliente"
    , RPAD(b.name, 12,'*') "Nombre del Consumidor" 
FROM 
    s_customer a, 
    s_region b 
WHERE 
    a.region_id = b.id 
    AND UPPER(a.name) LIKE '%SPORT%' 

nil detection in Go

The compiler is pointing the error to you, you're comparing a structure instance and nil. They're not of the same type so it considers it as an invalid comparison and yells at you.

What you want to do here is to compare a pointer to your config instance to nil, which is a valid comparison. To do that you can either use the golang new builtin, or initialize a pointer to it:

config := new(Config) // not nil

or

config := &Config{
                  host: "myhost.com", 
                  port: 22,
                 } // not nil

or

var config *Config // nil

Then you'll be able to check if

if config == nil {
    // then
}

Ways to circumvent the same-origin policy

The JSONP comes to mind:

JSONP or "JSON with padding" is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server. JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing.

Angular 4 - get input value

If you dont want to use two way data binding. You can do this.

In HTML

<form (ngSubmit)="onSubmit($event)">
   <input name="player" value="Name">
</form>

In component

onSubmit(event: any) {
   return event.target.player.value;
}

How do I inject a controller into another controller in AngularJS

<div ng-controller="TestCtrl1">
    <div ng-controller="TestCtrl2">
      <!-- your code--> 
    </div> 
</div>

This works best in my case, where TestCtrl2 has it's own directives.

var testCtrl2 = $controller('TestCtrl2')

This gives me an error saying scopeProvider injection error.

   var testCtrl1ViewModel = $scope.$new();
   $controller('TestCtrl1',{$scope : testCtrl1ViewModel });
   testCtrl1ViewModel.myMethod(); 

This doesn't really work if you have directives in 'TestCtrl1', that directive actually have a different scope from this one created here. You end up with two instances of 'TestCtrl1'.

Laravel migration: unique key is too long, even if specified

i had same problem and i am using a wamp

Solution : Open file : config/database.php

'engine' => null, => 'engine' => 'InnoDB',

Thanks

What does enctype='multipart/form-data' mean?

enctype='multipart/form-data is an encoding type that allows files to be sent through a POST. Quite simply, without this encoding the files cannot be sent through POST.

If you want to allow a user to upload a file via a form, you must use this enctype.

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Adding java.util.list will resolve your problem because List interface which you are trying to use is part of java.util.list package.

How to set a single, main title above all the subplots with Pyplot?

Use pyplot.suptitle or Figure.suptitle:

import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure()
data=np.arange(900).reshape((30,30))
for i in range(1,5):
    ax=fig.add_subplot(2,2,i)        
    ax.imshow(data)

fig.suptitle('Main title') # or plt.suptitle('Main title')
plt.show()

enter image description here

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

The head command can get the first n lines. Variations are:

head -7 file
head -n 7 file
head -7l file

which will get the first 7 lines of the file called "file". The command to use depends on your version of head. Linux will work with the first one.

To append lines to the end of the same file, use:

echo 'first line to add' >>file
echo 'second line to add' >>file
echo 'third line to add' >>file

or:

echo 'first line to add
second line to add
third line to add' >>file

to do it in one hit.

So, tying these two ideas together, if you wanted to get the first 10 lines of the input.txt file to output.txt and append a line with five "=" characters, you could use something like:

( head -10 input.txt ; echo '=====' ) > output.txt

In this case, we do both operations in a sub-shell so as to consolidate the output streams into one, which is then used to create or overwrite the output file.

How do I get the width and height of a HTML5 canvas?

It might be worth looking at a tutorial: MDN Canvas Tutorial

You can get the width and height of a canvas element simply by accessing those properties of the element. For example:

var canvas = document.getElementById('mycanvas');
var width = canvas.width;
var height = canvas.height;

If the width and height attributes are not present in the canvas element, the default 300x150 size will be returned. To dynamically get the correct width and height use the following code:

const canvasW = canvas.getBoundingClientRect().width;
const canvasH = canvas.getBoundingClientRect().height;

Or using the shorter object destructuring syntax:

const { width, height } = canvas.getBoundingClientRect();

The context is an object you get from the canvas to allow you to draw into it. You can think of the context as the API to the canvas, that provides you with the commands that enable you to draw on the canvas element.

Get the current script file name

Try this

_x000D_
_x000D_
$file = basename($_SERVER['PATH_INFO']);//Filename requested
_x000D_
_x000D_
_x000D_