Programs & Examples On #Heap

A heap (data structure) is a tree that is ordered with respect to depth. Heap can also refer to process memory set aside for dynamic allocation.

Heap vs Binary Search Tree (BST)

Summary

          Type      BST (*)   Heap
Insert    average   log(n)    1
Insert    worst     log(n)    log(n) or n (***)
Find any  worst     log(n)    n
Find max  worst     1 (**)    1
Create    worst     n log(n)  n
Delete    worst     log(n)    log(n)

All average times on this table are the same as their worst times except for Insert.

  • *: everywhere in this answer, BST == Balanced BST, since unbalanced sucks asymptotically
  • **: using a trivial modification explained in this answer
  • ***: log(n) for pointer tree heap, n for dynamic array heap

Advantages of binary heap over a BST

  • average time insertion into a binary heap is O(1), for BST is O(log(n)). This is the killer feature of heaps.

    There are also other heaps which reach O(1) amortized (stronger) like the Fibonacci Heap, and even worst case, like the Brodal queue, although they may not be practical because of non-asymptotic performance: Are Fibonacci heaps or Brodal queues used in practice anywhere?

  • binary heaps can be efficiently implemented on top of either dynamic arrays or pointer-based trees, BST only pointer-based trees. So for the heap we can choose the more space efficient array implementation, if we can afford occasional resize latencies.

  • binary heap creation is O(n) worst case, O(n log(n)) for BST.

Advantage of BST over binary heap

  • search for arbitrary elements is O(log(n)). This is the killer feature of BSTs.

    For heap, it is O(n) in general, except for the largest element which is O(1).

"False" advantage of heap over BST

  • heap is O(1) to find max, BST O(log(n)).

    This is a common misconception, because it is trivial to modify a BST to keep track of the largest element, and update it whenever that element could be changed: on insertion of a larger one swap, on removal find the second largest. Can we use binary search tree to simulate heap operation? (mentioned by Yeo).

    Actually, this is a limitation of heaps compared to BSTs: the only efficient search is that for the largest element.

Average binary heap insert is O(1)

Sources:

Intuitive argument:

  • bottom tree levels have exponentially more elements than top levels, so new elements are almost certain to go at the bottom
  • heap insertion starts from the bottom, BST must start from the top

In a binary heap, increasing the value at a given index is also O(1) for the same reason. But if you want to do that, it is likely that you will want to keep an extra index up-to-date on heap operations How to implement O(logn) decrease-key operation for min-heap based Priority Queue? e.g. for Dijkstra. Possible at no extra time cost.

GCC C++ standard library insert benchmark on real hardware

I benchmarked the C++ std::set (Red-black tree BST) and std::priority_queue (dynamic array heap) insert to see if I was right about the insert times, and this is what I got:

enter image description here

  • benchmark code
  • plot script
  • plot data
  • tested on Ubuntu 19.04, GCC 8.3.0 in a Lenovo ThinkPad P51 laptop with CPU: Intel Core i7-7820HQ CPU (4 cores / 8 threads, 2.90 GHz base, 8 MB cache), RAM: 2x Samsung M471A2K43BB1-CRC (2x 16GiB, 2400 Mbps), SSD: Samsung MZVLB512HAJQ-000L7 (512GB, 3,000 MB/s)

So clearly:

  • heap insert time is basically constant.

    We can clearly see dynamic array resize points. Since we are averaging every 10k inserts to be able to see anything at all above system noise, those peaks are in fact about 10k times larger than shown!

    The zoomed graph excludes essentially only the array resize points, and shows that almost all inserts fall under 25 nanoseconds.

  • BST is logarithmic. All inserts are much slower than the average heap insert.

  • BST vs hashmap detailed analysis at: What data structure is inside std::map in C++?

GCC C++ standard library insert benchmark on gem5

gem5 is a full system simulator, and therefore provides an infinitely accurate clock with with m5 dumpstats. So I tried to use it to estimate timings for individual inserts.

enter image description here

Interpretation:

  • heap is still constant, but now we see in more detail that there are a few lines, and each higher line is more sparse.

    This must correspond to memory access latencies are done for higher and higher inserts.

  • TODO I can't really interpret the BST fully one as it does not look so logarithmic and somewhat more constant.

    With this greater detail however we can see can also see a few distinct lines, but I'm not sure what they represent: I would expect the bottom line to be thinner, since we insert top bottom?

Benchmarked with this Buildroot setup on an aarch64 HPI CPU.

BST cannot be efficiently implemented on an array

Heap operations only need to bubble up or down a single tree branch, so O(log(n)) worst case swaps, O(1) average.

Keeping a BST balanced requires tree rotations, which can change the top element for another one, and would require moving the entire array around (O(n)).

Heaps can be efficiently implemented on an array

Parent and children indexes can be computed from the current index as shown here.

There are no balancing operations like BST.

Delete min is the most worrying operation as it has to be top down. But it can always be done by "percolating down" a single branch of the heap as explained here. This leads to an O(log(n)) worst case, since the heap is always well balanced.

If you are inserting a single node for every one you remove, then you lose the advantage of the asymptotic O(1) average insert that heaps provide as the delete would dominate, and you might as well use a BST. Dijkstra however updates nodes several times for each removal, so we are fine.

Dynamic array heaps vs pointer tree heaps

Heaps can be efficiently implemented on top of pointer heaps: Is it possible to make efficient pointer-based binary heap implementations?

The dynamic array implementation is more space efficient. Suppose that each heap element contains just a pointer to a struct:

  • the tree implementation must store three pointers for each element: parent, left child and right child. So the memory usage is always 4n (3 tree pointers + 1 struct pointer).

    Tree BSTs would also need further balancing information, e.g. black-red-ness.

  • the dynamic array implementation can be of size 2n just after a doubling. So on average it is going to be 1.5n.

On the other hand, the tree heap has better worst case insert, because copying the backing dynamic array to double its size takes O(n) worst case, while the tree heap just does new small allocations for each node.

Still, the backing array doubling is O(1) amortized, so it comes down to a maximum latency consideration. Mentioned here.

Philosophy

  • BSTs maintain a global property between a parent and all descendants (left smaller, right bigger).

    The top node of a BST is the middle element, which requires global knowledge to maintain (knowing how many smaller and larger elements are there).

    This global property is more expensive to maintain (log n insert), but gives more powerful searches (log n search).

  • Heaps maintain a local property between parent and direct children (parent > children).

    The top node of a heap is the big element, which only requires local knowledge to maintain (knowing your parent).

Comparing BST vs Heap vs Hashmap:

  • BST: can either be either a reasonable:

    • unordered set (a structure that determines if an element was previously inserted or not). But hashmap tends to be better due to O(1) amortized insert.
    • sorting machine. But heap is generally better at that, which is why heapsort is much more widely known than tree sort
  • heap: is just a sorting machine. Cannot be an efficient unordered set, because you can only check for the smallest/largest element fast.

  • hash map: can only be an unordered set, not an efficient sorting machine, because the hashing mixes up any ordering.

Doubly-linked list

A doubly linked list can be seen as subset of the heap where first item has greatest priority, so let's compare them here as well:

  • insertion:
    • position:
      • doubly linked list: the inserted item must be either the first or last, as we only have pointers to those elements.
      • binary heap: the inserted item can end up in any position. Less restrictive than linked list.
    • time:
      • doubly linked list: O(1) worst case since we have pointers to the items, and the update is really simple
      • binary heap: O(1) average, thus worse than linked list. Tradeoff for having more general insertion position.
  • search: O(n) for both

An use case for this is when the key of the heap is the current timestamp: in that case, new entries will always go to the beginning of the list. So we can even forget the exact timestamp altogether, and just keep the position in the list as the priority.

This can be used to implement an LRU cache. Just like for heap applications like Dijkstra, you will want to keep an additional hashmap from the key to the corresponding node of the list, to find which node to update quickly.

Comparison of different Balanced BST

Although the asymptotic insert and find times for all data structures that are commonly classified as "Balanced BSTs" that I've seen so far is the same, different BBSTs do have different trade-offs. I haven't fully studied this yet, but it would be good to summarize these trade-offs here:

  • Red-black tree. Appears to be the most commonly used BBST as of 2019, e.g. it is the one used by the GCC 8.3.0 C++ implementation
  • AVL tree. Appears to be a bit more balanced than BST, so it could be better for find latency, at the cost of slightly more expensive finds. Wiki summarizes: "AVL trees are often compared with red–black trees because both support the same set of operations and take [the same] time for the basic operations. For lookup-intensive applications, AVL trees are faster than red–black trees because they are more strictly balanced. Similar to red–black trees, AVL trees are height-balanced. Both are, in general, neither weight-balanced nor mu-balanced for any mu < 1/2; that is, sibling nodes can have hugely differing numbers of descendants."
  • WAVL. The original paper mentions advantages of that version in terms of bounds on rebalancing and rotation operations.

See also

Similar question on CS: https://cs.stackexchange.com/questions/27860/whats-the-difference-between-a-binary-search-tree-and-a-binary-heap

Why should C++ programmers minimize use of 'new'?

I see that a few important reasons for doing as few new's as possible are missed:

Operator new has a non-deterministic execution time

Calling new may or may not cause the OS to allocate a new physical page to your process this can be quite slow if you do it often. Or it may already have a suitable memory location ready, we don't know. If your program needs to have consistent and predictable execution time (like in a real-time system or game/physics simulation) you need to avoid new in your time critical loops.

Operator new is an implicit thread synchronization

Yes you heard me, your OS needs to make sure your page tables are consistent and as such calling new will cause your thread to acquire an implicit mutex lock. If you are consistently calling new from many threads you are actually serialising your threads (I've done this with 32 CPUs, each hitting on new to get a few hundred bytes each, ouch! that was a royal p.i.t.a. to debug)

The rest such as slow, fragmentation, error prone, etc have already been mentioned by other answers.

Stack, Static, and Heap in C++

What are the problems of static and stack?

The problem with "static" allocation is that the allocation is made at compile-time: you can't use it to allocate some variable number of data, the number of which isn't known until run-time.

The problem with allocating on the "stack" is that the allocation is destroyed as soon as the subroutine which does the allocation returns.

I could write an entire application without allocate variables in the heap?

Perhaps but not a non-trivial, normal, big application (but so-called "embedded" programs might be written without the heap, using a subset of C++).

What garbage collector does ?

It keeps watching your data ("mark and sweep") to detect when your application is no longer referencing it. This is convenient for the application, because the application doesn't need to deallocate the data ... but the garbage collector might be computationally expensive.

Garbage collectors aren't a usual feature of C++ programming.

What could you do manipulating the memory by yourself that you couldn't do using this garbage collector?

Learn the C++ mechanisms for deterministic memory deallocation:

  • 'static': never deallocated
  • 'stack': as soon as the variable "goes out of scope"
  • 'heap': when the pointer is deleted (explicitly deleted by the application, or implicitly deleted within some-or-other subroutine)

How can building a heap be O(n) time complexity?

There are already some great answers but I would like to add a little visual explanation

enter image description here

Now, take a look at the image, there are
n/2^1 green nodes with height 0 (here 23/2 = 12)
n/2^2 red nodes with height 1 (here 23/4 = 6)
n/2^3 blue node with height 2 (here 23/8 = 3)
n/2^4 purple nodes with height 3 (here 23/16 = 2)
so there are n/2^(h+1) nodes for height h
To find the time complexity lets count the amount of work done or max no of iterations performed by each node
now it can be noticed that each node can perform(atmost) iterations == height of the node

Green  = n/2^1 * 0 (no iterations since no children)  
red    = n/2^2 * 1 (heapify will perform atmost one swap for each red node)  
blue   = n/2^3 * 2 (heapify will perform atmost two swaps for each blue node)  
purple = n/2^4 * 3 (heapify will perform atmost three swaps for each purple node)   

so for any nodes with height h maximum work done is n/2^(h+1) * h

Now total work done is

->(n/2^1 * 0) + (n/2^2 * 1)+ (n/2^3 * 2) + (n/2^4 * 3) +...+ (n/2^(h+1) * h)  
-> n * ( 0 + 1/4 + 2/8 + 3/16 +...+ h/2^(h+1) ) 

now for any value of h, the sequence

-> ( 0 + 1/4 + 2/8 + 3/16 +...+ h/2^(h+1) ) 

will never exceed 1
Thus the time complexity will never exceed O(n) for building heap

Difference between javacore, thread dump and heap dump in Websphere

Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors Heap dumps - picture of in memory objects - used for memory analysis Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation System cores

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

This command shows the configured heap sizes in bytes.

java -XX:+PrintFlagsFinal -version | grep HeapSize

It works on Amazon AMI on EC2 as well.

How to increase application heap size in Eclipse?

In Eclipse Folder there is eclipse.ini file. Increase size -Xms512m -Xmx1024m

Which is faster: Stack allocation or Heap allocation

Never do premature assumption as other application code and usage can impact your function. So looking at function is isolation is of no use.

If you are serious with application then VTune it or use any similar profiling tool and look at hotspots.

Ketan

how to increase java heap memory permanently?

You also use this below to expand the memory

export _JAVA_OPTIONS="-Xms512m -Xmx1024m -Xss512m -XX:MaxPermSize=1024m"

Xmx specifies the maximum memory allocation pool for a Java virtual machine (JVM)

Xms specifies the initial memory allocation pool.

Xss setting memory size of thread stack

XX:MaxPermSize: the maximum permanent generation size

How do I analyze a .hprof file?

If you want to do a custom analysis of your heapdump then there's:

This library is fast but you will need to write your analysis code in Java.

From the docs:

  • Does not create any temporary files on disk to process heap dump
  • Can work directly GZ compressed heap dumps
  • HeapPath notation

increase the java heap size permanently?

what platform are you running?..
if its unix, maybe adding

alias java='java -Xmx1g'  

to .bashrc (or similar) work

edit: Changing XmX to Xmx

java.lang.OutOfMemoryError: GC overhead limit exceeded

For the record, we had the same problem today. We fixed it by using this option:

-XX:-UseConcMarkSweepGC

Apparently, this modified the strategy used for garbage collection, which made the issue disappear.

How do I set Java's min and max heap size through environment variables?

You can't do it using environment variables. It's done via "non standard" options. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.)

Priority queue in .Net

You may find useful this implementation: http://www.codeproject.com/Articles/126751/Priority-queue-in-Csharp-with-help-of-heap-data-st.aspx

it is generic and based on heap data structure

Could not reserve enough space for object heap

I know there are a lot of answers here already, but none of them helped me. In the end I opened the file /etc/elasticsearch/jvm.options and changed:

-Xms2G
-Xmx2G

to

-Xms256M
-Xmx256M

That solved it for me. Hopefully this helps someone else here.

How to view the current heap size that an application is using?

public class CheckHeapSize {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        long heapSize = Runtime.getRuntime().totalMemory(); 

        // Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
        long heapMaxSize = Runtime.getRuntime().maxMemory();

         // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
        long heapFreeSize = Runtime.getRuntime().freeMemory(); 

        System.out.println("heapsize"+formatSize(heapSize));
        System.out.println("heapmaxsize"+formatSize(heapMaxSize));
        System.out.println("heapFreesize"+formatSize(heapFreeSize));

    }
    public static String formatSize(long v) {
        if (v < 1024) return v + " B";
        int z = (63 - Long.numberOfLeadingZeros(v)) / 10;
        return String.format("%.1f %sB", (double)v / (1L << (z*10)), " KMGTPE".charAt(z));
    }
}

Find running median from a stream of integers

Here is my simple but efficient algorithm (in C++) for calculating running median from a stream of integers:

#include<algorithm>
#include<fstream>
#include<vector>
#include<list>

using namespace std;

