Programs & Examples On #G++

g++ is the C++ frontend to the GNU Compiler Collection (gcc).

C++ compile time error: expected identifier before numeric constant

You cannot do this:

vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);

in a class outside of a method.

You can initialize the data members at the point of declaration, but not with () brackets:

class Foo {
    vector<string> name = vector<string>(5);
    vector<int> val{vector<int>(5,0)};
};

Before C++11, you need to declare them first, then initialize them e.g in a contructor

class Foo {
    vector<string> name;
    vector<int> val;
 public:
  Foo() : name(5), val(5,0) {}
};

Using 'sudo apt-get install build-essentials'

The package is called build-essential without the plural "s". So

sudo apt-get install build-essential

should do what you want.

Compiling C++11 with g++

You can refer to following link for which features are supported in particular version of compiler. It has an exhaustive list of feature support in compiler. Looks GCC follows standard closely and implements before any other compiler.

Regarding your question you can compile using

  1. g++ -std=c++11 for C++11
  2. g++ -std=c++14 for C++14
  3. g++ -std=c++17 for C++17
  4. g++ -std=c++2a for C++20, although all features of C++20 are not yet supported refer this link for feature support list in GCC.

The list changes pretty fast, keep an eye on the list, if you are waiting for particular feature to be supported.

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

error: expected class-name before ‘{’ token

If you forward-declare Flight and Landing in Event.h, then you should be fixed.

Remember to #include "Flight.h" and #include "Landing.h" in your implementation file for Event.

The general rule of thumb is: if you derive from it, or compose from it, or use it by value, the compiler must know its full definition at the time of declaration. If you compose from a pointer-to-it, the compiler will know how big a pointer is. Similarly, if you pass a reference to it, the compiler will know how big the reference is, too.

How do I enable C++11 in gcc?

If you are using sublime then this code may work if you add it in build as code for building system. You can use this link for more information.

{
    "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\"",
    "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
    "working_dir": "${file_path}",
    "selector": "source.c, source.c++",

    "variants":
    [
        {
            "name": "Run",
            "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
        }
    ]
}

What is the difference between g++ and gcc?

GCC: GNU Compiler Collection

  • Referrers to all the different languages that are supported by the GNU compiler.

gcc: GNU C      Compiler
g++: GNU C++ Compiler

The main differences:

  1. gcc will compile: *.c\*.cpp files as C and C++ respectively.
  2. g++ will compile: *.c\*.cpp files but they will all be treated as C++ files.
  3. Also if you use g++ to link the object files it automatically links in the std C++ libraries (gcc does not do this).
  4. gcc compiling C files has fewer predefined macros.
  5. gcc compiling *.cpp and g++ compiling *.c\*.cpp files has a few extra macros.

Extra Macros when compiling *.cpp files:

#define __GXX_WEAK__ 1
#define __cplusplus 1
#define __DEPRECATED 1
#define __GNUG__ 4
#define __EXCEPTIONS 1
#define __private_extern__ extern

How do I install g++ for Fedora?

The package you're looking for is confusingly named gcc-c++.

LD_LIBRARY_PATH vs LIBRARY_PATH

LD_LIBRARY_PATH is searched when the program starts, LIBRARY_PATH is searched at link time.

caveat from comments:

Undefined reference to vtable

I just ran into another cause for this error that you can check for.

The base class defined a pure virtual function as:

virtual int foo(int x = 0);

And the subclass had

int foo(int x) override;

The problem was the typo that the "=0" was supposed to be outside of the parenthesis:

virtual int foo(int x) = 0;

So, in case you're scrolling this far down, you probably didn't find the answer - this is something else to check for.

C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile

g++ -std=c++0x *.cpp -o output

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

Compiling with g++ using multiple cores

You can do this with make - with gnu make it is the -j flag (this will also help on a uniprocessor machine).

For example if you want 4 parallel jobs from make:

make -j 4

You can also run gcc in a pipe with

gcc -pipe

This will pipeline the compile stages, which will also help keep the cores busy.

If you have additional machines available too, you might check out distcc, which will farm compiles out to those as well.

How to see which flags -march=native will activate?

I'm going to throw my two cents into this question and suggest a slightly more verbose extension of elias's answer. As of gcc 4.6, running of gcc -march=native -v -E - < /dev/null emits an increasing amount of spam in the form of superfluous -mno-* flags. The following will strip these:

gcc -march=native -v -E - < /dev/null 2>&1 | grep cc1 | perl -pe 's/ -mno-\S+//g; s/^.* - //g;'

However, I have only verified the correctness of this on two different CPUs (an Intel Core2 and AMD Phenom), so I suggest also running the following script to be sure that all of these -mno-* flags can be safely stripped.

2021 EDIT: There are indeed machines where -march=native uses a particular -march value, but must disable some implied ISAs (Instruction Set Architecture) with -mno-*.

#!/bin/bash

gcc_cmd="gcc"

# Optionally supply path to gcc as first argument
if (($#)); then
    gcc_cmd="$1"
fi

with_mno=$(
    "${gcc_cmd}" -march=native -mtune=native -v -E - < /dev/null 2>&1 |
    grep cc1 |
    perl -pe 's/^.* - //g;'
)
without_mno=$(echo "${with_mno}" | perl -pe 's/ -mno-\S+//g;')

"${gcc_cmd}" ${with_mno}    -dM -E - < /dev/null > /tmp/gcctest.a.$$
"${gcc_cmd}" ${without_mno} -dM -E - < /dev/null > /tmp/gcctest.b.$$

if diff -u /tmp/gcctest.{a,b}.$$; then
    echo "Safe to strip -mno-* options."
else
    echo
    echo "WARNING! Some -mno-* options are needed!"
    exit 1
fi

rm /tmp/gcctest.{a,b}.$$

I haven't found a difference between gcc -march=native -v -E - < /dev/null and gcc -march=native -### -E - < /dev/null other than some parameters being quoted -- and parameters that contain no special characters, so I'm not sure under what circumstances this makes any real difference.

Finally, note that --march=native was introduced in gcc 4.2, prior to which it is just an unrecognized argument.

How do I include a path to libraries in g++

To specify a directory to search for (binary) libraries, you just use -L:

-L/data[...]/lib

To specify the actual library name, you use -l:

-lfoo  # (links libfoo.a or libfoo.so)

To specify a directory to search for include files (different from libraries!) you use -I:

-I/data[...]/lib

So I think what you want is something like

g++ -g -Wall -I/data[...]/lib testing.cpp fileparameters.cpp main.cpp -o test

These compiler flags (amongst others) can also be found at the GNU GCC Command Options manual:

Compile c++14-code with g++

G++ does support C++14 both via -std=c++14 and -std=c++1y. The latter was the common name for the standard before it was known in which year it would be released. In older versions (including yours) only the latter is accepted as the release year wasn't known yet when those versions were released.

I used "sudo apt-get install g++" which should automatically retrieve the latest version, is that correct?

It installs the latest version available in the Ubuntu repositories, not the latest version that exists.

The latest GCC version is 5.2.

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

I had this error message. The problem was that I declared a virtual destructor in the header file, but the virtual functions' body was actually not implemented.

Undefined reference to static class member

Regarding the second question: push_ref takes reference as a parameter, and you cannot have a reference to static const memeber of a class/struct. Once you call static_cast, a temporary variable is created. And a reference to this object can be passed, everything works just fine.

Or at least my colleague who resolved this said so.

Is optimisation level -O3 dangerous in g++?

Recently I experienced a problem using optimization with g++. The problem was related to a PCI card, where the registers (for command and data) were repreented by a memory address. My driver mapped the physical address to a pointer within the application and gave it to the called process, which worked with it like this:

unsigned int * pciMemory;
askDriverForMapping( & pciMemory );
...
pciMemory[ 0 ] = someCommandIdx;
pciMemory[ 0 ] = someCommandLength;
for ( int i = 0; i < sizeof( someCommand ); i++ )
    pciMemory[ 0 ] = someCommand[ i ];

The card didn't act as expected. When I saw the assembly I understood that the compiler only wrote someCommand[ the last ] into pciMemory, omitting all preceding writes.

In conclusion: be accurate and attentive with optimization.

How do I capture all of my compiler's output to a file?

Try make 2> file. Compiler warnings come out on the standard error stream, not the standard output stream. If my suggestion doesn't work, check your shell manual for how to divert standard error.

usr/bin/ld: cannot find -l<nameOfTheLibrary>

I had this problem with compiling LXC on a fresh VM with Centos 7.8. I tried all the above and failed. Some suggested removing the -static flag from the compiler configuration but I didn't want to change anything.

The only thing that helped was to install glibc-static and retry. Hope that helps someone.

extra qualification error in C++

This is because you have the following code:

class JSONDeserializer
{
    Value JSONDeserializer::ParseValue(TDR type, const json_string& valueString);
};

This is not valid C++ but Visual Studio seems to accept it. You need to change it to the following code to be able to compile it with a standard compliant compiler (gcc is more compliant to the standard on this point).

class JSONDeserializer
{
    Value ParseValue(TDR type, const json_string& valueString);
};

The error come from the fact that JSONDeserializer::ParseValue is a qualified name (a name with a namespace qualification), and such a name is forbidden as a method name in a class.

Compiling a C++ program with gcc

The difference between gcc and g++ are:

     gcc            |        g++
compiles c source   |   compiles c++ source

use g++ instead of gcc to compile you c++ source.

Error: free(): invalid next size (fast):

We need the code, but that usually pops up when you try to free() memory from a pointer that is not allocated. This often happens when you're double-freeing.

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Umair R's answer is mostly the right move to solve the problem, as this error used to be caused by the missing links between opencv libs and the programme. so there is the need to specify the ld_libraty_path configuration. ps. the usual library path is suppose to be:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

I have tried this and it worked well.

Link error "undefined reference to `__gxx_personality_v0'" and g++

If g++ still gives error Try using:

g++ file.c -lstdc++

Look at this post: What is __gxx_personality_v0 for?

Make sure -lstdc++ is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.

error: use of deleted function

I encountered this error when inheriting from an abstract class and not implementing all of the pure virtual methods in my subclass.

Eclipse C++ : "Program "g++" not found in PATH"

I had the same problem, the only solution that worked for me was this:

  1. Open command-line and check whether "g++" actually executes the compiler
  2. If (1) works, uncheck Project->Build automatically in Eclipse
  3. Clean project
  4. Build project

gcc warning" 'will be initialized after'

For those using QT having this error, add this to .pro file

QMAKE_CXXFLAGS_WARN_ON += -Wno-reorder

How to make g++ search for header files in a specific directory?

Headers included with #include <> will be searched in all default directories , but you can also add your own location in the search path with -I command line arg.

I saw your edit you could install your headers in default locations usually

 /usr/local/include
 libdir/gcc/target/version/include
 /usr/target/include
 /usr/include

Confirm with compiler docs though.

How do I set up CLion to compile and run?

I met some problems in Clion and finally, I solved them. Here is some experience.

  1. Download and install MinGW
  2. g++ and gcc package should be installed by default. Use the MinGW installation manager to install mingw32-libz and mingw32-make. You can open MinGW installation manager through C:\MinGW\libexec\mingw-get.exe This step is the most important step. If Clion cannot find make, C compiler and C++ compiler, recheck the MinGW installation manager to make every necessary package is installed.
  3. In Clion, open File->Settings->Build,Execution,Deployment->Toolchains. Set MinGW home as your local MinGW file.
  4. Start your "Hello World"!

C++ unordered_map using a custom class type as the key

I think, jogojapan gave an very good and exhaustive answer. You definitively should take a look at it before reading my post. However, I'd like to add the following:

  1. You can define a comparison function for an unordered_map separately, instead of using the equality comparison operator (operator==). This might be helpful, for example, if you want to use the latter for comparing all members of two Node objects to each other, but only some specific members as key of an unordered_map.
  2. You can also use lambda expressions instead of defining the hash and comparison functions.

All in all, for your Node class, the code could be written as follows:

using h = std::hash<int>;
auto hash = [](const Node& n){return ((17 * 31 + h()(n.a)) * 31 + h()(n.b)) * 31 + h()(n.c);};
auto equal = [](const Node& l, const Node& r){return l.a == r.a && l.b == r.b && l.c == r.c;};
std::unordered_map<Node, int, decltype(hash), decltype(equal)> m(8, hash, equal);

Notes:

  • I just reused the hashing method at the end of jogojapan's answer, but you can find the idea for a more general solution here (if you don't want to use Boost).
  • My code is maybe a bit too minified. For a slightly more readable version, please see this code on Ideone.

C++ undefined reference to defined function

As Paul said, this can be a linker complaint, rather than a compiler error. If you read your build output/logs carefully (may need to look in a separate IDE window to see the full details) you can dell if the problem is from the compiler (needs to be fixed in code) or from the linker (and need to be fixed in the make/cmake/project level to include a missing lib).

How to forward declare a template class in namespace std?

The problem is not that you can't forward-declare a template class. Yes, you do need to know all of the template parameters and their defaults to be able to forward-declare it correctly:

namespace std {
  template<class T, class Allocator = std::allocator<T>>
  class list;
}

But to make even such a forward declaration in namespace std is explicitly prohibited by the standard: the only thing you're allowed to put in std is a template specialisation, commonly std::less on a user-defined type. Someone else can cite the relevant text if necessary.

Just #include <list> and don't worry about it.

Oh, incidentally, any name containing double-underscores is reserved for use by the implementation, so you should use something like TEST_H instead of __TEST__. It's not going to generate a warning or an error, but if your program has a clash with an implementation-defined identifier, then it's not guaranteed to compile or run correctly: it's ill-formed. Also prohibited are names beginning with an underscore followed by a capital letter, among others. In general, don't start things with underscores unless you know what magic you're dealing with.

to_string is not a member of std, says g++ (mingw)

As suggested this may be an issue with your compiler version.

Try using the following code to convert a long to std::string:

#include <sstream>
#include <string>
#include <iostream>

int main() {
    std::ostringstream ss;
    long num = 123456;
    ss << num;
    std::cout << ss.str() << std::endl;
}

What is the purpose of using -pedantic in GCC/G++ compiler?

If your code needs to be portable then you can test that it compiles without any gcc extensions or other non-standard features. If your code compiles with -pedantic -ansi then in theory it should compile OK with any other ANSI standard compiler.

Fatal error: iostream: No such file or directory in compiling C program using GCC

Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t. I am glad that you did.

Anyways, You have a .c source file, and most of the code looks as per C standards, except that #include <iostream> and using namespace std;

C equivalent for the built-in functions of C++ standard #include<iostream> can be availed through #include<stdio.h>

  1. Replace #include <iostream> with #include <stdio.h>, delete using namespace std;
  2. With #include <iostream> taken off, you would need a C standard alternative for cout << endl;, which can be done by printf("\n"); or putchar('\n');
    Out of the two options, printf("\n"); works the faster as I observed.

    When used printf("\n"); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.031s
    user    0m0.030s
    sys     0m0.030s
    

    When used putchar('\n'); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.047s
    user    0m0.030s
    sys     0m0.030s
    

Compiled with Cygwin gcc (GCC) 4.8.3 version. results averaged over 10 samples. (Took me 15 mins)

cc1plus: error: unrecognized command line option "-std=c++11" with g++

Quoting from the gcc website:

C++11 features are available as part of the "mainline" GCC compiler in the trunk of GCC's Subversion repository and in GCC 4.3 and later. To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.

So probably you use a version of g++ which doesn't support -std=c++11. Try -std=c++0x instead.

Availability of C++11 features is for versions >= 4.3 only.

g++ undefined reference to typeinfo

One possible reason is because you are declaring a virtual function without defining it.

When you declare it without defining it in the same compilation unit, you're indicating that it's defined somewhere else - this means the linker phase will try to find it in one of the other compilation units (or libraries).

An example of defining the virtual function is:

virtual void fn() { /* insert code here */ }

In this case, you are attaching a definition to the declaration, which means the linker doesn't need to resolve it later.

The line

virtual void fn();

declares fn() without defining it and will cause the error message you asked about.

It's very similar to the code:

extern int i;
int *pi = &i;

which states that the integer i is declared in another compilation unit which must be resolved at link time (otherwise pi can't be set to it's address).

How to make a variadic macro (variable number of arguments)

explained for g++ here, though it is part of C99 so should work for everyone

http://www.delorie.com/gnu/docs/gcc/gcc_44.html

quick example:

#define debug(format, args...) fprintf (stderr, format, args)

gcc/g++: "No such file or directory"

Your compiler just tried to compile the file named foo.cc. Upon hitting line number line, the compiler finds:

#include "bar"

or

#include <bar>

The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file bar. For an explanation of the difference between the versions of the include statement look here.

How to tell the compiler where to find it

g++ has an option -I. It lets you add include search paths to the command line. Imagine that your file bar is in a folder named frobnicate, relative to foo.cc (assume you are compiling from the directory where foo.cc is located):

g++ -Ifrobnicate foo.cc

You can add more include-paths; each you give is relative to the current directory. Microsoft's compiler has a correlating option /I that works in the same way, or in Visual Studio, the folders can be set in the Property Pages of the Project, under Configuration Properties->C/C++->General->Additional Include Directories.

Now imagine you have multiple version of bar in different folders, given:


// A/bar
#include<string>
std::string which() { return "A/bar"; }

// B/bar
#include<string>
std::string which() { return "B/bar"; }

// C/bar
#include<string>
std::string which() { return "C/bar"; }

// foo.cc
#include "bar"
#include <iostream>

int main () {
    std::cout << which() << std::endl;
}

The priority with #include "bar" is leftmost:

$ g++ -IA -IB -IC foo.cc
$ ./a.out
A/bar

As you see, when the compiler started looking through A/, B/ and C/, it stopped at the first or leftmost hit.

This is true of both forms, include <> and incude "".

Difference between #include <bar> and #include "bar"

Usually, the #include <xxx> makes it look into system folders first, the #include "xxx" makes it look into the current or custom folders first.

E.g.:

Imagine you have the following files in your project folder:

list
main.cc

with main.cc:

#include "list"
....

For this, your compiler will #include the file list in your project folder, because it currently compiles main.cc and there is that file list in the current folder.

But with main.cc:

#include <list>
....

and then g++ main.cc, your compiler will look into the system folders first, and because <list> is a standard header, it will #include the file named list that comes with your C++ platform as part of the standard library.

This is all a bit simplified, but should give you the basic idea.

Details on <>/""-priorities and -I

According to the gcc-documentation, the priority for include <> is, on a "normal Unix system", as follows:

 /usr/local/include
 libdir/gcc/target/version/include
 /usr/target/include
 /usr/include

For C++ programs, it will also look in /usr/include/c++/version, first. In the above, target is the canonical name of the system GCC was configured to compile code for; [...].

The documentation also states:

You can add to this list with the -Idir command line option. All the directories named by -I are searched, in left-to-right order, before the default directories. The only exception is when dir is already searched by default. In this case, the option is ignored and the search order for system directories remains unchanged.

To continue our #include<list> / #include"list" example (same code):

g++ -I. main.cc

and

#include<list>
int main () { std::list<int> l; }

and indeed, the -I. prioritizes the folder . over the system includes and we get a compiler error.

How does #include <bits/stdc++.h> work in C++?

That header file is not part of the C++ standard, is therefore non-portable, and should be avoided.

Moreover, even if there were some catch-all header in the standard, you would want to avoid it in lieu of specific headers, since the compiler has to actually read in and parse every included header (including recursively included headers) every single time that translation unit is compiled.

How to specify preference of library path?

As an alternative, you can use the environment variables LIBRARY_PATH and CPLUS_INCLUDE_PATH, which respectively indicate where to look for libraries and where to look for headers (CPATH will also do the job), without specifying the -L and -I options.

Edit: CPATH includes header with -I and CPLUS_INCLUDE_PATH with -isystem.

How do I install g++ on MacOS X?

Download Xcode, which is free with an ADC online membership (also free):

http://developer.apple.com/technology/xcode.html

std::enable_if to conditionally compile a member function

The boolean needs to depend on the template parameter being deduced. So an easy way to fix is to use a default boolean parameter:

template< class T >
class Y {

    public:
        template < bool EnableBool = true, typename = typename std::enable_if<( std::is_same<T, double>::value && EnableBool )>::type >
        T foo() {
            return 10;
        }

};

However, this won't work if you want to overload the member function. Instead, its best to use TICK_MEMBER_REQUIRES from the Tick library:

template< class T >
class Y {

    public:
        TICK_MEMBER_REQUIRES(std::is_same<T, double>::value)
        T foo() {
            return 10;
        }

        TICK_MEMBER_REQUIRES(!std::is_same<T, double>::value)
        T foo() {
            return 10;
        }

};

You can also implement your own member requires macro like this(just in case you don't want to use another library):

template<long N>
struct requires_enum
{
    enum class type
    {
        none,
        all       
    };
};


#define MEMBER_REQUIRES(...) \
typename requires_enum<__LINE__>::type PrivateRequiresEnum ## __LINE__ = requires_enum<__LINE__>::type::none, \
class=typename std::enable_if<((PrivateRequiresEnum ## __LINE__ == requires_enum<__LINE__>::type::none) && (__VA_ARGS__))>::type

Update GCC on OSX

Whatever Apple ships as the default gcc in xcode (4.2.1 on 10.6, 4.0.1 before) is well tested (and maintained) by the apple guys and the "standard" to build software with on OS X. Everything else is not, so think twice if you want to develop software, or be gcc/OS X beta tester.

GCC dump preprocessor defines

Yes, use -E -dM options instead of -c. Example (outputs them to stdout):

 gcc -dM -E - < /dev/null

For C++

 g++ -dM -E -x c++ - < /dev/null

From the gcc manual:

Instead of the normal output, generate a list of `#define' directives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor. Assuming you have no file foo.h, the command

touch foo.h; cpp -dM foo.h

will show all the predefined macros.

If you use -dM without the -E option, -dM is interpreted as a synonym for -fdump-rtl-mach.

How to create a static library with g++?

You can create a .a file using the ar utility, like so:

ar crf lib/libHeader.a header.o

lib is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a in the directory lib. So, in your current directory, do:

mkdir lib

Then run the above ar command.

When linking all libraries, you can do it like so:

g++ test.o -L./lib -lHeader -o test  

The -L flag will get g++ to add the lib/ directory to the path. This way, g++ knows what directory to search when looking for libHeader. -llibHeader flags the specific library to link.

where test.o is created like so:

g++ -c test.cpp -o test.o 

Get operating system info

Took the following code from php manual for get_browser.

$browser = get_browser(null, true);
print_r($browser);

The $browser array has platform information included which gives you the specific Operating System in use.

Please make sure to see the "Notes" section in that page. This might be something (thismachine.info) is using if not something already pointed in other answers.

addClass and removeClass in jQuery - not removing class

Whenever I see addClass and removeClass I think why not just use toggleClass. In this case we can remove the .clickable class to avoid event bubbling, and to avoid the event from being fired on everything we click inside of the .clickable div.

$(document).on("click", ".close_button", function () { 
    $(this).closest(".grown").toggleClass("spot grown clickable");
});  

$(document).on("click", ".clickable", function () {
    $(this).toggleClass("spot grown clickable");
}); 

I also recommend a parent wrapper for your .clickable divs instead of using the document. I am not sure how you are adding them dynamically so didn't want to assume your layout for you.

http://jsfiddle.net/bplumb/ECQg5/2/

Happy Coding :)

Git - remote: Repository not found

In our case it was simply a case of giving write rights in github. Initially the user had only read rights and it was giving this error.

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

Regarding to sampopes answer from Jun 6 '14 at 11:59:

I have insert a css style with font-size of 20px to display the excel data greater. In sampopes code the leading <tr> tags are missing, so i first output the headline and than the other tables lines within a loop.

function fnExcelReport()
{
    var tab_text = '<table border="1px" style="font-size:20px" ">';
    var textRange; 
    var j = 0;
    var tab = document.getElementById('DataTableId'); // id of table
    var lines = tab.rows.length;

    // the first headline of the table
    if (lines > 0) {
        tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>';
    }

    // table data lines, loop starting from 1
    for (j = 1 ; j < lines; j++) {     
        tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</tr>";
    }

    tab_text = tab_text + "</table>";
    tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");             //remove if u want links in your table
    tab_text = tab_text.replace(/<img[^>]*>/gi,"");                 // remove if u want images in your table
    tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, "");    // reomves input params
    // console.log(tab_text); // aktivate so see the result (press F12 in browser)

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

     // if Internet Explorer
    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa = txtArea1.document.execCommand("SaveAs", true, "DataTableExport.xls");
    }  
    else // other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}   

Proper way to initialize C++ structs

You need to initialize whatever members you have in your struct, e.g.:

struct MyStruct {
  private:
    int someInt_;
    float someFloat_;

  public:
    MyStruct(): someInt_(0), someFloat_(1.0) {} // Initializer list will set appropriate values

};

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

I spent half a day searching for answers to an identical "Illegal mix of collations" error with conflicts between utf8_unicode_ci and utf8_general_ci.

I found that some columns in my database were not specifically collated utf8_unicode_ci. It seems mysql implicitly collated these columns utf8_general_ci.

Specifically, running a 'SHOW CREATE TABLE table1' query outputted something like the following:

| table1 | CREATE TABLE `table1` (
`id` int(11) NOT NULL,
`col1` varchar(4) CHARACTER SET utf8 NOT NULL,
`col2` int(11) NOT NULL,
PRIMARY KEY (`col1`,`col2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |

Note the line 'col1' varchar(4) CHARACTER SET utf8 NOT NULL does not have a collation specified. I then ran the following query:

ALTER TABLE table1 CHANGE col1 col1 VARCHAR(4) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;

This solved my "Illegal mix of collations" error. Hope this might help someone else out there.

Does Java have a complete enum for HTTP response codes?

Another option is to use HttpStatus class from the Apache commons-httpclient which provides you the various Http statuses as constants.

"Operation must use an updateable query" error in MS Access

I had the same problem exactly, and I can't remember how I fond this solution but simply adding DISTINCTROW solved the problem.

In your code it will look like this:

UPDATE DISTINCTROW [GS] INNER JOIN [Views] ON <- the only change is here
    ([Views].Hostname = [GS].Hostname) 
    AND ([GS].APPID = [Views].APPID) 
 ...

I'm not sure why this works, but for me, it did exactly what I needed.

How to generate JAXB classes from XSD?

XJC is included in the bin directory in the JDK starting with Java SE 6. For an example see:

The contents of the blog are the following:

Processing Atom Feeds with JAXB Atom is an XML format for representing web feeds. A standard format allows reader applications to display feeds from different sources. In this example we will process the Atom feed for this blog.

Demo

In this example we will use JAXB to convert the Atom XML feed corresponding to this blog to objects and then back to XML.

import java.io.InputStream;
import java.net.URL;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.w3._2005.atom.FeedType;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance("org.w3._2005.atom");

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        URL url = new URL("http://bdoughan.blogspot.com/atom.xml");
        InputStream xml = url.openStream();
        JAXBElement<feedtype> feed = unmarshaller.unmarshal(new StreamSource(xml), FeedType.class);
        xml.close();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(feed, System.out);
    }

}

JAXB Model

The following model was generated by the schema to Java compiler (XJC). I have omitted the get/set methods and comments to save space.

xjc -d generated http://www.kbcafe.com/rss/atom.xsd.xml

package-info

@XmlSchema(
        namespace = "http://www.w3.org/2005/Atom",
        elementFormDefault = XmlNsForm.QUALIFIED)
@XmlAccessorType(XmlAccessType.FIELD)
package org.w3._2005.atom;

import javax.xml.bind.annotation.*;

CategoryType

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "categoryType")
public class CategoryType {
    @XmlAttribute(required = true)
    protected String term;

    @XmlAttribute
    @XmlSchemaType(name = "anyURI")
    protected String scheme;

    @XmlAttribute
    protected String label;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

Content Type

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "contentType", propOrder = {"content"})
public class ContentType {
    @XmlMixed
    @XmlAnyElement(lax = true)
    protected List<Object> content;

    @XmlAttribute
    protected String type;

    @XmlAttribute
    @XmlSchemaType(name = "anyURI")
    protected String src;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

DateTimeType

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;

@XmlType(name = "dateTimeType", propOrder = {"value"})
public class DateTimeType {
    @XmlValue
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar value;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

EntryType

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "entryType", propOrder = {"authorOrCategoryOrContent"})
public class EntryType {
    @XmlElementRefs({
        @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "summary", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "source", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "content", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "published", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class)
    })
    @XmlAnyElement(lax = true)
    protected List<Object> authorOrCategoryOrContent;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

FeedType

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "feedType", propOrder = {"authorOrCategoryOrContributor"})
public class FeedType {
    @XmlElementRefs({
        @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "generator", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "icon", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "subtitle", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "entry", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "logo", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class)
    })
    @XmlAnyElement(lax = true)
    protected List<Object> authorOrCategoryOrContributor;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

GeneratorType

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "generatorType", propOrder = {"value"})
public class GeneratorType {
    @XmlValue
    protected String value;

    @XmlAttribute
    @XmlSchemaType(name = "anyURI")
    protected String uri;

    @XmlAttribute
    protected String version;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

IconType

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "iconType", propOrder = {"value"})
public class IconType {
    @XmlValue
    @XmlSchemaType(name = "anyURI")
    protected String value;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

IdType

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "idType", propOrder = {"value"})
public class IdType {
    @XmlValue
    @XmlSchemaType(name = "anyURI")
    protected String value;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

LinkType

package org.w3._2005.atom;

import java.math.BigInteger;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "linkType", propOrder = {"content"})
public class LinkType {
    @XmlValue
    protected String content;

    @XmlAttribute(required = true)
    @XmlSchemaType(name = "anyURI")
    protected String href;

    @XmlAttribute
    protected String rel;

    @XmlAttribute
    protected String type;

    @XmlAttribute
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NMTOKEN")
    protected String hreflang;

    @XmlAttribute
    protected String title;

    @XmlAttribute
    @XmlSchemaType(name = "positiveInteger")
    protected BigInteger length;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

LogoType

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "logoType", propOrder = {"value"})
public class LogoType {
    @XmlValue
    @XmlSchemaType(name = "anyURI")
    protected String value;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

PersonType

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "personType", propOrder = {"nameOrUriOrEmail"})
public class PersonType {
    @XmlElementRefs({
        @XmlElementRef(name = "email", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "name", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "uri", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class)
    })
    @XmlAnyElement(lax = true)
    protected List<Object> nameOrUriOrEmail;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

SourceType

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "sourceType", propOrder = {"authorOrCategoryOrContributor"})
public class SourceType {
    @XmlElementRefs({
        @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "subtitle", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "logo", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "generator", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "icon", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class),
        @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class)
    })
    @XmlAnyElement(lax = true)
    protected List<Object> authorOrCategoryOrContributor;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

