Programs & Examples On #Iui

JavaScript UI framework for developing web applications with iOS-like interface

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

How to Fix Install Failed User Restricted Failure in Android Studio - For Xiaomi Redmi Note 4X (100% worked for me) Settings=>Additional settings=>Developer Options

  1. Mock SD card optimization = OFF
  2. USB debugging = ON
  3. Install via USB = ON
  4. USB debugging (Security settings) = ON
  5. Verify apps over USB = ON
  6. Force-closed apps = ON
  7. Turn on MIUI optimization = OFF

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

If you think a 64-bit DIV instruction is a good way to divide by two, then no wonder the compiler's asm output beat your hand-written code, even with -O0 (compile fast, no extra optimization, and store/reload to memory after/before every C statement so a debugger can modify variables).

See Agner Fog's Optimizing Assembly guide to learn how to write efficient asm. He also has instruction tables and a microarch guide for specific details for specific CPUs. See also the tag wiki for more perf links.

See also this more general question about beating the compiler with hand-written asm: Is inline assembly language slower than native C++ code?. TL:DR: yes if you do it wrong (like this question).

Usually you're fine letting the compiler do its thing, especially if you try to write C++ that can compile efficiently. Also see is assembly faster than compiled languages?. One of the answers links to these neat slides showing how various C compilers optimize some really simple functions with cool tricks. Matt Godbolt's CppCon2017 talk “What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid” is in a similar vein.


even:
    mov rbx, 2
    xor rdx, rdx
    div rbx

On Intel Haswell, div r64 is 36 uops, with a latency of 32-96 cycles, and a throughput of one per 21-74 cycles. (Plus the 2 uops to set up RBX and zero RDX, but out-of-order execution can run those early). High-uop-count instructions like DIV are microcoded, which can also cause front-end bottlenecks. In this case, latency is the most relevant factor because it's part of a loop-carried dependency chain.

shr rax, 1 does the same unsigned division: It's 1 uop, with 1c latency, and can run 2 per clock cycle.

For comparison, 32-bit division is faster, but still horrible vs. shifts. idiv r32 is 9 uops, 22-29c latency, and one per 8-11c throughput on Haswell.


As you can see from looking at gcc's -O0 asm output (Godbolt compiler explorer), it only uses shifts instructions. clang -O0 does compile naively like you thought, even using 64-bit IDIV twice. (When optimizing, compilers do use both outputs of IDIV when the source does a division and modulus with the same operands, if they use IDIV at all)

GCC doesn't have a totally-naive mode; it always transforms through GIMPLE, which means some "optimizations" can't be disabled. This includes recognizing division-by-constant and using shifts (power of 2) or a fixed-point multiplicative inverse (non power of 2) to avoid IDIV (see div_by_13 in the above godbolt link).

gcc -Os (optimize for size) does use IDIV for non-power-of-2 division, unfortunately even in cases where the multiplicative inverse code is only slightly larger but much faster.


Helping the compiler

(summary for this case: use uint64_t n)

First of all, it's only interesting to look at optimized compiler output. (-O3). -O0 speed is basically meaningless.

Look at your asm output (on Godbolt, or see How to remove "noise" from GCC/clang assembly output?). When the compiler doesn't make optimal code in the first place: Writing your C/C++ source in a way that guides the compiler into making better code is usually the best approach. You have to know asm, and know what's efficient, but you apply this knowledge indirectly. Compilers are also a good source of ideas: sometimes clang will do something cool, and you can hand-hold gcc into doing the same thing: see this answer and what I did with the non-unrolled loop in @Veedrac's code below.)

This approach is portable, and in 20 years some future compiler can compile it to whatever is efficient on future hardware (x86 or not), maybe using new ISA extension or auto-vectorizing. Hand-written x86-64 asm from 15 years ago would usually not be optimally tuned for Skylake. e.g. compare&branch macro-fusion didn't exist back then. What's optimal now for hand-crafted asm for one microarchitecture might not be optimal for other current and future CPUs. Comments on @johnfound's answer discuss major differences between AMD Bulldozer and Intel Haswell, which have a big effect on this code. But in theory, g++ -O3 -march=bdver3 and g++ -O3 -march=skylake will do the right thing. (Or -march=native.) Or -mtune=... to just tune, without using instructions that other CPUs might not support.

My feeling is that guiding the compiler to asm that's good for a current CPU you care about shouldn't be a problem for future compilers. They're hopefully better than current compilers at finding ways to transform code, and can find a way that works for future CPUs. Regardless, future x86 probably won't be terrible at anything that's good on current x86, and the future compiler will avoid any asm-specific pitfalls while implementing something like the data movement from your C source, if it doesn't see something better.

Hand-written asm is a black-box for the optimizer, so constant-propagation doesn't work when inlining makes an input a compile-time constant. Other optimizations are also affected. Read https://gcc.gnu.org/wiki/DontUseInlineAsm before using asm. (And avoid MSVC-style inline asm: inputs/outputs have to go through memory which adds overhead.)