void runningMedian(std::ifstream& ifs, std::ofstream& ofs, const unsigned bufSize) {
    if (bufSize < 1)
        throw exception("Wrong buffer size.");
    bool evenSize = bufSize % 2 == 0 ? true : false;
    list<int> q;
    vector<int> nums;
    int n;
    unsigned count = 0;
    while (ifs.good()) {
        ifs >> n;
        q.push_back(n);
        auto ub = std::upper_bound(nums.begin(), nums.end(), n);
        nums.insert(ub, n);
        count++;
        if (nums.size() >= bufSize) {
            auto it = std::find(nums.begin(), nums.end(), q.front());
            nums.erase(it);
            q.pop_front();
            if (evenSize)
                ofs << count << ": " << (static_cast<double>(nums[nums.size() / 2 - 1] +
                static_cast<double>(nums[nums.size() / 2]))) / 2.0 << '\n';
            else
                ofs << count << ": " << static_cast<double>(nums[nums.size() / 2]);
        }
    }
}

The bufferSize specifies the size of the numbers sequence, on which the running median must be calculated. When reading numbers from the input stream ifs the vector of the size bufferSize is maintained in sorted order. The median is calculated by taking the middle of the sorted vector, if bufferSize is odd, or the sum of the two middle elements divided by 2, when bufferSize is even. Additinally, I maintain a list of last bufferSize elements read from input. When a new element is added, I put it in the right place in sorted vector and remove from the vector the element added bufferSize steps before (the value of the element retained in the front of the list). In the same time I remove the old element from the list: every new element is placed on the back of the list, every old element is removed from the front. After reaching the bufferSize, both the list and the vector stop to grow, and every insertion of a new element is compensated be deletion of an old element, placed in the list bufferSize steps before. Note, I do not care, whether I remove from the vector exactly the element, placed bufferSize steps before, or just an element that has the same value. For the value of median it does not matter. All calculated median values are output in the output stream.

Increase JVM max heap size for Eclipse

You can use this configuration:

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M

How to give Jenkins more heap space when it´s started as a service under Windows?

In your Jenkins installation directory there is a jenkins.xml, where you can set various options. Add the parameter -Xmx with the size you want to the arguments-tag (or increase the size if its already there).

Finding the median of an unsorted array

As wikipedia says, Median-of-Medians is theoretically o(N), but it is not used in practice because the overhead of finding "good" pivots makes it too slow.
http://en.wikipedia.org/wiki/Selection_algorithm

Here is Java source for a Quickselect algorithm to find the k'th element in an array:

/**
 * Returns position of k'th largest element of sub-list.
 * 
 * @param list list to search, whose sub-list may be shuffled before
 *            returning
 * @param lo first element of sub-list in list
 * @param hi just after last element of sub-list in list
 * @param k
 * @return position of k'th largest element of (possibly shuffled) sub-list.
 */
static int select(double[] list, int lo, int hi, int k) {
    int n = hi - lo;
    if (n < 2)
        return lo;

    double pivot = list[lo + (k * 7919) % n]; // Pick a random pivot

    // Triage list to [<pivot][=pivot][>pivot]
    int nLess = 0, nSame = 0, nMore = 0;
    int lo3 = lo;
    int hi3 = hi;
    while (lo3 < hi3) {
        double e = list[lo3];
        int cmp = compare(e, pivot);
        if (cmp < 0) {
            nLess++;
            lo3++;
        } else if (cmp > 0) {
            swap(list, lo3, --hi3);
            if (nSame > 0)
                swap(list, hi3, hi3 + nSame);
            nMore++;
        } else {
            nSame++;
            swap(list, lo3, --hi3);
        }
    }
    assert (nSame > 0);
    assert (nLess + nSame + nMore == n);
    assert (list[lo + nLess] == pivot);
    assert (list[hi - nMore - 1] == pivot);
    if (k >= n - nMore)
        return select(list, hi - nMore, hi, k - nLess - nSame);
    else if (k < nLess)
        return select(list, lo, lo + nLess, k);
    return lo + k;
}

I have not included the source of the compare and swap methods, so it's easy to change the code to work with Object[] instead of double[].

In practice, you can expect the above code to be o(N).

How is the default max Java heap size determined?

A number of parameters affect generation size. The following diagram illustrates the difference between committed space and virtual space in the heap. At initialization of the virtual machine, the entire space for the heap is reserved. The size of the space reserved can be specified with the -Xmx option. If the value of the -Xms parameter is smaller than the value of the -Xmx parameter, not all of the space that is reserved is immediately committed to the virtual machine. The uncommitted space is labeled "virtual" in this figure. The different parts of the heap (permanent generation, tenured generation and young generation) can grow to the limit of the virtual space as needed.

enter image description here

By default, the virtual machine grows or shrinks the heap at each collection to try to keep the proportion of free space to live objects at each collection within a specific range. This target range is set as a percentage by the parameters -XX:MinHeapFreeRatio=<minimum> and -XX:MaxHeapFreeRatio=<maximum>, and the total size is bounded below by -Xms<min> and above by -Xmx<max>.

Parameter Default Value

MinHeapFreeRatio 40

MaxHeapFreeRatio 70

-Xms 3670k

-Xmx 64m

Default values of heap size parameters on 64-bit systems have been scaled up by approximately 30%. This increase is meant to compensate for the larger size of objects on a 64-bit system.

With these parameters, if the percent of free space in a generation falls below 40%, the generation will be expanded to maintain 40% free space, up to the maximum allowed size of the generation. Similarly, if the free space exceeds 70%, the generation will be contracted so that only 70% of the space is free, subject to the minimum size of the generation.

Large server applications often experience two problems with these defaults. One is slow startup, because the initial heap is small and must be resized over many major collections. A more pressing problem is that the default maximum heap size is unreasonably small for most server applications. The rules of thumb for server applications are:

  • Unless you have problems with pauses, try granting as much memory as possible to the virtual machine. The default size (64MB) is often too small.
  • Setting -Xms and -Xmx to the same value increases predictability by removing the most important sizing decision from the virtual machine. However, the virtual machine is then unable to compensate if you make a poor choice.
  • In general, increase the memory as you increase the number of processors, since allocation can be parallelized.

    There is the full article

Java Refuses to Start - Could not reserve enough space for object heap

It seems that for 32-bit servers there is a JVM limitation that cannot be overcome (unless you find a special 32-bit JVM that does not impose a 2GB limit or less).

This thread on The Server Side has more details including several people who tested out various JVMs on 32-bit architectures. IBM's JVM seems to allow 100 more MB but that's not really going to get you what you want.

http://www.theserverside.com/discussions/thread.tss?thread_id=26347

The "real" solution is to use a 64-bit server with a 64-bit JVM to get heaps larger than 2GB per process. However, it's important to also consider the impact of increasing your address size (not just the addressable space) by using a 64-bit JVM. There will likely be performance and memory impacts for processing using less than 4GB of memory.

Food for thought: do each of these jobs really require 2GB of memory? Is there any way for the jobs to be modified to run within 1.8GB so this limit is not a problem?

Object creation on the stack/heap?