TextType

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "textType", propOrder = {"content"})
public class TextType {
    @XmlMixed
    @XmlAnyElement(lax = true)
    protected List<Object> content;

    @XmlAttribute
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String type;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

UriType

package org.w3._2005.atom;

import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.namespace.QName;

@XmlType(name = "uriType", propOrder = {"value"})
public class UriType {
    @XmlValue
    @XmlSchemaType(name = "anyURI")
    protected String value;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anyURI")
    protected String base;

    @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();
}

How do I create a pause/wait function using Qt?

From Qt5 onwards we can also use

Static Public Members of QThread

void    msleep(unsigned long msecs)
void    sleep(unsigned long secs)
void    usleep(unsigned long usecs)

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

You can try this:

Select To_date ('15/2/2007 00:00:00', 'DD/MM/YYYY HH24:MI:SS'),
       To_date ('28/2/2007 10:12', 'DD/MM/YYYY HH24:MI:SS')
  From DUAL;

Source: http://notsyncing.org/2008/02/manipulando-fechas-con-horas-en-plsql-y-sql/

ASP.Net MVC 4 Form with 2 submit buttons/actions

With HTML5 you can use button[formaction]:

<form action="Edit">
  <button type="submit">Submit</button> <!-- Will post to default action "Edit" -->
  <button type="submit" formaction="Validate">Validate</button> <!-- Will override default action and post to "Validate -->
</form>

Pycharm: run only part of my Python file

I found out an easier way.

  • go to File -> Settings -> Keymap
  • Search for Execute Selection in Console and reassign it to a new shortcut, like Crl + Enter.

This is the same shortcut to the same action in Spyder and R-Studio.

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

I got this error but it is resolved interesting. As first, i got this error at api level 17. When i call a thread (AsyncTask or others) without progress dialog then i call an other thread method again using progress dialog, i got that crash and the reason is about usage of progress dialog.

In my case, there are two results that;

  • I took show(); method of progress dialog before first thread starts then i took dismiss(); method of progress dialog before last thread ends.

So :

ProgresDialog progressDialog = new ...

//configure progressDialog 

progressDialog.show();

start firstThread {
...
}

...

start lastThread {
...
} 

//be sure to finish threads

progressDialog.dismiss();
  • This is so strange but that error has an ability about destroy itself at least for me :)

how to use List<WebElement> webdriver

Try with below logic

driver.get("http://www.labmultis.info/jpecka.portal-exdrazby/index.php?c1=2&a=s&aa=&ta=1");

List<WebElement> allElements=driver.findElements(By.cssSelector(".list.list-categories li"));

for(WebElement ele :allElements) {
    System.out.println("Name + Number===>"+ele.getText());
    String s=ele.getText();
    s=s.substring(s.indexOf("(")+1, s.indexOf(")"));
    System.out.println("Number==>"+s);
}

====Output======
Name + Number===>Vše (950)
Number==>950
Name + Number===>Byty (181)
Number==>181
Name + Number===>Domy (512)
Number==>512
Name + Number===>Pozemky (172)
Number==>172
Name + Number===>Chaty (28)
Number==>28
Name + Number===>Zemedelské objekty (5)
Number==>5
Name + Number===>Komercní objekty (30)
Number==>30
Name + Number===>Ostatní (22)
Number==>22

INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

See this link it said that it will work when they are signed by the same key. The release key and the debug key are not the same.

So do it:

buildTypes {
        release {
            minifyEnabled true
            signingConfig signingConfigs.release//signing by the same key
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-android.txt'

        }
        debug {
            applicationIdSuffix ".debug"
            debuggable true
            signingConfig signingConfigs.release//signing by the same key
        }

    }

 signingConfigs {
        release {
            storeFile file("***\\key_.jks")
            storePassword "key_***"
            keyAlias "key_***"
            keyPassword "key_"***"
        }


}

what is numeric(18, 0) in sql server 2008 r2

This page explains it pretty well.

As a numeric the allowable range that can be stored in that field is -10^38 +1 to 10^38 - 1.

The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.

The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.

So the range that can be stored in this particular field is -(10^18 - 1) to (10^18 - 1)

Or -999999999999999999 to 999999999999999999 Integers only

PostgreSQL: Show tables in PostgreSQL

Running psql with the -E flag will echo the query used internally to implement \dt and similar:

sudo -u postgres psql -E

postgres=# \dt       
********* QUERY **********
SELECT n.nspname as "Schema",
c.relname as "Name", 
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' END as "Type",
pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
    LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','')
    AND n.nspname <> 'pg_catalog'
    AND n.nspname <> 'information_schema'
    AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;        
**************************

Backup/Restore a dockerized PostgreSQL database

I think you can also use a postgres backup container which would backup your databases within a given time duration.

  pgbackups:
    container_name: Backup
    image: prodrigestivill/postgres-backup-local
    restart: always
    volumes:
      - ./backup:/backups
    links:
      - db:db
    depends_on:
      - db
    environment:
      - POSTGRES_HOST=db
      - POSTGRES_DB=${DB_NAME} 
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_EXTRA_OPTS=-Z9 --schema=public --blobs
      - SCHEDULE=@every 0h30m00s
      - BACKUP_KEEP_DAYS=7
      - BACKUP_KEEP_WEEKS=4
      - BACKUP_KEEP_MONTHS=6
      - HEALTHCHECK_PORT=81

No plot window in matplotlib

You can type

import pylab
pylab.show()

or better, use ipython -pylab.


Since the use of pylab is not recommended anymore, the solution would nowadays be

import matplotlib.pyplot as plt

plt.plot([1,2,3])

plt.show()

Getting GET "?" variable in laravel

We have similar situation right now and as of this answer, I am using laravel 5.6 release.

I will not use your example in the question but mine, because it's related though.

I have route like this:

Route::name('your.name.here')->get('/your/uri', 'YourController@someMethod');

Then in your controller method, make sure you include

use Illuminate\Http\Request;

and this should be above your controller, most likely a default, if generated using php artisan, now to get variable from the url it should look like this:

  public function someMethod(Request $request)
  {
    $foo = $request->input("start");
    $bar = $request->input("limit");

    // some codes here
  }

Regardless of the HTTP verb, the input() method may be used to retrieve user input.

https://laravel.com/docs/5.6/requests#retrieving-input

Hope this help.

Replace a character at a specific index in a string?

String is an immutable class in java. Any method which seems to modify it always returns a new string object with modification.

If you want to manipulate a string, consider StringBuilder or StringBuffer in case you require thread safety.

Angular 2: How to access an HTTP response body?

Here is an example to access response body using angular2 built in Response

import { Injectable } from '@angular/core';
import {Http,Response} from '@angular/http';

@Injectable()
export class SampleService {
  constructor(private http:Http) { }