In this case: your n has a signed type, and gcc uses the SAR/SHR/ADD sequence that gives the correct rounding. (IDIV and arithmetic-shift "round" differently for negative inputs, see the SAR insn set ref manual entry). (IDK if gcc tried and failed to prove that n can't be negative, or what. Signed-overflow is undefined behaviour, so it should have been able to.)

You should have used uint64_t n, so it can just SHR. And so it's portable to systems where long is only 32-bit (e.g. x86-64 Windows).


BTW, gcc's optimized asm output looks pretty good (using unsigned long n): the inner loop it inlines into main() does this:

 # from gcc5.4 -O3  plus my comments

 # edx= count=1
 # rax= uint64_t n

.L9:                   # do{
    lea    rcx, [rax+1+rax*2]   # rcx = 3*n + 1
    mov    rdi, rax
    shr    rdi         # rdi = n>>1;
    test   al, 1       # set flags based on n%2 (aka n&1)
    mov    rax, rcx
    cmove  rax, rdi    # n= (n%2) ? 3*n+1 : n/2;
    add    edx, 1      # ++count;
    cmp    rax, 1
    jne   .L9          #}while(n!=1)

  cmp/branch to update max and maxi, and then do the next n

The inner loop is branchless, and the critical path of the loop-carried dependency chain is:

  • 3-component LEA (3 cycles)
  • cmov (2 cycles on Haswell, 1c on Broadwell or later).

Total: 5 cycle per iteration, latency bottleneck. Out-of-order execution takes care of everything else in parallel with this (in theory: I haven't tested with perf counters to see if it really runs at 5c/iter).

The FLAGS input of cmov (produced by TEST) is faster to produce than the RAX input (from LEA->MOV), so it's not on the critical path.

Similarly, the MOV->SHR that produces CMOV's RDI input is off the critical path, because it's also faster than the LEA. MOV on IvyBridge and later has zero latency (handled at register-rename time). (It still takes a uop, and a slot in the pipeline, so it's not free, just zero latency). The extra MOV in the LEA dep chain is part of the bottleneck on other CPUs.

The cmp/jne is also not part of the critical path: it's not loop-carried, because control dependencies are handled with branch prediction + speculative execution, unlike data dependencies on the critical path.


Beating the compiler

GCC did a pretty good job here. It could save one code byte by using inc edx instead of add edx, 1, because nobody cares about P4 and its false-dependencies for partial-flag-modifying instructions.

It could also save all the MOV instructions, and the TEST: SHR sets CF= the bit shifted out, so we can use cmovc instead of test / cmovz.

 ### Hand-optimized version of what gcc does
.L9:                       #do{
    lea     rcx, [rax+1+rax*2] # rcx = 3*n + 1
    shr     rax, 1         # n>>=1;    CF = n&1 = n%2
    cmovc   rax, rcx       # n= (n&1) ? 3*n+1 : n/2;
    inc     edx            # ++count;
    cmp     rax, 1
    jne     .L9            #}while(n!=1)

See @johnfound's answer for another clever trick: remove the CMP by branching on SHR's flag result as well as using it for CMOV: zero only if n was 1 (or 0) to start with. (Fun fact: SHR with count != 1 on Nehalem or earlier causes a stall if you read the flag results. That's how they made it single-uop. The shift-by-1 special encoding is fine, though.)

Avoiding MOV doesn't help with the latency at all on Haswell (Can x86's MOV really be "free"? Why can't I reproduce this at all?). It does help significantly on CPUs like Intel pre-IvB, and AMD Bulldozer-family, where MOV is not zero-latency. The compiler's wasted MOV instructions do affect the critical path. BD's complex-LEA and CMOV are both lower latency (2c and 1c respectively), so it's a bigger fraction of the latency. Also, throughput bottlenecks become an issue, because it only has two integer ALU pipes. See @johnfound's answer, where he has timing results from an AMD CPU.

Even on Haswell, this version may help a bit by avoiding some occasional delays where a non-critical uop steals an execution port from one on the critical path, delaying execution by 1 cycle. (This is called a resource conflict). It also saves a register, which may help when doing multiple n values in parallel in an interleaved loop (see below).

LEA's latency depends on the addressing mode, on Intel SnB-family CPUs. 3c for 3 components ([base+idx+const], which takes two separate adds), but only 1c with 2 or fewer components (one add). Some CPUs (like Core2) do even a 3-component LEA in a single cycle, but SnB-family doesn't. Worse, Intel SnB-family standardizes latencies so there are no 2c uops, otherwise 3-component LEA would be only 2c like Bulldozer. (3-component LEA is slower on AMD as well, just not by as much).

So lea rcx, [rax + rax*2] / inc rcx is only 2c latency, faster than lea rcx, [rax + rax*2 + 1], on Intel SnB-family CPUs like Haswell. Break-even on BD, and worse on Core2. It does cost an extra uop, which normally isn't worth it to save 1c latency, but latency is the major bottleneck here and Haswell has a wide enough pipeline to handle the extra uop throughput.

Neither gcc, icc, nor clang (on godbolt) used SHR's CF output, always using an AND or TEST. Silly compilers. :P They're great pieces of complex machinery, but a clever human can often beat them on small-scale problems. (Given thousands to millions of times longer to think about it, of course! Compilers don't use exhaustive algorithms to search for every possible way to do things, because that would take too long when optimizing a lot of inlined code, which is what they do best. They also don't model the pipeline in the target microarchitecture, at least not in the same detail as IACA or other static-analysis tools; they just use some heuristics.)


Simple loop unrolling won't help; this loop bottlenecks on the latency of a loop-carried dependency chain, not on loop overhead / throughput. This means it would do well with hyperthreading (or any other kind of SMT), since the CPU has lots of time to interleave instructions from two threads. This would mean parallelizing the loop in main, but that's fine because each thread can just check a range of n values and produce a pair of integers as a result.

Interleaving by hand within a single thread might be viable, too. Maybe compute the sequence for a pair of numbers in parallel, since each one only takes a couple registers, and they can all update the same max / maxi. This creates more instruction-level parallelism.

The trick is deciding whether to wait until all the n values have reached 1 before getting another pair of starting n values, or whether to break out and get a new start point for just one that reached the end condition, without touching the registers for the other sequence. Probably it's best to keep each chain working on useful data, otherwise you'd have to conditionally increment its counter.


You could maybe even do this with SSE packed-compare stuff to conditionally increment the counter for vector elements where n hadn't reached 1 yet. And then to hide the even longer latency of a SIMD conditional-increment implementation, you'd need to keep more vectors of n values up in the air. Maybe only worth with 256b vector (4x uint64_t).

I think the best strategy to make detection of a 1 "sticky" is to mask the vector of all-ones that you add to increment the counter. So after you've seen a 1 in an element, the increment-vector will have a zero, and +=0 is a no-op.

Untested idea for manual vectorization

# starting with YMM0 = [ n_d, n_c, n_b, n_a ]  (64-bit elements)
# ymm4 = _mm256_set1_epi64x(1):  increment vector
# ymm5 = all-zeros:  count vector

.inner_loop:
    vpaddq    ymm1, ymm0, xmm0
    vpaddq    ymm1, ymm1, xmm0
    vpaddq    ymm1, ymm1, set1_epi64(1)     # ymm1= 3*n + 1.  Maybe could do this more efficiently?

    vprllq    ymm3, ymm0, 63                # shift bit 1 to the sign bit

    vpsrlq    ymm0, ymm0, 1                 # n /= 2

    # FP blend between integer insns may cost extra bypass latency, but integer blends don't have 1 bit controlling a whole qword.
    vpblendvpd ymm0, ymm0, ymm1, ymm3       # variable blend controlled by the sign bit of each 64-bit element.  I might have the source operands backwards, I always have to look this up.

    # ymm0 = updated n  in each element.

    vpcmpeqq ymm1, ymm0, set1_epi64(1)
    vpandn   ymm4, ymm1, ymm4         # zero out elements of ymm4 where the compare was true

    vpaddq   ymm5, ymm5, ymm4         # count++ in elements where n has never been == 1

    vptest   ymm4, ymm4
    jnz  .inner_loop
    # Fall through when all the n values have reached 1 at some point, and our increment vector is all-zero

    vextracti128 ymm0, ymm5, 1
    vpmaxq .... crap this doesn't exist
    # Actually just delay doing a horizontal max until the very very end.  But you need some way to record max and maxi.

You can and should implement this with intrinsics instead of hand-written asm.


Algorithmic / implementation improvement:

Besides just implementing the same logic with more efficient asm, look for ways to simplify the logic, or avoid redundant work. e.g. memoize to detect common endings to sequences. Or even better, look at 8 trailing bits at once (gnasher's answer)

@EOF points out that tzcnt (or bsf) could be used to do multiple n/=2 iterations in one step. That's probably better than SIMD vectorizing; no SSE or AVX instruction can do that. It's still compatible with doing multiple scalar ns in parallel in different integer registers, though.

So the loop might look like this:

goto loop_entry;  // C++ structured like the asm, for illustration only
do {
   n = n*3 + 1;
  loop_entry:
   shift = _tzcnt_u64(n);
   n >>= shift;
   count += shift;
} while(n != 1);

This may do significantly fewer iterations, but variable-count shifts are slow on Intel SnB-family CPUs without BMI2. 3 uops, 2c latency. (They have an input dependency on the FLAGS because count=0 means the flags are unmodified. They handle this as a data dependency, and take multiple uops because a uop can only have 2 inputs (pre-HSW/BDW anyway)). This is the kind that people complaining about x86's crazy-CISC design are referring to. It makes x86 CPUs slower than they would be if the ISA was designed from scratch today, even in a mostly-similar way. (i.e. this is part of the "x86 tax" that costs speed / power.) SHRX/SHLX/SARX (BMI2) are a big win (1 uop / 1c latency).

It also puts tzcnt (3c on Haswell and later) on the critical path, so it significantly lengthens the total latency of the loop-carried dependency chain. It does remove any need for a CMOV, or for preparing a register holding n>>1, though. @Veedrac's answer overcomes all this by deferring the tzcnt/shift for multiple iterations, which is highly effective (see below).

We can safely use BSF or TZCNT interchangeably, because n can never be zero at that point. TZCNT's machine-code decodes as BSF on CPUs that don't support BMI1. (Meaningless prefixes are ignored, so REP BSF runs as BSF).

TZCNT performs much better than BSF on AMD CPUs that support it, so it can be a good idea to use REP BSF, even if you don't care about setting ZF if the input is zero rather than the output. Some compilers do this when you use __builtin_ctzll even with -mno-bmi.

They perform the same on Intel CPUs, so just save the byte if that's all that matters. TZCNT on Intel (pre-Skylake) still has a false-dependency on the supposedly write-only output operand, just like BSF, to support the undocumented behaviour that BSF with input = 0 leaves its destination unmodified. So you need to work around that unless optimizing only for Skylake, so there's nothing to gain from the extra REP byte. (Intel often goes above and beyond what the x86 ISA manual requires, to avoid breaking widely-used code that depends on something it shouldn't, or that is retroactively disallowed. e.g. Windows 9x's assumes no speculative prefetching of TLB entries, which was safe when the code was written, before Intel updated the TLB management rules.)

Anyway, LZCNT/TZCNT on Haswell have the same false dep as POPCNT: see this Q&A. This is why in gcc's asm output for @Veedrac's code, you see it breaking the dep chain with xor-zeroing on the register it's about to use as TZCNT's destination when it doesn't use dst=src. Since TZCNT/LZCNT/POPCNT never leave their destination undefined or unmodified, this false dependency on the output on Intel CPUs is a performance bug / limitation. Presumably it's worth some transistors / power to have them behave like other uops that go to the same execution unit. The only perf upside is interaction with another uarch limitation: they can micro-fuse a memory operand with an indexed addressing mode on Haswell, but on Skylake where Intel removed the false dep for LZCNT/TZCNT they "un-laminate" indexed addressing modes while POPCNT can still micro-fuse any addr mode.


Improvements to ideas / code from other answers:

@hidefromkgb's answer has a nice observation that you're guaranteed to be able to do one right shift after a 3n+1. You can compute this more even more efficiently than just leaving out the checks between steps. The asm implementation in that answer is broken, though (it depends on OF, which is undefined after SHRD with a count > 1), and slow: ROR rdi,2 is faster than SHRD rdi,rdi,2, and using two CMOV instructions on the critical path is slower than an extra TEST that can run in parallel.

I put tidied / improved C (which guides the compiler to produce better asm), and tested+working faster asm (in comments below the C) up on Godbolt: see the link in @hidefromkgb's answer. (This answer hit the 30k char limit from the large Godbolt URLs, but shortlinks can rot and were too long for goo.gl anyway.)

Also improved the output-printing to convert to a string and make one write() instead of writing one char at a time. This minimizes impact on timing the whole program with perf stat ./collatz (to record performance counters), and I de-obfuscated some of the non-critical asm.


@Veedrac's code

I got a minor speedup from right-shifting as much as we know needs doing, and checking to continue the loop. From 7.5s for limit=1e8 down to 7.275s, on Core2Duo (Merom), with an unroll factor of 16.

code + comments on Godbolt. Don't use this version with clang; it does something silly with the defer-loop. Using a tmp counter k and then adding it to count later changes what clang does, but that slightly hurts gcc.

See discussion in comments: Veedrac's code is excellent on CPUs with BMI1 (i.e. not Celeron/Pentium)

Adb install failure: INSTALL_CANCELED_BY_USER

One more thing: after some updates of MIUI developer mode becomes disabled. I was sure, that is was turned on, but i couldn't start the application. So i reenabled developer mode and everything started to work. I've encountered this problem several times. Hope it helps.

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

If you are using get method to fetch the places, you need to enable

Google Places API Web Service

I was facing the same issue and resolved after enabling it.

EDIT: According to https://developers.google.com/places/web-service/get-api-key

Note: The Google Places API Web Service does not work with an Android or iOS restricted API key.

So you have to create new key if or remove restricted access of existing key to work it properly.

How to iterate over columns of pandas dataframe to run regression

This answer is to iterate over selected columns as well as all columns in a DF.

df.columns gives a list containing all the columns' names in the DF. Now that isn't very helpful if you want to iterate over all the columns. But it comes in handy when you want to iterate over columns of your choosing only.

We can use Python's list slicing easily to slice df.columns according to our needs. For eg, to iterate over all columns but the first one, we can do:

for column in df.columns[1:]:
    print(df[column])

Similarly to iterate over all the columns in reversed order, we can do:

for column in df.columns[::-1]:
    print(df[column])

We can iterate over all the columns in a lot of cool ways using this technique. Also remember that you can get the indices of all columns easily using:

for ind, column in enumerate(df.columns):
    print(ind, column)

RSA Public Key format

You can't just change the delimiters from ---- BEGIN SSH2 PUBLIC KEY ---- to -----BEGIN RSA PUBLIC KEY----- and expect that it will be sufficient to convert from one format to another (which is what you've done in your example).

This article has a good explanation about both formats.

What you get in an RSA PUBLIC KEY is closer to the content of a PUBLIC KEY, but you need to offset the start of your ASN.1 structure to reflect the fact that PUBLIC KEY also has an indicator saying which type of key it is (see RFC 3447). You can see this using openssl asn1parse and -strparse 19, as described in this answer.

EDIT: Following your edit, your can get the details of your RSA PUBLIC KEY structure using grep -v -- ----- | tr -d '\n' | base64 -d | openssl asn1parse -inform DER:

    0:d=0  hl=4 l= 266 cons: SEQUENCE          
    4:d=1  hl=4 l= 257 prim: INTEGER           :FB1199FF0733F6E805A4FD3B36CA68E94D7B974621162169C71538A539372E27F3F51DF3B08B2E111C2D6BBF9F5887F13A8DB4F1EB6DFE386C92256875212DDD00468785C18A9C96A292B067DDC71DA0D564000B8BFD80FB14C1B56744A3B5C652E8CA0EF0B6FDA64ABA47E3A4E89423C0212C07E39A5703FD467540F874987B209513429A90B09B049703D54D9A1CFE3E207E0E69785969CA5BF547A36BA34D7C6AEFE79F314E07D9F9F2DD27B72983AC14F1466754CD41262516E4A15AB1CFB622E651D3E83FA095DA630BD6D93E97B0C822A5EB4212D428300278CE6BA0CC7490B854581F0FFB4BA3D4236534DE09459942EF115FAA231B15153D67837A63
  265:d=1  hl=2 l=   3 prim: INTEGER           :010001

To decode the SSH key format, you need to use the data format specification in RFC 4251 too, in conjunction with RFC 4253:

   The "ssh-rsa" key format has the following specific encoding:

      string    "ssh-rsa"
      mpint     e
      mpint     n

For example, at the beginning, you get 00 00 00 07 73 73 68 2d 72 73 61. The first four bytes (00 00 00 07) give you the length. The rest is the string itself: 73=s, 68=h, ... -> 73 73 68 2d 72 73 61=ssh-rsa, followed by the exponent of length 1 (00 00 00 01 25) and the modulus of length 256 (00 00 01 00 7f ...).

Converting a JToken (or string) to a given Type

var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);

throws a parsing exception due to missing quotes around the first argument (I think). I got it to work by adding the quotes:

var i2 = JsonConvert.DeserializeObject("\"" + obj["id"].ToString() + "\"", type);

How can I add a hint text to WPF textbox?

I used the got and lost focus events:

Private Sub txtSearchBox_GotFocus(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles txtSearchBox.GotFocus
    If txtSearchBox.Text = "Search" Then
        txtSearchBox.Text = ""
    Else

    End If

End Sub

Private Sub txtSearchBox_LostFocus(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles txtSearchBox.LostFocus
    If txtSearchBox.Text = "" Then
        txtSearchBox.Text = "Search"
    Else

    End If
End Sub

It works well, but the text is in gray still. Needs cleaning up. I was using VB.NET

Cookie blocked/not saved in IFRAME in Internet Explorer

One possible thing to do is to add the domain to allowed sites in tools -> internet options -> privacy -> sites: somedomain.com -> allow -> OK.

Is Java RegEx case-insensitive?

Yes, case insensitivity can be enabled and disabled at will in Java regex.

It looks like you want something like this:

    System.out.println(
        "Have a meRry MErrY Christmas ho Ho hO"
            .replaceAll("(?i)\\b(\\w+)(\\s+\\1)+\\b", "$1")
    );
    // Have a meRry Christmas ho

Note that the embedded Pattern.CASE_INSENSITIVE flag is (?i) not \?i. Note also that one superfluous \b has been removed from the pattern.

The (?i) is placed at the beginning of the pattern to enable case-insensitivity. In this particular case, it is not overridden later in the pattern, so in effect the whole pattern is case-insensitive.

It is worth noting that in fact you can limit case-insensitivity to only parts of the whole pattern. Thus, the question of where to put it really depends on the specification (although for this particular problem it doesn't matter since \w is case-insensitive.

To demonstrate, here's a similar example of collapsing runs of letters like "AaAaaA" to just "A".

    System.out.println(
        "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
            .replaceAll("(?i)\\b([A-Z])\\1+\\b", "$1")
    ); // A e I O u

Now suppose that we specify that the run should only be collapsed only if it starts with an uppercase letter. Then we must put the (?i) in the appropriate place:

    System.out.println(
        "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
            .replaceAll("\\b([A-Z])(?i)\\1+\\b", "$1")
    ); // A eeEeeE I O uuUuUuu

More generally, you can enable and disable any flag within the pattern as you wish.

See also

Related questions

MVC - Set selected value of SelectList

I ended up here because SelectListItem is no longer picking the selected value correctly. To fix it, I changed the usage of EditorFor for a "manual" approach:

        <select id="Role" class="form-control">
            @foreach (var role in ViewBag.Roles)
            {
                if (Model.Roles.First().RoleId == role.Value)
                {
                    <option value="@role.Value" selected>@role.Text</option>
                }
                else
                {
                    <option value="@role.Value">@role.Text</option>
                }
            }
        </select>

Hope it helps someone.

Calculating a 2D Vector's Cross Product

In short: It's a shorthand notation for a mathematical hack.

Long explanation:

You can't do a cross product with vectors in 2D space. The operation is not defined there.

However, often it is interesting to evaluate the cross product of two vectors assuming that the 2D vectors are extended to 3D by setting their z-coordinate to zero. This is the same as working with 3D vectors on the xy-plane.

If you extend the vectors that way and calculate the cross product of such an extended vector pair you'll notice that only the z-component has a meaningful value: x and y will always be zero.

That's the reason why the z-component of the result is often simply returned as a scalar. This scalar can for example be used to find the winding of three points in 2D space.

From a pure mathematical point of view the cross product in 2D space does not exist, the scalar version is the hack and a 2D cross product that returns a 2D vector makes no sense at all.

Mongodb service won't start

For me, the reason for not starting turned out to be an orphaned lock file at /var/lib/mongo/mongo.lock When I deleted that file, mongo would then start up OK. My system had had some messy crashes prior to this. [Fedora 14]

GIT commit as different user without email / or only email

The

standard A U Thor <[email protected]> format

Seems to be defined as followed: ( as far as i know, with absolutely no warranty )

A U Thor = required username

  • The separation of the characters probably indicates that spaces are allowed, it could also be resembling initials.
  • The username has to be followed by 1 space, extra spaces will be truncated

<[email protected]> = optional email address

  • Must always be between < > signs.
  • The email address format isn't validated, you can pretty much enter whatever you want
  • Optional, you can omit this explicitly by using <>

If you don't use this exact syntax, git will search through the existing commits and use the first commit that contains your provided string.

Examples:

  1. Only user name

    Omit the email address explicitly:

    git commit --author="John Doe <>" -m "Impersonation is evil."
    
  2. Only email

    Technically this isn't possible. You can however enter the email address as the username and explicitly omit the email address. This doesn't seem like it's very useful. I think it would make even more sense to extract the user name from the email address and then use that as the username. But if you have to:

    git commit --author="[email protected] <>" -m "Impersonation is evil." 
    

I ran in to this when trying to convert a repository from mercurial to git. I tested the commands on msysgit 1.7.10.

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I imported the project as general project from git repository.

  • Deleted .settings, .project and .classpath in project's folder
  • Configure -> Convert to Maven Project. Only this solved the problem in my case.

Loop through a comma-separated shell variable

Here is an alternative tr based solution that doesn't use echo, expressed as a one-liner.

for v in $(tr ',' '\n' <<< "$var") ; do something_with "$v" ; done

It feels tidier without echo but that is just my personal preference.

What is a Maven artifact?

In general software terms, an "artifact" is something produced by the software development process, whether it be software related documentation or an executable file.

In Maven terminology, the artifact is the resulting output of the maven build, generally a jar or war or other executable file. Artifacts in maven are identified by a coordinate system of groupId, artifactId, and version. Maven uses the groupId, artifactId, and version to identify dependencies (usually other jar files) needed to build and run your code.

How to get the unique ID of an object which overrides hashCode()?

If it's a class that you can modify, you could declare a class variable static java.util.concurrent.atomic.AtomicInteger nextInstanceId. (You'll have to give it an initial value in the obvious way.) Then declare an instance variable int instanceId = nextInstanceId.getAndIncrement().

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

Strangest language feature

Smalltalk:

Have a class method in a class Test, that returns a constant string:

method1
    ^ 'niko'

You should expect that this method constantly returns the string 'niko' whatever happens. But that is not the case.

s := Test method1 

(Set s to 'niko'.)

s at: 4 put: $i.

(Set s to 'niki'.)

s := Test method1

(Set s to 'niki' again.)

So, what happens is that the second line of code permanently changed method1 to return 'niki' rather than 'niko', even though the source code of the method was not updated.

UIImage: Resize, then Crop

Here is a Swift 3 version of Sam Wirch's guide to swift posted by William T.

extension UIImage {

    static func resizedCroppedImage(image: UIImage, newSize:CGSize) -> UIImage? {
        var ratio: CGFloat = 0
        var delta: CGFloat = 0
        var offset = CGPoint.zero

        if image.size.width > image.size.height {
            ratio = newSize.width / image.size.width
            delta = (ratio * image.size.width) - (ratio * image.size.height)
            offset = CGPoint(x: delta / 2, y: 0)
        } else {
            ratio = newSize.width / image.size.height
            delta = (ratio * image.size.height) - (ratio * image.size.width)
            offset = CGPoint(x: 0, y: delta / 2)
        }

        let clipRect = CGRect(x: -offset.x, y: -offset.y, width: (ratio * image.size.width) + delta, height: (ratio * image.size.height) + delta)
        UIGraphicsBeginImageContextWithOptions(newSize, true, 0.0)
        UIRectClip(clipRect)
        image.draw(in: clipRect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }

}

Combine two tables for one output

You'll need to use UNION to combine the results of two queries. In your case:

SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum

Note - If you use UNION ALL as in above, it's no slower than running the two queries separately as it does no duplicate-checking.

Use Excel pivot table as data source for another Pivot Table

here is how I've done this before.

  1. put a dummy column "X" off to the right of your source pivot table.
  2. click in that cell and start your pivot table.
  3. once the dialogue box pops up you can edit the data range to include your pivot table.
  4. this may require you to Refresh the source table first and then refresh your secondary pivot table...or do refresh all twice

How do I escape a single quote ( ' ) in JavaScript?

Since the values are actually inside of an HTML attribute, you should use &apos;

"<img src='something' onmouseover='change(&apos;ex1&apos;)' />";

Mysql select distinct

DISTINCT is not a function that applies only to some columns. It's a query modifier that applies to all columns in the select-list.

That is, DISTINCT reduces rows only if all columns are identical to the columns of another row.

DISTINCT must follow immediately after SELECT (along with other query modifiers, like SQL_CALC_FOUND_ROWS). Then following the query modifiers, you can list columns.

  • RIGHT: SELECT DISTINCT foo, ticket_id FROM table...

    Output a row for each distinct pairing of values across ticket_id and foo.

  • WRONG: SELECT foo, DISTINCT ticket_id FROM table...

    If there are three distinct values of ticket_id, would this return only three rows? What if there are six distinct values of foo? Which three values of the six possible values of foo should be output?
    It's ambiguous as written.

Safely casting long to int in Java

With Google Guava's Ints class, your method can be changed to:

public static int safeLongToInt(long l) {
    return Ints.checkedCast(l);
}

From the linked docs:

checkedCast

public static int checkedCast(long value)

Returns the int value that is equal to value, if possible.

Parameters: value - any value in the range of the int type

Returns: the int value that equals value

Throws: IllegalArgumentException - if value is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE

Incidentally, you don't need the safeLongToInt wrapper, unless you want to leave it in place for changing out the functionality without extensive refactoring of course.

How can I INSERT data into two tables simultaneously in SQL Server?

You could write a stored procedure that iterates over the transaction that you have proposed. The iterator would be the cursor for the table that contains the source data.

Spin or rotate an image on hover

if you want to rotate inline elements, you should set the inline element to inline-block first.

i {
  display: inline-block;
}

i:hover {
  animation: rotate-btn .5s linear 3;
  -webkit-animation: rotate-btn .5s linear 3;
}

@keyframes rotate-btn {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(-360deg);
  }
}

Is Fortran easier to optimize than C for heavy calculations?

The faster code is not really up to the language, is the compiler so you can see the ms-vb "compiler" that generates bloated, slower and redundant object code that is tied together inside an ".exe", but powerBasic generates too way better code. Object code made by a C and C++ compilers is generated in some phases (at least 2) but by design most Fortran compilers have at least 5 phases including high-level optimizations so by design Fortran will always have the capability to generate highly optimized code. So at the end is the compiler not the language you should ask for, the best compiler i know is the Intel Fortran Compiler because you can get it on LINUX and Windows and you can use VS as the IDE, if you're looking for a cheap tigh compiler you can always relay on OpenWatcom.

More info about this: http://ed-thelen.org/1401Project/1401-IBM-Systems-Journal-FORTRAN.html

Linq on DataTable: select specific column into datatable, not whole table

Here I get only three specific columns from mainDataTable and use the filter

DataTable checkedParams = mainDataTable.Select("checked = true").CopyToDataTable()
.DefaultView.ToTable(false, "lagerID", "reservePeriod", "discount");

INSERT VALUES WHERE NOT EXISTS

You could do this using an IF statement:

IF NOT EXISTS 
    (   SELECT  1
        FROM    tblSoftwareTitles 
        WHERE   Softwarename = @SoftwareName 
        AND     SoftwareSystemType = @Softwaretype
    )
    BEGIN
        INSERT tblSoftwareTitles (SoftwareName, SoftwareSystemType) 
        VALUES (@SoftwareName, @SoftwareType) 
    END;

You could do it without IF using SELECT

INSERT  tblSoftwareTitles (SoftwareName, SoftwareSystemType) 
SELECT  @SoftwareName,@SoftwareType
WHERE   NOT EXISTS 
        (   SELECT  1
            FROM    tblSoftwareTitles 
            WHERE   Softwarename = @SoftwareName 
            AND     SoftwareSystemType = @Softwaretype
        );

Both methods are susceptible to a race condition, so while I would still use one of the above to insert, but you can safeguard duplicate inserts with a unique constraint:

CREATE UNIQUE NONCLUSTERED INDEX UQ_tblSoftwareTitles_Softwarename_SoftwareSystemType
    ON tblSoftwareTitles (SoftwareName, SoftwareSystemType);

Example on SQL-Fiddle


ADDENDUM

In SQL Server 2008 or later you can use MERGE with HOLDLOCK to remove the chance of a race condition (which is still not a substitute for a unique constraint).

MERGE tblSoftwareTitles WITH (HOLDLOCK) AS t
USING (VALUES (@SoftwareName, @SoftwareType)) AS s (SoftwareName, SoftwareSystemType) 
    ON s.Softwarename = t.SoftwareName 
    AND s.SoftwareSystemType = t.SoftwareSystemType
WHEN NOT MATCHED BY TARGET THEN 
    INSERT (SoftwareName, SoftwareSystemType) 
    VALUES (s.SoftwareName, s.SoftwareSystemType);

Example of Merge on SQL Fiddle

How to add a jar in External Libraries in android studio

The GUI based approach would be to add an additional module in your project.

  1. From the File menu select Project Structure and click on the green plus icon on the top left.
  2. The new Module dialog pops
  3. From the phone and tablet application group select the "Import JAR or AAR package" option and click next.
  4. Follow the steps to create a new module that contains your JAR file.
  5. Click on the entry that corresponds to your main project and select the dependencies tab.
  6. Add a dependency to the module that you created in step 4.

One final piece of advice. Make sure that the JAR file you include is build with at most JDK 1.7. Many problems relating to error message "com.android.dx.cf.iface.ParseException: bad class file magic (cafebabe) or version (0034.0000)" root straight to this :0.

Can't find @Nullable inside javax.annotation.*

JSR-305 is a "Java Specification Request" to extend the specification. @Nullable etc. were part of it; however it appears to be "dormant" (or frozen) ever since (See this SO question). So to use these annotations, you have to add the library yourself.

FindBugs was renamed to SpotBugs and is being developed under that name.

For maven this is the current annotation-only dependency (other integrations here):

<dependency>
  <groupId>com.github.spotbugs</groupId>
  <artifactId>spotbugs-annotations</artifactId>
  <version>4.2.0</version>
</dependency>

If you wish to use the full plugin, refer to the documentation of SpotBugs.

this in equals method

this refers to the current instance of the class (object) your equals-method belongs to. When you test this against an object, the testing method (which is equals(Object obj) in your case) will check wether or not the object is equal to the current instance (referred to as this).

An example:

Object obj = this; this.equals(obj); //true   Object obj = this; new Object().equals(obj); //false 

jQuery Change event on an <input> element - any way to retain previous value?

In Russ answer he binds the focus event. I don't think it is necessary.

You can store the old value in the change event.

<script>
    $(document).ready(function(){

        var newValue = $('#myInputElement').val();
        var oldValue;

        $('#myInputElement').change(function(){
            oldValue = newValue;
            newValue = $(this).val();
        });
    });
</script>
<input id="myInputElement" type="text">

Set cURL to use local virtual hosts

Making a request to

C:\wnmp\curl>curl.exe --trace-ascii -H 'project1.loc' -d "uuid=d99a49d846d5ae570
667a00825373a7b5ae8e8e2" http://project1.loc/Users/getSettings.xml

Resulted in the -H log file containing:

== Info: Could not resolve host: 'project1.loc'; Host not found
== Info: Closing connection #0
== Info: About to connect() to project1.loc port 80 (#0)
== Info:   Trying 127.0.0.1... == Info: connected
== Info: Connected to project1.loc (127.0.0.1) port 80 (#0)
=> Send header, 230 bytes (0xe6)
0000: POST /Users/getSettings.xml HTTP/1.1
0026: User-Agent: curl/7.19.5 (i586-pc-mingw32msvc) libcurl/7.19.5 Ope
0066: nSSL/1.0.0a zlib/1.2.3
007e: Host: project1.loc
0092: Accept: */*
009f: Content-Length: 45
00b3: Content-Type: application/x-www-form-urlencoded
00e4: 
=> Send data, 45 bytes (0x2d)
0000: uuid=d99a49d846d5ae570667a00825373a7b5ae8e8e2
<= Recv header, 24 bytes (0x18)
0000: HTTP/1.1 403 Forbidden
<= Recv header, 22 bytes (0x16)
0000: Server: nginx/0.7.66
<= Recv header, 37 bytes (0x25)
0000: Date: Wed, 11 Aug 2010 15:37:06 GMT
<= Recv header, 25 bytes (0x19)
0000: Content-Type: text/html
<= Recv header, 28 bytes (0x1c)
0000: Transfer-Encoding: chunked
<= Recv header, 24 bytes (0x18)
0000: Connection: keep-alive
<= Recv header, 25 bytes (0x19)
0000: X-Powered-By: PHP/5.3.2
<= Recv header, 56 bytes (0x38)
0000: Set-Cookie: SESSION=m9j6caghb223uubiddolec2005; path=/
<= Recv header, 57 bytes (0x39)
0000: P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"
<= Recv header, 2 bytes (0x2)
0000: 
<= Recv data, 118 bytes (0x76)
0000: 6b
0004: <html><head><title>HTTP/1.1 403 Forbidden</title></head><body><h
0044: 1>HTTP/1.1 403 Forbidden</h1></body></html>
0071: 0
0074: 
== Info: Connection #0 to host project1.loc left intact
== Info: Closing connection #0

My hosts file looks like:

# Copyright (c) 1993-1999 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

127.0.0.1       localhost
...
...
127.0.0.1   project1.loc

CORS header 'Access-Control-Allow-Origin' missing

You have to modify your server side code, as given below

public class CorsResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext,   ContainerResponseContext responseContext)
    throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

  }
}

Creating columns in listView and add items

I didn't see anyone answer this correctly. So I'm posting it here. In order to get columns to show up you need to specify the following line.

lvRegAnimals.View = View.Details;

And then add your columns after that.

lvRegAnimals.Columns.Add("Id", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);

Hope this helps anyone else looking for this answer in the future.

How to pass arguments from command line to gradle

There's a great example here:

https://kb.novaordis.com/index.php/Gradle_Pass_Configuration_on_Command_Line

Which details that you can pass parameters and then provide a default in an ext variable like so:

gradle -Dmy_app.color=blue

and then reference in Gradle as:

ext {
   color = System.getProperty("my_app.color", "red");
}

And then anywhere in your build script you can reference it as course anywhere you can reference it as project.ext.color

More tips here: https://kb.novaordis.com/index.php/Gradle_Variables_and_Properties

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

Nesting CSS classes

I do not believe this is possible. You could add class1 to all elements which also have class2. If this is not practical to do manually, you could do it automatically with JavaScript (fairly easy to do with jQuery).

CSS transition effect makes image blurry / moves image 1px, in Chrome?

I've tried around 10 possibly solutions. Mixed them up and they still didn't work correctly. There was always 1px shake at the end.

I find solution by reducing transition time on filter.

This didn't work:

.elem {
  filter: blur(0);
  transition: filter 1.2s ease;
}
.elem:hover {
  filter: blur(7px);
}

Solution:

.elem {
  filter: blur(0);
  transition: filter .7s ease;
}
.elem:hover {
  filter: blur(7px);
}

Try this in fiddle:

_x000D_
_x000D_
.blur {_x000D_
  border: none;_x000D_
  outline: none;_x000D_
  width: 100px; height: 100px;_x000D_
  background: #f0f;_x000D_
  margin: 30px;_x000D_
  -webkit-filter: blur(10px);_x000D_
  transition: all .7s ease-out;_x000D_
  /* transition: all .2s ease-out; */_x000D_
}_x000D_
.blur:hover {_x000D_
  -webkit-filter: blur(0);_x000D_
}_x000D_
_x000D_
.blur2 {_x000D_
  border: none;_x000D_
  outline: none;_x000D_
  width: 100px; height: 100px;_x000D_
  background: tomato;_x000D_
  margin: 30px;_x000D_
  -webkit-filter: blur(10px);_x000D_
  transition: all .2s ease-out;_x000D_
}_x000D_
.blur2:hover {_x000D_
  -webkit-filter: blur(0);_x000D_
}
_x000D_
<div class="blur"></div>_x000D_
_x000D_
<div class="blur2"></div>
_x000D_
_x000D_
_x000D_

I hope this helps someone.

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

Add these two lines to your build.gradle in the android section:

android{
    compileOptions {
            sourceCompatibility 1.8
            targetCompatibility 1.8
        }
}

Displaying a message in iOS which has the same functionality as Toast in Android

Swift Implementation of Android Toast using Alert which dissipate after 3 secs.

    func showAlertView(title: String?, message: String?) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    let okAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
    alertController.addAction(okAction)
    self.presentViewController(alertController, animated: true, completion: nil)


    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * Double(NSEC_PER_SEC)))
    dispatch_after(delayTime, dispatch_get_main_queue()) {
        print("Bye. Lovvy")
        alertController.dismissViewControllerAnimated(true, completion: nil)
    }
}

To Call it simply :

self.showAlertView("Message sent...", message: nil)

How to Convert date into MM/DD/YY format in C#

Look into using the ToString() method with a specified format.

Vuejs: Event on route change

Another solution for typescript user:

import Vue from "vue";
import Component from "vue-class-component";

@Component({
  beforeRouteLeave(to, from, next) {
    // incase if you want to access `this`
    // const self = this as any;
    next();
  }
})

export default class ComponentName extends Vue {}

Swift Error: Editor placeholder in source file

Sometimes, XCode does not forget the line which had an "Editor Placeholder" even if you have replaced it with a value. Cut the portion of the code where XCode is complaining and paste the code back to the same place to make the error message go away. This worked for me.

Rename multiple columns by names

This would change all the occurrences of those letters in all names:

 names(x) <- gsub("q", "A", gsub("e", "B", names(x) ) )

How to add a downloaded .box file to Vagrant?

Try to change directory to where the .box is saved

Run vagrant box add my-box downloaded.box, this may work as it avoids absolute path (on Windows?).

npm notice created a lockfile as package-lock.json. You should commit this file

If this is output from a Dockerfile then you don't want / need to commit it.

However you will want to tag the base image and any other contributing images / applications.

E.g.

FROM node:12.18.1

Where can I get Google developer key

tl;dr

Developer Key = Api Key (any of yours)

find it in Google Console -> Google API -> Credentials

Gather multiple sets of columns

In case you are like me, and cannot work out how to use "regular expression with capturing groups" for extract, the following code replicates the extract(...) line in Hadleys' answer:

df %>% 
    gather(question_number, value, starts_with("Q3.")) %>%
    mutate(loop_number = str_sub(question_number,-2,-2), question_number = str_sub(question_number,1,4)) %>%
    select(id, time, loop_number, question_number, value) %>% 
    spread(key = question_number, value = value)

The problem here is that the initial gather forms a key column that is actually a combination of two keys. I chose to use mutate in my original solution in the comments to split this column into two columns with equivalent info, a loop_number column and a question_number column. spread can then be used to transform the long form data, which are key value pairs (question_number, value) to wide form data.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

@OneToMany(mappedBy = 'parent', cascade= CascadeType.ALL, orphanRemoval = true)
List<Child> children = new ArrayList<>();

I experienced the same error when I was adding child object to the existing list of Child Objects.

childService.saveOrUpdate(child);
parent.addToChildren(child);
parentService.saveOrUpdate(parent);

What resolved my problem is changing to:

child = childService.saveOrUpdate(child);

Now the child is revive with other details as well and it worked fine.

Java Mouse Event Right Click

Yes, take a look at this thread which talks about the differences between platforms.

How to detect right-click event for Mac OS

BUTTON3 is the same across all platforms, being equal to the right mouse button. BUTTON2 is simply ignored if the middle button does not exist.

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

How to make <div> fill <td> height

This questions is already answered here. Just put height: 100% in both the div and the container td.

Can I set max_retries for requests.request?

Be careful, Martijn Pieters's answer isn't suitable for version 1.2.1+. You can't set it globally without patching the library.

You can do this instead:

import requests
from requests.adapters import HTTPAdapter

s = requests.Session()
s.mount('http://www.github.com', HTTPAdapter(max_retries=5))
s.mount('https://www.github.com', HTTPAdapter(max_retries=5))

Convert a String In C++ To Upper Case

#include <algorithm>
#include <string>

std::string str = "Hello World";
std::transform(str.begin(), str.end(),str.begin(), ::toupper);

ERROR 1064 (42000) in MySQL

Check your dump file. Looks like a stray character at the beginning. SQL isn't standard the world around, and the MySQL importer expects MySQL-friendly SQL. I'm willing to bet that your exporter did something funky.

You may have to massage the file a bit to get it to work with MySQL.

How do you read scanf until EOF in C?

For C users, this will also work

while ( gets(str) != NULL )

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Add in your POM:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.junit</groupId>
            <artifactId>junit-bom</artifactId>
            <version>5.3.1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

How to make a promise from setTimeout

Update (2017)

Here in 2017, Promises are built into JavaScript, they were added by the ES2015 spec (polyfills are available for outdated environments like IE8-IE11). The syntax they went with uses a callback you pass into the Promise constructor (the Promise executor) which receives the functions for resolving/rejecting the promise as arguments.

First, since async now has a meaning in JavaScript (even though it's only a keyword in certain contexts), I'm going to use later as the name of the function to avoid confusion.

Basic Delay

Using native promises (or a faithful polyfill) it would look like this:

function later(delay) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay);
    });
}

Note that that assumes a version of setTimeout that's compliant with the definition for browsers where setTimeout doesn't pass any arguments to the callback unless you give them after the interval (this may not be true in non-browser environments, and didn't used to be true on Firefox, but is now; it's true on Chrome and even back on IE8).

Basic Delay with Value

If you want your function to optionally pass a resolution value, on any vaguely-modern browser that allows you to give extra arguments to setTimeout after the delay and then passes those to the callback when called, you can do this (current Firefox and Chrome; IE11+, presumably Edge; not IE8 or IE9, no idea about IE10):

function later(delay, value) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay, value); // Note the order, `delay` before `value`
        /* Or for outdated browsers that don't support doing that:
        setTimeout(function() {
            resolve(value);
        }, delay);
        Or alternately:
        setTimeout(resolve.bind(null, value), delay);
        */
    });
}