The two forms are the same with one exception: temporarily, the new (Object *) has an undefined value when the creation and assignment are separate. The compiler may combine them back together, since the undefined pointer is not particularly useful. This does not relate to global variables (unless the declaration is global, in which case it's still true for both forms).

What do I use for a max-heap implementation in Python?

In case if you would like to get the largest K element using max heap, you can do the following trick:

nums= [3,2,1,5,6,4]
k = 2  #k being the kth largest element you want to get
heapq.heapify(nums) 
temp = heapq.nlargest(k, nums)
return temp[-1]

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

I found it hard to decipher what is meant by "working directory of the VM". In my example, I was using the Java Service Wrapper program to execute a jar - the dump files were created in the directory where I had placed the wrapper program, e.g. c:\myapp\bin. The reason I discovered this is because the files can be quite large and they filled up the hard drive before I discovered their location.

Android Gradle Could not reserve enough space for object heap

Solution for Android Studio 2.3.3 on MacOS 10.12.6

Start Android Studios with more heap memory:

export JAVA_OPTS="-Xms6144m -Xmx6144m -XX:NewSize=256m -XX:MaxNewSize=356m -XX:PermSize=256m -XX:MaxPermSize=356m"
open -a /Applications/Android\ Studio.app

How to debug heap corruption errors?

In addition to looking for tools, consider looking for a likely culprit. Is there any component you're using, perhaps not written by you, which may not have been designed and tested to run in a multithreaded environment? Or simply one which you do not know has run in such an environment.

The last time it happened to me, it was a native package which had been successfully used from batch jobs for years. But it was the first time at this company that it had been used from a .NET web service (which is multithreaded). That was it - they had lied about the code being thread safe.

Difference between "on-heap" and "off-heap"

The on-heap store refers to objects that will be present in the Java heap (and also subject to GC). On the other hand, the off-heap store refers to (serialized) objects that are managed by EHCache, but stored outside the heap (and also not subject to GC). As the off-heap store continues to be managed in memory, it is slightly slower than the on-heap store, but still faster than the disk store.

The internal details involved in management and usage of the off-heap store aren't very evident in the link posted in the question, so it would be wise to check out the details of Terracotta BigMemory, which is used to manage the off-disk store. BigMemory (the off-heap store) is to be used to avoid the overhead of GC on a heap that is several Megabytes or Gigabytes large. BigMemory uses the memory address space of the JVM process, via direct ByteBuffers that are not subject to GC unlike other native Java objects.

What does "zend_mm_heap corrupted" mean

Some of tips that may helps some one

fedora 20, php 5.5.18

public function testRead() {
    $ri = new MediaItemReader(self::getMongoColl('Media'));

    foreach ($ri->dataReader(10) as $data) {
       // ...
    }
}

public function dataReader($numOfItems) {
    $cursor = $this->getStorage()->find()->limit($numOfItems);

    // here is the first place where "zend_mm_heap corrupted" error occurred
    // var_dump() inside foreach-loop and generator
    var_dump($cursor); 

    foreach ($cursor as $data) {
        // ...
        // and this is the second place where "zend_mm_heap corrupted" error occurred
        $data['Geo'] = [
            // try to access [0] index that is absent in ['Geo']
            'lon' => $data['Geo'][0],
            'lat' => $data['Geo'][1]
        ];
        // ...
        // Generator is used  !!!
        yield $data;
    }
}

using var_dummp() actually not an error, it was placed just for debugging and will be removed on production code. But real place where zend_mm_heap was happened is the second place.

What and where are the stack and heap?

In the following C# code

public void Method1()
{
    int i = 4;
    int y = 2;
    class1 cls1 = new class1();
}

Here's how the memory is managed

Picture of variables on the stack

Local Variables that only need to last as long as the function invocation go in the stack. The heap is used for variables whose lifetime we don't really know up front but we expect them to last a while. In most languages it's critical that we know at compile time how large a variable is if we want to store it on the stack.

Objects (which vary in size as we update them) go on the heap because we don't know at creation time how long they are going to last. In many languages the heap is garbage collected to find objects (such as the cls1 object) that no longer have any references.

In Java, most objects go directly into the heap. In languages like C / C++, structs and classes can often remain on the stack when you're not dealing with pointers.

More information can be found here:

The difference between stack and heap memory allocation « timmurphy.org

and here:

Creating Objects on the Stack and Heap

This article is the source of picture above: Six important .NET concepts: Stack, heap, value types, reference types, boxing, and unboxing - CodeProject

but be aware it may contain some inaccuracies.

Detect application heap size in Android

Asus Nexus 7 (2013) 32Gig: getMemoryClass()=192 maxMemory()=201326592

I made the mistake of prototyping my game on the Nexus 7, and then discovering it ran out of memory almost immediately on my wife's generic 4.04 tablet (memoryclass 48, maxmemory 50331648)

I'll need to restructure my project to load fewer resources when I determine memoryclass is low.
Is there a way in Java to see the current heap size? (I can see it clearly in the logCat when debugging, but I'd like a way to see it in code to adapt, like if currentheap>(maxmemory/2) unload high quality bitmaps load low quality

How to pass List<String> in post method using Spring MVC?

You can pass input as ["apple","orange"]if you want to leave the method as it is.

It worked for me with a similar method signature.

Sass - Converting Hex to RGBa for background opacity

The rgba() function can accept a single hex color as well decimal RGB values. For example, this would work just fine:

@mixin background-opacity($color, $opacity: 0.3) {
    background: $color; /* The Fallback */
    background: rgba($color, $opacity);
}

element {
     @include background-opacity(#333, 0.5);
}

If you ever need to break the hex color into RGB components, though, you can use the red(), green(), and blue() functions to do so:

$red: red($color);
$green: green($color);
$blue: blue($color);

background: rgb($red, $green, $blue); /* same as using "background: $color" */

Installing PHP Zip Extension

for PHP 7.3 / Ubuntu

sudo apt install php7.3-zip

for PHP 7.4

sudo apt install php7.4-zip

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

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

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

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

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

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

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

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

Auto reloading python Flask app upon code changes

app.run(use_reloader=True)

we can use this, use_reloader so every time we reload the page our code changes will be updated.

SyntaxError: non-default argument follows default argument

As the error message says, non-default argument til should not follow default argument hgt.

Changing order of parameters (function call also be adjusted accordingly) or making hgt non-default parameter will solve your problem.

def a(len1, hgt=len1, til, col=0):

->

def a(len1, hgt, til, col=0):

UPDATE

Another issue that is hidden by the SyntaxError.

os.system accepts only one string parameter.

def a(len1, hgt, til, col=0):
    system('mode con cols=%s lines=%s' % (len1, hgt))
    system('title %s' % til)
    system('color %s' % col)

ORA-01438: value larger than specified precision allows for this column

Further to previous answers, you should note that a column defined as VARCHARS(10) will store 10 bytes, not 10 characters unless you define it as VARCHAR2(10 CHAR)

[The OP's question seems to be number related... this is just in case anyone else has a similar issue]

link_to method and click event in Rails

just use

=link_to "link", "javascript:function()"

Validating URL in Java

Using only standard API, pass the string to a URL object then convert it to a URI object. This will accurately determine the validity of the URL according to the RFC2396 standard.

Example:

public boolean isValidURL(String url) {

    try {
        new URL(url).toURI();
    } catch (MalformedURLException | URISyntaxException e) {
        return false;
    }

    return true;
}

How do you join tables from two different SQL Server instances in one SQL query

The best way I can think of to accomplish this is via sp_addlinkedserver. You need to make sure that whatever account you use to add the link (via sp_addlinkedsrvlogin) has permissions to the table you're joining, but then once the link is established, you can call the server by name, i.e.:

SELECT *
FROM server1table
    INNER JOIN server2.database.dbo.server2table ON .....

Get element type with jQuery

Getting the element type the jQuery way:

var elementType = $(this).prev().prop('nodeName');

doing the same without jQuery

var elementType = this.previousSibling.nodeName;

Checking for specific element type:

var is_element_input = $(this).prev().is("input"); //true or false

How to enter newline character in Oracle?

According to the Oracle PLSQL language definition, a character literal can contain "any printable character in the character set". https://docs.oracle.com/cd/A97630_01/appdev.920/a96624/02_funds.htm#2876

@Robert Love's answer exhibits a best practice for readable code, but you can also just type in the linefeed character into the code. Here is an example from a Linux terminal using sqlplus:

SQL> set serveroutput on
SQL> begin   
  2  dbms_output.put_line( 'hello' || chr(10) || 'world' );
  3  end;
  4  /
hello
world

PL/SQL procedure successfully completed.

SQL> begin
  2  dbms_output.put_line( 'hello
  3  world' );
  4  end;
  5  /
hello
world

PL/SQL procedure successfully completed.

Instead of the CHR( NN ) function you can also use Unicode literal escape sequences like u'\0085' which I prefer because, well you know we are not living in 1970 anymore. See the equivalent example below:

SQL> begin
  2  dbms_output.put_line( 'hello' || u'\000A' || 'world' );
  3  end;
  4  /
hello
world

PL/SQL procedure successfully completed.

For fair coverage I guess it is worth noting that different operating systems use different characters/character sequences for end of line handling. You've got to have a think about the context in which your program output is going to be viewed or printed, in order to determine whether you are using the right technique.

  • Microsoft Windows: CR/LF or u'\000D\000A'
  • Unix (including Apple MacOS): LF or u'\000A'
  • IBM OS390: NEL or u'\0085'
  • HTML: '<BR>'
  • XHTML: '<br />'
  • etc. etc.

How to get the focused element with jQuery?

// Get the focused element:
var $focused = $(':focus');

// No jQuery:
var focused = document.activeElement;

// Does the element have focus:
var hasFocus = $('foo').is(':focus');

// No jQuery:
elem === elem.ownerDocument.activeElement;

Which one should you use? quoting the jQuery docs:

As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':focus') is equivalent to $('*:focus'). If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.

The answer is:

document.activeElement

And if you want a jQuery object wrapping the element:

$(document.activeElement)

What is the easiest way to install BLAS and LAPACK for scipy?

I got this problem on freeBSD. It seems lapack packages are missing, I solved it installing them (as root) with:

pkg install lapack
pkg install atlas-devel  #not sure this is needed, but just in case

I imagine it could work on other system too using the appropriate package installer (e.g. apt-get)

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I have a similar issue, have you tried:

proxy.ClientCredentials.Windows.AllowedImpersonationLevel =   
          System.Security.Principal.TokenImpersonationLevel.Impersonation;

Get current batchfile directory

Very simple:

setlocal
cd /d %~dp0
File.exe

Angular 2 ngfor first, last, index loop

Check out this plunkr.

When you're binding to variables, you need to use the brackets. Also, you use the hashtag when you want to get references to elements in your html, not for declaring variables inside of templates like that.

<md-button-toggle *ngFor="let indicador of indicadores; let first = first;" [value]="indicador.id" [checked]="first"> 
...

Edit: Thanks to Christopher Moore: Angular exposes the following local variables:

  • index
  • first
  • last
  • even
  • odd

Setting device orientation in Swift iOS

If someone wants the answer, I think I just got it. Try this:

  • Go to your .plist file and check all the orientations.
  • In the view controller you want to force orientation, add the following code:
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.Portrait.toRaw().hashValue | UIInterfaceOrientationMask.PortraitUpsideDown.toRaw().hashValue
}

Hope it helps !

EDIT :

To force rotation, use the following code :

let value = UIInterfaceOrientation.LandscapeRight.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")

It works for iOS 7 & 8 !

Upload Image using POST form data in Python-requests

I confronted similar issue when I wanted to post image file to a rest API from Python (Not wechat API though). The solution for me was to use 'data' parameter to post the file in binary data instead of 'files'. Requests API reference

data = open('your_image.png','rb').read()
r = requests.post(your_url,data=data)

Hope this works for your case.

Convert String with Dot or Comma as decimal separator to number in JavaScript

You could replace all spaces by an empty string, all comas by dots and then parse it.

var str = "110 000,23";
var num = parseFloat(str.replace(/\s/g, "").replace(",", "."));
console.log(num);

I used a regex in the first one to be able to match all spaces, not just the first one.

Laravel Eloquent LEFT JOIN WHERE NULL

I would be using laravel whereDoesntHave to achieve this.

Customer::whereDoesntHave('orders')->get();

Pass parameter to controller from @Html.ActionLink MVC 4

You are using a wrong overload of the Html.ActionLink helper. What you think is routeValues is actually htmlAttributes! Just look at the generated HTML, you will see that this anchor's href property doesn't look as you expect it to look.

Here's what you are using:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // routeValues
    new {                                                     // htmlAttributes
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    }
)

and here's what you should use:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // controllerName
    new {                                                     // routeValues
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    },
    null                                                      // htmlAttributes
)

Also there's another very serious issue with your code. The following routeValue:

replyblogPostmodel = Model

You cannot possibly pass complex objects like this in an ActionLink. So get rid of it and also remove the BlogPostModel parameter from your controller action. You should use the blogPostId parameter to retrieve the model from wherever this model is persisted, or if you prefer from wherever you retrieved the model in the GET action:

public ActionResult BlogReplyCommentAdd(int blogPostId, bool captchaValid)
{
    BlogPostModel model = repository.Get(blogPostId);
    ...
}

As far as your initial problem is concerned with the wrong overload I would recommend you writing your helpers using named parameters:

@Html.ActionLink(
    linkText: "Reply",
    actionName: "BlogReplyCommentAdd",
    controllerName: "Blog",
    routeValues: new {
        blogPostId = blogPostId, 
        captchaValid = Model.AddNewComment.DisplayCaptcha
    },
    htmlAttributes: null
)

Now not only that your code is more readable but you will never have confusion between the gazillions of overloads that Microsoft made for those helpers.

SQL: How to to SUM two values from different tables

select region,sum(number) total
from
(
    select region,number
    from cash_table
    union all
    select region,number
    from cheque_table
) t
group by region

Brew doctor says: "Warning: /usr/local/include isn't writable."

You need to create /usr/local/include and /usr/local/lib if they don't exists:

$ sudo mkdir -p /usr/local/include
$ sudo chown -R $USER:admin /usr/local/include

HTML: How to make a submit button with text + image in it?

In case dingbats/icon fonts are an option, you can use them instead of images.

The following uses a combination of

In HTML:

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

<form name="signin" action="#" method="POST">
    <input type="text" name="text-input" placeholder="&#xf183; your username" class="stylish"/><br/>
    <input type="submit" value="&#xf090; sign in" class="stylish"/>
</form>

In CSS:

.stylish {
    font-family: georgia, FontAwesome;
}

jsFiddle

Notice the font-family specification: all characters/code points will use georgia, falling back to FontAwesome for any code points georgia doesn't provide characters for. georgia doesn't provide any characters in the private use range, exactly where FontAwesome has placed its icons.

How to set downloading file name in ASP.NET Web API

EDIT: As mentioned in a comment, My answer doesn't account for characters that need to be escaped like a ;. You should use the accepted answer Darin made if your file name could contain a semi-colon.

Add a Response.AddHeader to set the file name

Response.AddHeader("Content-Disposition", "attachment; filename=*FILE_NAME*");

Just change FILE_NAME to the name of the file.

How to insert element into arrays at specific position?

This is an old question, but I posted a comment in 2014 and frequently come back to this. I thought I would leave a full answer. This isn't the shortest solution but it is quite easy to understand.

Insert a new value into an associative array, at a numbered position, preserving keys, and preserving order.

$columns = array(
    'id' => 'ID',
    'name' => 'Name',
    'email' => 'Email',
    'count' => 'Number of posts'
);

$columns = array_merge(
    array_slice( $columns, 0, 3, true ),     // The first 3 items from the old array
    array( 'subscribed' => 'Subscribed' ),   // New value to add after the 3rd item
    array_slice( $columns, 3, null, true )   // Other items after the 3rd
);

print_r( $columns );

/*
Array ( 
    [id] => ID 
    [name] => Name 
    [email] => Email 
    [subscribed] => Subscribed 
    [count] => Number of posts 
)
*/

Add a new column to existing table in a migration

this things is worked on laravel 5.1.

first, on your terminal execute this code

php artisan make:migration add_paid_to_users --table=users

after that go to your project directory and expand directory database - migration and edit file add_paid_to_users.php, add this code

public function up()
{
    Schema::table('users', function (Blueprint $table) {
         $table->string('paid'); //just add this line
    });
}

after that go back to your terminal and execute this command

php artisan migrate

hope this help.

Moment.js: Date between dates

I do believe that

if (startDate <= date && date <= endDate) {
  alert("Yay");
} else {
  alert("Nay! :("); 
}

works too...

difference between variables inside and outside of __init__()

class User(object):
    email = 'none'
    firstname = 'none'
    lastname = 'none'

    def __init__(self, email=None, firstname=None, lastname=None):
        self.email = email
        self.firstname = firstname
        self.lastname = lastname

    @classmethod
    def print_var(cls, obj):
        print ("obj.email obj.firstname obj.lastname")
        print(obj.email, obj.firstname, obj.lastname)
        print("cls.email cls.firstname cls.lastname")
        print(cls.email, cls.firstname, cls.lastname)

u1 = User(email='abc@xyz', firstname='first', lastname='last')
User.print_var(u1)

In the above code, the User class has 3 global variables, each with value 'none'. u1 is the object created by instantiating this class. The method print_var prints the value of class variables of class User and object variables of object u1. In the output shown below, each of the class variables User.email, User.firstname and User.lastname has value 'none', while the object variables u1.email, u1.firstname and u1.lastname have values 'abc@xyz', 'first' and 'last'.

obj.email obj.firstname obj.lastname
('abc@xyz', 'first', 'last')
cls.email cls.firstname cls.lastname
('none', 'none', 'none')

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Documentation for crypto: http://nodejs.org/api/crypto.html

const crypto = require('crypto')

const text = 'I love cupcakes'
const key = 'abcdeg'

crypto.createHmac('sha1', key)
  .update(text)
  .digest('hex')

How to quit a java app from within the program

Runtime.getCurrentRumtime().halt(0);

error: src refspec master does not match any

In my case the error was caused because I was typing

git push origin master

while I was on the develop branch try:

git push origin branchname

Hope this helps somebody

How to prevent vim from creating (and leaving) temporary files?

This answer applies to using gVim on Windows 10. I cannot guarantee the same results for other operating systems.

Add:

set nobackup
set noswapfile
set noundofile

To your _vimrc file.

Note: This is the direct answer to the question (for Windows 10) and probably not the safest thing to do (read the other answers), but this is the fastest solution in my case.

Timing Delays in VBA

I used the answer of Steve Mallory, but I am affraid the timer never or at least sometimes does not go to 86400 nor 0 (zero) sharp (MS Access 2013). So I modified the code. I changed the midnight condition to "If Timer >= 86399 Then" and added the break of the loop "Exit Do" as follows:

Public Function Pause(NumberOfSeconds As Variant)
    On Error GoTo Error_GoTo

    Dim PauseTime As Variant
    Dim Start As Variant
    Dim Elapsed As Variant

    PauseTime = NumberOfSeconds
    Start = Timer
    Elapsed = 0
    Do While Timer < Start + PauseTime
        Elapsed = Elapsed + 1
        If Timer >= 86399
            ' Crossing midnight
            ' PauseTime = PauseTime - Elapsed
            ' Start = 0
            ' Elapsed = 0
            Exit Do
        End If
        DoEvents
    Loop

Exit_GoTo:
    On Error GoTo 0
    Exit Function
Error_GoTo:
    Debug.Print Err.Number, Err.Description, Erl
    GoTo Exit_GoTo
End Function

Proper use of 'yield return'

Yield has two great uses

It helps to provide custom iteration with out creating temp collections. ( loading all data and looping)

It helps to do stateful iteration. ( streaming)

Below is a simple video which i have created with full demonstration in order to support the above two points

http://www.youtube.com/watch?v=4fju3xcm21M

Return array from function

neater:

function BlockID() {
  return {
    "s":"Images/Block_01.png",
    "g":"Images/Block_02.png",
    "C":"Images/Block_03.png",
    "d":"Images/Block_04.png"
   }
}

or just

var images = {
  "s":"Images/Block_01.png",
  "g":"Images/Block_02.png",
  "C":"Images/Block_03.png",
  "d":"Images/Block_04.png"
}

Is there a Python Library that contains a list of all the ascii characters?

The string constants may be what you want. (docs)

>>> import string
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

If you want all printable characters:

>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

JSON and escaping characters

hmm, well here's a workaround anyway:

function JSON_stringify(s, emit_unicode)
{
   var json = JSON.stringify(s);
   return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
      function(c) { 
        return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
      }
   );
}

test case:

js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

How to remove all whitespace from a string?

Please note that soultions written above removes only space. If you want also to remove tab or new line use stri_replace_all_charclass from stringi package.

library(stringi)
stri_replace_all_charclass("   ala \t  ma \n kota  ", "\\p{WHITE_SPACE}", "")
## [1] "alamakota"

NoClassDefFoundError - Eclipse and Android

Same thing worked for me: Properties -> Java Build Path -> "Order and Export" Interestingly - why this is not done automatically? I guess some setting is missing. Also this happened for me after SDK upgrade.

Android LinearLayout : Add border with shadow around a LinearLayout

This is so simple:

Create a drawable file with a gradient like this:

for shadow below a view below_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">   
<gradient
    android:startColor="#20000000"
    android:endColor="@android:color/transparent"
    android:angle="270" >
</gradient>
</shape>

for shadow above a view above_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">   
<gradient
    android:startColor="#20000000"
    android:endColor="@android:color/transparent"
    android:angle="90" >
</gradient>
</shape>

and so on for right and left shadow just change the angle of the gradient :)

Search text in stored procedure in SQL Server

Have you tried using some of the third party tools to do the search? There are several available out there that are free and that saved me a ton of time in the past.

Below are two SSMS Addins I used with good success.

ApexSQL Search – Searches both schema and data in databases and has additional features such as dependency tracking and more…

SSMS Tools pack – Has same search functionality as previous one and several other cool features. Not free for SQL Server 2012 but still very affordable.

I know this answer is not 100% related to the questions (which was more specific) but hopefully others will find this useful.

Can a Windows batch file determine its own file name?

Bear in mind that 0 is a special case of parameter numbers inside a batch file, where 0 means this file as given on the command line.

So if the file is myfile.bat, you could call it in several ways as follows, each of which would give you a different output from the %0 or %~0 usage:

myfile

myfile.bat

mydir\myfile.bat

c:\mydir\myfile.bat

"c:\mydir\myfile.bat"

All of the above are legal calls if you call it from the correct relative place to the directory in which it exists. %~0 strips the quotes from the last example, whereas %0 does not.

Because these all give different results, %0 and %~0 are very unlikely to be what you actually want to use.

Here's a batch file to illustrate:

@echo Full path and filename: %~f0
@echo Drive: %~d0
@echo Path: %~p0
@echo Drive and path: %~dp0
@echo Filename without extension: %~n0
@echo Filename with    extension: %~nx0
@echo Extension: %~x0
@echo Filename as given on command line: %0
@echo Filename as given on command line minus quotes: %~0
@REM Build from parts
@SETLOCAL
@SET drv=%~d0
@SET pth=%~p0
@SET fpath=%~dp0
@SET fname=%~n0
@SET ext=%~x0
@echo Simply Constructed name: %fpath%%fname%%ext%
@echo Fully  Constructed name: %drv%%pth%%fname%%ext%
@ENDLOCAL
pause

How to update column with null value

if you follow

UPDATE table SET name = NULL

then name is "" not NULL IN MYSQL means your query

SELECT * FROM table WHERE name = NULL not work or disappoint yourself

JFrame.dispose() vs System.exit()

  • If you have multiple windows open and only want to close the one that was closed use JFrame.dispose().

  • If you want to close all windows and terminate the application use System.exit()

How do I set a Windows scheduled task to run in the background?

As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.


It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.

enter image description here

enter image description here

enter image description here

Java Error: illegal start of expression

Declare

public static int[] locations={1,2,3};

outside of the main method.

Fit website background image to screen size

You can try with

.appBackground {
    position: relative;
    background-image: url(".../img/background.jpg");
    background-repeat:no-repeat;
    background-size:100% 100vh;
}

works for me :)

Neither BindingResult nor plain target object for bean name available as request attr