  getData(){

    this.http.get(url)
   .map((res:Response) => (
       res.json() //Convert response to JSON
       //OR
       res.text() //Convert response to a string
   ))
   .subscribe(data => {console.log(data)})

  }
}

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

It turns out that the solution is to stop all the related services and solve the “Another daemon is already running” issue.

The commands i used to solve the issue are as follows:

sudo /opt/lampp/lampp stop              
sudo /etc/init.d/apache2 stop    
sudo /etc/init.d/mysql stop

Or, you can also type instead:

sudo service apache2 stop
sudo service mysql stop

After that, we again start the lampp services:

sudo /opt/lampp/lampp start

Now, there must be no problems while opening:

http://localhost                  
http://localhost/phpmyadmin

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

Removing border from table cells

If none of the solutions on this page work and you are having the below issue:

enter image description here

You can simply use this snippet of CSS:

td {
   padding: 0;
}

how to run or install a *.jar file in windows?

Open up a command prompt and type java -jar jbpm-installer-3.2.7.jar

jquery-ui-dialog - How to hook into dialog close event

This is what worked for me...

$('#dialog').live("dialogclose", function(){
   //code to run on dialog close
});

Where can I download an offline installer of Cygwin?

If all you want is the UNIX command line tools I'd suggest not installing Cygwin. Cygwin wants to turn your Windows PC into a UNIX Workstation which is why it likes to install all its packages.

Have a look at GnuWin32 instead. It's Windows ports of the command line tools and nothing else. Here is the installer for the GnuWin32 diff.exe. There are offline installers for all the common tools.

(You asked for offline installers but in case you ever want one later there is a tool which will download and install everything for you.)

Method 2: make an offline install zip file for cygwin.

Don't mess with saving packages because the installed directory for cygwin can be canned in a zip file and expanded whenever you need it on any computer.

  1. Download Cygwin installer

  2. pick packages you want installed from gui.

  3. hit install and wait a really long time for everything to download.

  4. zip up the C:\Cygwin folder. Now you have your offline zip file for installing cygwin on any machine.

  5. Unzip this file on whatever computer you like. set cmd.exe paths appropriately to point to cygwin bin directory under windows control panel.

Binning column with python pandas

You can use pandas.cut:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

Or numpy.searchsorted:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and then value_counts or groupby and aggregate size:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

By default cut return categorical.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

How to count items in JSON object using command line?

A simple solution is to install jshon library :

jshon -l < /tmp/test.json
2

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

The root of the answer is that the person asking the question needs to have a JavaScript interpreter to get what they are after. What I have found is I am able to get all of the information I wanted on a website in json before it was interpreted by JavaScript. This has saved me a ton of time in what would be parsing html hoping each webpage is in the same format.

So when you get a response from a website using requests really look at the html/text because you might find the javascripts JSON in the footer ready to be parsed.

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

From the docs

In the Java programming language, every application must contain a main method whose signature is:

public static void main(String[] args)

The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".

As you say:

error: missing method body, or declare abstract public static void main(String[] args); ^ this is what i got after i added it after the class name

You probably haven't declared main with a body (as ';" would suggest in your error).

You need to have main method with a body, which means you need to add { and }:

public static void main(String[] args) {


}

Add it inside your class definition.

Although sometimes error messages are not very clear, most of the time they contain enough information to point to the issue. Worst case, you can search internet for the error message. Also, documentation can be really helpful.

One line if in VB .NET

It's actually pretty simple..

If CONDITION Then ..INSERT CODE HERE..

SQL RANK() over PARTITION on joined tables

SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID

How can I debug a Perl script?

Use Eclipse with EPIC: It gives you a nice IDE with debugging possibilities, including the ability to place breakpoints and the Perl Expression View for inspecting the value of variables.

window.location.reload with clear cache

i had this problem and i solved it using javascript

 location.reload(true);

you may also use

window.history.forward(1);

to stop the browser back button after user logs out of the application.

How to check if the key pressed was an arrow key in Java KeyListener?

Just to complete the answer (using the KeyEvent is the way to go) but up arrow is 38 and down arrow is 40 so:

    else if (e.getKeyCode()==38)
    {
            //Up arrow key code
    }
    else if (e.getKeyCode()==40)
    {
            //down arrow key code
    }

Installing SciPy and NumPy using pip

On windows python 3.5, I managed to install scipy by using conda not pip:

conda install scipy

jQuery vs. javascript?

It's all about performance and development speed. Of course, if you are a good programmer and design something that is really tailored to your needs, you might achieve better performance than if you had used a Javascript framework. But do you have the time to do it all by yourself?

My personal opinion is that Javascript is incredibly useful and overused, but that if you really need it, a framework is the way to go.

Now comes the choice of the framework. For what benchmarks are worth, you can find one at http://ejohn.org/files/142/ . It also depends on which plugins are available and what you intend to do with them. I started using jQuery because it seemed to be maintained and well featured, even though it wasn't the fastest at that moment. I do not regret it but I didn't test anything else since then.

How to get the pure text without HTML element using JavaScript?

You want to change the I am working in ABC company. to I am working in ABC company.. These are the same strings, so I don't see a reason to, but you can accomplish this by using the JavaScript innerHTML or textContent.

element.innerHTML is a property that defines the HTML inside an element. If you type element.innerHTML = "<strong>This is bold</strong>, it'll make the text "This is bold" bold text.

element.textContent, on the other hand, sets the text in an element. If you use element.textContent = "<strong>This is bold</strong>, The text "This is bold" will not be bold. The user will literally see the text "This is bold

In your case, you can use either one. I'll use .textContent. The code to change the <p> element is below.

function get_content(){
   document.getElementById("txt").textContent = "I am working in ABC company.";
}

<input type="button" onclick="get_content()" value="Get Content"/>
<p id='txt'>
<span class="A">I am</span>
<span class="B">working in </span>
<span class="C">ABC company.</span>
</p>

This, unfortunately, will not change it because it'll change it to the same exact text. You can chance that by changing the string "I am working in ABC company." to something else.

windows batch file rename

I rename in code

echo off

setlocal EnableDelayedExpansion

for %%a in (*.txt) do (
    REM echo %%a
    set x=%%a
    set mes=!x:~17,3!

    if !mes!==JAN (
        set mes=01
    )

    if !mes!==ENE (
        set mes=01
    )

    if !mes!==FEB (
        set mes=02
    )

    if !mes!==MAR (
        set mes=03
    )

    if !mes!==APR (
        set mes=04
    )

    if !mes!==MAY (
        set mes=05
    )

    if !mes!==JUN (
        set mes=06
    )

    if !mes!==JUL (
        set mes=07
    )

    if !mes!==AUG (
        set mes=08
    )

    if !mes!==SEP (
        set mes=09
    )

    if !mes!==OCT (
        set mes=10
    )

    if !mes!==NOV (
        set mes=11
    )

    if !mes!==DEC (
        set mes=12
    )

    ren %%a !x:~20,4!!mes!!x:~15,2!.txt 

    echo !x:~20,4!!mes!!x:~15,2!.txt 

)

"document.getElementByClass is not a function"

The getElementByClass does not exists, probably you want to use getElementsByClassName. However you can use alternative approach (used in angular/vue/react... templates)

_x000D_
_x000D_
function stop(ta) {_x000D_
  console.log(ta.value) // document['player'].stopMusicExt(ta.value);_x000D_
  ta.value='';_x000D_
}
_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 1'>_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 2'>
_x000D_
_x000D_
_x000D_

How do I prevent 'git diff' from using a pager?

The recent changes in the documentation mention a different way of removing a default option for less ("default options" being FRSX).

For this question, this would be (git 1.8+)

git config --global --replace-all core.pager 'less -+F -+X'

For example, Dirk Bester suggests in the comments:

export LESS="$LESS -FRXK" 

so that I get colored diff with Ctrl-C quit from less.

Wilson F mentions in the comments and in his question that:

less supports horizontal scrolling, so when lines are chopped off, less disables quit-if-one-screen so that the user can still scroll the text to the left to see what was cut off.


Those modifications were already visible in git 1.8.x, as illustrated in "Always use the pager for git diff" (see the comments). But the documentation just got reworded (for git 1.8.5 or 1.9, Q4 2013).

Text viewer for use by Git commands (e.g., 'less').
The value is meant to be interpreted by the shell.

The order of preference is:

  • the $GIT_PAGER environment variable,
  • then core.pager configuration,
  • then $PAGER,
  • and then the default chosen at compile time (usually 'less').

When the LESS environment variable is unset, Git sets it to FRSX
(if LESS environment variable is set, Git does not change it at all).

If you want to selectively override Git's default setting for LESS, you can set core.pager to e.g. less -+S.
This will be passed to the shell by Git, which will translate the final command to LESS=FRSX less -+S. The environment tells the command to set the S option to chop long lines but the command line resets it to the default to fold long lines.


See commit 97d01f2a for the reason behind the new documentation wording:

config: rewrite core.pager documentation

The text mentions core.pager and GIT_PAGER without giving the overall picture of precedence. Borrow a better description from the git var(1) documentation.

The use of the mechanism to allow system-wide, global and per-repository configuration files is not limited to this particular variable. Remove it to clarify the paragraph.

Rewrite the part that explains how the environment variable LESS is set to Git's default value, and how to selectively customize it.


Note: commit b327583 (Matthieu Moy moy, April 2014, for git 2.0.x/2.1, Q3 2014) will remove the S by default:

pager: remove 'S' from $LESS by default

By default, Git used to set $LESS to -FRSX if $LESS was not set by the user.
The FRX flags actually make sense for Git (F and X because sometimes the output Git pipes to less is short, and R because Git pipes colored output).
The S flag (chop long lines), on the other hand, is not related to Git and is a matter of user preference. Git should not decide for the user to change LESS's default.

More specifically, the S flag harms users who review untrusted code within a pager, since a patch looking like:

-old code;
+new good code; [... lots of tabs ...] malicious code;

would appear identical to:

-old code;
+new good code;

Users who prefer the old behavior can still set the $LESS environment variable to -FRSX explicitly, or set core.pager to 'less -S'.

The documentation will read:

The environment does not set the S option but the command line does, instructing less to truncate long lines.
Similarly, setting core.pager to less -+F will deactivate the F option specified by the environment from the command-line, deactivating the "quit if one screen" behavior of less.
One can specifically activate some flags for particular commands: for example, setting pager.blame to less -S enables line truncation only for git blame.

How to make a div with no content have a width?

There are different methods to make the empty DIV with float: left or float: right visible.

Here presents the ones I know:

  • set width(or min-width) with height (or min-height)
  • or set padding-top
  • or set padding-bottom
  • or set border-top
  • or set border-bottom
  • or use pseudo-elements: ::before or ::after with:
    • {content: "\200B";}
    • or {content: "."; visibility: hidden;}
  • or put &nbsp; inside DIV (this sometimes can bring unexpected effects eg. in combination with text-decoration: underline;)

The type initializer for 'MyClass' threw an exception

Check the InnerException property of the TypeInitializationException; it is likely to contain information about the underlying problem, and exactly where it occurred.

How to prevent a dialog from closing when a button is clicked

I found an other way to achieve this...

Step 1: Put the dialog opening code in a method (Or Function in C).
Step 2: Inside the onClick of yes (Your positiveButton), call this dialog opening method recursively if your condition is not satisfied (By using if...else...). Like below :

private void openSave() {
   
    final AlertDialog.Builder builder=new AlertDialog.Builder(Phase2Activity.this);

    builder.setTitle("SAVE")
            .setIcon(R.drawable.ic_save_icon)
            .setPositiveButton("Save", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    
                        if((!editText.getText().toString().isEmpty() && !editText1.getText().toString().isEmpty())){

                                createPdf(fileName,title,file);
                            
                        }else {
                            openSave();
                            Toast.makeText(Phase2Activity.this, "Some fields are empty.", Toast.LENGTH_SHORT).show();
                        }

                    
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
               dialogInterface.dismiss();
            }
        })
            .setCancelable(false)
            .create()
            .show();

}

But this will make the dialog disappear just for a moment and it will appear again instantly. :)

How to upload a file in Django?

Not sure if there any disadvantages to this approach but even more minimal, in views.py:

entry = form.save()

# save uploaded file
if request.FILES['myfile']:
    entry.myfile.save(request.FILES['myfile']._name, request.FILES['myfile'], True)

Delete topic in Kafka 0.8.1.1

bin/kafka-topics.sh –delete –zookeeper localhost:2181 –topic <topic-name>

Test a weekly cron job

A wee bit beyond the scope of your question... but here's what I do.

The "how do I test a cron job?" question is closely connected to "how do I test scripts that run in non-interactive contexts launched by other programs?" In cron, the trigger is some time condition, but lots of other *nix facilities launch scripts or script fragments in non-interactive ways, and often the conditions in which those scripts run contain something unexpected and cause breakage until the bugs are sorted out. (See also: https://stackoverflow.com/a/17805088/237059 )

A general approach to this problem is helpful to have.

One of my favorite techniques is to use a script I wrote called 'crontest'. It launches the target command inside a GNU screen session from within cron, so that you can attach with a separate terminal to see what's going on, interact with the script, even use a debugger.

To set this up, you would use "all stars" in your crontab entry, and specify crontest as the first command on the command line, e.g.:

* * * * * crontest /command/to/be/tested --param1 --param2

So now cron will run your command every minute, but crontest will ensure that only one instance runs at a time. If the command takes time to run, you can do a "screen -x" to attach and watch it run. If the command is a script, you can put a "read" command at the top to make it stop and wait for the screen attachment to complete (hit enter after attaching)

If your command is a bash script, you can do this instead:

* * * * * crontest --bashdb /command/to/be/tested --param1 --param2

Now, if you attach with "screen -x", you'll be facing an interactive bashdb session, and you can step through the code, examine variables, etc.

#!/bin/bash

# crontest
# See https://github.com/Stabledog/crontest for canonical source.

# Test wrapper for cron tasks.  The suggested use is:
#
#  1. When adding your cron job, use all 5 stars to make it run every minute
#  2. Wrap the command in crontest
#        
#
#  Example:
#
#  $ crontab -e
#     * * * * * /usr/local/bin/crontest $HOME/bin/my-new-script --myparams
#
#  Now, cron will run your job every minute, but crontest will only allow one
#  instance to run at a time.  
#
#  crontest always wraps the command in "screen -d -m" if possible, so you can
#  use "screen -x" to attach and interact with the job.   
#
#  If --bashdb is used, the command line will be passed to bashdb.  Thus you
#  can attach with "screen -x" and debug the remaining command in context.
#
#  NOTES:
#   - crontest can be used in other contexts, it doesn't have to be a cron job.
#       Any place where commands are invoked without an interactive terminal and
#       may need to be debugged.
#
#   - crontest writes its own stuff to /tmp/crontest.log
#
#   - If GNU screen isn't available, neither is --bashdb
#

crontestLog=/tmp/crontest.log
lockfile=$(if [[ -d /var/lock ]]; then echo /var/lock/crontest.lock; else echo /tmp/crontest.lock; fi )
useBashdb=false
useScreen=$( if which screen &>/dev/null; then echo true; else echo false; fi )
innerArgs="$@"
screenBin=$(which screen 2>/dev/null)

function errExit {
    echo "[-err-] $@" | tee -a $crontestLog >&2
}

function log {
    echo "[-stat-] $@" >> $crontestLog
}

function parseArgs {
    while [[ ! -z $1 ]]; do
        case $1 in
            --bashdb)
                if ! $useScreen; then
                    errExit "--bashdb invalid in crontest because GNU screen not installed"
                fi
                if ! which bashdb &>/dev/null; then
                    errExit "--bashdb invalid in crontest: no bashdb on the PATH"
                fi

                useBashdb=true
                ;;
            --)
                shift
                innerArgs="$@"
                return 0
                ;;
            *)
                innerArgs="$@"
                return 0
                ;;
        esac
        shift
    done
}

if [[ -z  $sourceMe ]]; then
    # Lock the lockfile (no, we do not wish to follow the standard
    # advice of wrapping this in a subshell!)
    exec 9>$lockfile
    flock -n 9 || exit 1

    # Zap any old log data:
    [[ -f $crontestLog ]] && rm -f $crontestLog

    parseArgs "$@"

    log "crontest starting at $(date)"
    log "Raw command line: $@"
    log "Inner args: $@"
    log "screenBin: $screenBin"
    log "useBashdb: $( if $useBashdb; then echo YES; else echo no; fi )"
    log "useScreen: $( if $useScreen; then echo YES; else echo no; fi )"

    # Were building a command line.
    cmdline=""

    # If screen is available, put the task inside a pseudo-terminal
    # owned by screen.  That allows the developer to do a "screen -x" to
    # interact with the running command:
    if $useScreen; then
        cmdline="$screenBin -D -m "
    fi

    # If bashdb is installed and --bashdb is specified on the command line,
    # pass the command to bashdb.  This allows the developer to do a "screen -x" to
    # interactively debug a bash shell script:
    if $useBashdb; then
        cmdline="$cmdline $(which bashdb) "
    fi

    # Finally, append the target command and params:
    cmdline="$cmdline $innerArgs"

    log "cmdline: $cmdline"


    # And run the whole schlock:
    $cmdline 

    res=$?

    log "Command result: $res"


    echo "[-result-] $(if [[ $res -eq 0 ]]; then echo ok; else echo fail; fi)" >> $crontestLog

    # Release the lock:
    9<&-
fi

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

I had similar problem with regex = "?". It happens for all special characters that have some meaning in a regex. So you need to have "\\" as a prefix to your regex.

String [] separado = line.split("\\*");

Google Maps how to Show city or an Area outline

use this code:

<iframe width="600" height="450" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?q=place_id:ChIJ5Rw5v9dCXz4R3SUtcL5ZLMk&key=..." allowfullscreen></iframe>

How to check if a string in Python is in ASCII?

I found this question while trying determine how to use/encode/decode a string whose encoding I wasn't sure of (and how to escape/convert special characters in that string).

My first step should have been to check the type of the string- I didn't realize there I could get good data about its formatting from type(s). This answer was very helpful and got to the real root of my issues.

If you're getting a rude and persistent

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 263: ordinal not in range(128)

particularly when you're ENCODING, make sure you're not trying to unicode() a string that already IS unicode- for some terrible reason, you get ascii codec errors. (See also the Python Kitchen recipe, and the Python docs tutorials for better understanding of how terrible this can be.)

Eventually I determined that what I wanted to do was this:

escaped_string = unicode(original_string.encode('ascii','xmlcharrefreplace'))

Also helpful in debugging was setting the default coding in my file to utf-8 (put this at the beginning of your python file):

# -*- coding: utf-8 -*-

That allows you to test special characters ('àéç') without having to use their unicode escapes (u'\xe0\xe9\xe7').

>>> specials='àéç'
>>> specials.decode('latin-1').encode('ascii','xmlcharrefreplace')
'&#224;&#233;&#231;'