If you're using ES2015+ arrow functions, that can be more concise:

function later(delay, value) {
    return new Promise(resolve => setTimeout(resolve, delay, value));
}

or even

const later = (delay, value) =>
    new Promise(resolve => setTimeout(resolve, delay, value));

Cancellable Delay with Value

If you want to make it possible to cancel the timeout, you can't just return a promise from later, because promises can't be cancelled.

But we can easily return an object with a cancel method and an accessor for the promise, and reject the promise on cancel:

const later = (delay, value) => {
    let timer = 0;
    let reject = null;
    const promise = new Promise((resolve, _reject) => {
        reject = _reject;
        timer = setTimeout(resolve, delay, value);
    });
    return {
        get promise() { return promise; },
        cancel() {
            if (timer) {
                clearTimeout(timer);
                timer = 0;
                reject();
                reject = null;
            }
        }
    };
};

Live Example:

_x000D_
_x000D_
const later = (delay, value) => {_x000D_
    let timer = 0;_x000D_
    let reject = null;_x000D_
    const promise = new Promise((resolve, _reject) => {_x000D_
        reject = _reject;_x000D_
        timer = setTimeout(resolve, delay, value);_x000D_
    });_x000D_
    return {_x000D_
        get promise() { return promise; },_x000D_
        cancel() {_x000D_
            if (timer) {_x000D_
                clearTimeout(timer);_x000D_
                timer = 0;_x000D_
                reject();_x000D_
                reject = null;_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
};_x000D_
_x000D_
const l1 = later(100, "l1");_x000D_
l1.promise_x000D_
  .then(msg => { console.log(msg); })_x000D_
  .catch(() => { console.log("l1 cancelled"); });_x000D_
_x000D_
const l2 = later(200, "l2");_x000D_
l2.promise_x000D_
  .then(msg => { console.log(msg); })_x000D_
  .catch(() => { console.log("l2 cancelled"); });_x000D_
setTimeout(() => {_x000D_
  l2.cancel();_x000D_
}, 150);
_x000D_
_x000D_
_x000D_


Original Answer from 2014

Usually you'll have a promise library (one you write yourself, or one of the several out there). That library will usually have an object that you can create and later "resolve," and that object will have a "promise" you can get from it.

Then later would tend to look something like this:

function later() {
    var p = new PromiseThingy();
    setTimeout(function() {
        p.resolve();
    }, 2000);

    return p.promise(); // Note we're not returning `p` directly
}

In a comment on the question, I asked:

Are you trying to create your own promise library?

and you said

I wasn't but I guess now that's actually what I was trying to understand. That how a library would do it

To aid that understanding, here's a very very basic example, which isn't remotely Promises-A compliant: Live Copy

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Very basic promises</title>
</head>
<body>
  <script>
    (function() {

      // ==== Very basic promise implementation, not remotely Promises-A compliant, just a very basic example
      var PromiseThingy = (function() {

        // Internal - trigger a callback
        function triggerCallback(callback, promise) {
          try {
            callback(promise.resolvedValue);
          }
          catch (e) {
          }
        }

        // The internal promise constructor, we don't share this
        function Promise() {
          this.callbacks = [];
        }

        // Register a 'then' callback
        Promise.prototype.then = function(callback) {
          var thispromise = this;

          if (!this.resolved) {
            // Not resolved yet, remember the callback
            this.callbacks.push(callback);
          }
          else {
            // Resolved; trigger callback right away, but always async
            setTimeout(function() {
              triggerCallback(callback, thispromise);
            }, 0);
          }
          return this;
        };

        // Our public constructor for PromiseThingys
        function PromiseThingy() {
          this.p = new Promise();
        }

        // Resolve our underlying promise
        PromiseThingy.prototype.resolve = function(value) {
          var n;

          if (!this.p.resolved) {
            this.p.resolved = true;
            this.p.resolvedValue = value;
            for (n = 0; n < this.p.callbacks.length; ++n) {
              triggerCallback(this.p.callbacks[n], this.p);
            }
          }
        };

        // Get our underlying promise
        PromiseThingy.prototype.promise = function() {
          return this.p;
        };

        // Export public
        return PromiseThingy;
      })();

      // ==== Using it

      function later() {
        var p = new PromiseThingy();
        setTimeout(function() {
          p.resolve();
        }, 2000);

        return p.promise(); // Note we're not returning `p` directly
      }

      display("Start " + Date.now());
      later().then(function() {
        display("Done1 " + Date.now());
      }).then(function() {
        display("Done2 " + Date.now());
      });

      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>

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

It's already answered here -> Is my virtual environment (python) causing my PYTHONPATH to break?

UNIX/LINUX

Add "export PYTHONPATH=/usr/local/lib/python2.0" this to ~/.bashrc file and source it by typing "source ~/.bashrc" OR ". ~/.bashrc".

WINDOWS XP

1) Go to the Control panel 2) Double click System 3) Go to the Advanced tab 4) Click on Environment Variables

In the System Variables window, check if you have a variable named PYTHONPATH. If you have one already, check that it points to the right directories. If you don't have one already, click the New button and create it.

PYTHON CODE

Alternatively, you can also do below your code:-

import sys
sys.path.append("/home/me/mypy") 

Cut Corners using CSS

If you need a diagonal border instead of a diagonal corner, you can stack 2 divs with each a pseudo element:

DEMO

http://codepen.io/remcokalf/pen/BNxLMJ

_x000D_
_x000D_
.container {_x000D_
  padding: 100px 200px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
div.diagonal {_x000D_
  background: #da1d00;_x000D_
  color: #fff;_x000D_
  font-family: Arial, Helvetica, sans-serif;_x000D_
  width: 300px;_x000D_
  height: 300px;_x000D_
  padding: 70px;_x000D_
  position: relative;_x000D_
  margin: 30px;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
div.diagonal2 {_x000D_
  background: #da1d00;_x000D_
  color: #fff;_x000D_
  font-family: Arial, Helvetica, sans-serif;_x000D_
  width: 300px;_x000D_
  height: 300px;_x000D_
  padding: 70px;_x000D_
  position: relative;_x000D_
  margin: 30px;_x000D_
  background: #da1d00 url(http://www.remcokalf.nl/background.jpg) left top;_x000D_
  background-size: cover;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
div.diagonal3 {_x000D_
  background: #da1d00;_x000D_
  color: #da1d00;_x000D_
  font-family: Arial, Helvetica, sans-serif;_x000D_
  width: 432px;_x000D_
  height: 432px;_x000D_
  padding: 4px;_x000D_
  position: relative;_x000D_
  margin: 30px;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
div.inside {_x000D_
  background: #fff;_x000D_
  color: #da1d00;_x000D_
  font-family: Arial, Helvetica, sans-serif;_x000D_
  width: 292px;_x000D_
  height: 292px;_x000D_
  padding: 70px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
div.diagonal:before,_x000D_
div.diagonal2:before {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  border-top: 80px solid #fff;_x000D_
  border-right: 80px solid transparent;_x000D_
  width: 0;_x000D_
}_x000D_
_x000D_
div.diagonal3:before {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  border-top: 80px solid #da1d00;_x000D_
  border-right: 80px solid transparent;_x000D_
  width: 0;_x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
div.inside:before {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  top: -4px;_x000D_
  left: -4px;_x000D_
  border-top: 74px solid #fff;_x000D_
  border-right: 74px solid transparent;_x000D_
  width: 0;_x000D_
  z-index: 2;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  font-size: 30px;_x000D_
  line-height: 1.3em;_x000D_
  margin-bottom: 1em;_x000D_
  position: relative;_x000D_
  z-index: 1000;_x000D_
}_x000D_
_x000D_
p {_x000D_
  font-size: 16px;_x000D_
  line-height: 1.6em;_x000D_
  margin-bottom: 1.8em;_x000D_
}_x000D_
_x000D_
#grey {_x000D_
  width: 100%;_x000D_
  height: 400px;_x000D_
  background: #ccc;_x000D_
  position: relative;_x000D_
  margin-top: 100px;_x000D_
}_x000D_
_x000D_
#grey:before {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  border-top: 80px solid #fff;_x000D_
  border-right: 80px solid #ccc;_x000D_
  width: 400px;_x000D_
}
_x000D_
<div id="grey"></div>_x000D_
<div class="container">_x000D_
  <div class="diagonal">_x000D_
    <h2>Header title</h2>_x000D_
    <p>Yes a CSS diagonal corner is possible</p>_x000D_
  </div>_x000D_
  <div class="diagonal2">_x000D_
    <h2>Header title</h2>_x000D_
    <p>Yes a CSS diagonal corner with background image is possible</p>_x000D_
  </div>_x000D_
  <div class="diagonal3">_x000D_
    <div class="inside">_x000D_
      <h2>Header title</h2>_x000D_
      <p>Yes a CSS diagonal border is even possible with an extra div</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

AWS EFS vs EBS vs S3 (differences & when to use?)

AWS EFS, EBS and S3. From Functional Standpoint, here is the difference

EFS:

  1. Network filesystem :can be shared across several Servers; even between regions. The same is not available for EBS case. This can be used esp for storing the ETL programs without the risk of security

  2. Highly available, scalable service.

  3. Running any application that has a high workload, requires scalable storage, and must produce output quickly.

  4. It can provide higher throughput. It match sudden file system growth, even for workloads up to 500,000 IOPS or 10 GB per second.

  5. Lift-and-shift application support: EFS is elastic, available, and scalable, and enables you to move enterprise applications easily and quickly without needing to re-architect them.

  6. Analytics for big data: It has the ability to run big data applications, which demand significant node throughput, low-latency file access, and read-after-write operations.

EBS:

  1. for NoSQL databases, EBS offers NoSQL databases the low-latency performance and dependability they need for peak performance.

S3:

Robust performance, scalability, and availability: Amazon S3 scales storage resources free from resource procurement cycles or investments upfront.

2)Data lake and big data analytics: Create a data lake to hold raw data in its native format, then using machine learning tools, analytics to draw insights.

  1. Backup and restoration: Secure, robust backup and restoration solutions
  2. Data archiving
  3. S3 is an object store good at storing vast numbers of backups or user files. Unlike EBS or EFS, S3 is not limited to EC2. Files stored within an S3 bucket can be accessed programmatically or directly from services such as AWS CloudFront. Many websites use it to hold their content and media files, which may be served efficiently via AWS CloudFront.

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

This message means that for some reason the garbage collector is taking an excessive amount of time (by default 98% of all CPU time of the process) and recovers very little memory in each run (by default 2% of the heap).

This effectively means that your program stops doing any progress and is busy running only the garbage collection at all time.

To prevent your application from soaking up CPU time without getting anything done, the JVM throws this Error so that you have a chance of diagnosing the problem.

The rare cases where I've seen this happen is where some code was creating tons of temporary objects and tons of weakly-referenced objects in an already very memory-constrained environment.

Check out the Java GC tuning guide, which is available for various Java versions and contains sections about this specific problem:

Bad Gateway 502 error with Apache mod_proxy and Tomcat

Most likely you should increase Timeout parameter in apache conf (default value 120 sec)

How to round a number to significant figures in Python

Using python 2.6+ new-style formatting (as %-style is deprecated):

>>> "{0}".format(float("{0:.1g}".format(1216)))
'1000.0'
>>> "{0}".format(float("{0:.1g}".format(0.00356)))
'0.004'

In python 2.7+ you can omit the leading 0s.

What is a daemon thread in Java?

Daemon threads are threads that run in the background as long as other non-daemon threads of the process are still running. Thus, when all of the non-daemon threads complete, the daemon threads are terminated. An example for the non-daemon thread is the thread running the Main. A thread is made daemon by calling the setDaemon() method before the thread is started

For More Reference : Daemon thread in Java

Link entire table row?

Example: http://xxjjnn.com/linktablerow.html

Link entire row:

<table>
  <tr onclick="location.href='SomeWherrrreOverTheWebsiiiite.html'">**
    <td> ...content... </td>
    <td> ...content... </td>
    ...
  </tr>
</table>

Iff you'd like to do highlight on mouseover for the entire row, then:

<table class="nogap">
  <tr class="lovelyrow" onclick="location.href='SomeWherrrreOverTheWebsiiiite.html'">**
     ...
  </tr>
</table>

with something like the following for css, which will remove the gap between the table cells and change the background on hover:

tr.lovelyrow{
  background-color: hsl(0,0%,90%);
}

tr.lovelyrow:hover{
  background-color: hsl(0,0%,40%);
  cursor: pointer;
}

table.nogap{
  border-collapse: collapse;
}

Iff you are using Rails 3.0.9 then you might find this example code useful:

Sea has many Fish, Fish has many Scales, here is snippet of app/view/fish/index.erb

<table>
<% @fishies.each do |fish| %>
  <tr onclick="location.href='<%= sea_fish_scales_path(@sea, fish) %>'"> 
    <td><%= fish.title %></td>
  </tr>
<% end %>
</table>

with @fishies and @sea are defined in app/controllers/seas_controller.rb

How do I use CSS with a ruby on rails application?

If you are using rails > 3 version, then there is a concept called asset pipeline. You could add your CSS to

app/assets/stylesheets

then it will automatically be picked up by the app. (this is useful as rails will automatically compress the CSS files)

read more here about the asset pipeline

Sites not accepting wget user agent header

You need to set both the user-agent and the referer:

 wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" --referrer  connect.wso2.com http://dist.wso2.org/products/carbon/4.2.0/wso2carbon-4.2.0.zip

Socket.IO handling disconnect event

For those like @sha1 wondering why the OP's code doesn't work -

OP's logic for deleting player at server side is in the handler for DelPlayer event, and the code that emits this event (DelPlayer) is in inside disconnected event callback of client.

The server side code that emits this disconnected event is inside the disconnect event callback which is fired when the socket loses connection. Since the socket already lost connection, disconnected event doesn't reach the client.


Accepted solution executes the logic on disconnect event at server side, which is fired when the socket disconnects, hence works.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

128M == 134217728, the number you are seeing.

The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.

Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.

UTF-8 problems while reading CSV file with fgetcsv

In my case the source file has windows-1250 encoding and iconv prints tons of notices about illegal characters in input string...

So this solution helped me a lot:

/**
 * getting CSV array with UTF-8 encoding
 *
 * @param   resource    &$handle
 * @param   integer     $length
 * @param   string      $separator
 *
 * @return  array|false
 */
private function fgetcsvUTF8(&$handle, $length, $separator = ';')
{
    if (($buffer = fgets($handle, $length)) !== false)
    {
        $buffer = $this->autoUTF($buffer);
        return str_getcsv($buffer, $separator);
    }
    return false;
}

/**
 * automatic convertion windows-1250 and iso-8859-2 info utf-8 string
 *
 * @param   string  $s
 *
 * @return  string
 */
private function autoUTF($s)
{
    // detect UTF-8
    if (preg_match('#[\x80-\x{1FF}\x{2000}-\x{3FFF}]#u', $s))
        return $s;

    // detect WINDOWS-1250
    if (preg_match('#[\x7F-\x9F\xBC]#', $s))
        return iconv('WINDOWS-1250', 'UTF-8', $s);

    // assume ISO-8859-2
    return iconv('ISO-8859-2', 'UTF-8', $s);
}

Response to @manvel's answer - use str_getcsv instead of explode - because of cases like this:

some;nice;value;"and;here;comes;combinated;value";and;some;others

explode will explode string into parts:

some
nice
value
"and
here
comes
combinated
value"
and
some
others

but str_getcsv will explode string into parts:

some
nice
value
and;here;comes;combinated;value
and
some
others

JQuery select2 set default value from an option in list?

One more way - just add a selected = "selected" attribute to the select markup and call select2 on it. It must take your selected value. No need for extra JavaScript. Like this :

Markup

<select class="select2">
   <option id="foo">Some Text</option>
   <option id="bar" selected="selected">Other Text</option>
</select>

JavaScript

$('select').select2(); //oh yes just this!

See fiddle : http://jsfiddle.net/6hZFU/

Edit: (Thanks, Jay Haase!)

If this doesn't work, try setting the val property of select2 to null, to clear the value, like this:

$('select').select2("val", null); //a lil' bit more :)

After this, it is simple enough to set val to "Whatever You Want".

How do I return multiple values from a function?

I prefer:

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

It seems everything else is just extra code to do the same thing.

Only on Firefox "Loading failed for the <script> with source"

I noticed that in Firefox this can happen when requests are aborted (switching page or quickly refreshing page), but it is hard to reproduce the error even if I try to.

Other possible reasons: cert related issues and this one talks about blockers (as other answers stated).

Using pip behind a proxy with CNTLM

  1. For PIP Installation:
ex:PORT = 9090
ex:PROXY_SERVER = stackoverflow
USERNAME:your user id
PASSWORD: your password

sudo pip2 install PACKAGENAME --proxy https://USERNAME:PASSWORD@PROXY_SERVER:PORT/ for Python2.7

sudo pip3 install PACKAGENAME --proxy https://USERNAME:PASSWORD@PROXY_SERVER:PORT/ for Python3.5

Example:

sudo pip2 install pandas --proxy https://USERNAME:PASSWORD@PROXY_SERVER:PORT/
  1. For apt-get Installation
sudo http_proxy=http://USERNAME:PASSWORD@PROXY_SERVER:PORT/ apt-get install PACKAGENAME

Example:

sudo http_proxy=http://USERNAME:YOURPASSWORD@PROXY_SERVER:PORT/ apt-get install tensorrt

sudo http_proxy=http://USERNAME:YOURPASSWORD@PROXY_SERVER:PORT/ apt-get update

Nested Recycler view height doesn't wrap its content

The code up above doesn't work well when you need to make your items "wrap_content", because it measures both items height and width with MeasureSpec.UNSPECIFIED. After some troubles I've modified that solution so now items can expand. The only difference is that it provides parents height or width MeasureSpec depends on layout orientation.

public class MyLinearLayoutManager extends LinearLayoutManager {

public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
    super(context, orientation, reverseLayout);
}

private int[] mMeasuredDimension = new int[2];

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                      int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int width = 0;
    int height = 0;
    for (int i = 0; i < getItemCount(); i++) {


        if (getOrientation() == HORIZONTAL) {

            measureScrapChild(recycler, i,
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    heightSpec,
                    mMeasuredDimension);

            width = width + mMeasuredDimension[0];
            if (i == 0) {
                height = mMeasuredDimension[1];
            }
        } else {
            measureScrapChild(recycler, i,
                    widthSpec,
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);
            height = height + mMeasuredDimension[1];
            if (i == 0) {
                width = mMeasuredDimension[0];
            }
        }
    }
    switch (widthMode) {
        case View.MeasureSpec.EXACTLY:
            width = widthSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    switch (heightMode) {
        case View.MeasureSpec.EXACTLY:
            height = heightSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    setMeasuredDimension(width, height);
}

private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                               int heightSpec, int[] measuredDimension) {
    View view = recycler.getViewForPosition(position);
    recycler.bindViewToPosition(view, position);
    if (view != null) {
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                getPaddingLeft() + getPaddingRight(), p.width);
        int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                getPaddingTop() + getPaddingBottom(), p.height);
        view.measure(childWidthSpec, childHeightSpec);
        measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
        measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
        recycler.recycleView(view);
    }
}
}

Failed to load the JNI shared Library (JDK)

This error we are getting because of different Java version download 32-bit version.

No ConcurrentList<T> in .Net 4.0?

In cases where reads greatly outnumber writes, or (however frequent) writes are non-concurrent, a copy-on-write approach may be appropriate.

The implementation shown below is

  • lockless
  • blazingly fast for concurrent reads, even while concurrent modifications are ongoing - no matter how long they take
  • because "snapshots" are immutable, lockless atomicity is possible, i.e. var snap = _list; snap[snap.Count - 1]; will never (well, except for an empty list of course) throw, and you also get thread-safe enumeration with snapshot semantics for free.. how I LOVE immutability!
  • implemented generically, applicable to any data structure and any type of modification
  • dead simple, i.e. easy to test, debug, verify by reading the code
  • usable in .Net 3.5

For copy-on-write to work, you have to keep your data structures effectively immutable, i.e. no one is allowed to change them after you made them available to other threads. When you want to modify, you

  1. clone the structure
  2. make modifications on the clone
  3. atomically swap in the reference to the modified clone

Code

static class CopyOnWriteSwapper
{
    public static void Swap<T>(ref T obj, Func<T, T> cloner, Action<T> op)
        where T : class
    {
        while (true)
        {
            var objBefore = Volatile.Read(ref obj);
            var newObj = cloner(objBefore);
            op(newObj);
            if (Interlocked.CompareExchange(ref obj, newObj, objBefore) == objBefore)
                return;
        }
    }
}

Usage

CopyOnWriteSwapper.Swap(ref _myList,
    orig => new List<string>(orig),
    clone => clone.Add("asdf"));

If you need more performance, it will help to ungenerify the method, e.g. create one method for every type of modification (Add, Remove, ...) you want, and hard code the function pointers cloner and op.

N.B. #1 It is your responsibility to make sure the no one modifies the (supposedly) immutable data structure. There's nothing we can do in a generic implementation to prevent that, but when specializing to List<T>, you could guard against modification using List.AsReadOnly()

N.B. #2 Be careful about the values in the list. The copy on write approach above guards their list membership only, but if you'd put not strings, but some other mutable objects in there, you have to take care of thread safety (e.g. locking). But that is orthogonal to this solution and e.g. locking of the mutable values can be easily used without issues. You just need to be aware of it.

N.B. #3 If your data structure is huge and you modify it frequently, the copy-all-on-write approach might be prohibitive both in terms of memory consumption and the CPU cost of copying involved. In that case, you might want to use MS's Immutable Collections instead.

Call angularjs function using jquery/javascript

Please check this answer

// In angularJS script
$scope.foo = function() {
    console.log('test');
};
$window.angFoo = function() {
    $scope.foo();
    $scope.$apply(); 
};
    
// In jQuery
if (window.angFoo) {
    window.angFoo();
}

Access maven properties defined in the pom

This can be done with standard java properties in combination with the maven-resource-plugin with enabled filtering on properties.

For more info see http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

This will work for standard maven project as for plugin projects

Can someone post a well formed crossdomain.xml sample?

If you're using webservices, you'll also need the 'allow-http-request-headers-from' element. Here's our default, development, 'allow everything' policy.

<?xml version="1.0" ?>
<cross-domain-policy>
  <site-control permitted-cross-domain-policies="master-only"/>
  <allow-access-from domain="*"/>
  <allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>

typeof operator in C

Since typeof is a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.g sizeof and _Alignof are also seen as an operators.

And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.

size_t n = strtoull(argv[1], 0, 0);
double A[n][n];
typeof(A) B;

can only be determined at run time.

Windows batch files: .bat vs .cmd?

RE: Apparently when command.com is invoked is a bit of a complex mystery;

Several months ago, during the course of a project, we had to figure out why some programs that we wanted to run under CMD.EXE were, in fact, running under COMMAND.COM. The "program" in question was a very old .BAT file, that still runs daily.

We discovered that the reason the batch file ran under COMMAND.COM is that it was being started from a .PIF file (also ancient). Since the special memory configuration settings available only through a PIF have become irrelevant, we replaced it with a conventional desktop shortcut.

The same batch file, launched from the shortcut, runs in CMD.EXE. When you think about it, this makes sense. The reason that it took us so long to figure it out was partially due to the fact that we had forgotten that its item in the startup group was a PIF, because it had been in production since 1998.

How to change Tkinter Button state from disabled to normal?

I think a quick way to change the options of a widget is using the configure method.

In your case, it would look like this:

self.x.configure(state=NORMAL)

How to make RatingBar to show five stars

<LinearLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RatingBar
        android:id="@+id/ruleRatingBar"
        android:isIndicator="true"
        android:numStars="5"
        android:stepSize="0.5"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

Can someone give an example of cosine similarity, in a very simple, graphical way?

Here's my implementation in C#.

using System;

namespace CosineSimilarity
{
    class Program
    {
        static void Main()
        {
            int[] vecA = {1, 2, 3, 4, 5};
            int[] vecB = {6, 7, 7, 9, 10};

            var cosSimilarity = CalculateCosineSimilarity(vecA, vecB);

            Console.WriteLine(cosSimilarity);
            Console.Read();
        }

        private static double CalculateCosineSimilarity(int[] vecA, int[] vecB)
        {
            var dotProduct = DotProduct(vecA, vecB);
            var magnitudeOfA = Magnitude(vecA);
            var magnitudeOfB = Magnitude(vecB);

            return dotProduct/(magnitudeOfA*magnitudeOfB);
        }

        private static double DotProduct(int[] vecA, int[] vecB)
        {
            // I'm not validating inputs here for simplicity.            
            double dotProduct = 0;
            for (var i = 0; i < vecA.Length; i++)
            {
                dotProduct += (vecA[i] * vecB[i]);
            }

            return dotProduct;
        }

        // Magnitude of the vector is the square root of the dot product of the vector with itself.
        private static double Magnitude(int[] vector)
        {
            return Math.Sqrt(DotProduct(vector, vector));
        }
    }
}

How to determine if object is in array

This function is to check for a unique field. Arg 1: the array with selected data Arg 2: key to check Arg 3: value that must be "validated"

function objectUnique( array, field, value )
{
    var unique = true;
    array.forEach(function ( entry )
    {
        if ( entry[field] == value )
        {
            unique = false;
        }
    });

    return unique;
}

Calculating how many days are between two dates in DB2?

Wouldn't it just be:

SELECT CURRENT_DATE - CHDLM FROM CHCART00 WHERE CHSTAT = '05';

That should return the number of days between the two dates, if I understand how date arithmetic works in DB2 correctly.

If CHDLM isn't a date you'll have to convert it to one. According to IBM the DATE() function would not be sufficient for the yyyymmdd format, but it would work if you can format like this: yyyy-mm-dd.

How can I get date and time formats based on Culture Info?

You could take a look at the DateTimeFormat property which contains the culture specific formats.

How to turn a String into a JavaScript function call?

Here is a more generic way to do the same, while supporting scopes :

// Get function from string, with or without scopes (by Nicolas Gauthier)
window.getFunctionFromString = function(string)
{
    var scope = window;
    var scopeSplit = string.split('.');
    for (i = 0; i < scopeSplit.length - 1; i++)
    {
        scope = scope[scopeSplit[i]];

        if (scope == undefined) return;
    }

    return scope[scopeSplit[scopeSplit.length - 1]];
}

Hope it can help some people out.

How can I delete using INNER JOIN with SQL Server?

It should be:

DELETE zpost 
FROM zpost 
INNER JOIN zcomment ON (zpost.zpostid = zcomment.zpostid)
WHERE zcomment.icomment = "first"       

Filter dataframe rows if value in column is in a set list of values

You can also directly query your DataFrame for this information.

rpt.query('STK_ID in (600809,600141,600329)')

Or similarly search for ranges:

rpt.query('60000 < STK_ID < 70000')

How to make an inline-block element fill the remainder of the line?

I've used flex-grow property to achieve this goal. You'll have to set display: flex for parent container, then you need to set flex-grow: 1 for the block you want to fill remaining space, or just flex: 1 as tanius mentioned in the comments.

All ASP.NET Web API controllers return 404

If you manage the IIS and you are the one who have to create new site then check the "Application Pool" and be sure the CLR version must be selected. In my situation, it had been selected "No Managed Code". After changed to v4.0 it started to work.

How to style SVG with external CSS?

What works for me: style tag with @import rule

<defs>
    <style type="text/css">
        @import url("svg-common.css");
    </style>
</defs>

React JS - Uncaught TypeError: this.props.data.map is not a function

I had the same problem. The solution was to change the useState initial state value from string to array. In App.js, previous useState was

const [favoriteFilms, setFavoriteFilms] = useState('');

I changed it to

const [favoriteFilms, setFavoriteFilms] = useState([]);

and the component that uses those values stopped throwing error with .map function.

Specifying onClick event type with Typescript and React.Konva

React.MouseEvent works for me:

private onClick = (e: React.MouseEvent<HTMLInputElement>) => {
  let button = e.target as HTMLInputElement;
}

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

One way that the Scala community can help ease the fear of programmers new to Scala is to focus on practice and to teach by example--a lot of examples that start small and grow gradually larger. Here are a few sites that take this approach:

After spending some time on these sites, one quickly realizes that Scala and its libraries, though perhaps difficult to design and implement, are not so difficult to use, especially in the common cases.

How can I open the interactive matplotlib window in IPython notebook?

According to the documentation, you should be able to switch back and forth like this:

In [2]: %matplotlib inline 
In [3]: plot(...)

In [4]: %matplotlib qt  # wx, gtk, osx, tk, empty uses default
In [5]: plot(...) 

and that will pop up a regular plot window (a restart on the notebook may be necessary).

I hope this helps.

How to print Unicode character in Python?

Just one more thing that hasn't been added yet

In Python 2, if you want to print a variable that has unicode and use .format(), then do this (make the base string that is being formatted a unicode string with u'':

>>> text = "Université de Montréal"
>>> print(u"This is unicode: {}".format(text))
>>> This is unicode: Université de Montréal

Convert columns to string in Pandas

If you need to convert ALL columns to strings, you can simply use:

df = df.astype(str)

This is useful if you need everything except a few columns to be strings/objects, then go back and convert the other ones to whatever you need (integer in this case):

 df[["D", "E"]] = df[["D", "E"]].astype(int) 

How do I unset an element in an array in javascript?

An important note: JavaScript Arrays are not associative arrays like those you might be used to from PHP. If your "array key" is a string, you're no longer operating on the contents of an array. Your array is an object, and you're using bracket notation to access the member named <key name>. Thus:

var myArray = [];
myArray["bar"] = true;
myArray["foo"] = true;
alert(myArray.length); // returns 0.

because you have not added elements to the array, you have only modified myArray's bar and foo members.

Fatal error: Class 'Illuminate\Foundation\Application' not found

For latest laravel version also check your version because I was also facing this error but after update latest php version, I got rid from this error.

How to close an iframe within iframe itself

Use this to remove iframe from parent within iframe itself

frameElement.parentNode.removeChild(frameElement)

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

What is copy-on-write?

I shall not repeat the same answer on Copy-on-Write. I think Andrew's answer and Charlie's answer have already made it very clear. I will give you an example from OS world, just to mention how widely this concept is used.

We can use fork() or vfork() to create a new process. vfork follows the concept of copy-on-write. For example, the child process created by vfork will share the data and code segment with the parent process. This speeds up the forking time. It is expected to use vfork if you are performing exec followed by vfork. So vfork will create the child process which will share data and code segment with its parent but when we call exec, it will load up the image of a new executable in the address space of the child process.

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

How to make Twitter Bootstrap menu dropdown on hover rather than click

Here is the JSFiddle -> https://jsfiddle.net/PRkonsult/mn31qf0p/1/

The JavaScript bit at the bottom is what does the actual magic.

HTML

<!--http://getbootstrap.com/components/#navbar-->
<div class="body-wrap">
  <div class="container">
    <nav class="navbar navbar-inverse" role="navigation">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Brand</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
              <ul class="dropdown-menu">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li class="divider"></li>
                <li><a href="#">Separated link</a></li>
                <li class="divider"></li>
                <li><a href="#">One more separated link</a></li>
              </ul>
            </li>
          </ul>

          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">Link</a></li>
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
              <ul class="dropdown-menu">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li class="divider"></li>
                <li><a href="#">Separated link</a></li>
              </ul>
            </li>
          </ul>
        </div>
        <!-- /.navbar-collapse -->
      </div>
      <!-- /.container-fluid -->
    </nav>
  </div>
</div>

CSS

/* Bootstrap dropdown hover menu */

body {
  font-family: 'PT Sans', sans-serif;
  font-size: 13px;
  font-weight: 400;
  color: #4f5d6e;
  position: relative;
  background: rgb(26, 49, 95);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(26, 49, 95, 1)), color-stop(10%, rgba(26, 49, 95, 1)), color-stop(24%, rgba(29, 108, 141, 1)), color-stop(37%, rgba(41, 136, 151, 1)), color-stop(77%, rgba(39, 45, 100, 1)), color-stop(90%, rgba(26, 49, 95, 1)), color-stop(100%, rgba(26, 49, 95, 1)));
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#1a315f', endColorstr='#1a315f', GradientType=0);
}