I have encountered this problem as well. Here is my solution:

Below is the error while running a small Spring Application:-

*HTTP Status 500 - 
--------------------------------------------------------------------------------
type Exception report
message 
description The server encountered an internal error () that prevented it from fulfilling this request.
exception 
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/employe.jsp at line 12
9: <form:form method="POST" commandName="command"  action="/SpringWeb/addEmploye">
10:    <table>
11:     <tr>
12:         <td><form:label path="name">Name</form:label></td>
13:         <td><form:input path="name" /></td>
14:     </tr>
15:     <tr>
Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause 
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
    org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
    org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
    org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005flabel_005f0(employe_jsp.java:185)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005fform_005f0(employe_jsp.java:120)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspService(employe_jsp.java:80)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.26 logs.*

In order to resolve this issue you need to do the following in the controller class:-

  1. Change the import package from "import org.springframework.web.portlet.ModelAndView;" to "import org.springframework.web.servlet.ModelAndView;"...
  2. Recompile and run the code... the problem should get resolved.

Is it possible to send a variable number of arguments to a JavaScript function?

Update: Since ES6, you can simply use the spread syntax when calling the function:

func(...arr);

Since ES6 also if you expect to treat your arguments as an array, you can also use the spread syntax in the parameter list, for example:

function func(...args) {
  args.forEach(arg => console.log(arg))
}

const values = ['a', 'b', 'c']
func(...values)
func(1, 2, 3)

And you can combine it with normal parameters, for example if you want to receive the first two arguments separately and the rest as an array:

function func(first, second, ...theRest) {
  //...
}

And maybe is useful to you, that you can know how many arguments a function expects:

var test = function (one, two, three) {}; 
test.length == 3;

But anyway you can pass an arbitrary number of arguments...

The spread syntax is shorter and "sweeter" than apply and if you don't need to set the this value in the function call, this is the way to go.

Here is an apply example, which was the former way to do it:

var arr = ['a','b','c'];

function func() {
  console.log(this); // 'test'
  console.log(arguments.length); // 3

  for(var i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }

};

func.apply('test', arr);

Nowadays I only recommend using apply only if you need to pass an arbitrary number of arguments from an array and set the this value. apply takes is the this value as the first arguments, which will be used on the function invocation, if we use null in non-strict code, the this keyword will refer to the Global object (window) inside func, in strict mode, when explicitly using 'use strict' or in ES modules, null will be used.

Also note that the arguments object is not really an Array, you can convert it by:

var argsArray = Array.prototype.slice.call(arguments);

And in ES6:

const argsArray = [...arguments] // or Array.from(arguments)

But you rarely use the arguments object directly nowadays thanks to the spread syntax.

How to change or add theme to Android Studio?

  • Go to File > Settings,
  • now under IDE settings click on appearance and select the theme of your choice from the dropdown.
  • you can also install themes, they are the jar files by
  • File > Import Settings, select the file or your choice and select ok a pop up to restart the studio will open up click yes and studio will restart and your theme will be applied.

Spring Data JPA Update @Query not updating?

I struggled with the same problem where I was trying to execute an update query like the same as you did-

@Modifying
@Transactional
@Query(value = "UPDATE SAMPLE_TABLE st SET st.status=:flag WHERE se.referenceNo in :ids")
public int updateStatus(@Param("flag")String flag, @Param("ids")List<String> references);

This will work if you have put @EnableTransactionManagement annotation on the main class. Spring 3.1 introduces the @EnableTransactionManagement annotation to be used in on @Configuration classes and enable transactional support.

How to join two JavaScript Objects, without using JQUERY

1)

var merged = {};
for(key in obj1)
    merged[key] = obj1[key];
for(key in obj2)
    merged[key] = obj2[key];

2)

var merged = {};
Object.keys(obj1).forEach(k => merged[k] = obj1[k]);
Object.keys(obj2).forEach(k => merged[k] = obj2[k]);

OR

Object.keys(obj1)
    .concat(Object.keys(obj2))
    .forEach(k => merged[k] = k in obj2 ? obj2[k] : obj1[k]);

3) Simplest way:

var merged = {};
Object.assign(merged, obj1, obj2);

How to create json by JavaScript for loop?

From what I understand of your request, this should work:

<script>
//  var status  = document.getElementsByID("uniqueID"); // this works too
var status  = document.getElementsByName("status")[0];
var jsonArr = [];

for (var i = 0; i < status.options.length; i++) {
    jsonArr.push({
        id: status.options[i].text,
        optionValue: status.options[i].value
    });
}
</script>

What Makes a Method Thread-safe? What are the rules?

There is no hard and fast rule.

Here are some rules to make code thread safe in .NET and why these are not good rules:

  1. Function and all functions it calls must be pure (no side effects) and use local variables. Although this will make your code thread-safe, there is also very little amount of interesting things you can do with this restriction in .NET.
  2. Every function that operates on a common object must lock on a common thing. All locks must be done in same order. This will make the code thread safe, but it will be incredibly slow, and you might as well not use multiple threads.
  3. ...

There is no rule that makes the code thread safe, the only thing you can do is make sure that your code will work no matter how many times is it being actively executed, each thread can be interrupted at any point, with each thread being in its own state/location, and this for each function (static or otherwise) that is accessing common objects.

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

Accessing localhost (xampp) from another computer over LAN network - how to?

These are the steps to follow when you want your PHP application to be installed on a LAN server (not on web)

  1. Get the internal IP or Static IP of the server (Ex: 192.168.1.193)
  2. Open XAMPP>apache>conf>httpd.conf file in notepad
  3. Search for Listen 80
  4. Above line would read like- #Listen 0.0.0.0:80 / 12.34.56.78:80
  5. Change the IP address and replace it with the static IP
  6. Save the httpd.conf file ensuring that the server is pointed to #Listen 192.168.1.193:80
  7. In the application root config.php (db connection) replace localhost with IP address of the server

Note: If firewall is installed, ensure that you add the http port 80 and 8080 to exceptions and allow to listen. Go to Control Panel>Windows Firewall>Allow a program to communicate through windows firewall>Add another program Name: http Port: 80 Add one more as http - 8080

If IIS (Microsoft .Net Application Internet Information Server) is installed with any Microsoft .Net application already on server, then it would have already occupied 80 port. In that case change the #Listen 192.168.1.193:80 to #Listen 192.168.1.193:8080

Hope this helps! :)

How to uninstall pip on OSX?

The first thing you should try is:

sudo pip uninstall pip

On many environments that doesn't work. So given the lack of info on that problem, I ended up removing pip manually from /usr/local/bin.

Need to make a clickable <div> button

Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

HTML:

<a id="music" href="Music.html">Music I Like</a>

CSS:

#music {
    background-color: black;
    color: white;
    display: block;
    height: 40px;
    line-height: 40px;
    text-decoration: none;
    width: 100px;
    text-align: center;
}

Output:

enter image description here

jquery clone div and append it after specific div

This works great if a straight copy is in order. If the situation calls for creating new objects from templates, I usually wrap the template div in a hidden storage div and use jquery's html() in conjunction with clone() applying the following technique:

<style>
#element-storage {
    display: none;
    top: 0;
    right: 0;
    position: fixed;
    width: 0;
    height: 0;
}
</style>

<script>
$("#new-div").append($("#template").clone().html(function(index, oldHTML){ 
    // .. code to modify template, e.g. below:
    var newHTML = "";
    newHTML = oldHTML.replace("[firstname]", "Tom");
    newHTML = newHTML.replace("[lastname]", "Smith");
    // newHTML = newHTML.replace(/[Example Replace String]/g, "Replacement"); // regex for global replace
    return newHTML;
}));
</script>

<div id="element-storage">
  <div id="template">
    <p>Hello [firstname] [lastname]</p>
  </div>
</div>

<div id="new-div">

</div>

Is there an "exists" function for jQuery?

Try testing for DOM element

if (!!$(selector)[0]) // do stuff

Why did my Git repo enter a detached HEAD state?

When you checkout to a commit git checkout <commit-hash> or to a remote branch your HEAD will get detached and try to create a new commit on it.

Commits that are not reachable by any branch or tag will be garbage collected and removed from the repository after 30 days.

Another way to solve this is by creating a new branch for the newly created commit and checkout to it. git checkout -b <branch-name> <commit-hash>

This article illustrates how you can get to detached HEAD state.

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I've no idea why the other two answers are so popular!

I believe you were right in assuming the ORM framework should handle it - after all, that is what it promises to deliver. Otherwise your domain model gets corrupted by persistence concerns. NHibernate manages this happily if you setup the cascade settings correctly. In Entity Framework it is also possible, they just expect you to follow better standards when setting up your database model, especially when they have to infer what cascading should be done:

You have to define the parent - child relationship correctly by using an "identifying relationship".

If you do this, Entity Framework knows the child object is identified by the parent, and therefore it must be a "cascade-delete-orphans" situation.

Other than the above, you might need to (from NHibernate experience)

thisParent.ChildItems.Clear();
thisParent.ChildItems.AddRange(modifiedParent.ChildItems);

instead of replacing the list entirely.

UPDATE

@Slauma's comment reminded me that detached entities are another part of the overall problem. To solve that, you can take the approach of using a custom model binder that constructs your models by attempting to load it from the context. This blog post shows an example of what I mean.

How to remove underline from a link in HTML?

  1. Add this to your external style sheet (preferred):

    a {text-decoration:none;}
    
  2. Or add this to the <head> of your HTML document:

    <style type="text/css">
     a {text-decoration:none;}
    </style>
    
  3. Or add it to the a element itself (not recommended):

    <!-- Add [ style="text-decoration:none;"] -->
    <a href="http://example.com" style="text-decoration:none;">Text</a>
    

How to concatenate variables into SQL strings

You could make use of Prepared Stements like this.

set @query = concat( "select name from " );
set @query = concat( "table_name"," [where condition] " );

prepare stmt from @like_q;
execute stmt;

How do I negate a test with regular expressions in a bash script?

the safest way is to put the ! for the regex negation within the [[ ]] like this:

if [[ ! ${STR} =~ YOUR_REGEX ]]; then

otherwise it might fail on certain systems.

box-shadow on bootstrap 3 container

For those wanting the box-shadow on the col-* container itself and not on the .container, you can add another div just inside the col-* element, and add the shadow to that. This element will not have the padding, and therefor not interfere.

The first image has the box-shadow on the col-* element. Because of the 15px padding on the col element, the shadow is pushed to the outside of the div element rather than on the visual edges of it.

box-shadow on col-* element

<div class="col-md-4" style="box-shadow: 0px 2px 25px rgba(0, 0, 0, .25);">
    <div class="thumbnail">
        {!! HTML::image('images/sampleImage.png') !!}
    </div>
</div>

The second image has a wrapper div with the box-shadow on it. This will place the box-shadow on the visual edges of the element.

box-shadow on wrapper div

<div class="col-md-4">
    <div id="wrapper-div" style="box-shadow: 0px 2px 25px rgba(0, 0, 0, .25);">
        <div class="thumbnail">
            {!! HTML::image('images/sampleImage.png') !!}
        </div>
    </div>
</div>

'Missing contentDescription attribute on image' in XML

It is giving you the warning because the image description is not defined.

We can resolve this warning by adding this code below in Strings.xml and activity_main.xml

Add this line below in Strings.xml