How to use Oracle ORDER BY and ROWNUM correctly?

Use ROW_NUMBER() instead. ROWNUM is a pseudocolumn and ROW_NUMBER() is a function. You can read about difference between them and see the difference in output of below queries:

SELECT * FROM (SELECT rownum, deptno, ename
           FROM scott.emp
        ORDER BY deptno
       )
 WHERE rownum <= 3
 /

ROWNUM    DEPTNO    ENAME
---------------------------
 7        10    CLARK
 14       10    MILLER
 9        10    KING


 SELECT * FROM 
 (
  SELECT deptno, ename
       , ROW_NUMBER() OVER (ORDER BY deptno) rno
  FROM scott.emp
 ORDER BY deptno
 )
WHERE rno <= 3
/

DEPTNO    ENAME    RNO
-------------------------
10    CLARK        1
10    MILLER       2
10    KING         3

How to convert buffered image to image and vice-versa?

Example: say you have an 'image' you want to scale you will need a bufferedImage probably, and probably will be starting out with just 'Image' object. So this works I think... The AVATAR_SIZE is the target width we want our image to be:

Image imgData = image.getScaledInstance(Constants.AVATAR_SIZE, -1, Image.SCALE_SMOOTH);     

BufferedImage bufferedImage = new BufferedImage(imgData.getWidth(null), imgData.getHeight(null), BufferedImage.TYPE_INT_RGB);

bufferedImage.getGraphics().drawImage(imgData, 0, 0, null);

Get element inside element by class and ID - JavaScript

You should not used document.getElementByID because its work only for client side controls which ids are fixed . You should use jquery instead like below example.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>                                                                                                             
<div id="foo">
   <div class="bar"> 
          Hello world!
     </div>
</div>

use this :

$("[id^='foo']").find("[class^='bar']")

// do not forget to add script tags as above

if you want any remove edit any operation then just add "." behind and do the operations

Angular2 QuickStart npm start is not working correctly

Change the start field in package.json from

"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" "

to

"start": "concurrently \"npm run tsc:w\" \"npm run lite\" "

Convert string to date then format the date

Tested this code

java.text.DateFormat formatter = new java.text.SimpleDateFormat("MM-dd-yyyy");
java.util.Date newDate = new java.util.Date();
System.out.println(formatter.format(newDate ));

http://download.oracle.com/javase/1,5.0/docs/api/java/text/SimpleDateFormat.html

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

New service updated to use the HttpClientModule and RxJS v5.5.x:

import { Injectable }                    from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable }                    from 'rxjs/Observable';
import { catchError, tap }               from 'rxjs/operators';
import { SomeClassOrInterface}           from './interfaces';
import 'rxjs/add/observable/throw';