.body-wrap {
  min-height: 700px;
}

.body-wrap {
  position: relative;
  z-index: 0;
}

.body-wrap: before,
.body-wrap: after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: -1;
  height: 260px;
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(26, 49, 95, 1)), color-stop(100%, rgba(26, 49, 95, 0)));
  background: linear-gradient(to bottom, rgba(26, 49, 95, 1) 0%, rgba(26, 49, 95, 0) 100%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#1a315f', endColorstr='#001a315f', GradientType=0);
}

.body-wrap:after {
  top: auto;
  bottom: 0;
  background: linear-gradient(to bottom, rgba(26, 49, 95, 0) 0%, rgba(26, 49, 95, 1) 100%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#001a315f', endColorstr='#1a315f', GradientType=0);
}

nav {
  margin-top: 60px;
  box-shadow: 5px 4px 5px #000;
}

Then the important bit of JavaScript code:

$('ul.nav li.dropdown').hover(function() {
  $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
}, function() {
  $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
});

How to get value of a div using javascript

DIVs do not have a value property.

Technically, according to the DTDs, they shouldn't have a value attribute either, but generally you'll want to use .getAttribute() in this case:

function overlay()
{
    var cookieValue = document.getElementById('demo').getAttribute('value');
    alert(cookieValue);
}

How to check Oracle patches are installed?

Maybe you need "sys." before:

select * from sys.registry$history;

Get the length of a String

in Swift 2.x the following is how to find the length of a string

let findLength = "This is a string of text"
findLength.characters.count

returns 24

When is assembly faster than C?

More often than you think, C needs to do things that seem to be unneccessary from an Assembly coder's point of view just because the C standards say so.

Integer promotion, for example. If you want to shift a char variable in C, one would usually expect that the code would do in fact just that, a single bit shift.

The standards, however, enforce the compiler to do a sign extend to int before the shift and truncate the result to char afterwards which might complicate code depending on the target processor's architecture.

Oracle: How to filter by date and time in a where clause

Put it this way

where ("R"."TIME_STAMP">=TO_DATE ('03-02-2013 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
   AND "R"."TIME_STAMP"<=TO_DATE ('09-02-2013 23:59:59', 'DD-MM-YYYY HH24:MI:SS')) 

Where R is table name.
TIME_STAMP is FieldName in Table R.

Turning multi-line string into single comma-separated

Yet another AWK solution

Run

awk '{printf "%s", $c; while(getline){printf "%s%s", sep, $c}}' c=2 sep=','

to use the 2nd column to form the list separated by commas. Give the input as usual in standard input or as a file name argument.

Change color of Button when Mouse is over

<Button Content="Click" Width="200" Height="50">
<Button.Style>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="LightBlue" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="Border" Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="LightGreen" TargetName="Border" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Button.Style>

Insert text with single quotes in PostgreSQL

According to PostgreSQL documentation (4.1.2.1. String Constants):

 To include a single-quote character within a string constant, write two 
 adjacent single quotes, e.g. 'Dianne''s horse'.

See also the standard_conforming_strings parameter, which controls whether escaping with backslashes works.

Using filesystem in node.js with async / await

This is the TypeScript version to the question. It is usable after Node 11.0:

import { promises as fs } from 'fs';

async function loadMonoCounter() {
    const data = await fs.readFile('monolitic.txt', 'binary');
    return Buffer.from(data);
}

Binary Data in JSON String. Something better than Base64

I dig a little bit more (during implementation of base128), and expose that when we send characters which ascii codes are bigger than 128 then browser (chrome) in fact send TWO characters (bytes) instead one :(. The reason is that JSON by defaul use utf8 characters for which characters with ascii codes above 127 are coded by two bytes what was mention by chmike answer. I made test in this way: type in chrome url bar chrome://net-export/ , select "Include raw bytes", start capturing, send POST requests (using snippet at the bottom), stop capturing and save json file with raw requests data. Then we look inside that json file:

  • We can find our base64 request by finding string 4142434445464748494a4b4c4d4e this is hex coding of ABCDEFGHIJKLMN and we will see that "byte_count": 639 for it.
  • We can find our above127 request by finding string C2BCC2BDC380C381C382C383C384C385C386C387C388C389C38AC38B this are request-hex utf8 codes of characters ¼½ÀÁÂÃÄÅÆÇÈÉÊË (however the ascii hex codes of this characters are c1c2c3c4c5c6c7c8c9cacbcccdce). The "byte_count": 703 so it is 64bytes longer than base64 request because characters with ascii codes above 127 are code by 2 bytes in request :(

So in fact we don't have profit with sending characters with codes >127 :( . For base64 strings we not observe such negative behaviour (probably for base85 too - I don check it) - however may be some solution for this problem will be sending data in binary part of POST multipart/form-data described in Ælex answer (however usually in this case we don't need to use any base coding at all...).

The alternative approach may rely on mapping two bytes data portion into one valid utf8 character by code it using something like base65280 / base65k but probably it would be less effective than base64 due to utf8 specification ...

_x000D_
_x000D_
function postBase64() {_x000D_
  let formData = new FormData();_x000D_
  let req = new XMLHttpRequest();_x000D_
_x000D_
  formData.append("base64ch", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");_x000D_
  req.open("POST", '/testBase64ch');_x000D_
  req.send(formData);_x000D_
}_x000D_
_x000D_
_x000D_
function postAbove127() {_x000D_
  let formData = new FormData();_x000D_
  let req = new XMLHttpRequest();_x000D_
_x000D_
  formData.append("above127", "¼½ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüý");_x000D_
  req.open("POST", '/testAbove127');_x000D_
  req.send(formData);_x000D_
}
_x000D_
<button onclick=postBase64()>POST base64 chars</button>_x000D_
<button onclick=postAbove127()>POST chars with codes>127</button>
_x000D_
_x000D_
_x000D_

Pure CSS scroll animation

And for webkit enabled browsers I've had good results with:

.myElement {
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth; // Added in from answer from Felix
    overflow-x: scroll;
}

This makes scrolling behave much more like the standard browser behavior - at least it works well on the iPhone we were testing on!

Hope that helps,

Ed

Add a duration to a moment (moment.js)

For people having a startTime (like 12h:30:30) and a duration (value in minutes like 120), you can guess the endTime like so:

const startTime = '12:30:00';
const durationInMinutes = '120';

const endTime = moment(startTime, 'HH:mm:ss').add(durationInMinutes, 'minutes').format('HH:mm');

// endTime is equal to "14:30"

jQuery AJAX cross domain

You need to have a look at Same Origin Policy:

In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.

For you to be able to get data, it has to be:

Same protocol and host

You need to implement JSONP to workaround it.

How do I add a new sourceset to Gradle?

Here is how I achieved this without using configurations{ }.

apply plugin: 'java'

sourceCompatibility = JavaVersion.VERSION_1_6

sourceSets {
    integrationTest {
        java {
            srcDir 'src/integrationtest/java'
        }
        resources {
            srcDir 'src/integrationtest/resources'
        }
        compileClasspath += sourceSets.main.runtimeClasspath
    }
}

task integrationTest(type: Test) {
    description = "Runs Integration Tests"
    testClassesDir = sourceSets.integrationTest.output.classesDir
    classpath += sourceSets.integrationTest.runtimeClasspath
}

Tested using: Gradle 1.4 and Gradle 1.6

Regular expression field validation in jQuery

I'm using jQuery and JavaScript and it works fine for me:

var rege = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(rege.test($('#uemail').val())){ //do something }

Openssl is not recognized as an internal or external command

This is worked for me successfully.

"C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe" -exportcert -alias sociallisting -keystore "D:\keystore\SocialListing" | "C:\cygwin\bin\openssl.exe" sha1 -binary | "C:\cygwin\bin\openssl.exe" base64

Be careful with below path :

  • "C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe"
  • "D:\keystore\SocialListing" or it can be like this "C:\Users\Shaon.android\debug.keystore"
  • "C:\cygwin\bin\openssl.exe" or can be like this C:\Users\openssl\bin\openssl.exe

If command successfully work then you will see this command :

Enter keystore password : typeyourpassword

Encryptedhashkey**

Java : Cannot format given Object as a Date

You have one DateFormat, but you need two: one for the input, and another for the output.

You've got one for the output, but I don't see anything that would match your input. When you give the input string to the output format, it's no surprise that you see that exception.

DateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss.SSS-Z");

Want custom title / image / description in facebook share link from a flash app

I actually have a similar problem. I have a page with multiple radio buttons; each button will set the title and description meta tags of the page, via JavaScript upon change.

For example, if users select the first button, the meta tags will say:

<meta name="title" content="First Title">
<meta name="description" content="First Description">

If the user select the second button, this changes the meta tags to:

<meta name="title" content="Second Title">
<meta name="description" content="Second Description">

... and so on. I have confirmed that the code is working fine via Firebug (i.e. I can see that those two tags were properly changed).

Apparently, Facebook Share only pulls in the title and description meta tags that are available upon page load. The changes to those two tags post page load are completely ignored.

Does anybody have any ideas on how to solve this? That is, to force Facebook to get the latest values that are change after the page loads.

Dynamically add event listener

I will add a StackBlitz example and a comment to the answer from @tahiche.

The return value is a function to remove the event listener after you have added it. It is considered good practice to remove event listeners when you don't need them anymore. So you can store this return value and call it inside your ngOnDestroy method.

I admit that it might seem confusing at first, but it is actually a very useful feature. How else can you clean up after yourself?

export class MyComponent implements OnInit, OnDestroy {

  public removeEventListener: () => void;

  constructor(
    private renderer: Renderer2, 
    private elementRef: ElementRef
  ) {
  }

  public ngOnInit() {
    this.removeEventListener = this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
      if (event.target instanceof HTMLAnchorElement) {
        // Prevent opening anchors the default way
        event.preventDefault();
        // Your custom anchor click event handler
        this.handleAnchorClick(event);
      }
    });
  }

  public ngOnDestroy() {
    this.removeEventListener();
  }
}

You can find a StackBlitz here to show how this could work for catching clicking on anchor elements.

I added a body with an image as follows:
<img src="x" onerror="alert(1)"></div>
to show that the sanitizer is doing its job.

Here in this fiddle you find the same body attached to an innerHTML without sanitizing it and it will demonstrate the issue.

java.lang.IllegalArgumentException: No converter found for return value of type

Add the below dependency to your pom.xml:

 <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.0.pr3</version>
</dependency>

SVN: Folder already under version control but not comitting?

Check for a directory 'apps/autocomplete/.svn'. Move it somewhere safe (in case you need to restore it because this did not work) and see if that fixes the problem.

Oracle SQL Developer: Unable to find a JVM

The secret is you need to copy msvcr100.dll to the path where the installation says msvcr100.dll is missing (dialog box) and then try to install the sql developer.

For me I had to create bin folder in

C:\sqldeveloper\jdk\bin

and Copy msvcr100.dll to it.

If still not working! Try this!

You might also need to change the config file settings found in

C:\sqldeveloper\sqldeveloper\bin

Download and install 32 bit JDK (Windows) and set the path in config file as

SetJavaHome C:/Program Files (x86)/Java/jdk1.7.0_01

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

Try to use mousemove event lisentner

var audio = document.createElement("AUDIO")
document.body.appendChild(audio);
audio.src = "./audio/rain.m4a"

document.body.addEventListener("mousemove", function () {
    audio.play()
})

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

Understanding inplace=True

inplace=True is used depending if you want to make changes to the original df or not.

df.drop_duplicates()

will only make a view of dropped values but not make any changes to df

df.drop_duplicates(inplace  = True)

will drop values and make changes to df.

Hope this helps.:)

How do I request and process JSON with python?

Python's standard library has json and urllib2 modules.

import json
import urllib2

data = json.load(urllib2.urlopen('http://someurl/path/to/json'))

How can I reorder my divs using only CSS?

Ordering only for mobile and keep the native order for desktop:

// html

<div>
  <div class="gridInverseMobile1">First</div>
  <div class="gridInverseMobile1">Second</div>
</div>

// css

@media only screen and (max-width: 960px) {
  .gridInverseMobile1 {
    order: 2;
    -webkit-order: 2;
  }
  .gridInverseMobile2 {
    order: 1;
    -webkit-order: 1;
  }
}

Result:

Desktop: First | Second
Mobile: Second | First

source: https://www.w3schools.com/cssref/css3_pr_order.asp

Can I dispatch an action in reducer?

Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

Sounds like your initialized AudioElement class and the event listener belong within a component rather than in state. Within the event listener you can dispatch an action, which will update progress in state.

You can either initialize the AudioElement class object in a new React component or just convert that class to a React component.

class MyAudioPlayer extends React.Component {
  constructor(props) {
    super(props);

    this.player = new AudioElement('test.mp3');

    this.player.audio.ontimeupdate = this.updateProgress;
  }

  updateProgress () {
    // Dispatch action to reducer with updated progress.
    // You might want to actually send the current time and do the
    // calculation from within the reducer.
    this.props.updateProgressAction();
  }

  render () {
    // Render the audio player controls, progress bar, whatever else
    return <p>Progress: {this.props.progress}</p>;
  }
}

class MyContainer extends React.Component {
   render() {
     return <MyAudioPlayer updateProgress={this.props.updateProgress} />
   }
}

function mapStateToProps (state) { return {}; }

return connect(mapStateToProps, {
  updateProgressAction
})(MyContainer);

Note that the updateProgressAction is automatically wrapped with dispatch so you don't need to call dispatch directly.

align divs to the bottom of their container

Why can't you use absolute positioning? Vertical-align does not work (except for tables). Make your container's position: relative. Then absolutely position the internal divs using bottom: 0; Should work like a charm.

EDIT By zoidberg (i will update the answer instead)

<div style="position:relative; border: 1px solid red;width: 40px; height: 40px;">
   <div style="border:1px solid green;position: absolute; bottom: 0; left: 0; width: 20px; height: 20px;"></div>
   <div style="border:1px solid blue;position: absolute; bottom: 0; left: 20px; width: 20px height: 20px;"></div>
</div>

How to stop asynctask thread in android?

You may also have to use it in onPause or onDestroy of Activity Life Cycle:

//you may call the cancel() method but if it is not handled in doInBackground() method
if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
    loginTask.cancel(true);

where loginTask is object of your AsyncTask

Thank you.

Bootstrap 3 Multi-column within a single ul not floating properly

you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]

http://www.bootply.com/118886

css

.even{background: red; color:white;}
.odd{background: darkred; color:white;}

html

<div class="container">
  <ul class="list-unstyled">
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
  </ul>
</div>

Validate that end date is greater than start date with jQuery

I was just tinkering with danteuno's answer and found that while good-intentioned, sadly it's broken on several browsers that are not IE. This is because IE will be quite strict about what it accepts as the argument to the Date constructor, but others will not. For example, Chrome 18 gives

> new Date("66")
  Sat Jan 01 1966 00:00:00 GMT+0200 (GTB Standard Time)

This causes the code to take the "compare dates" path and it all goes downhill from there (e.g. new Date("11") is greater than new Date("66") and this is obviously the opposite of the desired effect).

Therefore after consideration I modified the code to give priority to the "numbers" path over the "dates" path and validate that the input is indeed numeric with the excellent method provided in Validate decimal numbers in JavaScript - IsNumeric().

In the end, the code becomes:

$.validator.addMethod(
    "greaterThan",
    function(value, element, params) {
        var target = $(params).val();
        var isValueNumeric = !isNaN(parseFloat(value)) && isFinite(value);
        var isTargetNumeric = !isNaN(parseFloat(target)) && isFinite(target);
        if (isValueNumeric && isTargetNumeric) {
            return Number(value) > Number(target);
        }

        if (!/Invalid|NaN/.test(new Date(value))) {
            return new Date(value) > new Date(target);
        }

        return false;
    },
    'Must be greater than {0}.');

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

I am using angular 4 and faced the same issue apply, all possible solution but finally, this solve my problem

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}