<string name="imgDescription">Background Picture</string>
you image will be like that:
<ImageView
        android:id="@+id/imageView2"
        android:lay`enter code hereout_width="0dp"
        android:layout_height="wrap_content"
        android:contentDescription="@string/imgDescription"
        app:layout_editor_absoluteX="0dp"
        app:layout_editor_absoluteY="0dp"
        app:srcCompat="@drawable/background1"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp" />

Also add this line in activity_main.xml

android:contentDescription="@string/imgDescription"

Strings.xml

<resources>
    <string name="app_name">Saini_Browser</string>
    <string name="SainiBrowser">textView2</string>
    <string name="imgDescription">BackGround Picture</string>
</resources>

Batch file. Delete all files and folders in a directory

Use:

  • Create a batch file

  • Copy the below text into the batch file

    set folder="C:\test"
    cd /d %folder%
    for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
    

It will delete all files and folders.

XML Schema minOccurs / maxOccurs default values

New, expanded answer to an old, commonly asked question...

Default Values

  • Occurrence constraints minOccurs and maxOccurs default to 1.

Common Cases Explained

<xsd:element name="A"/>

means A is required and must appear exactly once.


<xsd:element name="A" minOccurs="0"/>

means A is optional and may appear at most once.


 <xsd:element name="A" maxOccurs="unbounded"/>

means A is required and may repeat an unlimited number of times.


 <xsd:element name="A" minOccurs="0" maxOccurs="unbounded"/>

means A is optional and may repeat an unlimited number of times.


See Also

  • W3C XML Schema Part 0: Primer

    In general, an element is required to appear when the value of minOccurs is 1 or more. The maximum number of times an element may appear is determined by the value of a maxOccurs attribute in its declaration. This value may be a positive integer such as 41, or the term unbounded to indicate there is no maximum number of occurrences. The default value for both the minOccurs and the maxOccurs attributes is 1. Thus, when an element such as comment is declared without a maxOccurs attribute, the element may not occur more than once. Be sure that if you specify a value for only the minOccurs attribute, it is less than or equal to the default value of maxOccurs, i.e. it is 0 or 1. Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs, i.e. 1 or more. If both attributes are omitted, the element must appear exactly once.

  • W3C XML Schema Part 1: Structures Second Edition

    <element
      maxOccurs = (nonNegativeInteger | unbounded)  : 1
      minOccurs = nonNegativeInteger : 1
      >
    
    </element>
    

Should C# or C++ be chosen for learning Games Programming (consoles)?

To tell the truth...you have to make the decision as to which is the better language. I know what I can do with C#. I know what can be done in C++. C# isn't made to do what C++ was made to do...write code at the most basic level and still be somewhat meaningful when read by human eyes.

We are developing a game engine with C#, DirectX...is it a challenge? hell yeah...but it's something we chose to do. We are looking at some performance levels that are very close to what C++ can give. So, I see no problems with this effort.

To cross-platform development, if it weren't for .Net, we might not have the Mono platform. The Mono platform has broadened our platform base.

Here is some support to my arguments...

How to code a very simple login system with java

Check this code :

import java.util.Scanner;

public class Main {

public static void main(String[] args) throws IllegalAccessException {

    String username ;
    String password;
    String yes_0r_no;
    String scann;
    String passscan;

    Scanner scan = new Scanner(System.in);
    Scanner scanner = new Scanner(System.in);

    Scanner name = new Scanner(System.in);
    System.out.println("Username:");
    username = name.next().toLowerCase();

    Scanner pass = new Scanner(System.in);
    System.out.println("Password:");
    password = pass.next().toLowerCase();


    System.out.println("You are logged in");

    Scanner ask = new Scanner(System.in);
    System.out.println("Do you want to check this or not(yes or no) :");

     yes_0r_no = ask.next().toLowerCase();



    while (true){
        if (yes_0r_no.equals("yes")){
            System.out.println("Username:");
          scann = scan.next().toLowerCase();
          if (scann == username) {
              continue;
          }
        System.out.println("Password");
        passscan = scanner.next().toLowerCase();
        if (passscan.equals(password)) {
            System.out.println("You are logged in");
            break;

        }if (!password.equals(passscan)) {
            throw new IllegalAccessException();
            }
        }

        if (yes_0r_no.equals("no"))
            break ;



    }


}

}

Alternate table row color using CSS?

Just add the following to your html code (withing the <head>) and you are done.

HTML:

<style>
      tr:nth-of-type(odd) {
      background-color:#ccc;
    }
</style>

Easier and faster than jQuery examples.

How do I make an http request using cookies on Android?

I do not work with google android but I think you'll find it's not that hard to get this working. If you read the relevant bit of the java tutorial you'll see that a registered cookiehandler gets callbacks from the HTTP code.

So if there is no default (have you checked if CookieHandler.getDefault() really is null?) then you can simply extend CookieHandler, implement put/get and make it work pretty much automatically. Be sure to consider concurrent access and the like if you go that route.

edit: Obviously you'd have to set an instance of your custom implementation as the default handler through CookieHandler.setDefault() to receive the callbacks. Forgot to mention that.

Xcode stuck on Indexing

I had a similar problem where Xcode would spend lots of time indexing and would frequently hang building the project, at which point I had to force-quit and relaunch Xcode. It was very annoying.

Then I noticed a warning in the project about improperly assigning self as a delegate. Sure enough, there was a missing protocol in the class declaration. Note that there is a similar assignment in the OP's sample code (though it is impossible to tell from the sample whether the correct protocol is declared):

leaderboardController.leaderboardDelegate == self;

After resolving that warning (by correctly declaring the implemented protocol), Xcode stopped misbehaving. Also, I should note that the project did execute correctly since the protocol methods were implemented. It was just that Xcode could not confirm that the protocol should in fact implemented by the class.

MySQL OPTIMIZE all tables?

You can use mysqlcheck to do this at the command line.

One database:

mysqlcheck -o <db_schema_name>

All databases:

mysqlcheck -o --all-databases

How to get html table td cell value by JavaScript?

This is my solution

var cells = Array.prototype.slice.call(document.getElementById("tableI").getElementsByTagName("td"));
for(var i in cells){
    console.log("My contents is \"" + cells[i].innerHTML + "\"");
}

How to add number of days to today's date?

You could extend the javascript Date object like this

Date.prototype.addDays = function(days) {
    this.setDate(this.getDate() + parseInt(days));
    return this;
};

and in your javascript code you could call

var currentDate = new Date();
// to add 4 days to current date
currentDate.addDays(4);

Get current url in Angular

With pure JavaScript:

console.log(window.location.href)

Using Angular:

this.router.url

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

How to stretch the background image to fill a div

For this you can use CSS3 background-size property. Write like this:

#div2{
    background-image:url(http://s7.static.hootsuite.com/3-0-48/images/themes/classic/streams/message-gradient.png);
    -moz-background-size:100% 100%;
    -webkit-background-size:100% 100%;
    background-size:100% 100%;
    height:180px;
    width:200px;
    border: 1px solid red;
}

Check this: http://jsfiddle.net/qdzaw/1/

How to load external scripts dynamically in Angular?

This might work. This Code dynamically appends the <script> tag to the head of the html file on button clicked.

const url = 'http://iknow.com/this/does/not/work/either/file.js';

export class MyAppComponent {
    loadAPI: Promise<any>;

    public buttonClicked() {
        this.loadAPI = new Promise((resolve) => {
            console.log('resolving promise...');
            this.loadScript();
        });
    }

    public loadScript() {
        console.log('preparing to load...')
        let node = document.createElement('script');
        node.src = url;
        node.type = 'text/javascript';
        node.async = true;
        node.charset = 'utf-8';
        document.getElementsByTagName('head')[0].appendChild(node);
    }
}

Making custom right-click context menus for my web-app

Simple One

  1. show context menu when right click anywhere in document
  2. avoid context menu hide when click inside context menu
  3. close context menu when press left mouse button

Note: dont use display:none instead use opacity to hide and show

_x000D_
_x000D_
var menu= document.querySelector('.context_menu');
document.addEventListener("contextmenu", function(e) {      
            e.preventDefault();  
            menu.style.position = 'absolute';
            menu.style.left = e.pageX + 'px';
            menu.style.top = e.pageY + 'px';        
             menu.style.opacity = 1;
        });
       
  document.addEventListener("click", function(e){
  if(e.target.closest('.context_menu'))
  return;
      menu.style.opacity = 0;
  });
_x000D_
.context_menu{

width:70px;
background:lightgrey;
padding:5px;
 opacity :0;
}
.context_menu div{
margin:5px;
background:grey;

}
.context_menu div:hover{
margin:5px;
background:red;
   cursor:pointer;

}
_x000D_
<div class="context_menu">
<div>menu 1</div>
<div>menu 2</div>
</div>
_x000D_
_x000D_
_x000D_

extra css

_x000D_
_x000D_
var menu= document.querySelector('.context_menu');
document.addEventListener("contextmenu", function(e) {      
            e.preventDefault();  
            menu.style.position = 'absolute';
            menu.style.left = e.pageX + 'px';
            menu.style.top = e.pageY + 'px';        
             menu.style.opacity = 1;
        });
       
  document.addEventListener("click", function(e){
  if(e.target.closest('.context_menu'))
  return;
      menu.style.opacity = 0;
  });
_x000D_
.context_menu{

width:120px;
background:white;
border:1px solid lightgrey;

 opacity :0;
}
.context_menu div{
padding:5px;
padding-left:15px;
margin:5px 2px;
border-bottom:1px solid lightgrey;
}
.context_menu div:last-child {
border:none;
}
.context_menu div:hover{

background:lightgrey;
   cursor:pointer;

}
_x000D_
<div class="context_menu">
<div>menu 1</div>
<div>menu 2</div>
<div>menu 3</div>
<div>menu 4</div>
</div>
_x000D_
_x000D_
_x000D_

Simple Deadlock Examples

package test.concurrent;
public class DeadLockTest {
   private static long sleepMillis;
   private final Object lock1 = new Object();
   private final Object lock2 = new Object();

   public static void main(String[] args) {
       sleepMillis = Long.parseLong(args[0]);
       DeadLockTest test = new DeadLockTest();
       test.doTest();
   }

   private void doTest() {
       Thread t1 = new Thread(new Runnable() {
           public void run() {
               lock12();
           }
       });
       Thread t2 = new Thread(new Runnable() {
           public void run() {
               lock21();
           }
       });
       t1.start();
       t2.start();
   }

   private void lock12() {
       synchronized (lock1) {
           sleep();
           synchronized (lock2) {
               sleep();
           }
       }
   }

   private void lock21() {
       synchronized (lock2) {
           sleep();
           synchronized (lock1) {
               sleep();
           }
       }
   }

   private void sleep() {
       try {
           Thread.sleep(sleepMillis);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
}
To run the deadlock test with sleep time 1 millisecond:
java -cp . test.concurrent.DeadLockTest 1

In SQL Server, how to create while loop in select

You Could do something like this .....
Your Table

CREATE TABLE TestTable 
(
ID INT,
Data NVARCHAR(50)
)
GO

INSERT INTO TestTable
VALUES (1,'AABBCC'),
       (2,'FFDD'),
       (3,'TTHHJJKKLL')
GO

SELECT * FROM TestTable

My Suggestion

CREATE TABLE #DestinationTable
(
ID INT,
Data NVARCHAR(50)
)
GO  
    SELECT * INTO #Temp FROM TestTable

    DECLARE @String NVARCHAR(2)
    DECLARE @Data NVARCHAR(50)
    DECLARE @ID INT

    WHILE EXISTS (SELECT * FROM #Temp)
     BEGIN 
        SELECT TOP 1 @Data =  DATA, @ID = ID FROM  #Temp

          WHILE LEN(@Data) > 0
            BEGIN
                SET @String = LEFT(@Data, 2)

                INSERT INTO #DestinationTable (ID, Data)
                VALUES (@ID, @String)

                SET @Data = RIGHT(@Data, LEN(@Data) -2)
            END
        DELETE FROM #Temp WHERE ID = @ID
     END


SELECT * FROM #DestinationTable

Result Set

ID  Data
1   AA
1   BB
1   CC
2   FF
2   DD
3   TT
3   HH
3   JJ
3   KK
3   LL

DROP Temp Tables

DROP TABLE #Temp
DROP TABLE #DestinationTable

Automating running command on Linux from Windows using PuTTY

Here is a totally out of the box solution.

  1. Install AutoHotKey (ahk)
  2. Map the script to a key (e.g. F9)
  3. In the ahk script, a) Ftp the commands (.ksh) file to the linux machine

    b) Use plink like below. Plink should be installed if you have putty.

plink sessionname -l username -pw password test.ksh

or

plink -ssh example.com -l username -pw password test.ksh

All the steps will be performed in sequence whenever you press F9 in windows.

How do you delete all text above a certain line

kdgg

delete all lines above the current one.

How to link external javascript file onclick of button

By loading the .js file first and then calling the function via onclick, there's less coding and it's fairly obvious what's going on. We'll call the JS file zipcodehelp.js.

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Button to call JS function.</title>
</head>
<body>
    <h1>Use Button to execute function in '.js' file.</h1>
    <script type="text/javascript" src="zipcodehelp.js"></script>
    <button onclick="ZipcodeHelp();">Get Zip Help!</button>
</body>
</html>

And the contents of zipcodehelp.js is :

function ZipcodeHelp() {
  alert("If Zipcode is missing in list at left, do: \n\n\
    1. Enter any zipcode and click Create Client. \n\
    2. Goto Zipcodes and create new zip code. \n\
    3. Edit this new client from the client list.\n\
    4. Select the new zipcode." );
}

Hope that helps! Cheers!

–Ken

Display date/time in user's locale format and time offset

Here's what I've used in past projects:

var myDate = new Date();
var tzo = (myDate.getTimezoneOffset()/60)*(-1);
//get server date value here, the parseInvariant is from MS Ajax, you would need to do something similar on your own
myDate = new Date.parseInvariant('<%=DataCurrentDate%>', 'yyyyMMdd hh:mm:ss');
myDate.setHours(myDate.getHours() + tzo);
//here you would have to get a handle to your span / div to set.  again, I'm using MS Ajax's $get
var dateSpn = $get('dataDate');
dateSpn.innerHTML = myDate.localeFormat('F');

How can I use custom fonts on a website?

You can use CSS3 font-face or webfonts

@font-face usage

@font-face {
   font-family: Delicious; 
   src: url('Delicious-Roman.otf');
} 

webfonts

take a look at Google Webfonts, http://www.google.com/webfonts

How to plot two histograms together in R?

That image you linked to was for density curves, not histograms.

If you've been reading on ggplot then maybe the only thing you're missing is combining your two data frames into one long one.

So, let's start with something like what you have, two separate sets of data and combine them.

carrots <- data.frame(length = rnorm(100000, 6, 2))
cukes <- data.frame(length = rnorm(50000, 7, 2.5))

# Now, combine your two dataframes into one.  
# First make a new column in each that will be 
# a variable to identify where they came from later.
carrots$veg <- 'carrot'
cukes$veg <- 'cuke'

# and combine into your new data frame vegLengths
vegLengths <- rbind(carrots, cukes)

After that, which is unnecessary if your data is in long format already, you only need one line to make your plot.

ggplot(vegLengths, aes(length, fill = veg)) + geom_density(alpha = 0.2)

enter image description here

Now, if you really did want histograms the following will work. Note that you must change position from the default "stack" argument. You might miss that if you don't really have an idea of what your data should look like. A higher alpha looks better there. Also note that I made it density histograms. It's easy to remove the y = ..density.. to get it back to counts.

ggplot(vegLengths, aes(length, fill = veg)) + 
   geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')

enter image description here

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

You can set the path variable for easily by command prompt.

  1. Open run and write cmd

  2. In the command window write the following: set path=%path%;C:\python36

  3. press enter.
  4. to check write python and enter. You will see the python version as shown in the picture.

enter image description here

Get the date (a day before current time) in Bash

Try the below code , which takes care of the DST part as well.

if [ $(date +%w) -eq $(date -u +%w) ]; then
  tz=$(( 10#$gmthour - 10#$localhour ))
else
  tz=$(( 24 - 10#$gmthour + 10#$localhour ))
fi
echo $tz
myTime=`TZ=GMT+$tz date +'%Y%m%d'`

Courtsey Ansgar Wiechers

Simpler way to create dictionary of separate variables?

With python-varname you can easily do it:

pip install python-varname

from varname import Wrapper

foo = Wrapper(True)
bar = Wrapper(False)

your_dict = {val.name: val.value for val in (foo, bar)}

print(your_dict)

# {'foo': True, 'bar': False}

Disclaimer: I'm the author of that python-varname library.

Get UTC time and local time from NSDate object

NSDate is a specific point in time without a time zone. Think of it as the number of seconds that have passed since a reference date. How many seconds have passed in one time zone vs. another since a particular reference date? The answer is the same.

Depending on how you output that date (including looking at the debugger), you may get an answer in a different time zone.

If they ran at the same moment, the values of these are the same. They're both the number of seconds since the reference date, which may be formatted on output to UTC or local time. Within the date variable, they're both UTC.

Objective-C:

NSDate *UTCDate = [NSDate date]

Swift:

let UTCDate = NSDate.date()

To explain this, we can use a NSDateFormatter in a playground:

import UIKit

let date = NSDate.date()
    // "Jul 23, 2014, 11:01 AM" <-- looks local without seconds. But:

var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
let defaultTimeZoneStr = formatter.stringFromDate(date)
    // "2014-07-23 11:01:35 -0700" <-- same date, local, but with seconds
formatter.timeZone = NSTimeZone(abbreviation: "UTC")
let utcTimeZoneStr = formatter.stringFromDate(date)
    // "2014-07-23 18:01:41 +0000" <-- same date, now in UTC

The date output varies, but the date is constant. This is exactly what you're saying. There's no such thing as a local NSDate.

As for how to get microseconds out, you can use this (put it at the bottom of the same playground):

let seconds = date.timeIntervalSince1970
let microseconds = Int(seconds * 1000) % 1000 // chops off seconds

To compare two dates, you can use date.compare(otherDate).

Getting the parent of a directory in Bash

dir=/home/smith/Desktop/Test
parentdir="$(dirname "$dir")"

Works if there is a trailing slash, too.

Prevent HTML5 video from being downloaded (right-click saved)?

We could make that not so easy by hiding context menu, like this:

<video oncontextmenu="return false;"  controls>
  <source src="https://yoursite.com/yourvideo.mp4" >
</video>

Java double comparison epsilon

Floating point numbers only have so many significant digits, but they can go much higher. If your app will ever handle large numbers, you will notice the epsilon value should be different.

0.001+0.001 = 0.002 BUT 12,345,678,900,000,000,000,000+1=12,345,678,900,000,000,000,000 if you are using floating point and double. It's not a good representation of money, unless you are damn sure you'll never handle more than a million dollars in this system.

bundle install fails with SSL certificate verification error

I was able to track this down to the fact that the binaries that rvm downloads do not play nice with OS X's OpenSSL, which is old and is no longer used by the OS.

The solution for me was to force compilation when installing Ruby via rvm:

rvm reinstall --disable-binary 2.2

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

There seem to be something quirky with the 'automatic' entitlements in Xcode 4.6.

There is an Entitlement.plist file for each SDK at:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk/Entitlements.plist

A workaround solution I came up with was to edit this file and add the sneaky aps-environment key manually like so:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>application-identifier</key>
    <string>$(AppIdentifierPrefix)$(CFBundleIdentifier)</string>
    <key>aps-environment</key>
    <string>development</string>
    <key>keychain-access-groups</key>
    <array>
        <string>$(AppIdentifierPrefix)$(CFBundleIdentifier)</string>
    </array>
</dict>
</plist>

Then, Xcode is generating correct Xcent file, which contains the aps-environment key at:

/Users/mySelf/Library/Developer/Xcode/DerivedData/myApp-buauvgusocvjyjcwdtpewdzycfmc/Build/Intermediates/myApp.build/Debug-iphoneos/myApp.build/myApp.xcent

You can locate where your Xcent file is created using Xcode's Log Navigator,
look for "ProcessProductPackaging".

Unfortunately, this is the only way I found that fixes the issue.
(and finally able to properly get push token now)

Just wondering if another more elegant solution is available.
Please see my SO question for more details on that:
Xcode 4.6 automatic entitlement not working - "no valid aps-environment"

Finding length of char array

If you are expecting 4 as output then try this:

char a[]={0x00,0xdc,0x01,0x04};

Post values from a multiple select

try this : here select is your select element

let select = document.getElementsByClassName('lstSelected')[0],
    options = select.options,
    len = options.length,
    data='',
    i=0;
while (i<len){
    if (options[i].selected)
        data+= "&" + select.name + '=' + options[i].value;
    i++;
}
return data;

Data is in the form of query string i.e.name=value&name=anotherValue

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

Create Setup/MSI installer in Visual Studio 2017

Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).

Instead, I used this method:

  1. Close all but one instance of Visual Studio.
  2. In the running instance, access the menu Tools->Extensions and Updates.
  3. In that dialog, choose Online->Visual Studio Marketplace->Tools->Setup & Deployment.
  4. From the list that appears, select Microsoft Visual Studio 2017 Installer Projects.

Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:

enter image description here

C++ cout hex values?

std::hex is defined in <ios> which is included by <iostream>. But to use things like std::setprecision/std::setw/std::setfill/etc you have to include <iomanip>.

Java Strings: "String s = new String("silly");"

String is a special built-in class of the language. It is for the String class only in which you should avoid saying

String s = new String("Polish");

Because the literal "Polish" is already of type String, and you're creating an extra unnecessary object. For any other class, saying

CaseInsensitiveString cis = new CaseInsensitiveString("Polish");

is the correct (and only, in this case) thing to do.

how to download file using AngularJS and calling MVC API?

This is how I solved this problem

$scope.downloadPDF = function () {
    var link = document.createElement("a");
    link.setAttribute("href",  "path_to_pdf_file/pdf_filename.pdf");
    link.setAttribute("download", "download_name.pdf");
    document.body.appendChild(link); // Required for FF
    link.click(); // This will download the data file named "download_name.pdf"
}

How to take character input in java

use :

char ch=**scanner.nextChar**()

How to execute a shell script on a remote server using Ansible?

You can use template module to copy if script exists on local machine to remote machine and execute it.

 - name: Copy script from local to remote machine
   hosts: remote_machine
   tasks:
    - name: Copy  script to remote_machine
      template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
    - name: Execute script on remote_machine
      script: sh <remote_machine path>/script.sh

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

Long story short, it probably doesn't matter. Use whichever you think looks nicest.

Longer answer, using Oracle's Java 7 JDK specifically, since this isn't defined at the JLS:

String.valueOf or Character.toString work the same way, so use whichever you feel looks nicer. In fact, Character.toString simply calls String.valueOf (source).

So the question is, should you use one of those or String.substring. Here again it doesn't matter much. String.substring uses the original string's char[] and so allocates one object fewer than String.valueOf. This also prevents the original string from being GC'ed until the one-character string is available for GC (which can be a memory leak), but in your example, they'll both be available for GC after each iteration, so that doesn't matter. The allocation you save also doesn't matter -- a char[1] is cheap to allocate, and short-lived objects (as the one-char string will be) are cheap to GC, too.

If you have a large enough data set that the three are even measurable, substring will probably give a slight edge. Like, really slight. But that "if... measurable" contains the real key to this answer: why don't you just try all three and measure which one is fastest?

How to add a column in TSQL after a specific column?

In Microsoft SQL Server Management Studio (the admin tool for MSSQL) just go into "design" on a table and drag the column to the new position. Not command line but you can do it.

How do I update the password for Git?

If you are using github and have enabled 2 factor authentication, you need to enter a Personal access token instead of your password

First reset your password:

git config --global --unset user.password

Then, log to your github account, on the right hand corner, click on Settings, then Developer Settings. Generate a Personal access token. Copy it.

git push

The terminal will prompt you for your username: enter your email address.

At the password prompt, enter the personal access token instead.

How do I execute a PowerShell script automatically using Windows task scheduler?

After several hours of test and research over the Internet, I've finally found how to start my PowerShell script with task scheduler, thanks to the video Scheduling a PowerShell Script using Windows Task Scheduler by Jack Fruh @sharepointjack.

Program/script -> put full path through powershell.exe

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe

Add arguments -> Full path to the script, and the script, without any " ".

Start in (optional) -> The directory where your script resides, without any " ".

How do I view Android application specific cache?

On Android Studio you can use Device File Explorer to view /data/data/my_app_package/cache.

Click View > Tool Windows > Device File Explorer or click the Device File Explorer button in the tool window bar to open the Device File Explorer.

Documentation

How do I plot list of tuples in Python?

In matplotlib it would be:

import matplotlib.pyplot as plt

data =  [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

x_val = [x[0] for x in data]
y_val = [x[1] for x in data]

print x_val
plt.plot(x_val,y_val)
plt.plot(x_val,y_val,'or')
plt.show()

which would produce:

enter image description here

How can I strip HTML tags from a string in ASP.NET?

I have written a pretty fast method in c# which beats the hell out of the Regex. It is hosted in an article on CodeProject.

Its advantages are, among better performance the ability to replace named and numbered HTML entities (those like &amp;amp; and &203;) and comment blocks replacement and more.

Please read the related article on CodeProject.

Thank you.

When should I use curly braces for ES6 import?

The curly braces are used only for import when export is named. If the export is default then curly braces are not used for import.

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

You can use this code for generating has code for a given string.

int hash = 7;
for (int i = 0; i < strlen; i++) {
    hash = hash*31 + charAt(i);
}

In Python, can I call the main() of an imported module?

It's just a function. Import it and call it:

import myModule

myModule.main()

If you need to parse arguments, you have two options:

  • Parse them in main(), but pass in sys.argv as a parameter (all code below in the same module myModule):

    def main(args):
        # parse arguments using optparse or argparse or what have you
    
    if __name__ == '__main__':
        import sys
        main(sys.argv[1:])
    

    Now you can import and call myModule.main(['arg1', 'arg2', 'arg3']) from other another module.

  • Have main() accept parameters that are already parsed (again all code in the myModule module):

    def main(foo, bar, baz='spam'):
        # run with already parsed arguments
    
    if __name__ == '__main__':
        import sys
        # parse sys.argv[1:] using optparse or argparse or what have you
        main(foovalue, barvalue, **dictofoptions)
    

    and import and call myModule.main(foovalue, barvalue, baz='ham') elsewhere and passing in python arguments as needed.

The trick here is to detect when your module is being used as a script; when you run a python file as the main script (python filename.py) no import statement is being used, so python calls that module "__main__". But if that same filename.py code is treated as a module (import filename), then python uses that as the module name instead. In both cases the variable __name__ is set, and testing against that tells you how your code was run.

Call Class Method From Another Class

Just call it and supply self

class A:
    def m(self, x, y):
        print(x+y)

class B:
    def call_a(self):
        A.m(self, 1, 2)

b = B()
b.call_a()

output: 3

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

What does the ">" (greater-than sign) CSS selector mean?

The greater sign ( > ) selector in CSS means that the selector on the right is a direct descendant / child of whatever is on the left.

An example:

article > p { }

Means only style a paragraph that comes after an article.

How can I open a Shell inside a Vim Window?

:vsp or :sp - splits vim into two instance but you cannot use :shell in only one of them.

Why not display another tab of the terminal not another tab of vim. If you like the idea you can try it: Ctrl-shift-t. and move between them with Ctrl - pageup and Ctrl - pagedown

If you want just a few shell commands you can make any shell command in vim using !

For example :!./a.out.

PHP form - on submit stay on same page

In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.

For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.

Like this:

<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
  $input = $_POST['inputText']; //get input text
  $message = "Success! You entered: ".$input;
}    
?>

<html>
<body>    
<form action="" method="post">
<?php echo $message; ?>
  <input type="text" name="inputText"/>
  <input type="submit" name="SubmitButton"/>
</form>    
</body>
</html>

Copy text from nano editor to shell

nano does not seem to have the ability to copy/paste from the global/system clipboard or shell.

However, you can copy text from one file to another using nano's file buffers. When you open another file buffer with ^R (Ctrl + r), you can use nanos built-in copy/paste functionality (outlined below) to copy between files:

  • M-6 (Meta + 6) to copy lines to nano's clipboard.
  • ^K (Ctrl + k) to cut the current line and store it in nano's clipboard.
  • ^^ (Ctrl + Shift + 6) to select text. Once you have selected the text, you can use the above commands to copy it or cut it.
  • ^U (Ctrl + u) to paste the text from nano's clipboard.

Finally, if the above solution will not work for you and you are using a terminal emulator, you may be able to copy/paste from the global clipboard with Ctrl + Shift + c and Ctrl + Shift + v (Cmd + c and Cmd + v on OSX) respectively. screen also provides an external copy/paste that should work in nano. Finally if all you need to do is capture certain lines or text from a file, consider using grep to find the lines and xclip or xsel (or pbcopy/pbpaste on OSX) to copy them to the global clipboard (and/or paste from the clipboard) instead of nano.

PHP how to get value from array if key is in a variable

$value = ( array_key_exists($key, $array) && !empty($array[$key]) ) 
         ? $array[$key] 
         : 'non-existant or empty value key';

How to add List<> to a List<> in asp.net

Use .AddRange to append any Enumrable collection to the list.

ValueError: could not convert string to float: id

This error is pretty verbose:

ValueError: could not convert string to float: id

Somewhere in your text file, a line has the word id in it, which can't really be converted to a number.

Your test code works because the word id isn't present in line 2.


If you want to catch that line, try this code. I cleaned your code up a tad:

#!/usr/bin/python

import os, sys
from scipy import stats
import numpy as np

for index, line in enumerate(open('data2.txt', 'r').readlines()):
    w = line.split(' ')
    l1 = w[1:8]
    l2 = w[8:15]

    try:
        list1 = map(float, l1)
        list2 = map(float, l2)
    except ValueError:
        print 'Line {i} is corrupt!'.format(i = index)'
        break

    result = stats.ttest_ind(list1, list2)
    print result[1]

Correct way to focus an element in Selenium WebDriver using Java

This code actually doesn't provide focus:

new Actions(driver).moveToElement(element).perform();

It provides a hover effect.

Additionally, the JS code .focus() requires that the window be active in order to work.

js.executeScript("element.focus();");

I have found that this code works:

element.sendKeys(Keys.SHIFT);

For my own code, I use both:

element.sendKeys(Keys.SHIFT);
js.executeScript("element.focus();");

Java : How to determine the correct charset encoding of a stream

You cannot determine the encoding of a arbitrary byte stream. This is the nature of encodings. A encoding means a mapping between a byte value and its representation. So every encoding "could" be the right.

The getEncoding() method will return the encoding which was set up (read the JavaDoc) for the stream. It will not guess the encoding for you.

Some streams tell you which encoding was used to create them: XML, HTML. But not an arbitrary byte stream.

Anyway, you could try to guess an encoding on your own if you have to. Every language has a common frequency for every char. In English the char e appears very often but ê will appear very very seldom. In a ISO-8859-1 stream there are usually no 0x00 chars. But a UTF-16 stream has a lot of them.

Or: you could ask the user. I've already seen applications which present you a snippet of the file in different encodings and ask you to select the "correct" one.

How to install a specific JDK on Mac OS X?

As a rule you cannot install other versions of Java on a Mac than those provided by Apple through Software Update. If you need Java 6 you must have a 64-bit Intel computer. You should always have Java 5 and 1.4 and perhaps 1.3 installed if you have at least OS X 10.4.

If you have VERY much elbow grease and is willing to work with beta software you can install the OpenJDK under OS X, but I don't think you want to go there.

Storing sex (gender) in database

I'd call the column "gender".

Data Type   Bytes Taken          Number/Range of Values
------------------------------------------------
TinyINT     1                    255 (zero to 255)
INT         4            -       2,147,483,648 to 2,147,483,647
BIT         1 (2 if 9+ columns)  2 (0 and 1)
CHAR(1)     1                    26 if case insensitive, 52 otherwise

The BIT data type can be ruled out because it only supports two possible genders which is inadequate. While INT supports more than two options, it takes 4 bytes -- performance will be better with a smaller/more narrow data type.

CHAR(1) has the edge over TinyINT - both take the same number of bytes, but CHAR provides a more narrow number of values. Using CHAR(1) would make using "m", "f",etc natural keys, vs the use of numeric data which are referred to as surrogate/artificial keys. CHAR(1) is also supported on any database, should there be a need to port.

Conclusion

I would use Option 2: CHAR(1).

Addendum

An index on the gender column likely would not help because there's no value in an index on a low cardinality column. Meaning, there's not enough variety in the values for the index to provide any value.

What does mscorlib stand for?

Microsoft Core Library, ie they are at the heart of everything.

There is a more "massaged" explanation you may prefer:

"When Microsoft first started working on the .NET Framework, MSCorLib.dll was an acronym for Microsoft Common Object Runtime Library. Once ECMA started to standardize the CLR and parts of the FCL, MSCorLib.dll officially became the acronym for Multilanguage Standard Common Object Runtime Library."

From http://weblogs.asp.net/mreynolds/archive/2004/01/31/65551.aspx

Around 1999, to my personal memory, .Net was known as "COOL", so I am a little suspicious of this derivation. I never heard it called "COR", which is a silly-sounding name to a native English speaker.

Is there a way to add a gif to a Markdown file?

Giphy Gotcha

After following the 2 requirements listed above (must end in .gif and using the image syntax), if you are having trouble with a gif from giphy:

Be sure you have the correct giphy url! You can't just add .gif to the end of this one and have it work.

If you just copy the url from a browser, you will get something like:

https://giphy.com/gifs/gol-automaton-game-of-life-QfsvYoBSSpfbtFJIVo

You need to instead click on "Copy Link" and then grab the "GIF Link" specifically. Notice the correct one points to media.giphy.com instead of just giphy.com:

https://media.giphy.com/media/QfsvYoBSSpfbtFJIVo/giphy.gif

Partition Function COUNT() OVER possible using DISTINCT

I think the only way of doing this in SQL-Server 2008R2 is to use a correlated subquery, or an outer apply:

SELECT  datekey,
        COALESCE(RunningTotal, 0) AS RunningTotal,
        COALESCE(RunningCount, 0) AS RunningCount,
        COALESCE(RunningDistinctCount, 0) AS RunningDistinctCount
FROM    document
        OUTER APPLY
        (   SELECT  SUM(Amount) AS RunningTotal,
                    COUNT(1) AS RunningCount,
                    COUNT(DISTINCT d2.dateKey) AS RunningDistinctCount
            FROM    Document d2
            WHERE   d2.DateKey <= document.DateKey
        ) rt;

This can be done in SQL-Server 2012 using the syntax you have suggested:

SELECT  datekey,
        SUM(Amount) OVER(ORDER BY DateKey) AS RunningTotal
FROM    document

However, use of DISTINCT is still not allowed, so if DISTINCT is required and/or if upgrading isn't an option then I think OUTER APPLY is your best option

Setting up a cron job in Windows

The windows equivalent to a cron job is a scheduled task.

A scheduled task can be created as described by Alex and Rudu, but it can also be done command line with schtasks (if you for instance need to script it or add it to version control).

An example:

schtasks /create /tn calculate /tr calc /sc weekly /d MON /st 06:05 /ru "System"

Creates the task calculate, which starts the calculator(calc) every monday at 6:05 (should you ever need that.)

All available commands can be found here: http://technet.microsoft.com/en-us/library/cc772785%28WS.10%29.aspx

It works on windows server 2008 as well as windows server 2003.

Convert char to int in C#

Comparison of some of the methods based on the result when the character is not an ASCII digit:

char c1 = (char)('0' - 1), c2 = (char)('9' + 1); 

Debug.Print($"{c1 & 15}, {c2 & 15}");                                   // 15, 10
Debug.Print($"{c1 ^ '0'}, {c2 ^ '0'}");                                 // 31, 10
Debug.Print($"{c1 - '0'}, {c2 - '0'}");                                 // -1, 10
Debug.Print($"{(uint)c1 - '0'}, {(uint)c2 - '0'}");                     // 4294967295, 10
Debug.Print($"{char.GetNumericValue(c1)}, {char.GetNumericValue(c2)}"); // -1, -1

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

How to pass an event object to a function in Javascript?

Although this is the accepted answer, toto_tico's answer below is better :)

Try making the onclick js use 'return' to ensure the desired return value gets used...

<button type="button" value="click me" onclick="return check_me();" />

Including an anchor tag in an ASP.NET MVC Html.ActionLink

My solution will work if you apply the ActionFilter to the Subcategory action method, as long as you always want to redirect the user to the same bookmark:

http://spikehd.blogspot.com/2012/01/mvc3-redirect-action-to-html-bookmark.html

It modifies the HTML buffer and outputs a small piece of javascript to instruct the browser to append the bookmark.

You could modify the javascript to manually scroll, instead of using a bookmark in the URL, of course!

Hope it helps :)

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

I tried Ricardo Stuven's way but it didn't work for me. What worked in the end was adding "compact": false to my .babelrc file:

{
    "compact": false,
    "presets": ["latest", "react", "stage-0"]
}

What is the difference between buffer and cache memory in Linux?

Buffers are associated with a specific block device, and cover caching of filesystem metadata as well as tracking in-flight pages. The cache only contains parked file data. That is, the buffers remember what's in directories, what file permissions are, and keep track of what memory is being written from or read to for a particular block device. The cache only contains the contents of the files themselves.

quote link

How to default to other directory instead of home directory

If you want to have projects choice list when u open GIT bash:

  • edit ppath in code header to your git projects path, put this code into .bashrc file and copy it into your $HOME dir (in Win Vista / 7 it is usually c:\Users\$YOU)

.

#!/bin/bash
ppath="/d/-projects/-github"
cd $ppath
unset PROJECTS
PROJECTS+=(".")
i=0

echo
echo -e "projects:\n-------------"

for f in *
do
    if [ -d "$f" ]
    then
        PROJECTS+=("$f")
        echo -e $((++i)) "- \e[1m$f\e[0m"
    fi
done


if [ ${#PROJECTS[@]} -gt 1 ]
then
    echo -ne "\nchoose project: "
    read proj
    case "$proj" in
        [0-`expr ${#PROJECTS[@]} - 1`]) cd "${PROJECTS[proj]}" ;;
        *) echo " wrong choice" ;;
    esac