@Injectable() 
export class MyService {
    url = 'http://my_url';
    constructor(private _http:HttpClient) {}
    private handleError(operation: String) {
        return (err: any) => {
            let errMsg = `error in ${operation}() retrieving ${this.url}`;
            console.log(`${errMsg}:`, err)
            if(err instanceof HttpErrorResponse) {
                // you could extract more info about the error if you want, e.g.:
                console.log(`status: ${err.status}, ${err.statusText}`);
                // errMsg = ...
            }
            return Observable.throw(errMsg);
        }
    }
    // public API
    public getData() : Observable<SomeClassOrInterface> {
        // HttpClient.get() returns the body of the response as an untyped JSON object.
        // We specify the type as SomeClassOrInterfaceto get a typed result.
        return this._http.get<SomeClassOrInterface>(this.url)
            .pipe(
                tap(data => console.log('server data:', data)), 
                catchError(this.handleError('getData'))
            );
    }

Old service, which uses the deprecated HttpModule:

import {Injectable}              from 'angular2/core';
import {Http, Response, Request} from 'angular2/http';
import {Observable}              from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
//import 'rxjs/Rx';  // use this line if you want to be lazy, otherwise:
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';  // debug
import 'rxjs/add/operator/catch';

@Injectable()
export class MyService {
    constructor(private _http:Http) {}
    private _serverError(err: any) {
        console.log('sever error:', err);  // debug
        if(err instanceof Response) {
          return Observable.throw(err.json().error || 'backend server error');
          // if you're using lite-server, use the following line
          // instead of the line above:
          //return Observable.throw(err.text() || 'backend server error');
        }
        return Observable.throw(err || 'backend server error');
    }
    private _request = new Request({
        method: "GET",
        // change url to "./data/data.junk" to generate an error
        url: "./data/data.json"
    });
    // public API
    public getData() {
        return this._http.request(this._request)
          // modify file data.json to contain invalid JSON to have .json() raise an error
          .map(res => res.json())  // could raise an error if invalid JSON
          .do(data => console.log('server data:', data))  // debug
          .catch(this._serverError);
    }
}

I use .do() (now .tap()) for debugging.

When there is a server error, the body of the Response object I get from the server I'm using (lite-server) contains just text, hence the reason I use err.text() above rather than err.json().error. You may need to adjust that line for your server.

If res.json() raises an error because it could not parse the JSON data, _serverError will not get a Response object, hence the reason for the instanceof check.

In this plunker, change url to ./data/data.junk to generate an error.


Users of either service should have code that can handle the error:

@Component({
    selector: 'my-app',
    template: '<div>{{data}}</div> 
       <div>{{errorMsg}}</div>`
})
export class AppComponent {
    errorMsg: string;
    constructor(private _myService: MyService ) {}
    ngOnInit() {
        this._myService.getData()
            .subscribe(
                data => this.data = data,
                err  => this.errorMsg = <any>err
            );
    }
}

How do you UrlEncode without using System.Web?

System.Uri.EscapeUriString() can be problematic with certain characters, for me it was a number / pound '#' sign in the string.

If that is an issue for you, try:

System.Uri.EscapeDataString() //Works excellent with individual values

Here is a SO question answer that explains the difference:

What's the difference between EscapeUriString and EscapeDataString?

and recommends to use Uri.EscapeDataString() in any aspect.

How can I get name of element with jQuery?

If anyone is also looking for how to get the name of the HTML tag, you can use "tagName": $(this)[0].tagName

JavaScript pattern for multiple constructors

Sometimes, default values for parameters is enough for multiple constructors. And when that doesn't suffice, I try to wrap most of the constructor functionality into an init(other-params) function that is called afterwards. Also consider using the factory concept to make an object that can effectively create the other objects you want.

http://en.wikipedia.org/w/index.php?title=Factory_method_pattern&oldid=363482142#Javascript

Checking if a field contains a string

As of version 2.4, you can create a text index on the field(s) to search and use the $text operator for querying.

First, create the index:

db.users.createIndex( { "username": "text" } )

Then, to search:

db.users.find( { $text: { $search: "son" } } )

Benchmarks (~150K documents):

  • Regex (other answers) => 5.6-6.9 seconds
  • Text Search => .164-.201 seconds

Notes:

  • A collection can have only one text index. You can use a wildcard text index if you want to search any string field, like this: db.collection.createIndex( { "$**": "text" } ).
  • A text index can be large. It contains one index entry for each unique post-stemmed word in each indexed field for each document inserted.
  • A text index will take longer to build than a normal index.
  • A text index does not store phrases or information about the proximity of words in the documents. As a result, phrase queries will run much more effectively when the entire collection fits in RAM.

How do I convert a decimal to an int in C#?

A neat trick for fast rounding is to add .5 before you cast your decimal to an int.

decimal d = 10.1m;
d += .5m;
int i = (int)d;

Still leaves i=10, but

decimal d = 10.5m;
d += .5m;
int i = (int)d;

Would round up so that i=11.

Difference between Groovy Binary and Source release?

Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.

How do I get formatted JSON in .NET using C#?

This worked for me. In case someone is looking for a VB.NET version.

@imports System
@imports System.IO
@imports Newtonsoft.Json

Public Shared Function JsonPrettify(ByVal json As String) As String
  Using stringReader = New StringReader(json)

    Using stringWriter = New StringWriter()
      Dim jsonReader = New JsonTextReader(stringReader)
      Dim jsonWriter = New JsonTextWriter(stringWriter) With {
          .Formatting = Formatting.Indented
      }
      jsonWriter.WriteToken(jsonReader)
      Return stringWriter.ToString()
    End Using
  End Using
End Function

How to set the DefaultRoute to another Route in React Router

UPDATE : 2020

Instead of using Redirect, Simply add multiple route in the path

Example:

<Route exact path={["/","/defaultPath"]} component={searchDashboard} />

What is the difference between resource and endpoint?

REST

Resource is a RESTful subset of Endpoint.

An endpoint by itself is the location where a service can be accessed:

https://www.google.com    # Serves HTML
8.8.8.8                   # Serves DNS
/services/service.asmx    # Serves an ASP.NET Web Service

A resource refers to one or more nouns being served, represented in namespaced fashion, because it is easy for humans to comprehend:

/api/users/johnny         # Look up johnny from a users collection.
/v2/books/1234            # Get book with ID 1234 in API v2 schema.

All of the above could be considered service endpoints, but only the bottom group would be considered resources, RESTfully speaking. The top group is not expressive regarding the content it provides.

A REST request is like a sentence composed of nouns (resources) and verbs (HTTP methods):

  • GET (method) the user named johnny (resource).
  • DELETE (method) the book with id 1234 (resource).

Non-REST

Endpoint typically refers to a service, but resource could mean a lot of things. Here are some examples of resource that are dependent on the context they're used in.

URL: Uniform "Resource" Locator

  • Could be RESTful, but often is not. In this case, endpoint is almost synonymous.

Resource Management

Dictionary

Something that can be used to help you:

The library was a valuable resource, and he frequently made use of it.

Resources are natural substances such as water and wood which are valuable in supporting life:

[ pl ] The earth has limited resources, and if we don’t recycle them we use them up.

Resources are also things of value such as money or possessions that you can use when you need them:

[ pl ] The government doesn’t have the resources to hire the number of teachers needed.


The Moral

The term resource by definition has a lot of nuance. It all depends on the context its used in.

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

what is trailing whitespace and how can I handle this?

Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.

In your posted question, there is one extra space after try:, and there are 12 extra spaces after pass:

>>> post_text = '''\
...             if self.tagname and self.tagname2 in list1:
...                 try: 
...                     question = soup.find("div", "post-text")
...                     title = soup.find("a", "question-hyperlink")
...                     self.list2.append(str(title)+str(question)+url)
...                     current += 1
...                 except AttributeError:
...                     pass            
...             logging.info("%s questions passed, %s questions \
...                 collected" % (count, current))
...             count += 1
...         return self.list2
... '''
>>> for line in post_text.splitlines():
...     if line.rstrip() != line:
...         print(repr(line))
... 
'                try: '
'                    pass            '

See where the strings end? There are spaces before the lines (indentation), but also spaces after.

Use your editor to find the end of the line and backspace. Many modern text editors can also automatically remove trailing whitespace from the end of the line, for example every time you save a file.

How does a Java HashMap handle different objects with the same hash code?

It gonna be a long answer , grab a drink and read on …

Hashing is all about storing a key-value pair in memory that can be read and written faster. It stores keys in an array and values in a LinkedList .

Lets Say I want to store 4 key value pairs -

{
“girl” => “ahhan” , 
“misused” => “Manmohan Singh” , 
“horsemints” => “guess what”, 
“no” => “way”
}

So to store the keys we need an array of 4 element . Now how do I map one of these 4 keys to 4 array indexes (0,1,2,3)?

So java finds the hashCode of individual keys and map them to a particular array index . Hashcode Formulae is -

1) reverse the string.

2) keep on multiplying ascii of each character with increasing power of 31 . then add the components .

3) So hashCode() of girl would be –(ascii values of  l,r,i,g are 108, 114, 105 and 103) . 

e.g. girl =  108 * 31^0  + 114 * 31^1  + 105 * 31^2 + 103 * 31^3  = 3173020

Hash and girl !! I know what you are thinking. Your fascination about that wild duet might made you miss an important thing .

Why java multiply it with 31 ?

It’s because, 31 is an odd prime in the form 2^5 – 1 . And odd prime reduces the chance of Hash Collision

Now how this hash code is mapped to an array index?

answer is , Hash Code % (Array length -1) . So “girl” is mapped to (3173020 % 3) = 1 in our case . which is second element of the array .

and the value “ahhan” is stored in a LinkedList associated with array index 1 .

HashCollision - If you try to find hasHCode of the keys “misused” and “horsemints” using the formulae described above you’ll see both giving us same 1069518484. Whooaa !! lesson learnt -

2 equal objects must have same hashCode but there is no guarantee if the hashCode matches then the objects are equal . So it should store both values corresponding to “misused” and “horsemints” to bucket 1 (1069518484 % 3) .

Now the hash map looks like –

Array Index 0 –
Array Index 1 - LinkedIst (“ahhan” , “Manmohan Singh” , “guess what”)
Array Index 2 – LinkedList (“way”)
Array Index 3 – 

Now if some body tries to find the value for the key “horsemints” , java quickly will find the hashCode of it , module it and start searching for it’s value in the LinkedList corresponding index 1 . So this way we need not search all the 4 array indexes thus making data access faster.

But , wait , one sec . there are 3 values in that linkedList corresponding Array index 1, how it finds out which one was was the value for key “horsemints” ?

Actually I lied , when I said HashMap just stores values in LinkedList .

It stores both key value pair as map entry. So actually Map looks like this .

Array Index 0 –
Array Index 1 - LinkedIst (<”girl” => “ahhan”> , <” misused” => “Manmohan Singh”> , <”horsemints” => “guess what”>)
Array Index 2 – LinkedList (<”no” => “way”>)
Array Index 3 – 

Now you can see While traversing through the linkedList corresponding to ArrayIndex1 it actually compares key of each entry to of that LinkedList to “horsemints” and when it finds one it just returns the value of it .

Hope you had fun while reading it :)

jQuery click events not working in iOS

Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.

Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):

onClick=""

OR

The element css needs to have the following declaration:

cursor:pointer

Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working

How can I scroll a web page using selenium webdriver in python?

You can use send_keys to simulate a PAGE_DOWN key press (which normally scroll the page):

from selenium.webdriver.common.keys import Keys
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.PAGE_DOWN)

Creating dummy variables in pandas for python

Handling categorical features scikit-learn expects all features to be numeric. So how do we include a categorical feature in our model?

Ordered categories: transform them to sensible numeric values (example: small=1, medium=2, large=3) Unordered categories: use dummy encoding (0/1) What are the categorical features in our dataset?

Ordered categories: weather (already encoded with sensible numeric values) Unordered categories: season (needs dummy encoding), holiday (already dummy encoded), workingday (already dummy encoded) For season, we can't simply leave the encoding as 1 = spring, 2 = summer, 3 = fall, and 4 = winter, because that would imply an ordered relationship. Instead, we create multiple dummy variables:

# An utility function to create dummy variable
`def create_dummies( df, colname ):
col_dummies = pd.get_dummies(df[colname], prefix=colname)
col_dummies.drop(col_dummies.columns[0], axis=1, inplace=True)
df = pd.concat([df, col_dummies], axis=1)
df.drop( colname, axis = 1, inplace = True )
return df`

"Thinking in AngularJS" if I have a jQuery background?

AngularJS and jQuery:

AngularJs and JQuery are completely different at every level except the JQLite functionality and you will see it once you start learning the AngularJs core features (I explained it below).

AngularJs is a client side framework that offers to build the independent client side application. JQuery is a client side library that play around the DOM.

AngularJs Cool Principle - If you want some changes on your UI think from model data change perspective. Change your data and UI will re-render itself. You need not to play around DOM each time unless and until it is hardly required and that should also be handled through Angular Directives.

To answer this question, I want to share my experience on the first enterprise application with AngularJS. These are the most awesome features that Angular provide where we start changing our jQuery mindset and we get the Angular like a framework and not the library.

Two-way data binding is amazing: I had a grid with all functionality UPDATE, DELTE, INSERT. I have a data object that binds the grid's model using ng-repeat. You only need to write a single line of simple JavaScript code for delete and insert and that's it. grid automatically updates as the grid model changes instantly. Update functionality is real time, no code for it. You feel amazing!!!

Reusable directives are super: Write directives in one place and use it throughout the application. OMG!!! I used these directive for paging, regex, validations, etc. It is really cool!

Routing is strong: It's up to your implementation how you want to use it, but it requires very few lines of code to route the request to specify HTML and controller (JavaScript)

Controllers are great: Controllers take care of their own HTML, but this separation works well for common functionality well as. If you want to call the same function on the click of a button on master HTML, just write the same function name in each controller and write individual code.

Plugins: There are many other similar features like showing an overlay in your app. You don't need to write code for it, just use an overlay plugin available as wc-overlay, and this will automatically take care of all XMLHttpRequest (XHR) requests.

Ideal for RESTful architecture: Being a complete frameworks makes AngularJS great to work with a RESTful architecture. To call REST CRUD APIs is very easier and

Services: Write common codes using services and less code in controllers. Sevices can be used to share common functionalities among the controllers.

Extensibility: Angular has extended the HTML directives using angular directives. Write expressions inside html and evaluate them on runtime. Create your own directives and services and use them in another project without any extra effort.

How do I update an entity using spring-data-jpa?

Specifically how do I tell spring-data-jpa that users that have the same username and firstname are actually EQUAL and that it is supposed to update the entity. Overriding equals did not work.

For this particular purpose one can introduce a composite key like this:

CREATE TABLE IF NOT EXISTS `test`.`user` (
  `username` VARCHAR(45) NOT NULL,
  `firstname` VARCHAR(45) NOT NULL,
  `description` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`username`, `firstname`))

Mapping:

@Embeddable
public class UserKey implements Serializable {
    protected String username;
    protected String firstname;

    public UserKey() {}

    public UserKey(String username, String firstname) {
        this.username = username;
        this.firstname = firstname;
    }
    // equals, hashCode
}

Here is how to use it:

@Entity
public class UserEntity implements Serializable {
    @EmbeddedId
    private UserKey primaryKey;

    private String description;

    //...
}

JpaRepository would look like this:

public interface UserEntityRepository extends JpaRepository<UserEntity, UserKey>

Then, you could use the following idiom: accept DTO with user info, extract name and firstname and create UserKey, then create a UserEntity with this composite key and then invoke Spring Data save() which should sort everything out for you.

Fastest way to check if a string is JSON in PHP?

This will return true if your string represents a json array or object:

function isJson($str) {
    $json = json_decode($str);
    return $json && $str != $json;
}

It rejects json strings that only contains a number, string or boolean, although those strings are technically valid json.

var_dump(isJson('{"a":5}')); // bool(true)
var_dump(isJson('[1,2,3]')); // bool(true)
var_dump(isJson('1')); // bool(false)
var_dump(isJson('1.5')); // bool(false)
var_dump(isJson('true')); // bool(false)
var_dump(isJson('false')); // bool(false)
var_dump(isJson('null')); // bool(false)
var_dump(isJson('hello')); // bool(false)
var_dump(isJson('')); // bool(false)

It is the shortest way I can come up with.

Open source face recognition for Android

macgyver offers face detection programs via a simple to use API.

The program below takes a reference to a public image and will return an array of the coordinates and dimensions of any faces detected in the image.

https://askmacgyver.com/explore/program/face-location/5w8J9u4z

Number prime test in JavaScript

As simple as possible:

function isPrime(num) {
  for(var i = 2; i < num; i++)
    if(num % i === 0) return false;
  return num > 1;
}

With the ES6 syntax:

const isPrime = num => {
  for(let i = 2; i < num; i++)
    if(num % i === 0) return false;
  return num > 1;
}

You can also decrease the complexity of the algorithm from O(n) to O(sqrt(n)) if you run the loop until square root of a number:

const isPrime = num => {
    for(let i = 2, s = Math.sqrt(num); i <= s; i++)
        if(num % i === 0) return false; 
    return num > 1;
}

Using Postman to access OAuth 2.0 Google APIs

The current answer is outdated. Here's the up-to-date flow:

The approach outlined here still works (10.12.2020) as confirmed by alexwhan.

We will use the YouTube Data API for our example. Make changes accordingly.

Make sure you have enabled your desired API for your project.

Create the OAuth 2.0 Client

  1. Visit https://console.cloud.google.com/apis/credentials
  2. Click on CREATE CREDENTIALS
  3. Select OAuth client ID
  4. For Application Type choose Web Application
  5. Add a name
  6. Add following URI for Authorized redirect URIs
https://oauth.pstmn.io/v1/callback
  1. Click Save
  2. Click on the OAuth client you just generated
  3. In the Topbar click on DOWNLOAD JSON and save the file somewhere on your machine.

We will use the file later to authenticate Postman.

Authorize Postman via OAuth 2.0 Client

  1. In the Auth tab under TYPE choose OAuth 2.0
  2. For Access Token enter the Access Token found inside the client_secret_[YourClientID].json file we downloaded in step 9
  3. Click on Get New Access Token
  4. Make sure your settings are as follows:

Click here to see the settings

You can find everything else you need in your .json file.

  1. Click on Request Token
  2. A new browser tab/window will open
  3. Once the browser tab opens, login via the appropriate Google account
  4. Accept the consent screen
  5. Done

Ignore the browser message "Not safe" etc. This will be shown until your app has been screened by Google officials. In this case it will always be shown since Postman is the app.

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

For someone looking to solve same by using maven. Add below dependency in POM:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>7.0.0.jre8</version>
</dependency>

And use below code for connection:

String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";

try {
    System.out.print("Connecting to SQL Server ... ");
    try (Connection connection = DriverManager.getConnection(connectionUrl))        {
        System.out.println("Done.");
    }
} catch (Exception e) {
    System.out.println();
    e.printStackTrace();
}

Look for this link for other CRUD type of queries.

How to read html from a url in python 3

For python 2

import urllib
some_url = 'https://docs.python.org/2/library/urllib.html'
filehandle = urllib.urlopen(some_url)
print filehandle.read()

gcc makefile error: "No rule to make target ..."

In my experience, this error is frequently caused by a spelling error.

I got this error today.

make[1]: *** No rule to make target maintenaceDialog.cpp', needed bymaintenaceDialog.o'. Stop.

In my case the error was simply a spelling error. The word MAINTENANCE was missing it's third N.

Also check the spelling on your filenames.

How do I find out what all symbols are exported from a shared object?

Usually, you would also have a header file that you include in your code to access the symbols.

Get Application Name/ Label via ADB Shell or Terminal

Inorder to find an app's name (application label), you need to do the following:
(as shown in other answers)

  1. Find the APK path of the app whose name you want to find.
  2. Using aapt command, find the app label.

But devices don't ship with the aapt binary out-of-the-box.
So you will need to install it first. You can download it from here:
https://github.com/Calsign/APDE/tree/master/APDE/src/main/assets/aapt-binaries


Check this guide for complete steps:
How to find an app name using package name through ADB Android?
(Disclaimer: I am the author of that blog post)

Regex expressions in Java, \\s vs. \\s+

The first regex will match one whitespace character. The second regex will reluctantly match one or more whitespace characters. For most purposes, these two regexes are very similar, except in the second case, the regex can match more of the string, if it prevents the regex match from failing.  from http://www.coderanch.com/t/570917/java/java/regex-difference

How to handle invalid SSL certificates with Apache HttpClient?

I'm useing httpclient 3.1.X ,and this works for me

        try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        sslContext.init(null, new TrustManager[]{trustManager}, null);
        SslContextSecureProtocolSocketFactory socketFactory = new SslContextSecureProtocolSocketFactory(sslContext,false);
        Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) socketFactory, 443));//??????HttpUtils
    } catch (Throwable e) {
        e.printStackTrace();

}

public class SslContextSecureProtocolSocketFactory implements      SecureProtocolSocketFactory {

private SSLContext sslContext;
private boolean verifyHostname;

public SslContextSecureProtocolSocketFactory(SSLContext sslContext, boolean verifyHostname) {
    this.verifyHostname = true;
    this.sslContext = sslContext;
    this.verifyHostname = verifyHostname;
}

public SslContextSecureProtocolSocketFactory(SSLContext sslContext) {
    this(sslContext, true);
}

public SslContextSecureProtocolSocketFactory(boolean verifyHostname) {
    this((SSLContext)null, verifyHostname);
}

public SslContextSecureProtocolSocketFactory() {
    this((SSLContext)null, true);
}

public synchronized void setHostnameVerification(boolean verifyHostname) {
    this.verifyHostname = verifyHostname;
}

public synchronized boolean getHostnameVerification() {
    return this.verifyHostname;
}

public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException {
    SSLSocketFactory sf = this.getSslSocketFactory();
    SSLSocket sslSocket = (SSLSocket)sf.createSocket(host, port, clientHost, clientPort);
    this.verifyHostname(sslSocket);
    return sslSocket;
}

public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    if(params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    } else {
        int timeout = params.getConnectionTimeout();
        Socket socket = null;
        SSLSocketFactory socketfactory = this.getSslSocketFactory();
        if(timeout == 0) {
            socket = socketfactory.createSocket(host, port, localAddress, localPort);
        } else {
            socket = socketfactory.createSocket();
            InetSocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
            InetSocketAddress remoteaddr = new InetSocketAddress(host, port);
            socket.bind(localaddr);
            socket.connect(remoteaddr, timeout);
        }

        this.verifyHostname((SSLSocket)socket);
        return socket;
    }
}

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    SSLSocketFactory sf = this.getSslSocketFactory();
    SSLSocket sslSocket = (SSLSocket)sf.createSocket(host, port);
    this.verifyHostname(sslSocket);
    return sslSocket;
}

public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
    SSLSocketFactory sf = this.getSslSocketFactory();
    SSLSocket sslSocket = (SSLSocket)sf.createSocket(socket, host, port, autoClose);
    this.verifyHostname(sslSocket);
    return sslSocket;
}

private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    synchronized(this) {
        if(!this.verifyHostname) {
            return;
        }
    }

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();

    try {
        InetAddress.getByName(hostname);
    } catch (UnknownHostException var10) {
        throw new UnknownHostException("Could not resolve SSL sessions server hostname: " + hostname);
    }

    X509Certificate[] certs = (X509Certificate[])((X509Certificate[])session.getPeerCertificates());
    if(certs != null && certs.length != 0) {
        X500Principal subjectDN = certs[0].getSubjectX500Principal();
        List cns = this.getCNs(subjectDN);
        boolean foundHostName = false;
        Iterator i$ = cns.iterator();
        AntPathMatcher matcher  = new AntPathMatcher();
        while(i$.hasNext()) {
            String cn = (String)i$.next();
            if(matcher.match(cn.toLowerCase(),hostname.toLowerCase())) {
                foundHostName = true;
                break;
            }
        }

        if(!foundHostName) {
            throw new SSLPeerUnverifiedException("HTTPS hostname invalid: expected \'" + hostname + "\', received \'" + cns + "\'");
        }
    } else {
        throw new SSLPeerUnverifiedException("No server certificates found!");
    }
}

private List<String> getCNs(X500Principal subjectDN) {
    ArrayList cns = new ArrayList();
    StringTokenizer st = new StringTokenizer(subjectDN.getName(), ",");

    while(st.hasMoreTokens()) {
        String cnField = st.nextToken();
        if(cnField.startsWith("CN=")) {
            cns.add(cnField.substring(3));
        }
    }

    return cns;
}

protected SSLSocketFactory getSslSocketFactory() {
    SSLSocketFactory sslSocketFactory = null;
    synchronized(this) {
        if(this.sslContext != null) {
            sslSocketFactory = this.sslContext.getSocketFactory();
        }
    }

    if(sslSocketFactory == null) {
        sslSocketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
    }

    return sslSocketFactory;
}

public synchronized void setSSLContext(SSLContext sslContext) {
    this.sslContext = sslContext;
}

}

RecyclerView - How to smooth scroll to top of item on a certain position?

We can try like this

    recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView,new RecyclerView.State(), recyclerView.getAdapter().getItemCount());

How can I plot separate Pandas DataFrames as subplots?

You can use the familiar Matplotlib style calling a figure and subplot, but you simply need to specify the current axis using plt.gca(). An example:

plt.figure(1)
plt.subplot(2,2,1)
df.A.plot() #no need to specify for first axis
plt.subplot(2,2,2)
df.B.plot(ax=plt.gca())
plt.subplot(2,2,3)
df.C.plot(ax=plt.gca())

etc...

How to get row count in an Excel file using POI library?

Sheet.getPhysicalNumberOfRows() does not involve some empty rows. If you want to loop for all rows, do not use this to know the loop size.

Babel command not found

This worked for me inside package.json as an npm script but it does seem to take to long grabbing the packages even though I have them as dev dependancies. It also seems too long.

"babel": "npx -p @babel/cli -p @babel/core babel --version"

What end up solving it was much simpler but funny too

npm install

I thought I ran that already but I guess somethings needed to be rebuilt. Then just:

"babel": "babel --version"

Can multiple different HTML elements have the same ID if they're different elements?

And for what it's worth, on Chrome 26.0.1410.65, Firefox 19.0.2, and Safari 6.0.3 at least, if you have multiple elements with the same ID, jquery selectors (at least) will return the first element with that ID.

e.g.

<div id="one">first text for one</div>
<div id="one">second text for one</div>

and

alert($('#one').size());

See http://jsfiddle.net/RuysX/ for a test.

What is the Linux equivalent to DOS pause?

read -n1 is not portable. A portable way to do the same might be:

(   trap "stty $(stty -g;stty -icanon)" EXIT
    LC_ALL=C dd bs=1 count=1 >/dev/null 2>&1
)   </dev/tty

Besides using read, for just a press ENTER to continue prompt you could do:

sed -n q </dev/tty

Excel: the Incredible Shrinking and Expanding Controls

The fixes discussed earlier, programatically resizing/repositioning the Active X Controls after click events, or modifying the registry (with the D word LegacyAnchorResize), didn't solve the issue for me with Excel 2010/ Windows 7 64 bit.

The solution for me was found here:https://support.microsoft.com/en-us/kb/838006

For Excel 2010 the link instructs to:

  1. Exit all the programs that are running.
  2. Click Start, click Run, in the Open box, type regedit, and then click OK.
  3. Locate, and then click the following registry key:
  4. HKEY_CURRENT_USER\Software\microsoft\office\14.0\common
  5. On the Edit menu, point to New, and then click Key.
  6. Type Draw, and then press Enter.
  7. On the Edit menu, point to New, and then click DWORD value.
  8. Type UpdateDeviceInfoForEmf, and then press Enter
  9. Right-click UpdateDeviceInfoForEmf, and then click Modify. 10.In the Value data box, type 1, and then click OK.
  10. On the File menu, click Exit to close Registry Editor.

What is the best way to iterate over multiple lists at once?

You can use zip:

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
...   print x, y
... 
1 a
2 b
3 c

How do I copy a folder from remote to local using scp?

In case you run into "Too many authentication failures", specify the exact SSH key you have added to your severs ssh server:

scp -r -i /path/to/local/key [email protected]:/path/to/folder /your/local/target/dir

Can you get a Windows (AD) username in PHP?

try this code :

$user= shell_exec("echo %username%"); 
    echo "user : $user";

you get your windows(AD) username in php

How to set maximum height for table-cell?

By CSS 2.1 rules, the height of a table cell is “the minimum height required by the content”. Thus, you need to restrict the height indirectly using inner markup, normally a div element (<td><div>content</div></td>), and set height and overflow properties on the the div element (without setting display: table-cell on it, of course, as that would make its height obey CSS 2.1 table cell rules).

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

Swift 3.0

I decided to have a little fun with this and produce an extension on String. I might not be using the word truncate properly in what I'm having the function actually do.

extension String {

    func truncate(from initialSpot: Int, withLengthOf endSpot: Int) -> String? {

        guard endSpot > initialSpot else { return nil }
        guard endSpot + initialSpot <= self.characters.count else { return nil }

        let truncated = String(self.characters.dropFirst(initialSpot))
        let lastIndex = truncated.index(truncated.startIndex, offsetBy: endSpot)

        return truncated.substring(to: lastIndex)
    }

}

let favGameOfThronesSong = "Light of the Seven"

let word = favGameOfThronesSong.truncate(from: 1, withLengthOf: 4)
// "ight"

Maximum concurrent Socket.IO connections

This guy appears to have succeeded in having over 1 million concurrent connections on a single Node.js server.

http://blog.caustik.com/2012/08/19/node-js-w1m-concurrent-connections/

It's not clear to me exactly how many ports he was using though.

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

To avoid all the Oracle mess of not knowing where it is looking for the TNSNAMES.ORA (I have the added confusion of multiple Oracle versions and 32/64 bit), you can copy the setting from your existing TNSNAMES.ORA to your own config file and use that for your connection.
Say you're happy with the 'DSDSDS' reference in TNSNAMES.ORA which maps to something like:

DSDSDS=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=DSDSDSHost)(Port=4521)))(CONNECT_DATA=(SERVICE_NAME=DSDSDSService)))

You can take the text after the first '=' and use that wherever you are using 'DSDSDS' and it won't need to find TNSNAMES.ORA to know how to connect.
Now your connection string would look like this:
string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=DSDSDSHost)(Port=4521)))(CONNECT_DATA=(SERVICE_NAME=DSDSDSService)));User Id=UNUNUN;Password=PWPWPW;";

How can I find out which server hosts LDAP on my windows domain?

If the machine you are on is part of the AD domain, it should have its name servers set to the AD name servers (or hopefully use a DNS server path that will eventually resolve your AD domains). Using your example of dc=domain,dc=com, if you look up domain.com in the AD name servers it will return a list of the IPs of each AD Controller. Example from my company (w/ the domain name changed, but otherwise it's a real example):

    mokey 0 /home/jj33 > nslookup example.ad
    Server:         172.16.2.10
    Address:        172.16.2.10#53

    Non-authoritative answer:
    Name:   example.ad
    Address: 172.16.6.2
    Name:   example.ad
    Address: 172.16.141.160
    Name:   example.ad
    Address: 172.16.7.9
    Name:   example.ad
    Address: 172.19.1.14
    Name:   example.ad
    Address: 172.19.1.3
    Name:   example.ad
    Address: 172.19.1.11
    Name:   example.ad
    Address: 172.16.3.2

Note I'm actually making the query from a non-AD machine, but our unix name servers know to send queries for our AD domain (example.ad) over to the AD DNS servers.

I'm sure there's a super-slick windowsy way to do this, but I like using the DNS method when I need to find the LDAP servers from a non-windows server.

How can you integrate a custom file browser/uploader with CKEditor?

I just went through the learning process myself. I figured it out, but I agree the documentation is written in a way that was sorta intimidating to me. The big "aha" moment for me was understanding that for browsing, all CKeditor does is open a new window and provide a few parameters in the url. It allows you to add additional parameters but be advised you will need to use encodeURIComponent() on your values.

I call the browser and the uploader with

CKEDITOR.replace( 'body',  
{  
    filebrowserBrowseUrl: 'browse.php?type=Images&dir=' +  
        encodeURIComponent('content/images'),  
    filebrowserUploadUrl: 'upload.php?type=Files&dir=' +  
        encodeURIComponent('content/images')  
}

For the browser, in the open window (browse.php) you use php & js to supply a list of choices and then upon your supplied onclick handler, you call a CKeditor function with two arguments, the url/path to the selected image and CKEditorFuncNum supplied by CKeditor in the url:

function myOnclickHandler(){  
//..    
    window.opener.CKEDITOR.tools.callFunction(<?php echo $_GET['CKEditorFuncNum']; ?>, pathToImage);  
    window.close();
}       

Simarly, the uploader simply calls the url you supply, e.g., upload.php, and again supplies $_GET['CKEditorFuncNum']. The target is an iframe so, after you save the file from $_FILES you pass your feedback to CKeditor as thus:

$funcNum = $_GET['CKEditorFuncNum'];  
exit("<script>window.parent.CKEDITOR.tools.callFunction($funcNum, '$filePath', '$errorMessage');</script>");  

Below is a simple to understand custom browser script. While it does not allow users to navigate around in the server, it does allow you to indicate which directory to pull image files from when calling the browser.

It's all rather basic coding so it should work in all relatively modern browsers.

CKeditor merely opens a new window with the url provided

/*          
    in CKeditor **use encodeURIComponent()** to add dir param to the filebrowserBrowseUrl property

    Replace content/images with directory where your images are housed.
*/          
        CKEDITOR.replace( 'editor1', {  
            filebrowserBrowseUrl: '**browse.php**?type=Images&dir=' + encodeURIComponent('content/images'),  
            filebrowserUploadUrl: 'upload.php?type=Files&dir=' + encodeURIComponent('content/images') 
        });   

// ========= complete code below for browse.php

<?php  
header("Content-Type: text/html; charset=utf-8\n");  
header("Cache-Control: no-cache, must-revalidate\n");  
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");  

// e-z params  
$dim = 150;         /* image displays proportionally within this square dimension ) */  
$cols = 4;          /* thumbnails per row */
$thumIndicator = '_th'; /* e.g., *image123_th.jpg*) -> if not using thumbNails then use empty string */  
?>  
<!DOCTYPE html>  
<html>  
<head>  
    <title>browse file</title>  
    <meta charset="utf-8">  

    <style>  
        html,  
        body {padding:0; margin:0; background:black; }  
        table {width:100%; border-spacing:15px; }  
        td {text-align:center; padding:5px; background:#181818; }  
        img {border:5px solid #303030; padding:0; verticle-align: middle;}  
        img:hover { border-color:blue; cursor:pointer; }  
    </style>  

</head>  


<body>  

<table>  

<?php  

$dir = $_GET['dir'];    

$dir = rtrim($dir, '/'); // the script will add the ending slash when appropriate  

$files = scandir($dir);  

$images = array();  

foreach($files as $file){  
    // filter for thumbNail image files (use an empty string for $thumIndicator if not using thumbnails )
    if( !preg_match('/'. $thumIndicator .'\.(jpg|jpeg|png|gif)$/i', $file) )  
        continue;  

    $thumbSrc = $dir . '/' . $file;  
    $fileBaseName = str_replace('_th.','.',$file);  

    $image_info = getimagesize($thumbSrc);  
    $_w = $image_info[0];  
    $_h = $image_info[1]; 

    if( $_w > $_h ) {       // $a is the longer side and $b is the shorter side
        $a = $_w;  
        $b = $_h;  
    } else {  
        $a = $_h;  
        $b = $_w;  
    }     

    $pct = $b / $a;     // the shorter sides relationship to the longer side

    if( $a > $dim )   
        $a = $dim;      // limit the longer side to the dimension specified

    $b = (int)($a * $pct);  // calculate the shorter side

    $width =    $_w > $_h ? $a : $b;  
    $height =   $_w > $_h ? $b : $a;  

    // produce an image tag
    $str = sprintf('<img src="%s" width="%d" height="%d" title="%s" alt="">',   
        $thumbSrc,  
        $width,  
        $height,  
        $fileBaseName  
    );  

    // save image tags in an array
    $images[] = str_replace("'", "\\'", $str); // an unescaped apostrophe would break js  

}

$numRows = floor( count($images) / $cols );  

// if there are any images left over then add another row
if( count($images) % $cols != 0 )  
    $numRows++;  


// produce the correct number of table rows with empty cells
for($i=0; $i<$numRows; $i++)   
    echo "\t<tr>" . implode('', array_fill(0, $cols, '<td></td>')) . "</tr>\n\n";  

?>  
</table>  


<script>  

// make a js array from the php array
images = [  
<?php   

foreach( $images as $v)  
    echo sprintf("\t'%s',\n", $v);  

?>];  

tbl = document.getElementsByTagName('table')[0];  

td = tbl.getElementsByTagName('td');  

// fill the empty table cells with data
for(var i=0; i < images.length; i++)  
    td[i].innerHTML = images[i];  


// event handler to place clicked image into CKeditor
tbl.onclick =   

    function(e) {  

        var tgt = e.target || event.srcElement,  
            url;  

        if( tgt.nodeName != 'IMG' )  
            return;  

        url = '<?php echo $dir;?>' + '/' + tgt.title;  

        this.onclick = null;  

        window.opener.CKEDITOR.tools.callFunction(<?php echo $_GET['CKEditorFuncNum']; ?>, url);  

        window.close();  
    }  
</script>  
</body>  
</html>            

OpenCV Python rotate image by X degrees around specific point

import numpy as np
import cv2

def rotate_image(image, angle):
  image_center = tuple(np.array(image.shape[1::-1]) / 2)
  rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
  result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)
  return result

Assuming you're using the cv2 version, that code finds the center of the image you want to rotate, calculates the transformation matrix and applies to the image.

How do you plot bar charts in gnuplot?

plot "data.dat" using 2: xtic(1) with histogram

Here data.dat contains data of the form

title 1
title2 3
"long title" 5

Webdriver and proxy server for firefox

In case if you have an autoconfig URL -

        FirefoxProfile firefoxProfile = new FirefoxProfile();
        firefoxProfile.setPreference("network.proxy.type", 2);
        firefoxProfile.setPreference("network.proxy.autoconfig_url", "http://www.etc.com/wpad.dat");
        firefoxProfile.setPreference("network.proxy.no_proxies_on", "localhost");
        WebDriver driver = new FirefoxDriver(firefoxProfile);

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

You have to use latest version with SSMS

You can check latest builds via this page https://sqlserverbuilds.blogspot.com/

"make clean" results in "No rule to make target `clean'"

You have fallen victim to the most common of errors in Makefiles. You always need to put a Tab at the beginning of each command. You've put spaces before the $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) and @rm -f $(PROGRAMS) *.o core lines. If you replace them with a Tab, you'll be fine.

However, this error doesn't lead to a "No rule to make target ..." error. That probably means your issue lies beyond your Makefile. Have you checked this is the correct Makefile, as in the one you want to be specifying your commands? Try explicitly passing it as a parameter to make, make -f Makefile and let us know what happens.

Data at the root level is invalid

I found that the example I was using had an xml document specification on the first line. I was using a stylesheet I got at this blog entry and the first line was

<?xmlversion="1.0"encoding="utf-8"?>

which was causing the error. When I removed that line, so that the stylesheet started with the line

<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

my transform worked. By the way, that blog post was the first good, easy-to follow example I have found for trying to get information from the XML definition of an SSIS package, but I did have to modify the paths in the example for my SSIS 2008 packages, so you might too. I also created a version to extract the "flow" from the precedence constraints. My final one looks like this:

    <xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="utf-8" />
    <xsl:template match="/">
    <xsl:text>From,To~</xsl:text>
    <xsl:text>
</xsl:text>
    <xsl:for-each select="//DTS:PrecedenceConstraints/DTS:PrecedenceConstraint">
      <xsl:value-of select="@DTS:From"/>
      <xsl:text>,</xsl:text>
      <xsl:value-of select="@DTS:To"/>
       <xsl:text>~</xsl:text>
      <xsl:text>
</xsl:text>
    </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

and gave me a CSV with the tilde as my line delimiter. I replaced that with a line feed in my text editor then imported into excel to get a with look at the data flow in the package.

Woocommerce, get current product id

2017 Update - since WooCommerce 3:

global $product;
$id = $product->get_id();

Woocommerce doesn't like you accessing those variables directly. This will get rid of any warnings from woocommerce if your wp_debug is true.

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

@Html.ValidationSummary(false,"", new { @class = "text-danger" })

Using this line may be helpful

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

you can try sklearn.metrics.classification_report as below:

import sklearn
y_true = [1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0]
y_pred = [1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0]

print sklearn.metrics.classification_report(y_true, y_pred)

output:

         precision    recall  f1-score   support

      0       0.80      0.57      0.67         7
      1       0.50      0.75      0.60         4

      avg / total       0.69      0.64      0.64        11

How to get WordPress post featured image URL

You can also get the URL for image attachments as follows:

<?php
    "<div><a href=".get_permalink(id).">".wp_get_attachment_url(304, array(50,50), 1)."</a></div>";
?>

How to add shortcut keys for java code in eclipse

I've been Eclipse-free for over a year now, but I believe Eclipse calls these "Templates". Look in your settings for them. You invoke a template by typing its abbreviation and pressing the normal code completion hotkey (ctrl+space by default) or using the Tab key. The standard eclipse shortcut for System.out.println() is "sysout", so "sysout" would do what you want.

Here's another stackoverflow question that has some more details about it: How to use the "sysout" snippet in Eclipse with selected text?

How to generate random colors in matplotlib?

elaborating @john-mee 's answer, if you have arbitrarily long data but don't need strictly unique colors:

for python 2:

from itertools import cycle
cycol = cycle('bgrcmk')

for X,Y in data:
    scatter(X, Y, c=cycol.next())

for python 3:

from itertools import cycle
cycol = cycle('bgrcmk')

for X,Y in data:
    scatter(X, Y, c=next(cycol))

this has the advantage that the colors are easy to control and that it's short.

How to delete a cookie using jQuery?

it is the problem of misunderstand of cookie. Browsers recognize cookie values for not just keys also compare the options path & domain. So Browsers recognize different value which cookie values that key is 'name' with server setting option(path='/'; domain='mydomain.com') and key is 'name' with no option.

Why use HttpClient for Synchronous Connection

In my case the accepted answer did not work. I was calling the API from an MVC application which had no async actions.

This is how I managed to make it work:

private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
public static T RunSync<T>(Func<Task<T>> func)
    {           
        CultureInfo cultureUi = CultureInfo.CurrentUICulture;
        CultureInfo culture = CultureInfo.CurrentCulture;
        return _myTaskFactory.StartNew<Task<T>>(delegate
        {
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = cultureUi;
            return func();
        }).Unwrap<T>().GetAwaiter().GetResult();
    }

Then I called it like this:

Helper.RunSync(new Func<Task<ReturnTypeGoesHere>>(async () => await AsyncCallGoesHere(myparameter)));

jQuery 'if .change() or .keyup()'

you can bind to multiple events by separating them with a space:

$(":input").on("keyup change", function(e) {
    // do stuff!
})

docs here.

hope that helps. cheers!

Byte Array in Python

Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')

Indexing get and sets the individual bytes

>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')

and if you need it as a str (or bytes in Python 3), it's as simple as

>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'

Base64 PNG data to HTML5 canvas

By the looks of it you need to actually pass drawImage an image object like so

_x000D_
_x000D_
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
  ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

I've tried it in chrome and it works fine.

Check if string ends with one of the strings from a list

Another possibility could be to make use of IN statement:

extensions = ['.mp3','.avi']
file_name  = 'test.mp3'
if "." in file_name and file_name[file_name.rindex("."):] in extensions:
    print(True)

SSRS Field Expression to change the background color of the Cell

=IIF(Fields!Column.Value = "Approved", "Green", "No Color")

Vagrant ssh authentication failure

Another simple solution, in windows, go to the file Homestead/Vagrantfile and add these lines to connect with a username/password instead of a private key:

config.ssh.username = "vagrant"  
config.ssh.password = "vagrant"  
config.ssh.insert_key = false 

So, finally part of the file will look like this :

if File.exists? homesteadYamlPath then
    settings = YAML::load(File.read(homesteadYamlPath))
elsif File.exists? homesteadJsonPath then
    settings = JSON.parse(File.read(homesteadJsonPath))
end

config.ssh.username = "vagrant"  
config.ssh.password = "vagrant"  
config.ssh.insert_key = false 

Homestead.configure(config, settings)

if File.exists? afterScriptPath then
    config.vm.provision "shell", path: afterScriptPath, privileged: false
end

Hope this help ..

vi/vim editor, copy a block (not usual action)

Their Documentation says:

Cut and paste:

  1. Position the cursor where you want to begin cutting.
  2. Press v to select characters (or uppercase V to select whole lines).
  3. Move the cursor to the end of what you want to cut.
  4. Press d to cut (or y to copy).
  5. Move to where you would like to paste.
  6. Press P to paste before the cursor, or p to paste after.

Copy and paste is performed with the same steps except for step 4 where you would press y instead of d:

d = delete = cut

y = yank = copy

input[type='text'] CSS selector does not apply to default-type text inputs?

The CSS uses only the data in the DOM tree, which has little to do with how the renderer decides what to do with elements with missing attributes.

So either let the CSS reflect the HTML

input:not([type]), input[type="text"]
{
background:red;
}

or make the HTML explicit.

<input name='t1' type='text'/> /* Is Not Red */

If it didn't do that, you'd never be able to distinguish between

element { ...properties... }

and

element[attr] { ...properties... }

because all attributes would always be defined on all elements. (For example, table always has a border attribute, with 0 for a default.)

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

I had a similar experience with Chai-Webdriver for Selenium. I added await to the assertion and it fixed the issue:

Example using Cucumberjs:

Then(/I see heading with the text of Tasks/, async function() {
    await chai.expect('h1').dom.to.contain.text('Tasks');
});

CSS background image in :after element

As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:

background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;

Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).

No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.

MySQL Workbench Dark Theme

Here's how to change MySQL Workbench's colors (INCLUDING THE BACKGROUND COLOR).

Open the XML file called code_editor.xml located in the data folder of the MySQL Workbench's installation directory (usually C:\Program Files\MySQL\MySQL Workbench 6.3 CE\data). Here you'll find a lot of styling for different code elements, but there are some missing.

MySQL Workbench uses scintilla as the code editor, and scintilla defines a few more styles that you can use in the code_editor.xml file. The one that is used for the background color is style id 32.

Here's the complete list for MySQL (scintilla has thousands of styles for many languages) with my configuration:

<style id= "0" fore-color="#DDDDDD" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_DEFAULT                  -->
<style id= "1" fore-color="#999999" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_COMMENT                  -->
<style id= "2" fore-color="#999999" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_COMMENTLINE              -->
<style id= "3" fore-color="#DDDDDD" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_VARIABLE                 -->
<style id= "4" fore-color="#9B859D" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_SYSTEMVARIABLE           -->
<style id= "5" fore-color="#9B859D" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE      -->
<style id= "6" fore-color="#FF8080" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_NUMBER                   -->
<style id= "7" fore-color="#7AAAD7" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_MAJORKEYWORD             -->
<style id= "8" fore-color="#7AAAD7" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_KEYWORD                  -->
<style id= "9" fore-color="#9B859D" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_DATABASEOBJECT           -->
<style id="10" fore-color="#DDDDDD" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_PROCEDUREKEYWORD         -->
<style id="11" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_STRING                   -->
<style id="12" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_SQSTRING                 -->
<style id="13" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_DQSTRING                 -->
<style id="14" fore-color="#FFBB80" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_OPERATOR                 -->
<style id="15" fore-color="#9B859D" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_FUNCTION                 -->
<style id="16" fore-color="#DDDDDD" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_IDENTIFIER               -->
<style id="17" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_QUOTEDIDENTIFIER         -->
<style id="18" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_USER1                    -->
<style id="19" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_USER2                    -->
<style id="20" fore-color="#B9CB89" back-color="#2A2A2A" bold="No" />   <!-- SCE_MYSQL_USER3                    -->
<style id="21" fore-color="#FFBB80" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_HIDDENCOMMAND            -->
<style id="22" fore-color="#909090" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_PLACEHOLDER              -->

<!-- These two are for scintilla globally. -->
<style id="32" fore-color="#DDDDDD" back-color="#2A2A2A" bold="No" />   <!-- STYLE_DEFAULT                      THIS IS THE ONE FOR THE BACKGROUND!!!!! -->
<style id="33" fore-color="#2A2A2A" back-color="#DDDDDD" bold="No" />   <!-- STYLE_LINENUMBER                   -->

<!-- All styles again in their variant in a hidden command (with a 0x40 offset). -->
<style id="65" fore-color="#999999" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_COMMENT                  -->
<style id="66" fore-color="#999999" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_COMMENTLINE              -->
<style id="67" fore-color="#DDDDDD" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_VARIABLE                 -->
<style id="68" fore-color="#9B859D" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_SYSTEMVARIABLE           -->
<style id="69" fore-color="#9B859D" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE      -->
<style id="70" fore-color="#FF8080" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_NUMBER                   -->
<style id="71" fore-color="#7AAAD7" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_MAJORKEYWORD             -->
<style id="72" fore-color="#7AAAD7" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_KEYWORD                  -->
<style id="73" fore-color="#9B859D" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_DATABASEOBJECT           -->
<style id="74" fore-color="#DDDDDD" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_PROCEDUREKEYWORD         -->
<style id="75" fore-color="#B9CB89" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_STRING                   -->
<style id="76" fore-color="#B9CB89" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_SQSTRING                 -->
<style id="77" fore-color="#B9CB89" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_DQSTRING                 -->
<style id="78" fore-color="#FFBB80" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_OPERATOR                 -->
<style id="79" fore-color="#9B859D" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_FUNCTION                 -->
<style id="80" fore-color="#DDDDDD" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_IDENTIFIER               -->
<style id="81" fore-color="#B9CB89" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_QUOTEDIDENTIFIER         -->
<style id="82" fore-color="#B9CB89" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_USER1                    -->
<style id="83" fore-color="#B9CB89" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_USER2                    -->
<style id="84" fore-color="#B9CB89" back-color="#707070" bold="No" />   <!-- SCE_MYSQL_USER3                    -->
<style id="85" fore-color="#FFBB80" back-color="#909090" bold="No" />   <!-- SCE_MYSQL_HIDDENCOMMAND            -->
<style id="86" fore-color="#AAAAAA" back-color="#909090" bold="No" />   <!-- SCE_MYSQL_PLACEHOLDER              -->

jQuery UI DatePicker to show year only

Try this way it will hide the calendar and show year only

$(function() {
    $( "#datepicker" ).datepicker({dateFormat: 'yy'});
    });?

CSS

.ui-datepicker-calendar {
   display: none;
}

DEMO ?

Difference between margin and padding?

One of the key differences between margin and padding is not mentioned in any of the answers: clickability and hover detection

Increasing the padding increases the effective size of the element. Sometimes I have a smallish icon that I don't want to make visibly larger but the user still needs to interact with that icon. I increase the icon's padding to give it a larger footprint for clicks and hover. Increasing the icon's margin will not have the same effect.

An answer to another question on this topic gives an example.

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

If your website also on the oxfordlearnersdictionaries.com domain, USE the following into the oxfordlearnersdictionaries.com .htaccess file:

Header set Access-Control-Allow-Origin "*"

Codesign error: Provisioning profile cannot be found after deleting expired profile

I just encountered this problem in my Xcode 4. To fix it, you need to put all the correct provisions into both Debug and Release config.

I was trying to submit (by archiving) my app. So I just change the Debug provisions to "Don't Code Sign", and the Release provision to my app's appstore provision.

This fix it and enables me to archive normally. Hope that helps.

How to clear Facebook Sharer cache?

This answer is intended for developers.

Clearing the cache means that new shares of this webpage will show the new content which is provided in the OG tags. But only if the URL that you are working on has less than 50 interactions (likes + shares). It will also not affect old links to this webpage which have already been posted on Facebook. Only when sharing the URL on Facebook again will the way that Facebook shows the link be updated.

catandmouse's answer is correct but you can also make Facebook clear the OG (OpenGraph) cache by sending a post request to graph.facebook.com (works for both http and https as of the writing of this answer). You do not need an access token.

A post request to graph.facebook.com may look as follows:

POST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: graph.facebook.com
Content-Length: 63
Accept-Encoding: gzip
User-Agent: Mojolicious (Perl)

id=<url_encoded_url>&scrape=true

In Perl, you can use the following code where the library Mojo::UserAgent is used to send and receive HTTP requests:

sub _clear_og_cache_on_facebook {
    my $fburl     = "http://graph.facebook.com";
    my $ua        = Mojo::UserAgent->new;
    my $clearurl  = <the url you want Facebook to forget>;
    my $post_body = {id => $clearurl, scrape => 'true'};
    my $res       = $ua->post($fburl => form => $post_body)->res;
    my $code      = $res->code;
    unless ($code eq '200') {
        Log->warn("Clearing cached OG data for $clearurl failed with code $code.");
        }
    }
}

Sending this post request through the terminal can be done with the following command:

curl -F id="<URL>" -F scrape=true graph.facebook.com

List to array conversion to use ravel() function

Use numpy.asarray:

import numpy as np
myarray = np.asarray(mylist)

is python capable of running on multiple cores?

As stated in prior answers - it depends on the answer to "cpu or i/o bound?",
but also to the answer to "threaded or multi-processing?":

Examples run on Raspberry Pi 3B 1.2GHz 4-core with Python3.7.3
--( With other processes running including htop )