Hope this will help you.

How to add default value for html <textarea>?

You can also add the "value" attribute and set that so something like so:


<textarea value="your value"> </textarea>

WhatsApp API (java/python)

Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.

System.IO.IOException: file used by another process

I realize that I is kinda late, but still better late than never. I was having similar problem recently. I used XMLWriter to subsequently update XML file and was receiving the same errors. I found the clean solution for this:

The XMLWriter uses underlying FileStream to access the modified file. Problem is that when you call XMLWriter.Close() method, the underlying stream doesn't get closed and is locking the file. What you need to do is to instantiate your XMLWriter with settings and specify that you need that underlying stream closed.

Example:

XMLWriterSettings settings = new Settings();
settings.CloseOutput = true;
XMLWriter writer = new XMLWriter(filepath, settings);

Hope it helps.

Difference between numpy.array shape (R, 1) and (R,)

The data structure of shape (n,) is called a rank 1 array. It doesn't behave consistently as a row vector or a column vector which makes some of its operations and effects non intuitive. If you take the transpose of this (n,) data structure, it'll look exactly same and the dot product will give you a number and not a matrix. The vectors of shape (n,1) or (1,n) row or column vectors are much more intuitive and consistent.

What to do on TransactionTooLargeException

For me it was also the FragmentStatePagerAdapter, however overriding saveState() did not work. Here's how I fixed it:

When calling the FragmentStatePagerAdapter constructor, keep a separate list of fragments within the class, and add a method to remove the fragments:

class PagerAdapter extends FragmentStatePagerAdapter {
    ArrayList<Fragment> items;

    PagerAdapter(ArrayList<Fragment> frags) {
        super(getFragmentManager()); //or getChildFragmentManager() or getSupportFragmentManager()
        this.items = new ArrayList<>();
        this.items.addAll(frags);
    }

    public void removeFragments() {
        Iterator<Fragment> iter = items.iterator();

        while (iter.hasNext()) {
            Fragment item = iter.next();
                getFragmentManager().beginTransaction().remove(item).commit();
                iter.remove();
            }
            notifyDataSetChanged();
        }
    }
    //...getItem() and etc methods...
}

Then in the Activity, save the ViewPager position and call adapter.removeFragments() in the overridden onSaveInstanceState() method:

private int pagerPosition;

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //save other view state here
    pagerPosition = mViewPager.getCurrentItem();
    adapter.removeFragments();
}

Lastly, in the overridden onResume() method, re-instantiate the adapter if it isn't null. (If it's null, then the Activity is being opened for the first time or after the app has been killed off by Android, in which onCreate will do the adapter creation.)

@Override
public void onResume() {
    super.onResume();
    if (adapter != null) {
        adapter = new PagerAdapter(frags);
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(currentTabPosition);
    }
}

android TextView: setting the background color dynamically doesn't work

I had a similar issue where I was creating a numeric color without considering the leading alpha channel. ie. mytext.setTextColor(0xFF0000) (thinking this would be red ). While this is a red color it is also 100% transparent as it = 0x00FF0000; The correct 100% opaque value is 0xFFFF0000 or mytext.setTextcolor(0xFFFF0000).

What is the difference between background and background-color

About CSS performance :

background vs background-color :

Comparison of 18 color swatches rendered 100 times on a page as small rectangles, once with background and once with background-color.

Background vs background-color

While these numbers are from a single page reload, with subsequent refreshes the render times changed, but the percent difference was basically the same every time.

That's a savings of almost 42.6ms, almost twice as fast, when using background instead of background-color in Safari 7.0.1. Chrome 33 appears to be about the same.

This honestly blew me away because for the longest time for two reasons:

  • I usually always argue for explicitness in CSS properties, especially with backgrounds because it can adversely affect specificity down the road.
  • I thought that when a browser sees background: #000;, they really see background: #000 none no-repeat top center;. I don't have a link to a resource here, but I recall reading this somewhere.

Ref : https://github.com/mdo/css-perf#background-vs-background-color

BATCH file asks for file or folder

The virtual parent trick

Assuming you have your source and destination file in

%SRC_FILENAME% and %DST_FILENAME%

you could use a 2 step method:

@REM on my win 7 system mkdir creates all parent directories also
mkdir "%DST_FILENAME%\.."
xcopy "%SRC_FILENAME% "%DST_FILENAME%\.."

this would be resolved to e.g

mkdir "c:\destination\b\c\file.txt\.."
@REM The special trick here is that mkdir can create the parent
@REM directory of a "virtual" directory (c:\destination\b\c\file.txt\) that 
@REM doesn't even need to exist.
@REM So the directory "c:\destination\b\c" is created here.
@REM mkdir "c:\destination\b\c\dummystring\.." would have the same effect

xcopy "c:\source\b\c\file.txt" "c:\destination\b\c\file.txt\.."
@REM xcopy computes the real location of  "c:\destination\b\c\file.txt\.."
@REM which is the now existing directory "c:\destination\b\c"
@REM (the parent directory of the "virtual" directory c:\destination\b\c\file.txt\).

I came to the idea when I stumbled over some really wild ../..-constructs in the command lines generated from a build process.

How to find the php.ini file used by the command line?

You can get a full phpinfo() using :

php -i 

And, in there, there is the php.ini file used :

$ php -i | grep 'Configuration File'
Configuration File (php.ini) Path => /etc
Loaded Configuration File => /etc/php.ini

On Windows use find instead:

php -i|find/i"configuration file"

Using Switch Statement to Handle Button Clicks

    XML CODE FOR TWO BUTTONS  
     <Button
            android:id="@+id/btn_save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SAVE"
            android:onClick="process"
            />
        <Button
            android:id="@+id/btn_show"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SHOW"
            android:onClick="process"/> 

  Java Code
 <pre> public void process(View view) {
            switch (view.getId()){
                case R.id.btn_save:
                  //add your own code
                    break;
                case R.id.btn_show:
                   //add your own code
                    break;
            }</pre>

Merging cells in Excel using Apache POI

i made a method that merge cells and put border.

protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
    CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
    sheet.addMergedRegion(cellMerge);
    if (border) {
        setBordersToMergedCells(sheet, cellMerge);
    }

}



protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
    RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}

Flatten List in LINQ

With query syntax:

var values =
from inner in outer
from value in inner
select value;

How do I store the select column in a variable?

Assuming such a query would return a single row, you could use either

select @EmpId = Id from dbo.Employee

Or

set @EmpId = (select Id from dbo.Employee)

File.Move Does Not Work - File Already Exists

Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True). The last parameter is Overwrite switch, which System.IO.File.Move doesn't have.

How to set password for Redis?