else
    echo "there is no projects"
fi
unset PROJECTS
  • you may want set this file as executable inside GIT bash chmod +x .bashrc (but its probably redundant, since this file is stored on ntfs filesystem)

Java: print contents of text file to screen

With Java 7's try-with-resources Jiri's answer can be improved upon:

try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
   String line = null;
   while ((line = br.readLine()) != null) {
       System.out.println(line);
   }
}

Add exception handling at the place of your choice, either in this try or elsewhere.

Convert string to date in Swift

make global function

func convertDateFormat(inputDate: String) -> String {

     let olDateFormatter = DateFormatter()
     olDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

     let oldDate = olDateFormatter.date(from: inputDate)

     let convertDateFormatter = DateFormatter()
     convertDateFormatter.dateFormat = "MMM dd yyyy h:mm a"

     return convertDateFormatter.string(from: oldDate!)
}

Called function and pass value in it

get_OutputStr = convertDateFormat(inputDate: "2019-03-30T05:30:00+0000")

and here is output

Feb 25 2020 4:51 PM



 

How to remove list elements in a for loop in Python?

As other answers have said, the best way to do this involves making a new list - either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable. The difference between these depends on your use case, since they affect other variables for the original list differently (or, rather, the first affects them, the second doesn't).

If a copy isn't an option for some reason, you do have one other option that relies on an understanding of why modifying a list you're iterating breaks. List iteration works by keeping track of an index, incrementing it each time around the loop until it falls off the end of the list. So, if you remove at (or before) the current index, everything from that point until the end shifts one spot to the left. But the iterator doesn't know about this, and effectively skips the next element since it is now at the current index rather than the next one. However, removing things that are after the current index doesn't affect things.

This implies that if you iterate the list back to front, if you remove an item at the current index, everything to it's right shifts left - but that doesn't matter, since you've already dealt with all the elements to the right of the current position, and you're moving left - the next element to the left is unaffected by the change, and so the iterator gives you the element you expect.

TL;DR:

>>> a = list(range(5))
>>> for b in reversed(a):
    if b == 3:
        a.remove(b)
>>> a
[0, 1, 2, 4]

However, making a copy is usually better in terms of making your code easy to read. I only mention this possibility for sake of completeness.

Get path to execution directory of Windows Forms application

System.Windows.Forms.Application.StartupPath will solve your problem, I think

How to send an HTTP request with a header parameter?

With your own Code and a Slight Change withou jQuery,

function testingAPI(){ 
    var key = "8a1c6a354c884c658ff29a8636fd7c18"; 
    var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
    console.log(httpGet(url,key)); 
}


function httpGet(url,key){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

Thank You

When to use RSpec let()?

I always prefer let to an instance variable for a couple of reasons:

  • Instance variables spring into existence when referenced. This means that if you fat finger the spelling of the instance variable, a new one will be created and initialized to nil, which can lead to subtle bugs and false positives. Since let creates a method, you'll get a NameError when you misspell it, which I find preferable. It makes it easier to refactor specs, too.
  • A before(:each) hook will run before each example, even if the example doesn't use any of the instance variables defined in the hook. This isn't usually a big deal, but if the setup of the instance variable takes a long time, then you're wasting cycles. For the method defined by let, the initialization code only runs if the example calls it.
  • You can refactor from a local variable in an example directly into a let without changing the referencing syntax in the example. If you refactor to an instance variable, you have to change how you reference the object in the example (e.g. add an @).
  • This is a bit subjective, but as Mike Lewis pointed out, I think it makes the spec easier to read. I like the organization of defining all my dependent objects with let and keeping my it block nice and short.

A related link can be found here: http://www.betterspecs.org/#let

count distinct values in spreadsheet

You can use the query function, so if your data were in col A where the first row was the column title...

=query(A2:A,"select A, count(A) where A != '' group by A order by count(A) desc label A 'City'", 0)

yields

City    count 
London  2
Paris   2
Berlin  1
Rome    1

Link to working Google Sheet.

https://docs.google.com/spreadsheets/d/1N5xw8-YP2GEPYOaRkX8iRA6DoeRXI86OkfuYxwXUCbc/edit#gid=0

Can you use Microsoft Entity Framework with Oracle?

In case you don't know it already, Oracle has released ODP.NET which supports Entity Framework. It doesn't support code first yet though.

http://www.oracle.com/technetwork/topics/dotnet/index-085163.html

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Use

=LEFT(B2, 2)*3600000 + MID(B2,4,2) * 60000 + MID(B2,7,2)*1000 + RIGHT(B2,3)

How to read one single line of csv data in Python?

Just for reference, a for loop can be used after getting the first row to get the rest of the file:

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    row1 = next(reader)  # gets the first line
    for row in reader:
        print(row)       # prints rows 2 and onward

Detect Close windows event by jQuery

There is no specific event for capturing browser close event. But we can detect by the browser positions XY.

<script type="text/javascript">
$(document).ready(function() {
  $(document).mousemove(function(e) {
    if(e.pageY <= 5)
    {
        //this condition would occur when the user brings their cursor on address bar 
        //do something here 
    }
  });
});
</script>

How can I use the apply() function for a single column?

Let me try a complex computation using datetime and considering nulls or empty spaces. I am reducing 30 years on a datetime column and using apply method as well as lambda and converting datetime format. Line if x != '' else x will take care of all empty spaces or nulls accordingly.

df['Date'] = df['Date'].fillna('')
df['Date'] = df['Date'].apply(lambda x : ((datetime.datetime.strptime(str(x), '%m/%d/%Y') - datetime.timedelta(days=30*365)).strftime('%Y%m%d')) if x != '' else x)

Remove all child nodes from a parent?

A other users suggested,

.empty()

is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.

If you wish to keep data, like event handlers for example, you should use

.detach()

as described on the JQuery's API detach documentation.

The method .remove() could be usefull for similar purposes.

How to find array / dictionary value using key?

It's as simple as this :

$array[$key];

Excel Create Collapsible Indented Row Hierarchies

Create a Pivot Table. It has these features and many more.

If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.

C# Version Of SQL LIKE

Simply .Contains() would do the work for you.

"Example String".Contains("amp");   //like '%amp%'

This would return true, and performing a select on it would return the desired output.

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

Format with Currency format string

=Format(Fields!Price.Value, "C")

It will give you 2 decimal places with "$" prefixed.

You can find other format strings on MSDN: Adding Style and Formatting to a ReportViewer Report

Note: The MSDN article has been archived to the "VS2005_General" document, which is no longer directly accessible online. Here is the excerpt of the formatting strings referenced:

Formatting Numbers

The following table lists common .NET Framework number formatting strings.

Format string, Name

C or c Currency

D or d Decimal

E or e Scientific

F or f Fixed-point

G or g General

N or n Number

P or p Percentage

R or r Round-trip

X or x Hexadecimal

You can modify many of the format strings to include a precision specifier that defines the number of digits to the right of the

decimal point. For example, a formatting string of D0 formats the number so that it has no digits after the decimal point. You

can also use custom formatting strings, for example, #,###.

Formatting Dates

The following table lists common .NET Framework date formatting strings.

Format string, Name

d Short date

D Long date

t Short time

T Long time

f Full date/time (short time)

F Full date/time (long time)

g General date/time (short time)

G General date/time (long time)

M or m Month day

R or r RFC1123 pattern

Y or y Year month

You can also a use custom formatting strings; for example, dd/MM/yy. For more information about .NET Framework formatting strings, see Formatting Types.

Sort arrays of primitive types in descending order

Your implementation (the one in the question) is faster than e.g. wrapping with toList() and using a comparator-based method. Auto-boxing and running through comparator methods or wrapped Collections objects is far slower than just reversing.

Of course you could write your own sort. That might not be the answer you're looking for, but note that if your comment about "if the array is already sorted quite well" happens frequently, you might do well to choose a sorting algorithm that handles that case well (e.g. insertion) rather than use Arrays.sort() (which is mergesort, or insertion if the number of elements is small).

How to find children of nodes using BeautifulSoup

"How to find all a which are children of <li class=test> but not any others?"

Given the HTML below (I added another <a> to show te difference between select and select_one):

<div>
  <li class="test">
    <a>link1</a>
    <ul>
      <li>
        <a>link2</a>
      </li>
    </ul>
    <a>link3</a>
  </li>
</div>

The solution is to use child combinator (>) that is placed between two CSS selectors:

>>> soup.select('li.test > a')
[<a>link1</a>, <a>link3</a>]

In case you want to find only the first child:

>>> soup.select_one('li.test > a')
<a>link1</a>

Parsing arguments to a Java command line program

Here is @DwB solution upgraded to Commons CLI 1.3.1 compliance (replaced deprecated components OptionBuilder and GnuParser). The Apache documentation uses examples that in real life have unmarked/bare arguments but ignores them. Thanks @DwB for showing how it works.

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public static void main(String[] parameters) {
    CommandLine commandLine;
    Option option_A = Option.builder("A").argName("opt3").hasArg().desc("The A option").build();
    Option option_r = Option.builder("r").argName("opt1").hasArg().desc("The r option").build();
    Option option_S = Option.builder("S").argName("opt2").hasArg().desc("The S option").build();
    Option option_test = Option.builder().longOpt("test").desc("The test option").build();
    Options options = new Options();
    CommandLineParser parser = new DefaultParser();

    options.addOption(option_A);
    options.addOption(option_r);
    options.addOption(option_S);
    options.addOption(option_test);

    String header = "               [<arg1> [<arg2> [<arg3> ...\n       Options, flags and arguments may be in any order";
    String footer = "This is DwB's solution brought to Commons CLI 1.3.1 compliance (deprecated methods replaced)";
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("CLIsample", header, options, footer, true);    

    String[] testArgs =
            { "-r", "opt1", "-S", "opt2", "arg1", "arg2",
                    "arg3", "arg4", "--test", "-A", "opt3", };

    try
    {
        commandLine = parser.parse(options, testArgs);

        if (commandLine.hasOption("A"))
        {
            System.out.print("Option A is present.  The value is: ");
            System.out.println(commandLine.getOptionValue("A"));
        }

        if (commandLine.hasOption("r"))
        {
            System.out.print("Option r is present.  The value is: ");
            System.out.println(commandLine.getOptionValue("r"));
        }

        if (commandLine.hasOption("S"))
        {
            System.out.print("Option S is present.  The value is: ");
            System.out.println(commandLine.getOptionValue("S"));
        }

        if (commandLine.hasOption("test"))
        {
            System.out.println("Option test is present.  This is a flag option.");
        }

        {
            String[] remainder = commandLine.getArgs();
            System.out.print("Remaining arguments: ");
            for (String argument : remainder)
            {
                System.out.print(argument);
                System.out.print(" ");
            }

            System.out.println();
        }

    }
    catch (ParseException exception)
    {
        System.out.print("Parse error: ");
        System.out.println(exception.getMessage());
    }

}

Output:

usage: CLIsample [-A <opt3>] [-r <opt1>] [-S <opt2>] [--test]
                 [<arg1> [<arg2> [<arg3> ...
       Options, flags and arguments may be in any order
 -A <opt3>   The A option
 -r <opt1>   The r option
 -S <opt2>   The S option
    --test   The test option
This is DwB's solution brought to Commons CLI 1.3.1 compliance (deprecated
methods replaced)
Option A is present.  The value is: opt3
Option r is present.  The value is: opt1
Option S is present.  The value is: opt2
Option test is present.  This is a flag option.
Remaining arguments: arg1 arg2 arg3 arg4

CodeIgniter removing index.php from url

Solved it with 2 steps.

  1. Update 2 parameters in the config file application/config/config.php
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
  1. Update the file .htaccess in the root folder
<IfModule mod_rewrite.c>
    RewriteEngine On
      RewriteBase /
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

In My Case, Im trying to pass messages from Salesforce Marketing Cloud Custom Activity(Domain 1) to Heroku(Domain 2) on load.

The Error Appeared in console, when I loaded my original html page from where message is being passed.

Issue I noticed after reading many blogs is that, the receiver page is not loaded yet. i.e

I need to debug from my receiver page not from sender page.

Simple but glad if it helps anyone.

Setting environment variable in react-native?

@chapinkapa's answer is good. An approach that I have taken since Mobile Center does not support environment variables, is to expose build configuration through a native module:

On android:

   @Override
    public Map<String, Object> getConstants() {
        final Map<String, Object> constants = new HashMap<>();
        String buildConfig = BuildConfig.BUILD_TYPE.toLowerCase();
        constants.put("ENVIRONMENT", buildConfig);
        return constants;
    } 

or on ios:

  override func constantsToExport() -> [String: Any]! {
    // debug/ staging / release
    // on android, I can tell the build config used, but here I use bundle name
    let STAGING = "staging"
    let DEBUG = "debug"

    var environment = "release"
    if let bundleIdentifier: String = Bundle.main.bundleIdentifier {
      if (bundleIdentifier.lowercased().hasSuffix(STAGING)) {
        environment = STAGING
      } else if (bundleIdentifier.lowercased().hasSuffix(DEBUG)){
        environment = DEBUG
      }
    }

    return ["ENVIRONMENT": environment]
  }

You can read the build config synchronously and decide in Javascript how you're going to behave.

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

Trigger event on body load complete js/jquery

The windows.load function is useful if you want to do something when everything is loaded.

$(window).load(function(){
    // full load
});

But you can also use the .load function on any other element. So if you have one particularly large image and you want to do something when that loads but the rest of your page loading code when the dom has loaded you could do:

$(function(){
    // Dom loaded code

    $('#largeImage').load({
        // Image loaded code
    });
});

Also the jquery .load function is pretty much the same as a normal .onload.

Creating a file name as a timestamp in a batch job

I put together a little C program to print out the current timestamp (locale-safe, no bad characters...). Then, I use the FOR command to save the result in an environment variable:

:: Get the timestamp
for /f %%x in ('@timestamp') do set TIMESTAMP=%%x

:: Use it to generate a filename
for /r %%x in (.\processed\*) do move "%%~x" ".\archived\%%~nx-%TIMESTAMP%%%~xx"

Here's a link:

https://github.com/HarryPehkonen/dos-timestamp

Android Studio doesn't see device

In case anyone having problem with Samsung GT-I9060 I followed this answer on SO:

If you are on windows, many times it will not recognize the device fully and because of driver issues, the device won't show up.

  1. go to settings
  2. control panel
  3. hardware and sound
  4. device manager

And look for any devices showing an error. Many androids will show as an unknown USB device. Select that device and try to update the drivers for it.

I uninstalled the device, unplug the device and plug it again. This time Windows properly installed the driver. What a bummer.

When is del useful in Python?

del is the equivalent of "unset" in many languages and as a cross reference point moving from another language to python.. people tend to look for commands that do the same thing that they used to do in their first language... also setting a var to "" or none doesn't really remove the var from scope..it just empties its value the name of the var itself would still be stored in memory...why?!? in a memory intensive script..keeping trash behind its just a no no and anyways...every language out there has some form of an "unset/delete" var function..why not python?

Javascript Regular Expression Remove Spaces

This works just as well: http://jsfiddle.net/maniator/ge59E/3/

var reg = new RegExp(" ","g"); //<< just look for a space.

Get values from a listbox on a sheet

Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)

Dim StrSelection As String

Private Sub ListBox1_Change()
    If ListBox1.Selected(ListBox1.ListIndex) Then
        If StrSelection = "" Then
            StrSelection = ListBox1.List(ListBox1.ListIndex)
        Else
            StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
        End If
    Else
        StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
    End If
End Sub

Spring security CORS Filter

  1. You don't need:

    @Configuration
    @ComponentScan("com.company.praktikant")
    

    @EnableWebSecurity already has @Configuration in it, and I cannot imagine why you put @ComponentScan there.

  2. About CORS filter, I would just put this:

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0); 
        return bean;
    }
    

    Into SecurityConfiguration class and remove configure and configure global methods. You don't need to set allowde orgins, headers and methods twice. Especially if you put different properties in filter and spring security config :)

  3. According to above, your "MyFilter" class is redundant.

  4. You can also remove those:

    final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
    annotationConfigApplicationContext.register(CORSConfig.class);
    annotationConfigApplicationContext.refresh();
    

    From Application class.

  5. At the end small advice - not connected to the question. You don't want to put verbs in URI. Instead of http://localhost:8080/getKunden you should use HTTP GET method on http://localhost:8080/kunden resource. You can learn about best practices for design RESTful api here: http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

How do I get an apk file from an Android device?

Simplest one is: Install "ShareIt" app on phone. Now install shareIt app in PC or other phone. Now from the phone, where the app is installed, open ShareIt and send. On other phone or PC, open ShareIt and receive.

Automapper missing type map configuration or unsupported mapping - Error

In my case, I had created the map, but was missing the ReverseMap function. Adding it got rid of the error.

      private static void RegisterServices(ContainerBuilder bldr)
      {
         var config = new MapperConfiguration(cfg =>
         {
            cfg.AddProfile(new CampMappingProfile());
         });
         ...
       }


      public CampMappingProfile()
      {
         CreateMap<Talk, TalkModel>().ReverseMap();
         ...
      }

How to add a fragment to a programmatically generated layout?

Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear). You can change number 3 with any other number or take a number from a spinner!