  • For this test - multiprocessing and threading had similar results for i/o bound,
    but multi-processing was more efficient than threading for cpu-bound.

Using threads:

Typical Result:
. Starting 4000 cycles of io-bound threading
. Sequential run time: 39.15 seconds
. 4 threads Parallel run time: 18.19 seconds
. 2 threads Parallel - twice run time: 20.61 seconds

Typical Result:
. Starting 1000000 cycles of cpu-only threading
. Sequential run time: 9.39 seconds
. 4 threads Parallel run time: 10.19 seconds
. 2 threads Parallel twice - run time: 9.58 seconds

Using multiprocessing:

Typical Result:
. Starting 4000 cycles of io-bound processing
. Sequential - run time: 39.74 seconds
. 4 procs Parallel - run time: 17.68 seconds
. 2 procs Parallel twice - run time: 20.68 seconds

Typical Result:
. Starting 1000000 cycles of cpu-only processing
. Sequential run time: 9.24 seconds
. 4 procs Parallel - run time: 2.59 seconds
. 2 procs Parallel twice - run time: 4.76 seconds

compare_io_multiproc.py:
#!/usr/bin/env python3

# Compare single proc vs multiple procs execution for io bound operation

"""
Typical Result:
  Starting 4000 cycles of io-bound processing
  Sequential - run time: 39.74 seconds
  4 procs Parallel - run time: 17.68 seconds
  2 procs Parallel twice - run time: 20.68 seconds
"""
import time
import multiprocessing as mp

# one thousand
cycles = 1 * 1000

def t():
        with open('/dev/urandom', 'rb') as f:
                for x in range(cycles):
                        f.read(4 * 65535)

if __name__ == '__main__':
    print("  Starting {} cycles of io-bound processing".format(cycles*4))
    start_time = time.time()
    t()
    t()
    t()
    t()
    print("  Sequential - run time: %.2f seconds" % (time.time() - start_time))