For that, you need to update the redis configuration file.By default, there is no any password for redis.

01) open redis configuration file

sudo vi /etc/redis/redis.conf

find requirepass field under SECURITY section and uncomment that field.Then set your password instead of "foobared"

# requirepass foobared

It should be like,

requirepass YOUR_PASSWORD

Then restart redis and start redis-cli.

If you need to check whether you have set the password correctly, you can run below commads in redis-cli.

sithara@sithara-X555UJ ~ $ redis-cli
127.0.0.1:6379> set key1 18
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth admin
OK
127.0.0.1:6379> get key1
(nil)
127.0.0.1:6379> exit


sithara@sithara-X555UJ ~ $ redis-cli
127.0.0.1:6379> set key1 18
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth admin
OK
127.0.0.1:6379> set key2 check
OK
127.0.0.1:6379> get key2
"check"
127.0.0.1:6379> get key1
(nil)
127.0.0.1:6379> set key1 20
OK
127.0.0.1:6379> get key1
"20"
127.0.0.1:6379> exit

`

C#, Looping through dataset and show each record from a dataset column

I believe you intended it more this way:

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
        TaskStart.ToString("dd-MMMM-yyyy");
        rpt.SetParameterValue("TaskStartDate", TaskStart);
    }
}

You always accessed your first row in your dataset.

How to get time difference in minutes in PHP

Subtract the past most one from the future most one and divide by 60.

Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT

How to use ArgumentCaptor for stubbing?

The line

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);

would do the same as

when(someObject.doSomething(Matchers.any())).thenReturn(true);

So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.

And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.

How to make the Facebook Like Box responsive?

None of the css trick worked for me (in my case the fb-like box was pulled right with "float:right"). However, what worked without any additional tricks is an IFRAME version of the button code. I.e.:

<iframe src="//www.facebook.com/plugins/like.php?href=..." 
        scrolling="no" frameborder="0" 
        style="border:none; overflow:hidden; width:71px; height:21px;" 
        allowTransparency="true">
</iframe>

(Note custom width in style, and no need to include additional javascript.)

How to install wget in macOS?

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

And then install wget with brew and also enable openressl for TLS support

brew install wget --with-libressl

It worked perfectly for me.

pandas how to check dtype for all columns in a dataframe?

To go one step further, I assume you want to do something with these dtypes. df.dtypes.to_dict() comes in handy.

my_type = 'float64' #<---

dtypes = dataframe.dtypes.to_dict()

for col_nam, typ in dtypes.items():
    if (typ != my_type): #<---
        raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")

You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype will succeed when .dtype==np.float64.

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

How to highlight a current menu item?

Using Angular Version 6 with Bootstrap 4.1

I was able to get it done like as seen below.

In the example below, when the URL sees '/contact', the bootstrap active is then added to the html tag. When the URL changes it is then removed.

<ul>
<li class="nav-item" routerLink="/contact" routerLinkActive="active">
    <a class="nav-link" href="/contact">Contact</a>
</li>
</ul>

This directive lets you add a CSS class to an element when the link's route becomes active.

Read more on Angular website

Where can I get a virtual machine online?

koding.com has a free VM running Ubuntu. The specs are pretty good, 1 gig memory for example. They have a terminal online you can access through their website, or use SSH. The VM will go to sleep approximately 20 minutes after you log out. The reason is to discourage users from running live production code on the VM. The VM resides behind a proxy. Running web servers that only speak HTTP (port 80) should work just fine, but I think you'll get into a lot of trouble whenever you want to work directly with other ports. Many mind-like alternatives offer similar setups. Good luck!

I had the same idea as you but given all restrictions everybody keep imposing everywhere I feel that I must go out and pay for a VPS.

Oracle insert if not exists statement

MERGE INTO OPT
USING
    (SELECT 1 "one" FROM dual) 
ON
    (OPT.email= '[email protected]' and OPT.campaign_id= 100) 
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100) 
;

Trigger css hover with JS

If you bind events to the onmouseover and onmouseout events in Jquery, you can then trigger that effect using mouseenter().

What are you trying to accomplish?

How can I declare and use Boolean variables in a shell script?

I found the existing answers confusing.

Personally, I just want to have something which looks and works like C.

This snippet works many times a day in production:

snapshotEvents=true

if ($snapshotEvents)
then
    # Do stuff if true
fi

and to keep everyone happy, I tested:

snapshotEvents=false

if !($snapshotEvents)
then
    # Do stuff if false
fi

Which also worked fine.

The $snapshotEvents evaluates the contents of value of the variable. So you need the $.

You don't really need the parentheses, I just find them helpful.

How do I see active SQL Server connections?

Click the "activity monitor" icon in the toolbar.

From Thorsten's comment:

In SQL Server Management Studio, right click on Server, choose "Activity Monitor" from context menu -or- use keyboard shortcut Ctrl + Alt + A.

Reference: Microsoft Docs - Open Activity Monitor in SQL Server Management Studio (SSMS)

How to determine if a decimal/double is an integer?

For floating point numbers, n % 1 == 0 is typically the way to check if there is anything past the decimal point.

public static void Main (string[] args)
{
    decimal d = 3.1M;
    Console.WriteLine((d % 1) == 0);
    d = 3.0M;
    Console.WriteLine((d % 1) == 0);
}

Output:

False
True

Update: As @Adrian Lopez mentioned below, comparison with a small value epsilon will discard floating-point computation mis-calculations. Since the question is about double values, below will be a more floating-point calculation proof answer:

Math.Abs(d % 1) <= (Double.Epsilon * 100)

Java: Identifier expected

input.name() needs to be inside a function; classes contain declarations, not random code.

Android disable screen timeout while app is running

1.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);is best solution for Native Android.
2. if you want to do with React android application then please use the below code.

@ReactMethod
    public void activate() {
        final Activity activity = getCurrentActivity();
        if (activity != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }
            });
        }

    }

Get all inherited classes of an abstract class

typeof(AbstractDataExport).Assembly tells you an assembly your types are located in (assuming all are in the same).

assembly.GetTypes() gives you all types in that assembly or assembly.GetExportedTypes() gives you types that are public.

Iterating through the types and using type.IsAssignableFrom() gives you whether the type is derived.

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>            

How to make a new List in Java

If you need a serializable, immutable list with a single entity you can use:

List<String> singList = Collections.singletonList("stackoverlow");

Get the value of bootstrap Datetimepicker in JavaScript

Since the return value has changed, $("#datetimepicker1").data("DateTimePicker").date() actually returns a moment object as Alexandre Bourlier stated:

It seems the doc evolved.

One should now use : $("#datetimepicker1").data("DateTimePicker").date().

NB : Doing so return a Moment object, not a Date object

Therefore, we must use .toDate() to change this statement to a date as such:

$("#datetimepicker1").data("DateTimePicker").date().toDate();

Get $_POST from multiple checkboxes

Set the name in the form to check_list[] and you will be able to access all the checkboxes as an array($_POST['check_list'][]).

Here's a little sample as requested:

<form action="test.php" method="post">
    <input type="checkbox" name="check_list[]" value="value 1">
    <input type="checkbox" name="check_list[]" value="value 2">
    <input type="checkbox" name="check_list[]" value="value 3">
    <input type="checkbox" name="check_list[]" value="value 4">
    <input type="checkbox" name="check_list[]" value="value 5">
    <input type="submit" />
</form>
<?php
if(!empty($_POST['check_list'])) {
    foreach($_POST['check_list'] as $check) {
            echo $check; //echoes the value set in the HTML form for each checked checkbox.
                         //so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
                         //in your case, it would echo whatever $row['Report ID'] is equivalent to.
    }
}
?>

How can I detect when the mouse leaves the window?

I take back what i said. It is possible. I wrote this code, works perfectly.

window.onload = function() {

    $span = document.getElementById('text');

    window.onmouseout = function() {
        $span.innerHTML = "mouse out";  
    }

    window.onmousemove = function() {
        $span.innerHTML = "mouse in";   
    }

}

works in chrome, firefox, opera. Aint tested in IE but assume it works.

edit. IE as always causes trouble. To make it work in IE, replace the events from window to document:

window.onload = function() {

    $span = document.getElementById('text');

    document.onmousemove = function() {
        $span.innerHTML = "mouse move";
    }

    document.onmouseout = function() {
        $span.innerHTML = "mouse out";
    }

}

combine them for crossbrowser kick ass cursor detection o0 :P

How to pick a new color for each plotted line within a figure in matplotlib?

I usually use the second one of these:

from matplotlib.pyplot import cm
import numpy as np

#variable n below should be number of curves to plot

#version 1:

color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
   plt.plot(x, y,c=c)

#or version 2:

color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
   c=next(color)
   plt.plot(x, y,c=c)

Example of 2: example plot with iter,next color

How do I remove a submodule?

With git 2.17 and above it's just:

git submodule deinit -f {module_name}
git add {module_name}
git commit

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

Just in case this is helpful to others, here's my anecdote:

I found this thread as a result of a problem I encountered while I was using Postman to send test data to my RESTEasy server, where- after a significant code change- I was getting nothing but 415 Unsupported Media Type errors.

Long story short, I tore everything out, eventually I tried to run the trivial file upload example I knew worked; it didn't. That's when I realized that the problem was with my Postman request. I normally don't send any special headers, but in a previous test I had added a "Content-Type": "application/json" header. OF COURSE, I was trying to upload "multipart/form-data." Removing it solved my issue.

Moral: Check your headers before you blow up your world. ;)

php is null or empty?

No it's not a bug. Have a look at the Loose comparisons with == table (second table), which shows the result of comparing each value in the first column with the values in the other columns:

    TRUE    FALSE   1       0       -1      "1"     "0"     "-1"    NULL    array() "php"   ""

    [...]    

""  FALSE   TRUE    FALSE   TRUE    FALSE   FALSE   FALSE   FALSE   TRUE    FALSE   FALSE   TRUE

There you can see that an empty string "" compared with false, 0, NULL or "" will yield true.

You might want to use is_null [docs] instead, or strict comparison (third table).

Find multiple files and rename them in Linux

For renaming recursively I use the following commands:

find -iname \*.* | rename -v "s/ /-/g"

how to convert 2d list to 2d numpy array?

I am using large data sets exported to a python file in the form

XVals1 = [.........] 
XVals2 = [.........] 

Each list is of identical length. I use

>>> a1 = np.array(SV.XVals1)

>>> a2 = np.array(SV.XVals2)

Then

>>> A = np.matrix([a1,a2])

Creating a list/array in excel using VBA to get a list of unique names in a column

I realize this is an old question, but I use a much simpler way. Typically I just grab the list that I need, either by query or copying an existing list or whatever, then remove the duplicates. We will assume for this answer that your list is already in column C, row 4, as per the original question. This method works for whatever size list you have and you can select header yes or no.

Dim rng as range
Range("C4").Select
Set rng = Range(Selection, Selection.End(xlDown))
rng.RemoveDuplicates Columns:=1, Header:=xlYes

Android RatingBar change star colors

Simple solution, use AppCompatRatingBar and its setProgressTintList method to achieve this, see this answer for reference.

JS. How to replace html element with another element/text, represented in string?

Because you are talking about your replacement being anything, and also replacing in the middle of an element's children, it becomes more tricky than just inserting a singular element, or directly removing and appending:

function replaceTargetWith( targetID, html ){
  /// find our target
  var i, tmp, elm, last, target = document.getElementById(targetID);
  /// create a temporary div or tr (to support tds)
  tmp = document.createElement(html.indexOf('<td')!=-1?'tr':'div'));
  /// fill that div with our html, this generates our children
  tmp.innerHTML = html;
  /// step through the temporary div's children and insertBefore our target
  i = tmp.childNodes.length;
  /// the insertBefore method was more complicated than I first thought so I 
  /// have improved it. Have to be careful when dealing with child lists as  
  /// they are counted as live lists and so will update as and when you make
  /// changes. This is why it is best to work backwards when moving children 
  /// around, and why I'm assigning the elements I'm working with to `elm` 
  /// and `last`
  last = target;
  while(i--){
    target.parentNode.insertBefore((elm = tmp.childNodes[i]), last);
    last = elm;
  }
  /// remove the target.
  target.parentNode.removeChild(target);
}

example usage:

replaceTargetWith( 'idTABLE', 'I <b>can</b> be <div>anything</div>' );

demo:

By using the .innerHTML of our temporary div this will generate the TextNodes and Elements we need to insert without any hard work. But rather than insert the temporary div itself -- this would give us mark up that we don't want -- we can just scan and insert it's children.

...either that or look to using jQuery and it's replaceWith method.

jQuery('#idTABLE').replaceWith('<blink>Why this tag??</blink>');


update 2012/11/15

As a response to EL 2002's comment above:

It not always possible. For example, when createElement('div') and set its innerHTML as <td>123</td>, this div becomes <div>123</div> (js throws away inappropriate td tag)

The above problem obviously negates my solution as well - I have updated my code above accordingly (at least for the td issue). However for certain HTML this will occur no matter what you do. All user agents interpret HTML via their own parsing rules, but nearly all of them will attempt to auto-correct bad HTML. The only way to achieve exactly what you are talking about (in some of your examples) is to take the HTML out of the DOM entirely, and manipulate it as a string. This will be the only way to achieve a markup string with the following (jQuery will not get around this issue either):

<table><tr>123 text<td>END</td></tr></table>

If you then take this string an inject it into the DOM, depending on the browser you will get the following:

123 text<table><tr><td>END</td></tr></table>

<table><tr><td>END</td></tr></table>

The only question that remains is why you would want to achieve broken HTML in the first place? :)

How to use multiple @RequestMapping annotations in spring?

Doesn't need to. RequestMapping annotation supports wildcards and ant-style paths. Also looks like you just want a default view, so you can put

<mvc:view-controller path="/" view-name="welcome"/>

in your config file. That will forward all requests to the Root to the welcome view.

Lua - Current time in milliseconds

I use LuaSocket to get more precision.

require "socket"
print("Milliseconds: " .. socket.gettime()*1000)

This adds a dependency of course, but works fine for personal use (in benchmarking scripts for example).

WCF ServiceHost access rights

Running Visual Studio as administrator could fix the issue, but if you use Visual Studio with for example TortoiseSVN, you cannot commit any changes. Another possible solution would be to run the service as administrator and the rest Visual Studio as local user.

How to upload and parse a CSV file in php

function doParseCSVFile($filesArray)
    {
        if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

            $strFilePath = $filesArray['frmUpload']['tmp_name']; 

            $strFileHandle = fopen($strFilePath,"r");
            $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
            $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

            do { 
                if ($line_of_text[0]) { 
                    $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                    ExecuteQry($strInsertSql);
                }               
            } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

        } else {
            return FALSE;
        }
    }

How to horizontally center an element

You can use the calc method. The usage is for the div you're centering. If you know its width, let's say it's 1200 pixels, go for:

.container {
    width:1200px;
    margin-left: calc(50% - 600px);
}

So basically it'll add a left margin of 50% minus half the known width.

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I had the same error when multiline string included new line (\n) characters. Merging all lines into one (thus removing all new line characters) and sending it to a browser used to solve. But was very inconvenient to code.

Often could not understand why this was an issue in Chrome until I came across to a statement which said that the current version of JavaScript engine in Chrome doesn't support multiline strings which are wrapped in single quotes and have new line (\n) characters in them. To make it work, multiline string need to be wrapped in double quotes. Changing my code to this, resolved this issue.

I will try to find a reference to a standard or Chrome doc which proves this. Until then, try this solution and see if works for you as well.

How to use QTimer

  1. It's good practice to give a parent to your QTimer to use Qt's memory management system.

  2. update() is a QWidget function - is that what you are trying to call or not? http://qt-project.org/doc/qt-4.8/qwidget.html#update.

  3. If number 2 does not apply, make sure that the function you are trying to trigger is declared as a slot in the header.

  4. Finally if none of these are your issue, it would be helpful to know if you are getting any run-time connect errors.

How can I pad an integer with zeros on the left?

Here is how you can format your string without using DecimalFormat.

String.format("%02d", 9)

09

String.format("%03d", 19)

019

String.format("%04d", 119)

0119

Check if an object exists

I think the easiest from a logical and efficiency point of view is using the queryset's exists() function, documented here:

https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.exists

So in your example above I would simply write:

if User.objects.filter(email = cleaned_info['username']).exists():
    # at least one object satisfying query exists
else:
    # no object satisfying query exists

How to insert newline in string literal?

One more way of convenient placement of Environment.NewLine in format string. The idea is to create string extension method that formats string as usual but also replaces {nl} in text with Environment.NewLine

Usage

   " X={0} {nl} Y={1}{nl} X+Y={2}".FormatIt(1, 2, 1+2);
   gives:
    X=1
    Y=2
    X+Y=3

Code

    ///<summary>
    /// Use "string".FormatIt(...) instead of string.Format("string, ...)
    /// Use {nl} in text to insert Environment.NewLine 
    ///</summary>
    ///<exception cref="ArgumentNullException">If format is null</exception>
    [StringFormatMethod("format")]
    public static string FormatIt(this string format, params object[] args)
    {
        if (format == null) throw new ArgumentNullException("format");

        return string.Format(format.Replace("{nl}", Environment.NewLine), args);
    }

Note

  1. If you want ReSharper to highlight your parameters, add attribute to the method above

    [StringFormatMethod("format")]

  2. This implementation is obviously less efficient than just String.Format

  3. Maybe one, who interested in this question would be interested in the next question too: Named string formatting in C#

Get query from java.sql.PreparedStatement

I have made a workaround to solve this problem. Visit the below link for more details http://code-outofbox.blogspot.com/2015/07/java-prepared-statement-print-values.html

Solution:

// Initialize connection
PreparedStatement prepStmt = connection.prepareStatement(sql);

PreparedStatementHelper prepHelper = new PreparedStatementHelper(prepStmt);

// User prepHelper.setXXX(indx++, value);
// .....

try {
   Pattern pattern = Pattern.compile("\\?");
   Matcher matcher = pattern.matcher(sql);
   StringBuffer sb = new StringBuffer();
   int indx = 1;  // Parameter begin with index 1
   while (matcher.find()) {
 matcher.appendReplacement(sb, prepHelper.getParameter(indx++));
   }
   matcher.appendTail(sb);
   LOGGER.debug("Executing Query [" + sb.toString() + "] with Database[" + /*db name*/ + "] ...");
   } catch (Exception ex) {
    LOGGER.debug("Executing Query [" + sql + "] with Database[" +  /*db name*/+ "] ...");
}

/****************************************************/

package java.sql;

import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;

public class PreparedStatementHelper implements PreparedStatement {

 private PreparedStatement prepStmt;
 private String[] values;

 public PreparedStatementHelper(PreparedStatement prepStmt) throws SQLException {
  this.prepStmt = prepStmt;
  this.values = new String[this.prepStmt.getParameterMetaData().getParameterCount()];
 }

 public String getParameter(int index) {
  String value = this.values[index-1];
  return String.valueOf(value);
 }

 private void setParameter(int index, Object value) {
  String valueStr = "";
  if (value instanceof String) {
   valueStr = "'" + String.valueOf(value).replaceAll("'", "''") + "'";
  } else if (value instanceof Integer) {
   valueStr = String.valueOf(value);
  } else if (value instanceof Date || value instanceof Time || value instanceof Timestamp) {
   valueStr = "'" + String.valueOf(value) + "'";
  } else {
   valueStr = String.valueOf(value);
  }
  this.values[index-1] = valueStr;
 }

 @Override
 public ResultSet executeQuery(String sql) throws SQLException {
  return this.prepStmt.executeQuery(sql);
 }

 @Override
 public int executeUpdate(String sql) throws SQLException {
  return this.prepStmt.executeUpdate(sql);
 }

 @Override
 public void close() throws SQLException {
  this.prepStmt.close();

 }

 @Override
 public int getMaxFieldSize() throws SQLException {
  return this.prepStmt.getMaxFieldSize();
 }

 @Override
 public void setMaxFieldSize(int max) throws SQLException {
  this.prepStmt.setMaxFieldSize(max);
 }

 @Override
 public int getMaxRows() throws SQLException {
  return this.prepStmt.getMaxRows();
 }

 @Override
 public void setMaxRows(int max) throws SQLException {
  this.prepStmt.setMaxRows(max);
 }

 @Override
 public void setEscapeProcessing(boolean enable) throws SQLException {
  this.prepStmt.setEscapeProcessing(enable);
 }

 @Override
 public int getQueryTimeout() throws SQLException {
  return this.prepStmt.getQueryTimeout();
 }

 @Override
 public void setQueryTimeout(int seconds) throws SQLException {
  this.prepStmt.setQueryTimeout(seconds);
 }

 @Override
 public void cancel() throws SQLException {
  this.prepStmt.cancel();
 }

 @Override
 public SQLWarning getWarnings() throws SQLException {
  return this.prepStmt.getWarnings();
 }

 @Override
 public void clearWarnings() throws SQLException {
  this.prepStmt.clearWarnings();
 }

 @Override
 public void setCursorName(String name) throws SQLException {
  this.prepStmt.setCursorName(name);
 }

 @Override
 public boolean execute(String sql) throws SQLException {
  return this.prepStmt.execute(sql);
 }

 @Override
 public ResultSet getResultSet() throws SQLException {
  return this.prepStmt.getResultSet();
 }

 @Override
 public int getUpdateCount() throws SQLException {
  return this.prepStmt.getUpdateCount();
 }

 @Override
 public boolean getMoreResults() throws SQLException {
  return this.prepStmt.getMoreResults();
 }

 @Override
 public void setFetchDirection(int direction) throws SQLException {
  this.prepStmt.setFetchDirection(direction);
 }

 @Override
 public int getFetchDirection() throws SQLException {
  return this.prepStmt.getFetchDirection();
 }

 @Override
 public void setFetchSize(int rows) throws SQLException {
  this.prepStmt.setFetchSize(rows);
 }

 @Override
 public int getFetchSize() throws SQLException {
  return this.prepStmt.getFetchSize();
 }

 @Override
 public int getResultSetConcurrency() throws SQLException {
  return this.prepStmt.getResultSetConcurrency();
 }

 @Override
 public int getResultSetType() throws SQLException {
  return this.prepStmt.getResultSetType();
 }

 @Override
 public void addBatch(String sql) throws SQLException {
  this.prepStmt.addBatch(sql);
 }

 @Override
 public void clearBatch() throws SQLException {
  this.prepStmt.clearBatch();
 }

 @Override
 public int[] executeBatch() throws SQLException {
  return this.prepStmt.executeBatch();
 }

 @Override
 public Connection getConnection() throws SQLException {
  return this.prepStmt.getConnection();
 }

 @Override
 public boolean getMoreResults(int current) throws SQLException {
  return this.prepStmt.getMoreResults(current);
 }

 @Override
 public ResultSet getGeneratedKeys() throws SQLException {
  return this.prepStmt.getGeneratedKeys();
 }

 @Override
 public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
  return this.prepStmt.executeUpdate(sql, autoGeneratedKeys);
 }

 @Override
 public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
  return this.prepStmt.executeUpdate(sql, columnIndexes);
 }

 @Override
 public int executeUpdate(String sql, String[] columnNames) throws SQLException {
  return this.prepStmt.executeUpdate(sql, columnNames);
 }

 @Override
 public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
  return this.prepStmt.execute(sql, autoGeneratedKeys);
 }

 @Override
 public boolean execute(String sql, int[] columnIndexes) throws SQLException {
  return this.prepStmt.execute(sql, columnIndexes);
 }

 @Override
 public boolean execute(String sql, String[] columnNames) throws SQLException {
  return this.prepStmt.execute(sql, columnNames);
 }

 @Override
 public int getResultSetHoldability() throws SQLException {
  return this.prepStmt.getResultSetHoldability();
 }

 @Override
 public boolean isClosed() throws SQLException {
  return this.prepStmt.isClosed();
 }

 @Override
 public void setPoolable(boolean poolable) throws SQLException {
  this.prepStmt.setPoolable(poolable);
 }

 @Override
 public boolean isPoolable() throws SQLException {
  return this.prepStmt.isPoolable();
 }

 @Override
 public <T> T unwrap(Class<T> iface) throws SQLException {
  return this.prepStmt.unwrap(iface);
 }

 @Override
 public boolean isWrapperFor(Class<?> iface) throws SQLException {
  return this.prepStmt.isWrapperFor(iface);
 }

 @Override
 public ResultSet executeQuery() throws SQLException {
  return this.prepStmt.executeQuery();
 }

 @Override
 public int executeUpdate() throws SQLException {
  return this.prepStmt.executeUpdate();
 }

 @Override
 public void setNull(int parameterIndex, int sqlType) throws SQLException {
  this.prepStmt.setNull(parameterIndex, sqlType);
  setParameter(parameterIndex, null);
 }

 @Override
 public void setBoolean(int parameterIndex, boolean x) throws SQLException {
  this.prepStmt.setBoolean(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setByte(int parameterIndex, byte x) throws SQLException {
  this.prepStmt.setByte(parameterIndex, x);
  // TODO Add to tree set
 }

 @Override
 public void setShort(int parameterIndex, short x) throws SQLException {
  this.prepStmt.setShort(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setInt(int parameterIndex, int x) throws SQLException {
  this.prepStmt.setInt(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setLong(int parameterIndex, long x) throws SQLException {
  this.prepStmt.setLong(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setFloat(int parameterIndex, float x) throws SQLException {
  this.prepStmt.setFloat(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setDouble(int parameterIndex, double x) throws SQLException {
  this.prepStmt.setDouble(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
  this.prepStmt.setBigDecimal(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setString(int parameterIndex, String x) throws SQLException {
  this.prepStmt.setString(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setBytes(int parameterIndex, byte[] x) throws SQLException {
  this.prepStmt.setBytes(parameterIndex, x);
  // TODO Add to tree set
 }

 @Override
 public void setDate(int parameterIndex, Date x) throws SQLException {
  this.prepStmt.setDate(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setTime(int parameterIndex, Time x) throws SQLException {
  this.prepStmt.setTime(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
  this.prepStmt.setTimestamp(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
  this.prepStmt.setAsciiStream(parameterIndex, x, length);
 }

 @SuppressWarnings("deprecation")
 @Override
 public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
  this.prepStmt.setUnicodeStream(parameterIndex, x, length);
 }

 @Override
 public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
  this.prepStmt.setBinaryStream(parameterIndex, x, length);
 }

 @Override
 public void clearParameters() throws SQLException {
  this.prepStmt.clearParameters();
 }

 @Override
 public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
  this.prepStmt.setObject(parameterIndex, x, targetSqlType);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setObject(int parameterIndex, Object x) throws SQLException {
  this.prepStmt.setObject(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public boolean execute() throws SQLException {
  return this.prepStmt.execute();
 }

 @Override
 public void addBatch() throws SQLException {
  this.prepStmt.addBatch();
 }

 @Override
 public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
  this.prepStmt.setCharacterStream(parameterIndex, reader, length);
 }

 @Override
 public void setRef(int parameterIndex, Ref x) throws SQLException {
  this.prepStmt.setRef(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setBlob(int parameterIndex, Blob x) throws SQLException {
  this.prepStmt.setBlob(parameterIndex, x);
 }

 @Override
 public void setClob(int parameterIndex, Clob x) throws SQLException {
  this.prepStmt.setClob(parameterIndex, x);
 }

 @Override
 public void setArray(int parameterIndex, Array x) throws SQLException {
  this.prepStmt.setArray(parameterIndex, x);
  // TODO Add to tree set
 }

 @Override
 public ResultSetMetaData getMetaData() throws SQLException {
  return this.prepStmt.getMetaData();
 }

 @Override
 public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
  this.prepStmt.setDate(parameterIndex, x, cal);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
  this.prepStmt.setTime(parameterIndex, x, cal);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
  this.prepStmt.setTimestamp(parameterIndex, x, cal);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
  this.prepStmt.setNull(parameterIndex, sqlType, typeName);
  setParameter(parameterIndex, null);
 }

 @Override
 public void setURL(int parameterIndex, URL x) throws SQLException {
  this.prepStmt.setURL(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public ParameterMetaData getParameterMetaData() throws SQLException {
  return this.prepStmt.getParameterMetaData();
 }

 @Override
 public void setRowId(int parameterIndex, RowId x) throws SQLException {
  this.prepStmt.setRowId(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setNString(int parameterIndex, String value) throws SQLException {
  this.prepStmt.setNString(parameterIndex, value);
  setParameter(parameterIndex, value);
 }

 @Override
 public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
  this.prepStmt.setNCharacterStream(parameterIndex, value, length);
 }

 @Override
 public void setNClob(int parameterIndex, NClob value) throws SQLException {
  this.prepStmt.setNClob(parameterIndex, value);
 }

 @Override
 public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
  this.prepStmt.setClob(parameterIndex, reader, length);
 }

 @Override
 public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
  this.prepStmt.setBlob(parameterIndex, inputStream, length);
 }

 @Override
 public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
  this.prepStmt.setNClob(parameterIndex, reader, length);
 }

 @Override
 public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
  this.prepStmt.setSQLXML(parameterIndex, xmlObject);
  setParameter(parameterIndex, xmlObject);
 }

 @Override
 public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
  this.prepStmt.setObject(parameterIndex, x, targetSqlType, scaleOrLength);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
  this.prepStmt.setAsciiStream(parameterIndex, x, length);
 }

 @Override
 public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
  this.prepStmt.setBinaryStream(parameterIndex, x, length);
 }

 @Override
 public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
  this.prepStmt.setCharacterStream(parameterIndex, reader, length);
 }

 @Override
 public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
  this.prepStmt.setAsciiStream(parameterIndex, x);
  // TODO Add to tree set
 }

 @Override
 public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
  this.prepStmt.setBinaryStream(parameterIndex, x);
 }

 @Override
 public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
  this.prepStmt.setCharacterStream(parameterIndex, reader);
 }

 @Override
 public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
  this.prepStmt.setNCharacterStream(parameterIndex, value);
 }

 @Override
 public void setClob(int parameterIndex, Reader reader) throws SQLException {
  this.prepStmt.setClob(parameterIndex, reader);
  // TODO Add to tree set
 }

 @Override
 public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
  this.prepStmt.setBlob(parameterIndex, inputStream);
 }

 @Override
 public void setNClob(int parameterIndex, Reader reader) throws SQLException {
  this.prepStmt.setNClob(parameterIndex, reader);
 }

}

Why is synchronized block better than synchronized method?

Define 'better'. A synchronized block is only better because it allows you to:

  1. Synchronize on a different object
  2. Limit the scope of synchronization

Now your specific example is an example of the double-checked locking pattern which is suspect (in older Java versions it was broken, and it is easy to do it wrong).

If your initialization is cheap, it might be better to initialize immediately with a final field, and not on the first request, it would also remove the need for synchronization.

jQuery scroll to ID from different page

I made a reusable plugin that can do this... I left the binding to events outside the plugin itself because I feel it is too intrusive for such a little helper....

jQuery(function ($) {

    /**
     * This small plugin will scrollTo a target, smoothly
     *
     * First argument = time to scroll to the target
     * Second argument = set the hash in the current url yes or no
     */
    $.fn.smoothScroll = function(t, setHash) {
        // Set time to t variable to if undefined 500 for 500ms transition
        t = t || 500;
        setHash = (typeof setHash == 'undefined') ? true : setHash;

        // Return this as a proper jQuery plugin should
        return this.each(function() {
            $('html, body').animate({
                scrollTop: $(this).offset().top
            }, t);

            // Lets set the hash to the current ID since if an event was prevented this doesn't get done
            if (this.id && setHash) {
                window.location.hash = this.id;
            }
        });
    };

});

Now next, we can onload just do this, check for a hash and if its there try to use it directly as a selector for jQuery. Now I couldn't easily test this at the time but I made similar stuff for production sites not long ago, if this doesn't immediatly work let me know and I'll look into the solution I got there.

(script should be within an onload section)

if (window.location.hash) {
    window.scrollTo(0,0);
    $(window.location.hash).smoothScroll();
}

Next we bind the plugin to onclick of anchors which only contain a hash in their href attribute.

(script should be within an onload section)

$('a[href^="#"]').click(function(e) {
    e.preventDefault();

    $($(this).attr('href')).smoothScroll();
});

Since jQuery doesn't do anything if the match itself fails we have a nice fallback for when a target on a page can't be found yay \o/

Update

Alternative onclick handler to scroll to the top when theres only a hash:

$('a[href^="#"]').click(function(e) {
    e.preventDefault();
    var href = $(this).attr('href');

    // In this case we have only a hash, so maybe we want to scroll to the top of the page?
    if(href.length === 1) { href = 'body' }

    $(href).smoothScroll();
});

Here is also a simple jsfiddle that demonstrates the scrolling within page, onload is a little hard to set up...

http://jsfiddle.net/sg3s/bZnWN/

Update 2

So you might get in trouble with the window already scrolling to the element onload. This fixes that: window.scrollTo(0,0); it just scrolls the page to the left top. Added it to the code snippet above.

What is the JavaScript version of sleep()?

To keep the main thread busy for some milliseconds:

function wait(ms) {
  const start = performance.now();
  while(performance.now() - start < ms);
}

MongoDb query condition on comparing 2 fields

In case performance is more important than readability and as long as your condition consists of simple arithmetic operations, you can use aggregation pipeline. First, use $project to calculate the left hand side of the condition (take all fields to left hand side). Then use $match to compare with a constant and filter. This way you avoid javascript execution. Below is my test in python:

import pymongo
from random import randrange

docs = [{'Grade1': randrange(10), 'Grade2': randrange(10)} for __ in range(100000)]

coll = pymongo.MongoClient().test_db.grades
coll.insert_many(docs)

Using aggregate:

%timeit -n1 -r1 list(coll.aggregate([
    {
        '$project': {
            'diff': {'$subtract': ['$Grade1', '$Grade2']},
            'Grade1': 1,
            'Grade2': 1
        }
    },
    {
        '$match': {'diff': {'$gt': 0}}
    }
]))

1 loop, best of 1: 192 ms per loop

Using find and $where:

%timeit -n1 -r1 list(coll.find({'$where': 'this.Grade1 > this.Grade2'}))

1 loop, best of 1: 4.54 s per loop