for (int i = 0; i < 3; i++) {
            LinearLayout linearDummy = new LinearLayout(getActivity());
            linearDummy.setOrientation(LinearLayout.VERTICAL);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

                Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

            } else {
                linearDummy.setId(View.generateViewId());
            }
            fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

            xNumberLinear.addView(linearDummy);
        }

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

I had the same problem when my network config was incorrect and DNS was not resolving. In other words the issue could arise when there is no Network Access.

set up device for development (???????????? no permissions)

If anyone faces the following error message when they use adb devices

no permissions (verify udev rules); see [http://developer.android.com/tools/device.html]

Execute the following

sudo -s 
adb kill-server
adb start-server

That fixed the issue for me on a custom build android device

How do you import classes in JSP?

FYI - if you are importing a List into a JSP, chances are pretty good that you are violating MVC principles. Take a few hours now to read up on the MVC approach to web app development (including use of taglibs) - do some more googling on the subject, it's fascinating and will definitely help you write better apps.

If you are doing anything more complicated than a single JSP displaying some database results, please consider using a framework like Spring, Grails, etc... It will absolutely take you a bit more effort to get going, but it will save you so much time and effort down the road that I really recommend it. Besides, it's cool stuff :-)

EXC_BAD_ACCESS signal received

Even another possibility: using blocks in queues, it might easily happen that you try to access an object in another queue, that has already been de-allocated at this time. Typically when you try to send something to the GUI. If your exception breakpoint is being set at a strange place, then this might be the cause.

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

Javascript "Not a Constructor" Exception while creating objects

In my case I'd forgotten the open and close parantheses at the end of the definition of the function wrapping all of my code in the exported module. I.e. I had:

(function () {
  'use strict';

  module.exports.MyClass = class{
  ...
);

Instead of:

(function () {
  'use strict';

  module.exports.MyClass = class{
  ...
)();

The compiler doesn't complain, but the require statement in the importing module doesn't set the variable it's being assigned to, so it's undefined at the point you try to construct it and it will give the TypeError: MyClass is not a constructor error.

"Line contains NULL byte" in CSV reader (Python)

This will tell you what line is the problem.

import csv

lines = []
with open('output.txt','r') as f:
    for line in f.readlines():
        lines.append(line[:-1])

with open('corrected.csv','w') as correct:
    writer = csv.writer(correct, dialect = 'excel')
    with open('input.csv', 'r') as mycsv:
        reader = csv.reader(mycsv)
        try:
            for i, row in enumerate(reader):
                if row[0] not in lines:
                   writer.writerow(row)
        except csv.Error:
            print('csv choked on line %s' % (i+1))
            raise

Perhaps this from daniweb would be helpful:

I'm getting this error when reading from a csv file: "Runtime Error! line contains NULL byte". Any idea about the root cause of this error?

...

Ok, I got it and thought I'd post the solution. Simply yet caused me grief... Used file was saved in a .xls format instead of a .csv Didn't catch this because the file name itself had the .csv extension while the type was still .xls

How to install Android Studio on Ubuntu?

To install android studio on ubuntu here is the simplest way possible:

First of all, you have to install Ubuntu Make before installing Android Studio. Type following commands in the same order one by one on terminal:

1) sudo add-apt-repository ppa:ubuntu-desktop/ubuntu-make

2) sudo apt-get update

3) sudo apt-get install ubuntu-make

Now since you are done with Ubuntu make, use below command to install Android Studio:

4) umake android

While installation it will give you a couple of option which you can handle. So, Installation is done. You can open it and run an App of your choice. Isn’t it very easy? Let me know if you go through any problem, I can help.

Source Install Android Studio

Angular 2: How to write a for loop, not a foreach loop

Depending on the length of the wanted loop, maybe even a more "template-driven" solution:

<ul>
  <li *ngFor="let index of [0,1,2,3,4,5]">
    {{ index }}
  </li>
</ul>

SimpleDateFormat parse loses timezone

tl;dr

what is the way to retrieve a Date object so that its always in GMT?

Instant.now() 

Details

You are using troublesome confusing old date-time classes that are now supplanted by the java.time classes.

Instant = UTC

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now() ; // Current moment in UTC.

ISO 8601

To exchange this data as text, use the standard ISO 8601 formats exclusively. These formats are sensibly designed to be unambiguous, easy to process by machine, and easy to read across many cultures by people.

The java.time classes use the standard formats by default when parsing and generating strings.

String output = instant.toString() ;  

2017-01-23T12:34:56.123456789Z

Time zone

If you want to see that same moment as presented in the wall-clock time of a particular region, apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Asia/Singapore" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same simultaneous moment, same point on the timeline.

See this code live at IdeOne.com.

Notice the eight hour difference, as the time zone of Asia/Singapore currently has an offset-from-UTC of +08:00. Same moment, different wall-clock time.

instant.toString(): 2017-01-23T12:34:56.123456789Z

zdt.toString(): 2017-01-23T20:34:56.123456789+08:00[Asia/Singapore]

Convert

Avoid the legacy java.util.Date class. But if you must, you can convert. Look to new methods added to the old classes.

java.util.Date date = Date.from( instant ) ;

…going the other way…

Instant instant = myJavaUtilDate.toInstant() ;

Date-only

For date-only, use LocalDate.

LocalDate ld = zdt.toLocalDate() ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

When does System.getProperty("java.io.tmpdir") return "c:\temp"

On the one hand, when you call System.getProperty("java.io.tmpdir") instruction, Java calls the Win32 API's function GetTempPath. According to the MSDN :

The GetTempPath function checks for the existence of environment variables in the following order and uses the first path found:

  1. The path specified by the TMP environment variable.
  2. The path specified by the TEMP environment variable.
  3. The path specified by the USERPROFILE environment variable.
  4. The Windows directory.

On the other hand, please check the historical reasons on why TMP and TEMP coexist. It's really worth reading.

RestClientException: Could not extract response. no suitable HttpMessageConverter found

I was trying to use Feign, while I encounter same issue, As I understood HTTP message converter will help but wanted to understand how to achieve this.

@FeignClient(name = "mobilesearch", url = "${mobile.search.uri}" ,
        fallbackFactory = MobileSearchFallbackFactory.class,
        configuration = MobileSearchFeignConfig.class)
public interface MobileSearchClient {

    @RequestMapping(method = RequestMethod.GET)
    List<MobileSearchResponse> getPhones();
}

You have to use Customer Configuration for the decoder, MobileSearchFeignConfig,

public class MobileSearchFeignConfig {

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }


    @Bean
    public Decoder feignDecoder() {
        return new ResponseEntityDecoder(new SpringDecoder(feignHttpMessageConverter()));
    }

    public ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
        final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(new MappingJackson2HttpMessageConverter());
        return new ObjectFactory<HttpMessageConverters>() {
            @Override
            public HttpMessageConverters getObject() throws BeansException {
                return httpMessageConverters;
            }
        };
    }

    public class MappingJackson2HttpMessageConverter extends org.springframework.http.converter.json.MappingJackson2HttpMessageConverter {
        MappingJackson2HttpMessageConverter() {
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.valueOf(MediaType.TEXT_HTML_VALUE + ";charset=UTF-8"));
            setSupportedMediaTypes(mediaTypes);
        }
    }

}