    # four procs
    start_time = time.time()
    p1 = mp.Process(target=t)
    p2 = mp.Process(target=t)
    p3 = mp.Process(target=t)
    p4 = mp.Process(target=t)
    p1.start()
    p2.start()
    p3.start()
    p4.start()
    p1.join()
    p2.join()
    p3.join()
    p4.join()
    print("  4 procs Parallel - run time: %.2f seconds" % (time.time() - start_time))

    # two procs
    start_time = time.time()
    p1 = mp.Process(target=t)
    p2 = mp.Process(target=t)
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    p3 = mp.Process(target=t)
    p4 = mp.Process(target=t)
    p3.start()
    p4.start()
    p3.join()
    p4.join()
    print("  2 procs Parallel twice - run time: %.2f seconds" % (time.time() - start_time))

compare_cpu_multiproc.py
#!/usr/bin/env python3

# Compare single proc vs multiple procs execution for cpu bound operation

"""
Typical Result:
  Starting 1000000 cycles of cpu-only processing
  Sequential run time: 9.24 seconds
  4 procs Parallel - run time: 2.59 seconds
  2 procs Parallel twice - run time: 4.76 seconds
"""
import time
import multiprocessing as mp

# one million
cycles = 1000 * 1000

def t():
    for x in range(cycles):
        fdivision = cycles / 2.0
        fcomparison = (x > fdivision)
        faddition = fdivision + 1.0
        fsubtract = fdivision - 2.0
        fmultiply = fdivision * 2.0

if __name__ == '__main__':
    print("  Starting {} cycles of cpu-only processing".format(cycles))
    start_time = time.time()
    t()
    t()
    t()
    t()
    print("  Sequential run time: %.2f seconds" % (time.time() - start_time))

    # four procs
    start_time = time.time()
    p1 = mp.Process(target=t)
    p2 = mp.Process(target=t)
    p3 = mp.Process(target=t)
    p4 = mp.Process(target=t)
    p1.start()
    p2.start()
    p3.start()
    p4.start()
    p1.join()
    p2.join()
    p3.join()
    p4.join()
    print("  4 procs Parallel - run time: %.2f seconds" % (time.time() - start_time))

    # two procs
    start_time = time.time()
    p1 = mp.Process(target=t)
    p2 = mp.Process(target=t)
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    p3 = mp.Process(target=t)
    p4 = mp.Process(target=t)
    p3.start()
    p4.start()
    p3.join()
    p4.join()
    print("  2 procs Parallel twice - run time: %.2f seconds" % (time.time() - start_time))


Haskell: Converting Int to String

An example based on Chuck's answer:

myIntToStr :: Int -> String
myIntToStr x
    | x < 3     = show x ++ " is less than three"
    | otherwise = "normal"

Note that without the show the third line will not compile.

How to get the max of two values in MySQL?

To get the maximum value of a column across a set of rows:

SELECT MAX(column1) FROM table; -- expect one result

To get the maximum value of a set of columns, literals, or variables for each row:

SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results

jQuery looping .each() JSON key/value not working

With a simple JSON object, you don't need jQuery:

for (var i in json) {
   for (var j in json[i]) {
     console.log(json[i][j]);
   }
}

Remove decimal values using SQL query

Your data type is DECIMAL with decimal places, say DECIMAL(10,2). The values in your database are 12, 15, 18, and 20.

12 is the same as 12.0 and 12.00 and 12.000 . It is up to the tool you are using to select the data with, how to display the numbers. Yours either defaults to two digits for decimals or it takes the places from your data definition.

If you only want integers in your column, then change its data type to INT. It makes no sense to use DECIMAL then.

If you want integers and decimals in that column then stay with the DECIMAL type. If you don't like the way you are shown the values, then format them in your application. It's up to that client program to decide for instance if to display point or comma for the decimal separator. (The database can be used from different locations.)

Also don't rely on any database or session settings like a decimal separator being a point and not a comma and then use REPLACE on it. That can work for one person and not for the other.

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

This is my function for the clients timezone, it's lite weight and simple

  function getCurrentDateTimeMySql() {        
      var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
      var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, 19).replace('T', ' ');
      var mySqlDT = localISOTime;
      return mySqlDT;
  }

Set Background color programmatically

This must work:

you must use getResources().getColor(R.color.WHITE) to get the color resource, which you must add in the colors.xml resource file

View someView = findViewById(R.id.screen);

someView.setBackgroundColor(getResources().getColor(R.color.WHITE));

How do I position a div relative to the mouse pointer using jQuery?

There are plenty of examples of using JQuery to retrieve the mouse coordinates, but none fixed my issue.

The Body of my webpage is 1000 pixels wide, and I centre it in the middle of the user's browser window.

body {
    position:absolute;
    width:1000px;
    left: 50%;
    margin-left:-500px;
}

Now, in my JavaScript code, when the user right-clicked on my page, I wanted a div to appear at the mouse position.

Problem is, just using e.pageX value wasn't quite right. It'd work fine if I resized my browser window to be about 1000 pixels wide. Then, the pop div would appear at the correct position.

But if increased the size of my browser window to, say, 1200 pixels wide, then the div would appear about 100 pixels to the right of where the user had clicked.

The solution is to combine e.pageX with the bounding rectangle of the body element. When the user changes the size of their browser window, the "left" value of body element changes, and we need to take this into account:

// Temporary variables to hold the mouse x and y position
var tempX = 0;
var tempY = 0;

jQuery(document).ready(function () {
    $(document).mousemove(function (e) {
        var bodyOffsets = document.body.getBoundingClientRect();
        tempX = e.pageX - bodyOffsets.left;
        tempY = e.pageY;
    });
}) 

Phew. That took me a while to fix ! I hope this is useful to other developers !

Find size and free space of the filesystem containing a given file

For the second part of your question, "get usage statistics of the given partition", psutil makes this easy with the disk_usage(path) function. Given a path, disk_usage() returns a named tuple including total, used, and free space expressed in bytes, plus the percentage usage.

Simple example from documentation:

>>> import psutil
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)

Psutil works with Python versions from 2.6 to 3.6 and on Linux, Windows, and OSX among other platforms.

Very Simple, Very Smooth, JavaScript Marquee

I made my own version, based in the code presented above by @Tats_innit . The difference is the pause function. Works a little better in that aspect.

(function ($) {
var timeVar, width=0;

$.fn.textWidth = function () {
    var calc = '<span style="display:none">' + $(this).text() + '</span>';
    $('body').append(calc);
    var width = $('body').find('span:last').width();
    $('body').find('span:last').remove();
    return width;
};

$.fn.marquee = function (args) {
    var that = $(this);
    if (width == 0) { width = that.width(); };
    var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
        css = {
            'text-indent': that.css('text-indent'),
            'overflow': that.css('overflow'),
            'white-space': that.css('white-space')
        },
        marqueeCss = {
            'text-indent': width,
            'overflow': 'hidden',
            'white-space': 'nowrap'
        },
        args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);

    function go() {
        if (!that.length) return dfd.reject();
        if (width <= stop) {
            i++;
            if (i <= args.count) {
                that.css(css);
                return dfd.resolve();
            }
            if (args.leftToRight) {
                width = textWidth * -1;
            } else {
                width = offset;
            }
        }
        that.css('text-indent', width + 'px');
        if (args.leftToRight) {
            width++;
        } else {
            width=width-2;
        }
        if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
        if (args.pause == true) { clearTimeout(timeVar); };
    };

    if (args.leftToRight) {
        width = textWidth * -1;
        width++;
        stop = offset;
    } else {
        width--;
    }
    that.css(marqueeCss);

    timeVar = setTimeout(function () { go() }, 100);

    return dfd.promise();
};
})(jQuery);

usage:

for start: $('#Text1').marquee()

pause: $('#Text1').marquee({ pause: true })

resume: $('#Text1').marquee({ pause: false })

How Can I Override Style Info from a CSS Class in the Body of a Page?

you can test a color by writing the CSS inline like <div style="color:red";>...</div>

Warning :-Presenting view controllers on detached view controllers is discouraged

The reason of this warning is i was presenting a view controller over a small view that is not full size view. Given below is the image of my project. where on click on four option above. User navigate to different childviewcontroller's view.(it works like tabViewcontroller). But the childviewcontroller contains view of small size. So if we present a view from childviewcontroller it gives this warning.

master detail view

And to avoid this, you can present a view on childviewcontroller's parent

  [self.parentViewController presentViewController:viewController animated:YES completion:nil];

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this:

 Select 
    Id, 
    Salt, 
    Password, 
    BannedEndDate, 
    (Select Count(*) 
        From LoginFails 
        Where username = '" + LoginModel.Username + "' And IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "')
 From Users 
 Where username = '" + LoginModel.Username + "'

And I recommend you strongly to use parameters in your query to avoid security risks with sql injection attacks!

Hope that helps!

Get Cell Value from a DataTable in C#

You can iterate DataTable like this:

private void button1_Click(object sender, EventArgs e)
{
    for(int i = 0; i< dt.Rows.Count;i++)
        for (int j = 0; j <dt.Columns.Count ; j++)
        {
            object o = dt.Rows[i].ItemArray[j];
            //if you want to get the string
            //string s = o = dt.Rows[i].ItemArray[j].ToString();
        }
}

Depending on the type of the data in the DataTable cell, you can cast the object to whatever you want.

How to make modal dialog in WPF?

Window.Show will show the window, and continue execution -- it's a non-blocking call.

Window.ShowDialog will block the calling thread (kinda [1]), and show the dialog. It will also block interaction with the parent/owning window. When the dialog is dismissed (for whatever reason), ShowDialog will return to the caller, and will allow you to access DialogResult (if you want it).

[1] It will keep the dispatcher pumping by pushing a dispatcher frame onto the WPF dispatcher. This will cause the message pump to keep pumping.

How do I tokenize a string sentence in NLTK?

As @PavelAnossov answered, the canonical answer, use the word_tokenize function in nltk:

from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)

If your sentence is truly simple enough:

Using the string.punctuation set, remove punctuation then split using the whitespace delimiter:

import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y

An item with the same key has already been added

Here is what I did to find out the key that was being added twice. I downloaded the source code from http://referencesource.microsoft.com/DotNetReferenceSource.zip and setup VS to debug framework source. Opened up Dictionary.cs in VS ran the project, once page loads, added a debug at the line ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); and was able to see the 'key' value. I realized that in the JSON one letter of a variable was in upper case but in my model it was lowercase. I fixed the model and now the same code works.

Intel's HAXM equivalent for AMD on Windows OS

hello to run the avd manager on AMD processor you need update your SDK MANAGER in Android Studio: https://android-developers.googleblog.com/2018/07/android-emulator-amd-processor-hyper-v.html

You go to tools->SDK MANAGER->SDK Tools

then look for Android Emulator and Android Emulator Hypervisor Driver for AMD Processors

check the boxes and click apply or OK

Java 8: How do I work with exception throwing methods in streams?

You might want to do one of the following:

  • propagate checked exception,
  • wrap it and propagate unchecked exception, or
  • catch the exception and stop propagation.

Several libraries let you do that easily. Example below is written using my NoException library.

// Propagate checked exception
as.forEach(Exceptions.sneak().consumer(A::foo));

// Wrap and propagate unchecked exception
as.forEach(Exceptions.wrap().consumer(A::foo));
as.forEach(Exceptions.wrap(MyUncheckedException::new).consumer(A::foo));

// Catch the exception and stop propagation (using logging handler for example)
as.forEach(Exceptions.log().consumer(Exceptions.sneak().consumer(A::foo)));

Should I use typescript? or I can just use ES6?

Decision tree between ES5, ES6 and TypeScript

Do you mind having a build step?

  • Yes - Use ES5
  • No - keep going

Do you want to use types?

  • Yes - Use TypeScript
  • No - Use ES6

More Details

ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers

ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.

TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.

Default port for SQL Server

The default, unnamed instance always gets port 1433 for TCP. UDP port 1434 is used by the SQL Browser service to allow named instances to be located. In SQL Server 2000 the first instance to be started took this role.

Non-default instances get their own dynamically-allocated port, by default. If necessary, for example to configure a firewall, you can set them explicitly. If you don't want to enable or allow access to SQL Browser, you have to either include the instance's port number in the connection string, or set it up with the Alias tab in cliconfg (SQL Server Client Network Utility) on each client machine.

For more information see SQL Server Browser Service on MSDN.

What does an exclamation mark mean in the Swift language?

The ! means that you are force unwrapping the object the ! follows. More info can be found in Apples documentation, which can be found here: https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/TheBasics.html

How do I set up IntelliJ IDEA for Android applications?

You just need to install Android development kit from http://developer.android.com/sdk/installing/studio.html#Updating

and also Download and install Java JDK (Choose the Java platform)

define the environment variable in windows System setting https://confluence.atlassian.com/display/DOC/Setting+the+JAVA_HOME+Variable+in+Windows

Voila ! You are Donezo !

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

I faced the same problem, so please check is there mongodb folder, firstly try to remove that folder

rm -rf /var/lib/mongodb/*

Now try to start mongo and if same problem then its mongodb lock file which prevent to start mongo, so please delete the mongo lock file

rm /var/lib/mongodb/mongod.lock

For forcefully rm -rf /var/lib/mongodb/mongod.lock

service mongodb restart if already in sudo mode otherwise you need to use like sudo service mongod start

or you can start the server using fork method

mongod --fork --config /etc/mongod.conf

and for watching the same is it forked please check using the below command

ps aux | grep mongo

pandas groupby sort descending order

Do your groupby, and use reset_index() to make it back into a DataFrame. Then sort.

grouped = df.groupby('mygroups').sum().reset_index()
grouped.sort_values('mygroups', ascending=False)

Regex: ignore case sensitivity

The i flag is normally used for case insensitivity. You don't give a language here, but it'll probably be something like /G[ab].*/i or /(?i)G[ab].*/.

How to remove "Server name" items from history of SQL Server Management Studio

Over on this duplicate question @arcticdev posted some code that will get rid of individual entries (as opposed to all entries being delete the bin file). I have wrapped it in a very ugly UI and put it here: http://ssmsmru.codeplex.com/

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

your $(this).val() has no scope in your ajax call, because its not in change event function scope

May be you implemented that ajax call in your change event itself first, in that case it works fine. but when u created a function and calling that funciton in change event, scope for $(this).val() is not valid.

simply get the value using id selector instead of