Spring Boot - How to get the running port

Just so others who have configured their apps like mine benefit from what I went through...

None of the above solutions worked for me because I have a ./config directory just under my project base with 2 files:

application.properties
application-dev.properties

In application.properties I have:

spring.profiles.active = dev  # set my default profile to 'dev'

In application-dev.properties I have:

server_host = localhost
server_port = 8080

This is so when I run my fat jar from the CLI the *.properties files will be read from the ./config dir and all is good.

Well, it turns out that these properties files completely override the webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT setting in @SpringBootTest in my Spock specs. No matter what I tried, even with webEnvironment set to RANDOM_PORT Spring would always startup the embedded Tomcat container on port 8080 (or whatever value I'd set in my ./config/*.properties files).

The ONLY way I was able to overcome this was by adding an explicit properties = "server_port=0" to the @SpringBootTest annotation in my Spock integration specs:

@SpringBootTest (webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "server_port=0")

Then, and only then did Spring finally start to spin up Tomcat on a random port. IMHO this is a Spring testing framework bug, but I'm sure they'll have their own opinion on this.

Hope this helped someone.

Accessing a Dictionary.Keys Key through a numeric index

In case you decide to use dangerous code that is subject to breakage, this extension function will fetch a key from a Dictionary<K,V> according to its internal indexing (which for Mono and .NET currently appears to be in the same order as you get by enumerating the Keys property).

It is much preferable to use Linq: dict.Keys.ElementAt(i), but that function will iterate O(N); the following is O(1) but with a reflection performance penalty.

using System;
using System.Collections.Generic;
using System.Reflection;

public static class Extensions
{
    public static TKey KeyByIndex<TKey,TValue>(this Dictionary<TKey, TValue> dict, int idx)
    {
        Type type = typeof(Dictionary<TKey, TValue>);
        FieldInfo info = type.GetField("entries", BindingFlags.NonPublic | BindingFlags.Instance);
        if (info != null)
        {
            // .NET
            Object element = ((Array)info.GetValue(dict)).GetValue(idx);
            return (TKey)element.GetType().GetField("key", BindingFlags.Public | BindingFlags.Instance).GetValue(element);
        }
        // Mono:
        info = type.GetField("keySlots", BindingFlags.NonPublic | BindingFlags.Instance);
        return (TKey)((Array)info.GetValue(dict)).GetValue(idx);
    }
};

Laravel Advanced Wheres how to pass variable into function?

You can pass the necessary variables from the parent scope into the closure with the use keyword.

For example:

DB::table('users')->where(function ($query) use ($activated) {
    $query->where('activated', '=', $activated);
})->get();

More on that here.

EDIT (2019 update):

PHP 7.4 (will be released at November 28, 2019) introduces a shorter variation of the anonymous functions called arrow functions which makes this a bit less verbose.

An example using PHP 7.4 which is functionally nearly equivalent (see the 3rd bullet point below):

DB::table('users')->where(fn($query) => $query->where('activated', '=', $activated))->get();

Differences compared to the regular syntax:

  • fn keyword instead of function.
  • No need to explicitly list all variables which should be captured from the parent scope - this is now done automatically by-value. See the lack of use keyword in the latter example.
  • Arrow functions always return a value. This also means that it's impossible to use void return type when declaring them.
  • The return keyword must be omitted.
  • Arrow functions must have a single expression which is the return statement. Multi-line functions aren't supported at the moment. You can still chain methods though.

Add two textbox values and display the sum in a third textbox automatically

i didn't find who made elegant answer , that's why let me say :

Array.from(
   document.querySelectorAll('#txt1,#txt2')
).map(e => parseInt(e.value) || 0) // to avoid NaN
.reduce((a, b) => a+b, 0)

_x000D_
_x000D_
window.sum= () => _x000D_
 document.getElementById('result').innerHTML=    _x000D_
   Array.from(_x000D_
     document.querySelectorAll('#txt1,#txt2')_x000D_
   ).map(e=>parseInt(e.value)||0)_x000D_
   .reduce((a,b)=>a+b,0)
_x000D_
<input type="text" id="txt1" onkeyup="sum()"/>_x000D_
<input type="text" id="txt2" onkeyup="sum()"  style="margin-right:10px;"/><span id="result"></span>
_x000D_
_x000D_
_x000D_