$(#CourseSelect).val()

whole code should be like this:

 $(document).ready(function () 
{
    $("#CourseSelect").change(loadTeachers);
    loadTeachers();
});

function loadTeachers()
{
    $.ajax({ type:'GET', url:'/Manage/getTeachers/' + $(#CourseSelect).val(), dataType:'json', cache:false,
        success:function(data)
        { 
            $('#TeacherSelect').get(0).options.length = 0;    

            $.each(data, function(i, teacher) 
            {
                var option = $('<option />');
                option.val(teacher.employeeId);
                option.text(teacher.name);
                $('#TeacherSelect').append(option);
            });
        }, error:function(){ alert("Error while getting results"); }
    });
}

is there a 'block until condition becomes true' function in java?

Similar to EboMike's answer you can use a mechanism similar to wait/notify/notifyAll but geared up for using a Lock.

For example,

public void doSomething() throws InterruptedException {
    lock.lock();
    try {
        condition.await(); // releases lock and waits until doSomethingElse is called
    } finally {
        lock.unlock();
    }
}

public void doSomethingElse() {
    lock.lock();
    try {
        condition.signal();
    } finally {
        lock.unlock();
    }
}

Where you'll wait for some condition which is notified by another thread (in this case calling doSomethingElse), at that point, the first thread will continue...

Using Locks over intrinsic synchronisation has lots of advantages but I just prefer having an explicit Condition object to represent the condition (you can have more than one which is a nice touch for things like producer-consumer).

Also, I can't help but notice how you deal with the interrupted exception in your example. You probably shouldn't consume the exception like this, instead reset the interrupt status flag using Thread.currentThread().interrupt.

This because if the exception is thrown, the interrupt status flag will have been reset (it's saying "I no longer remember being interrupted, I won't be able to tell anyone else that I have been if they ask") and another process may rely on this question. The example being that something else has implemented an interruption policy based on this... phew. A further example might be that your interruption policy, rather that while(true) might have been implemented as while(!Thread.currentThread().isInterrupted() (which will also make your code be more... socially considerate).

So, in summary, using Condition is rougly equivalent to using wait/notify/notifyAll when you want to use a Lock, logging is evil and swallowing InterruptedException is naughty ;)

Get the Last Inserted Id Using Laravel Eloquent

Although this question is a bit dated. My quick and dirty solution would look like this:

$last_entry = Model::latest()->first();

But I guess it's vulnerable to race conditions on highly frequented databases.

! [rejected] master -> master (fetch first)

The answer is there, git is telling you to fetch first.

Probably somebody else has pushed to master already, and your commit is behind. Therefore you have to fetch, merge the changeset, and then you'll be able to push again.

If you don't (or even worse, if you force it by using the --force option), you can mess up the commit history.

EDIT: I get into more detail about the last point, since a guy here just gave the Very Bad Advice of using the --force option.

As git is a DVCS, ideally many other developers are working on the same project as you, using the same repository (or a fork of it). If you overwrite forcefully with your changeset, your repository will mismatch other people's, because "you rewrote history". You will make other people unhappy and the repository will suffer. Probably a kitten in the world will cry, too.

TL;DR

  1. If you want to solve, fetch first (and then merge).
  2. If you want to hack, use the --force option.

You asked for the former, though. Go for 1) always, even if you will always use git by yourself, because it is a good practice.

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

Taken from Retrieving File information | Android developers

Retrieving a File's name.

private String queryName(ContentResolver resolver, Uri uri) {
    Cursor returnCursor =
            resolver.query(uri, null, null, null, null);
    assert returnCursor != null;
    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    returnCursor.moveToFirst();
    String name = returnCursor.getString(nameIndex);
    returnCursor.close();
    return name;
}

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

JS: Uncaught TypeError: object is not a function (onclick)

Since the behavior is kind of strange, I have done some testing on the behavior, and here's my result:

TL;DR

If you are:

  • In a form, and
  • uses onclick="xxx()" on an element
  • don't add id="xxx" or name="xxx" to that element
    • (e.g. <form><button id="totalbandwidth" onclick="totalbandwidth()">BAD</button></form> )

Here's are some test and their result:

Control sample (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
_x000D_
_x000D_

Add id to button (failed to call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button id="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
_x000D_
_x000D_

Add name to button (failed to call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button name="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
_x000D_
_x000D_

Add value to button (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <input type="button" value="totalbandwidth" onclick="totalbandwidth()" />SUCCESS
</form>
_x000D_
_x000D_
_x000D_

Add id to button, but not in a form (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<button id="totalbandwidth" onclick="totalbandwidth()">SUCCESS</button>
_x000D_
_x000D_
_x000D_

Add id to another element inside the form (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("The answer is no, the span will not affect button"); }
_x000D_
<form onsubmit="return false;">
<span name="totalbandwidth" >Will this span affect button? </span>
<button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
_x000D_
_x000D_

How do I convert a calendar week into a date in Excel?

The following formula is suitable for every year. You don't need to adjust it anymore. The precondition is that Monday is your first day of the week.

If A2 = Year and Week = B2
=IF(ISOWEEKNUM(DATE($A$2;1;1)-WEEKDAY(DATE($A$2;1;1);2)+1)>1;DATE($A$2;1;1)-WEEKDAY(DATE($A$2;1;1);2)+1+B2*7;DATE($A$2;1;1)-WEEKDAY(DATE($A$2;1;1);2)-6+B2*7)

Finding the average of a list

Find the average in list By using the following PYTHON code:

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(sum(l)//len(l))

try this it easy.

Spark SQL: apply aggregate functions to a list of columns

Another example of the same concept - but say - you have 2 different columns - and you want to apply different agg functions to each of them i.e

f.groupBy("col1").agg(sum("col2").alias("col2"), avg("col3").alias("col3"), ...)

Here is the way to achieve it - though I do not yet know how to add the alias in this case

See the example below - Using Maps

val Claim1 = StructType(Seq(StructField("pid", StringType, true),StructField("diag1", StringType, true),StructField("diag2", StringType, true), StructField("allowed", IntegerType, true), StructField("allowed1", IntegerType, true)))
val claimsData1 = Seq(("PID1", "diag1", "diag2", 100, 200), ("PID1", "diag2", "diag3", 300, 600), ("PID1", "diag1", "diag5", 340, 680), ("PID2", "diag3", "diag4", 245, 490), ("PID2", "diag2", "diag1", 124, 248))

val claimRDD1 = sc.parallelize(claimsData1)
val claimRDDRow1 = claimRDD1.map(p => Row(p._1, p._2, p._3, p._4, p._5))
val claimRDD2DF1 = sqlContext.createDataFrame(claimRDDRow1, Claim1)

val l = List("allowed", "allowed1")
val exprs = l.map((_ -> "sum")).toMap
claimRDD2DF1.groupBy("pid").agg(exprs) show false
val exprs = Map("allowed" -> "sum", "allowed1" -> "avg")

claimRDD2DF1.groupBy("pid").agg(exprs) show false

Best way to center a <div> on a page vertically and horizontally?

One more method (bulletproof) taken from here utilizing 'display:table' rule:

Markup

<div class="container">
  <div class="outer">
    <div class="inner">
      <div class="centered">
        ...
      </div>
    </div>
  </div>
</div>

CSS:

.outer {
  display: table;
  width: 100%;
  height: 100%;
}
.inner {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.centered {
  position: relative;
  display: inline-block;

  width: 50%;
  padding: 1em;
  background: orange;
  color: white;
}

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

flask.Flask.run accepts additional keyword arguments (**options) that it forwards to werkzeug.serving.run_simple - two of those arguments are threaded (a boolean) and processes (which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).

threaded defaults to True as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True to enable this behaviour.

For example, you can do

if __name__ == '__main__':
    app.run(threaded=True)

to handle multiple clients using threads in a way compatible with old Flask versions, or

if __name__ == '__main__':
    app.run(threaded=False, processes=3)

to tell Werkzeug to spawn three processes to handle incoming requests, or just

if __name__ == '__main__':
    app.run()

to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.

That being said, Werkzeug's serving.run_simple wraps the standard library's wsgiref package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).

Compile to a stand-alone executable (.exe) in Visual Studio

Anything using the managed environment (which includes anything written in C# and VB.NET) requires the .NET framework. You can simply redistribute your .EXE in that scenario, but they'll need to install the appropriate framework if they don't already have it.

Python urllib2 Basic Auth Problem

(copy-paste/adapted from https://stackoverflow.com/a/24048772/1733117).

First you can subclass urllib2.BaseHandler or urllib2.HTTPBasicAuthHandler, and implement http_request so that each request has the appropriate Authorization header.

import urllib2
import base64

class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
    '''Preemptive basic auth.

    Instead of waiting for a 403 to then retry with the credentials,
    send the credentials if the url is handled by the password manager.
    Note: please use realm=None when calling add_password.'''
    def http_request(self, req):
        url = req.get_full_url()
        realm = None
        # this is very similar to the code from retry_http_basic_auth()
        # but returns a request object.
        user, pw = self.passwd.find_user_password(realm, url)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.b64encode(raw).strip()
            req.add_unredirected_header(self.auth_header, auth)
        return req

    https_request = http_request

Then if you are lazy like me, install the handler globally

api_url = "http://api.foursquare.com/"
api_username = "johndoe"
api_password = "some-cryptic-value"

auth_handler = PreemptiveBasicAuthHandler()
auth_handler.add_password(
    realm=None, # default realm.
    uri=api_url,
    user=api_username,
    passwd=api_password)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)

Synchronizing a local Git repository with a remote one

These steps will do it:

git reset --hard HEAD
git clean -f -x -d -n

then without -n

This will take care of all local changes. Now the commits...

git status

and note the line such as:

Your branch is ahead of 'xxxx' by N commits.

Take a note of number 'N' now:

git reset --hard HEAD~N
git pull

and finally:

git status

should show nothing to add/commit. All clean.

However, a fresh clone can do the same (but is much slow).

===Updated===

As my git knowledge slightly improved over the the time, I have come up with yet another simpler way to do the same. Here is how (#with explanation). While in your working branch:

git fetch # This updates 'remote' portion of local repo. 
git reset --hard origin/<your-working-branch>
# this will sync your local copy with remote content, discarding any committed
# or uncommitted changes.

Although your local commits and changes will disappear from sight after this, it is possible to recover committed changes, if necessary.

How to write string literals in python without having to escape them?

You will find Python's string literal documentation here:

http://docs.python.org/tutorial/introduction.html#strings

and here:

http://docs.python.org/reference/lexical_analysis.html#literals

The simplest example would be using the 'r' prefix:

ss = r'Hello\nWorld'
print(ss)
Hello\nWorld

How can I define a composite primary key in SQL?

In Oracle database we can achieve like this.

CREATE TABLE Student(
  StudentID Number(38, 0) not null,
  DepartmentID Number(38, 0) not null,
  PRIMARY KEY (StudentID, DepartmentID)
);

What's the difference between 'r+' and 'a+' when open file in python?

If you have used them in C, then they are almost same as were in C.

From the manpage of fopen() function : -

  • r+ : - Open for reading and writing. The stream is positioned at the beginning of the file.

  • a+ : - Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

How to Detect Browser Window /Tab Close Event?

Yes there is! After a lot of headache i found one solution to this.

Monitor.php

This php file will be monitoring the browser close event. Once the browser is closed the connection_aborted will return 1 hence the loop will break.

<?php
// Ignore user aborts and allow the script
// to run forever
ignore_user_abort(true);
set_time_limit(0);

echo connection_aborted();
while(1)
{
echo "Whatever you echo here wont be printed anywhere but it is required in order to work.";
flush();
if(connection_aborted())
{
break;
// Breaks only when browser is closed
}
}

/*
Action you want to take after browser is closed.
Write your code here
*/
?>

Caller.php

This is the file which will call Monitor.php

<?php
Header('Location: monitor.php');
?>

Parent.html

This will be the file which you will actually interact with. On loading this will directly make an AJAX call to Caller.php which will automatically start Monitor.php in background mode.

<script>

 var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            }
         }

   xmlhttp.open("GET", "Caller.php", true);
        xmlhttp.send();   

</script>

So the final flow is Parent.html----->Caller.php----->Monitor.php

In Angular, how do you determine the active route?

And in the latest version of angular, you can simply do check router.isActive(routeNameAsString). For example see the example below:

 <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item" [class.active] = "router.isActive('/dashboard')">
        <a class="nav-link" href="#">??????? <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item" [class.active] = "router.isActive(route.path)" *ngFor="let route of (routes$ | async)">
        <a class="nav-link" href="javascript:void(0)" *ngIf="route.childRoutes && route.childRoutes.length > 0"
          [matMenuTriggerFor]="menu">{{route.name}}</a>
        <a class="nav-link" href="{{route.path}}"
          *ngIf="!route.childRoutes || route.childRoutes.length === 0">{{route.name}}</a>
        <mat-menu #menu="matMenu">
          <span *ngIf="route.childRoutes && route.childRoutes.length > 0">
            <a *ngFor="let child of route.childRoutes" class="nav-link" href="{{route.path + child.path}}"
              mat-menu-item>{{child.name}}</a>
          </span>
        </mat-menu>
      </li>
    </ul>
    <span class="navbar-text mr-auto">
      <small>????</small> {{ (currentUser$ | async) ? (currentUser$ | async).firstName : '?????' }}
      {{ (currentUser$ | async) ? (currentUser$ | async).lastName : '??????' }}
    </span>
  </div>

And make sure you are not forgetting injecting router in your component.

html form - make inputs appear on the same line

You can make a class for each label and inside it put:

display: inline-block;

And width the value that you need.

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

A comparison between the different Visual Studio Express editions can be found at Visual Studio Express (archive.org link). The difference between Windows and Windows Desktop is that with the Windows edition you can build Windows Store Apps (using .NET, WPF/XAML) while the Windows Desktop edition allows you to write classic Windows Desktop applications. It is possible to install both products on the same machine.

Visual Studio Express 2010 allows you to build Windows Desktop applications. Writing Windows Store applications is not possible with this product.

For learning I would suggest Notepad and the command line. While an IDE provides significant productivity enhancements to professionals, it can be intimidating to a beginner. If you want to use an IDE nevertheless I would recommend Visual Studio Express 2013 for Windows Desktop.


Update 2015-07-27: In addition to the Express Editions, Microsoft now offers Community Editions. These are still free for individual developers, open source contributors, and small teams. There are no Web, Windows, and Windows Desktop releases anymore either; the Community Edition can be used to develop any app type. In addition, the Community Edition does support (3rd party) Add-ins. The Community Edition offers the same functionality as the commercial Professional Edition.

React Router Pass Param to Component

If you want to pass props to a component inside a route, the simplest way is by utilizing the render, like this:

<Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />

You can access the props inside the DetailPage using:

this.props.match
this.props.globalStore

The {...props} is needed to pass the original Route's props, otherwise you will only get this.props.globalStore inside the DetailPage.

How do I download a binary file over HTTP?

I had problems, if the file contained German Umlauts (ä,ö,ü). I could solve the problem by using:

ec = Encoding::Converter.new('iso-8859-1', 'utf-8')
...
f << ec.convert(seg)
...

Why do package names often begin with "com"

It's the domain name spelt out in reverse.

For example, one of my domains is hedgee.com. So, I use com.hedgee as the base name of all my packages.

What is parsing in terms that a new programmer would understand?

What is parsing?

In computer science, parsing is the process of analysing text to determine if it belongs to a specific language or not (i.e. is syntactically valid for that language's grammar). It is an informal name for the syntactic analysis process.

For example, suppose the language a^n b^n (which means same number of characters A followed by the same number of characters B). A parser for that language would accept AABB input and reject the AAAB input. That is what a parser does.

In addition, during this process a data structure could be created for further processing. In my previous example, it could, for instance, to store the AA and BB in two separate stacks.

Anything that happens after it, like giving meaning to AA or BB, or transform it in something else, is not parsing. Giving meaning to parts of an input sequence of tokens is called semantic analysis.

What isn't parsing?

  • Parsing is not transform one thing into another. Transforming A into B, is, in essence, what a compiler does. Compiling takes several steps, parsing is only one of them.
  • Parsing is not extracting meaning from a text. That is semantic analysis, a step of the compiling process.

What is the simplest way to understand it?

I think the best way for understanding the parsing concept is to begin with the simpler concepts. The simplest one in language processing subject is the finite automaton. It is a formalism to parsing regular languages, such as regular expressions.

It is very simple, you have an input, a set of states and a set of transitions. Consider the following language built over the alphabet { A, B }, L = { w | w starts with 'AA' or 'BB' as substring }. The automaton below represents a possible parser for that language whose all valid words starts with 'AA' or 'BB'.

    A-->(q1)--A-->(qf)
   /  
 (q0)    
   \          
    B-->(q2)--B-->(qf)

It is a very simple parser for that language. You start at (q0), the initial state, then you read a symbol from the input, if it is A then you move to (q1) state, otherwise (it is a B, remember the remember the alphabet is only A and B) you move to (q2) state and so on. If you reach (qf) state, then the input was accepted.

As it is visual, you only need a pencil and a piece of paper to explain what a parser is to anyone, including a child. I think the simplicity is what makes the automata the most suitable way to teaching language processing concepts, such as parsing.

Finally, being a Computer Science student, you will study such concepts in-deep at theoretical computer science classes such as Formal Languages and Theory of Computation.

How to get file creation date/time in Bash/Debian?

Creation date/time is normally not stored. So no, you can't.

python requests file upload

Client Upload

If you want to upload a single file with Python requests library, then requests lib supports streaming uploads, which allow you to send large files or streams without reading into memory.

with open('massive-body', 'rb') as f:
    requests.post('http://some.url/streamed', data=f)

Server Side

Then store the file on the server.py side such that save the stream into file without loading into the memory. Following is an example with using Flask file uploads.

@app.route("/upload", methods=['POST'])
def upload_file():
    from werkzeug.datastructures import FileStorage
    FileStorage(request.stream).save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return 'OK', 200

Or use werkzeug Form Data Parsing as mentioned in a fix for the issue of "large file uploads eating up memory" in order to avoid using memory inefficiently on large files upload (s.t. 22 GiB file in ~60 seconds. Memory usage is constant at about 13 MiB.).

@app.route("/upload", methods=['POST'])
def upload_file():
    def custom_stream_factory(total_content_length, filename, content_type, content_length=None):
        import tempfile
        tmpfile = tempfile.NamedTemporaryFile('wb+', prefix='flaskapp', suffix='.nc')
        app.logger.info("start receiving file ... filename => " + str(tmpfile.name))
        return tmpfile

    import werkzeug, flask
    stream, form, files = werkzeug.formparser.parse_form_data(flask.request.environ, stream_factory=custom_stream_factory)
    for fil in files.values():
        app.logger.info(" ".join(["saved form name", fil.name, "submitted as", fil.filename, "to temporary file", fil.stream.name]))
        # Do whatever with stored file at `fil.stream.name`
    return 'OK', 200

How to justify a single flexbox item (override justify-content)

For those situations where width of the items you do want to flex-end is known, you can set their flex to "0 0 ##px" and set the item you want to flex-start with flex:1

This will cause the pseudo flex-start item to fill the container, just format it to text-align:left or whatever.

replace special characters in a string python

str.replace is the wrong function for what you want to do (apart from it being used incorrectly). You want to replace any character of a set with a space, not the whole set with a single space (the latter is what replace does). You can use translate like this:

removeSpecialChars = z.translate ({ord(c): " " for c in "!@#$%^&*()[]{};:,./<>?\|`~-=_+"})

This creates a mapping which maps every character in your list of special characters to a space, then calls translate() on the string, replacing every single character in the set of special characters with a space.

Difference between Hive internal tables and external tables?

Hive tables can be created as EXTERNAL or INTERNAL. This is a choice that affects how data is loaded, controlled, and managed.

Use EXTERNAL tables when:

  1. The data is also used outside of Hive. For example, the data files are read and processed by an existing program that doesn't lock the files.
  2. Data needs to remain in the underlying location even after a DROP TABLE. This can apply if you are pointing multiple schemas (tables or views) at a single data set or if you are iterating through various possible schemas.
  3. You want to use a custom location such as ASV.
  4. Hive should not own data and control settings, dirs, etc., you have another program or process that will do those things.
  5. You are not creating table based on existing table (AS SELECT).

Use INTERNAL tables when:

The data is temporary.

You want Hive to completely manage the lifecycle of the table and data.

Changing precision of numeric column in Oracle

Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.

The easiest way to handle this is to rename the column, copy the data over, then drop the original column:

alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;

alter table EVAPP_FEES add AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_OLD;

alter table EVAPP_FEES drop column AMOUNT_OLD;

If you really want to retain the column ordering, you can move the data twice instead:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

How to read an entire file to a string using C#?

you can read a text from a text file in to string as follows also

string str = "";
StreamReader sr = new StreamReader(Application.StartupPath + "\\Sample.txt");
while(sr.Peek() != -1)
{
  str = str + sr.ReadLine();
}

How do you style a TextInput in react native for password input

A little plus:

version = RN 0.57.7

secureTextEntry={true}

does not work when the keyboardType was "phone-pad" or "email-address"