Programs & Examples On #Time complexity

The time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the size of the input to the problem. The time complexity of an algorithm is commonly expressed using big O notation, which suppresses multiplicative constants and lower order terms.

Computational complexity of Fibonacci Sequence

It is bounded on the lower end by 2^(n/2) and on the upper end by 2^n (as noted in other comments). And an interesting fact of that recursive implementation is that it has a tight asymptotic bound of Fib(n) itself. These facts can be summarized:

T(n) = O(2^(n/2))  (lower bound)
T(n) = O(2^n)   (upper bound)
T(n) = T(Fib(n)) (tight bound)

The tight bound can be reduced further using its closed form if you like.

How do I check if an array includes a value in JavaScript?

While array.indexOf(x)!=-1 is the most concise way to do this (and has been supported by non-Internet Explorer browsers for over decade...), it is not O(1), but rather O(N), which is terrible. If your array will not be changing, you can convert your array to a hashtable, then do table[x]!==undefined or ===undefined:

Array.prototype.toTable = function() {
    var t = {};
    this.forEach(function(x){t[x]=true});
    return t;
}

Demo:

var toRemove = [2,4].toTable();
[1,2,3,4,5].filter(function(x){return toRemove[x]===undefined})

(Unfortunately, while you can create an Array.prototype.contains to "freeze" an array and store a hashtable in this._cache in two lines, this would give wrong results if you chose to edit your array later. JavaScript has insufficient hooks to let you keep this state, unlike Python for example.)

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

O (n log n) is famously the upper bound on how fast you can sort an arbitrary set (assuming a standard and not highly parallel computing model).

Is a Java hashmap search really O(1)?

A particular feature of a HashMap is that unlike, say, balanced trees, its behavior is probabilistic. In these cases its usually most helpful to talk about complexity in terms of the probability of a worst-case event occurring would be. For a hash map, that of course is the case of a collision with respect to how full the map happens to be. A collision is pretty easy to estimate.

pcollision = n / capacity

So a hash map with even a modest number of elements is pretty likely to experience at least one collision. Big O notation allows us to do something more compelling. Observe that for any arbitrary, fixed constant k.

O(n) = O(k * n)

We can use this feature to improve the performance of the hash map. We could instead think about the probability of at most 2 collisions.

pcollision x 2 = (n / capacity)2

This is much lower. Since the cost of handling one extra collision is irrelevant to Big O performance, we've found a way to improve performance without actually changing the algorithm! We can generalzie this to

pcollision x k = (n / capacity)k

And now we can disregard some arbitrary number of collisions and end up with vanishingly tiny likelihood of more collisions than we are accounting for. You could get the probability to an arbitrarily tiny level by choosing the correct k, all without altering the actual implementation of the algorithm.

We talk about this by saying that the hash-map has O(1) access with high probability

Find common substring between two strings

The same as Evo's, but with arbitrary number of strings to compare:

def common_start(*strings):
    """ Returns the longest common substring
        from the beginning of the `strings`
    """
    def _iter():
        for z in zip(*strings):
            if z.count(z[0]) == len(z):  # check all elements in `z` are the same
                yield z[0]
            else:
                return

    return ''.join(_iter())

Time complexity of nested for-loop

Yes, the time complexity of this is O(n^2).

What is the difference between T(n) and O(n)?

f(n) belongs to O(n) if exists positive k as f(n)<=k*n

f(n) belongs to T(n) if exists positive k1, k2 as k1*n<=f(n)<=k2*n

Wikipedia article on Big O Notation

Complexities of binary tree traversals

T(n) = 2T(n/2)+ c

T(n/2) = 2T(n/4) + c => T(n) = 4T(n/4) + 2c + c

similarly T(n) = 8T(n/8) + 4c+ 2c + c

....

....

last step ... T(n) = nT(1) + c(sum of powers of 2 from 0 to h(height of tree))

so Complexity is O(2^(h+1) -1)

but h = log(n)

so, O(2n - 1) = O(n)

What does O(log n) mean exactly?

It simply means that the time needed for this task grows with log(n) (example : 2s for n = 10, 4s for n = 100, ...). Read the Wikipedia articles on Binary Search Algorithm and Big O Notation for more precisions.

how to calculate binary search complexity

Here a more mathematical way of seeing it, though not really complicated. IMO much clearer as informal ones:

The question is, how many times can you divide N by 2 until you have 1? This is essentially saying, do a binary search (half the elements) until you found it. In a formula this would be this:

1 = N / 2x

multiply by 2x:

2x = N

now do the log2:

log2(2x)    = log2 N
x * log2(2) = log2 N
x * 1         = log2 N

this means you can divide log N times until you have everything divided. Which means you have to divide log N ("do the binary search step") until you found your element.

Difference between Big-O and Little-O Notation

Big-O is to little-o as = is to <. Big-O is an inclusive upper bound, while little-o is a strict upper bound.

For example, the function f(n) = 3n is:

  • in O(n²), o(n²), and O(n)
  • not in O(lg n), o(lg n), or o(n)

Analogously, the number 1 is:

  • = 2, < 2, and = 1
  • not = 0, < 0, or < 1

Here's a table, showing the general idea:

Big o table

(Note: the table is a good guide but its limit definition should be in terms of the superior limit instead of the normal limit. For example, 3 + (n mod 2) oscillates between 3 and 4 forever. It's in O(1) despite not having a normal limit, because it still has a lim sup: 4.)

I recommend memorizing how the Big-O notation converts to asymptotic comparisons. The comparisons are easier to remember, but less flexible because you can't say things like nO(1) = P.

How can you profile a Python script?

cProfile is great for quick profiling but most of the time it was ending for me with the errors. Function runctx solves this problem by initializing correctly the environment and variables, hope it can be useful for someone:

import cProfile
cProfile.runctx('foo()', None, locals())

What is a plain English explanation of "Big O" notation?

Ok, my 2cents.

Big-O, is rate of increase of resource consumed by program, w.r.t. problem-instance-size

Resource : Could be total-CPU time, could be maximum RAM space. By default refers to CPU time.

Say the problem is "Find the sum",

int Sum(int*arr,int size){
      int sum=0;
      while(size-->0) 
         sum+=arr[size]; 

      return sum;
}

problem-instance= {5,10,15} ==> problem-instance-size = 3, iterations-in-loop= 3

problem-instance= {5,10,15,20,25} ==> problem-instance-size = 5 iterations-in-loop = 5

For input of size "n" the program is growing at speed of "n" iterations in array. Hence Big-O is N expressed as O(n)

Say the problem is "Find the Combination",

    void Combination(int*arr,int size)
    { int outer=size,inner=size;
      while(outer -->0) {
        inner=size;
        while(inner -->0)
          cout<<arr[outer]<<"-"<<arr[inner]<<endl;
      }
    }

problem-instance= {5,10,15} ==> problem-instance-size = 3, total-iterations = 3*3 = 9

problem-instance= {5,10,15,20,25} ==> problem-instance-size = 5, total-iterations= 5*5 =25

For input of size "n" the program is growing at speed of "n*n" iterations in array. Hence Big-O is N2 expressed as O(n2)

Why is the time complexity of both DFS and BFS O( V + E )

An intuitive explanation to this is by simply analysing a single loop:

  1. visit a vertex -> O(1)
  2. a for loop on all the incident edges -> O(e) where e is a number of edges incident on a given vertex v.

So the total time for a single loop is O(1)+O(e). Now sum it for each vertex as each vertex is visited once. This gives

For every V
=> 

    O(1)
    +

    O(e)

=> O(V) + O(E)

Time complexity of Euclid's Algorithm

Worst case will arise when both n and m are consecutive Fibonacci numbers.

gcd(Fn,Fn-1)=gcd(Fn-1,Fn-2)=?=gcd(F1,F0)=1 and nth Fibonacci number is 1.618^n, where 1.618 is the Golden ratio.

So, to find gcd(n,m), number of recursive calls will be T(logn).

How to find time complexity of an algorithm

When you're analyzing code, you have to analyse it line by line, counting every operation/recognizing time complexity, in the end, you have to sum it to get whole picture.

For example, you can have one simple loop with linear complexity, but later in that same program you can have a triple loop that has cubic complexity, so your program will have cubic complexity. Function order of growth comes into play right here.

Let's look at what are possibilities for time complexity of an algorithm, you can see order of growth I mentioned above:

  • Constant time has an order of growth 1, for example: a = b + c.

  • Logarithmic time has an order of growth LogN, it usually occurs when you're dividing something in half (binary search, trees, even loops), or multiplying something in same way.

  • Linear, order of growth is N, for example

    int p = 0;
    for (int i = 1; i < N; i++)
      p = p + 2;
    
  • Linearithmic, order of growth is n*logN, usually occurs in divide and conquer algorithms.

  • Cubic, order of growth N^3, classic example is a triple loop where you check all triplets:

    int x = 0;
    for (int i = 0; i < N; i++)
       for (int j = 0; j < N; j++)
          for (int k = 0; k < N; k++)
              x = x + 2
    
  • Exponential, order of growth 2^N, usually occurs when you do exhaustive search, for example check subsets of some set.

matrix multiplication algorithm time complexity

Using linear algebra, there exist algorithms that achieve better complexity than the naive O(n3). Solvay Strassen algorithm achieves a complexity of O(n2.807) by reducing the number of multiplications required for each 2x2 sub-matrix from 8 to 7.

The fastest known matrix multiplication algorithm is Coppersmith-Winograd algorithm with a complexity of O(n2.3737). Unless the matrix is huge, these algorithms do not result in a vast difference in computation time. In practice, it is easier and faster to use parallel algorithms for matrix multiplication.

Hash table runtime complexity (insert, search and delete)

Perhaps you were looking at the space complexity? That is O(n). The other complexities are as expected on the hash table entry. The search complexity approaches O(1) as the number of buckets increases. If at the worst case you have only one bucket in the hash table, then the search complexity is O(n).

Edit in response to comment I don't think it is correct to say O(1) is the average case. It really is (as the wikipedia page says) O(1+n/k) where K is the hash table size. If K is large enough, then the result is effectively O(1). But suppose K is 10 and N is 100. In that case each bucket will have on average 10 entries, so the search time is definitely not O(1); it is a linear search through up to 10 entries.

How / can I display a console window in Intellij IDEA?

More IntelliJ 13+ Shortcuts for Terminal

Mac OS X:

alt ?F12

cmd ?shift ?A then type Terminal then hit Enter

shift ?shift ?shift ?shift ? then type Terminal then hit Enter

Windows:

altF12 press Enter

ctrlshift ?A start typing Terminal then hit Enter

shift ?shift ? then type Terminal then hit Enter

How to get table list in database, using MS SQL 2008?

Answering the question in your title, you can query sys.tables or sys.objects where type = 'U' to check for the existence of a table. You can also use OBJECT_ID('table_name', 'U'). If it returns a non-null value then the table exists:

IF (OBJECT_ID('dbo.My_Table', 'U') IS NULL)
BEGIN
    CREATE TABLE dbo.My_Table (...)
END

You can do the same for databases with DB_ID():

IF (DB_ID('My_Database') IS NULL)
BEGIN
    CREATE DATABASE My_Database
END

If you want to create the database and then start using it, that needs to be done in separate batches. I don't know the specifics of your case, but there shouldn't be many cases where this isn't possible. In a SQL script you can use GO statements. In an application it's easy enough to send across a new command after the database is created.

The only place that you might have an issue is if you were trying to do this in a stored procedure and creating databases on the fly like that is usually a bad idea.

If you really need to do this in one batch, you can get around the issue by using EXEC to get around the parsing error of the database not existing:

CREATE DATABASE Test_DB2

IF (OBJECT_ID('Test_DB2.dbo.My_Table', 'U') IS NULL)
BEGIN
    EXEC('CREATE TABLE Test_DB2.dbo.My_Table (my_id INT)')
END

EDIT: As others have suggested, the INFORMATION_SCHEMA.TABLES system view is probably preferable since it is supposedly a standard going forward and possibly between RDBMSs.

How do I associate file types with an iPhone application?

In addition to Brad's excellent answer, I have found out that (on iOS 4.2.1 at least) when opening custom files from the Mail app, your app is not fired or notified if the attachment has been opened before. The "open with…" popup appears, but just does nothing.

This seems to be fixed by (re)moving the file from the Inbox directory. A safe approach seems to be to both (re)move the file as it is opened (in -(BOOL)application:openURL:sourceApplication:annotation:) as well as going through the Documents/Inbox directory, removing all items, e.g. in applicationDidBecomeActive:. That last catch-all may be needed to get the app in a clean state again, in case a previous import causes a crash or is interrupted.

How to set scope property with ng-init?

Like CodeHater said you are accessing the variable before it is set.

To fix this move the ng-init directive to the first div.

<body ng-app>
    <div ng-controller="testController" ng-init="testInput='value'">
        <input type="hidden" id="testInput" ng-model="testInput" />
       {{ testInput }}
    </div>
</body>

That should work!

Centos/Linux setting logrotate to maximum file size for all logs

It specifies the size of the log file to trigger rotation. For example size 50M will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M for megabytes, k for kilobytes, and G for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size, maxsize, and minsize. According to manpage:

minsize size
              Log  files  are  rotated when they grow bigger than size bytes,
              but not before the additionally specified time interval (daily,
              weekly,  monthly, or yearly).  The related size option is simi-
              lar except that it is mutually exclusive with the time interval
              options,  and  it causes log files to be rotated without regard
              for the last rotation time.  When minsize  is  used,  both  the
              size and timestamp of a log file are considered.

size size
              Log files are rotated only if they grow bigger then size bytes.
              If size is followed by k, the size is assumed to  be  in  kilo-
              bytes.  If the M is used, the size is in megabytes, and if G is
              used, the size is in gigabytes. So size 100,  size  100k,  size
              100M and size 100G are all valid.
maxsize size
              Log files are rotated when they grow bigger than size bytes even before
              the additionally specified time interval (daily, weekly, monthly, 
              or yearly).  The related size option is  similar  except  that  it 
              is mutually exclusive with the time interval options, and it causes
              log files to be rotated without regard for the last rotation time.  
              When maxsize is used, both the size and timestamp of a log file are                  
              considered.

Here is an example:

"/var/log/httpd/access.log" /var/log/httpd/error.log {
           rotate 5
           mail [email protected]
           size 100k
           sharedscripts
           postrotate
               /usr/bin/killall -HUP httpd
           endscript
       }

Here is an explanation for both files /var/log/httpd/access.log and /var/log/httpd/error.log. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected] after going through 5 rotations, rather than being removed. The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,, and \ characters supported.

struct in class

I'd like to add another use case for an internal struct/class and its usability. An inner struct is often used to declare a data only member of a class that packs together relevant information and as such we can enclose it all in a struct instead of loose data members lying around.

The inner struct/class is but a data only compartment, ie it has no functions (except maybe constructors).

#include <iostream>

class E
{
    // E functions..
public:
    struct X
    {
        int v;
        // X variables..
    } x;
    // E variables..
};

int main()
{
    E e;
    e.x.v = 9;
    std::cout << e.x.v << '\n';
    
    E e2{5};
    std::cout << e2.x.v << '\n';

    // You can instantiate an X outside E like so:
    //E::X xOut{24};
    //std::cout << xOut.v << '\n';
    // But you shouldn't want to in this scenario.
    // X is only a data member (containing other data members)
    // for use only inside the internal operations of E
    // just like the other E's data members
}

This practice is widely used in graphics, where the inner struct will be sent as a Constant Buffer to HLSL. But I find it neat and useful in many cases.

JavaFX FXML controller - constructor vs initialize method

The initialize method is called after all @FXML annotated members have been injected. Suppose you have a table view you want to populate with data:

class MyController { 
    @FXML
    TableView<MyModel> tableView; 

    public MyController() {
        tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point. 
    }

    @FXML
    public void initialize() {
        tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members. 
    }
}

convert double to int

label8.Text = "" + years.ToString("00") + " years";

when you want to send it to a label, or something, and you don't want any fractional component, this is the best way

label8.Text = "" + years.ToString("00.00") + " years";

if you want with only 2, and it's always like that

Disable Buttons in jQuery Mobile

For disabling a button add css class disabled to it . write

$("button").addClass('disabled')

Syntax for a for loop in ruby

array.each do |element|
  element.do_stuff
end

or

for element in array do
  element.do_stuff
end

If you need index, you can use this:

array.each_with_index do |element,index|
  element.do_stuff(index)
end

Including JavaScript class definition from another file in Node.js

Using ES6, you can have user.js:

export default class User {
  constructor() {
    ...
  }
}

And then use it in server.js

const User = require('./user.js').default;
const user = new User();

How to get maximum value from the Collection (for example ArrayList)?

Integer class implements Comparable.So we can easily get the max or min value of the Integer list.

public int maxOfNumList() {
    List<Integer> numList = new ArrayList<>();
    numList.add(1);
    numList.add(10);
    return Collections.max(numList);
}

If a class does not implements Comparable and we have to find max and min value then we have to write our own Comparator.

List<MyObject> objList = new ArrayList<MyObject>();
objList.add(object1);
objList.add(object2);
objList.add(object3);
MyObject maxObject = Collections.max(objList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        if (o1.getValue() == o2.getValue()) {
            return 0;
        } else if (o1.getValue() > o2.getValue()) {
            return -1;
        } else if (o1.getValue() < o2.getValue()) {
            return 1;
        }
        return 0;
    }
});

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

This thread caught my attention since it deals with a simple problem that requires a lot of work (CPU cycles) even for a modern CPU. And one day I also stood there with the same ¤#%"#" problem. I had to flip millions of bytes. However I know all my target systems are modern Intel-based so let's start optimizing to the extreme!!!

So I used Matt J's lookup code as the base. the system I'm benchmarking on is a i7 haswell 4700eq.

Matt J's lookup bitflipping 400 000 000 bytes: Around 0.272 seconds.

I then went ahead and tried to see if Intel's ISPC compiler could vectorise the arithmetics in the reverse.c.

I'm not going to bore you with my findings here since I tried a lot to help the compiler find stuff, anyhow I ended up with performance of around 0.15 seconds to bitflip 400 000 000 bytes. It's a great reduction but for my application that's still way way too slow..

So people let me present the fastest Intel based bitflipper in the world. Clocked at:

Time to bitflip 400000000 bytes: 0.050082 seconds !!!!!

// Bitflip using AVX2 - The fastest Intel based bitflip in the world!!
// Made by Anders Cedronius 2014 (anders.cedronius (you know what) gmail.com)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>

using namespace std;

#define DISPLAY_HEIGHT  4
#define DISPLAY_WIDTH   32
#define NUM_DATA_BYTES  400000000

// Constants (first we got the mask, then the high order nibble look up table and last we got the low order nibble lookup table)
__attribute__ ((aligned(32))) static unsigned char k1[32*3]={
        0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,
        0x00,0x08,0x04,0x0c,0x02,0x0a,0x06,0x0e,0x01,0x09,0x05,0x0d,0x03,0x0b,0x07,0x0f,0x00,0x08,0x04,0x0c,0x02,0x0a,0x06,0x0e,0x01,0x09,0x05,0x0d,0x03,0x0b,0x07,0x0f,
        0x00,0x80,0x40,0xc0,0x20,0xa0,0x60,0xe0,0x10,0x90,0x50,0xd0,0x30,0xb0,0x70,0xf0,0x00,0x80,0x40,0xc0,0x20,0xa0,0x60,0xe0,0x10,0x90,0x50,0xd0,0x30,0xb0,0x70,0xf0
};

// The data to be bitflipped (+32 to avoid the quantization out of memory problem)
__attribute__ ((aligned(32))) static unsigned char data[NUM_DATA_BYTES+32]={};

extern "C" {
void bitflipbyte(unsigned char[],unsigned int,unsigned char[]);
}

int main()
{

    for(unsigned int i = 0; i < NUM_DATA_BYTES; i++)
    {
        data[i] = rand();
    }

    printf ("\r\nData in(start):\r\n");
    for (unsigned int j = 0; j < 4; j++)
    {
        for (unsigned int i = 0; i < DISPLAY_WIDTH; i++)
        {
            printf ("0x%02x,",data[i+(j*DISPLAY_WIDTH)]);
        }
        printf ("\r\n");
    }

    printf ("\r\nNumber of 32-byte chunks to convert: %d\r\n",(unsigned int)ceil(NUM_DATA_BYTES/32.0));

    double start_time = omp_get_wtime();
    bitflipbyte(data,(unsigned int)ceil(NUM_DATA_BYTES/32.0),k1);
    double end_time = omp_get_wtime();

    printf ("\r\nData out:\r\n");
    for (unsigned int j = 0; j < 4; j++)
    {
        for (unsigned int i = 0; i < DISPLAY_WIDTH; i++)
        {
            printf ("0x%02x,",data[i+(j*DISPLAY_WIDTH)]);
        }
        printf ("\r\n");
    }
    printf("\r\n\r\nTime to bitflip %d bytes: %f seconds\r\n\r\n",NUM_DATA_BYTES, end_time-start_time);

    // return with no errors
    return 0;
}

The printf's are for debugging..

Here is the workhorse:

bits 64
global bitflipbyte

bitflipbyte:    
        vmovdqa     ymm2, [rdx]
        add         rdx, 20h
        vmovdqa     ymm3, [rdx]
        add         rdx, 20h
        vmovdqa     ymm4, [rdx]
bitflipp_loop:
        vmovdqa     ymm0, [rdi] 
        vpand       ymm1, ymm2, ymm0 
        vpandn      ymm0, ymm2, ymm0 
        vpsrld      ymm0, ymm0, 4h 
        vpshufb     ymm1, ymm4, ymm1 
        vpshufb     ymm0, ymm3, ymm0         
        vpor        ymm0, ymm0, ymm1
        vmovdqa     [rdi], ymm0
        add     rdi, 20h
        dec     rsi
        jnz     bitflipp_loop
        ret

The code takes 32 bytes then masks out the nibbles. The high nibble gets shifted right by 4. Then I use vpshufb and ymm4 / ymm3 as lookup tables. I could use a single lookup table but then I would have to shift left before ORing the nibbles together again.

There are even faster ways of flipping the bits. But I'm bound to single thread and CPU so this was the fastest I could achieve. Can you make a faster version?

Please make no comments about using the Intel C/C++ Compiler Intrinsic Equivalent commands...

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

Don't forget about fragmentation. If you have a lot of traffic, your pools can be fragmented and even if you have several MB free, there could be no block larger than 4KB. Check size of largest free block with a query like:

 select
  '0 (<140)' BUCKET, KSMCHCLS, KSMCHIDX,
  10*trunc(KSMCHSIZ/10) "From",
  count(*) "Count" ,
  max(KSMCHSIZ) "Biggest",
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ<140
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 10*trunc(KSMCHSIZ/10)
UNION ALL
select
  '1 (140-267)' BUCKET,
  KSMCHCLS,
  KSMCHIDX,
  20*trunc(KSMCHSIZ/20) ,
  count(*) ,
  max(KSMCHSIZ) ,
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ between 140 and 267
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 20*trunc(KSMCHSIZ/20)
UNION ALL
select
  '2 (268-523)' BUCKET,
  KSMCHCLS,
  KSMCHIDX,
  50*trunc(KSMCHSIZ/50) ,
  count(*) ,
  max(KSMCHSIZ) ,
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ between 268 and 523
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 50*trunc(KSMCHSIZ/50)
UNION ALL
select
  '3-5 (524-4107)' BUCKET,
  KSMCHCLS,
  KSMCHIDX,
  500*trunc(KSMCHSIZ/500) ,
  count(*) ,
  max(KSMCHSIZ) ,
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ between 524 and 4107
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 500*trunc(KSMCHSIZ/500)
UNION ALL
select
  '6+ (4108+)' BUCKET,
  KSMCHCLS,
  KSMCHIDX,
  1000*trunc(KSMCHSIZ/1000) ,
  count(*) ,
  max(KSMCHSIZ) ,
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ >= 4108
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 1000*trunc(KSMCHSIZ/1000);

Code from

How to disable/enable a button with a checkbox if checked

You will have to use javascript, or the JQuery framework to do that. her is an example using Jquery

   $('#toggle').click(function () {
        //check if checkbox is checked
        if ($(this).is(':checked')) {

            $('#sendNewSms').removeAttr('disabled'); //enable input

        } else {
            $('#sendNewSms').attr('disabled', true); //disable input
        }
    });

DEMO: http://jsfiddle.net/T6hvz/

Laravel Eloquent groupBy() AND also return count of each group

Works that way as well, a bit more tidy. getQuery() just returns the underlying builder, which already contains the table reference.

$browser_total_raw = DB::raw('count(*) as total');
$user_info = Usermeta::getQuery()
                     ->select('browser', $browser_total_raw)
                     ->groupBy('browser')
                     ->pluck('total','browser');

Get css top value as number not as string?

A jQuery plugin based on M4N's answer

jQuery.fn.cssNumber = function(prop){
    var v = parseInt(this.css(prop),10);
    return isNaN(v) ? 0 : v;
};

So then you just use this method to get number values

$("#logo").cssNumber("top")

How to loop over grouped Pandas dataframe?

df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)) does already return a dataframe, so you cannot loop over the groups anymore.

In general:

  • df.groupby(...) returns a GroupBy object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:

    grouped = df.groupby('A')
    
    for name, group in grouped:
        ...
    
  • When you apply a function on the groupby, in your example df.groupby(...).agg(...) (but this can also be transform, apply, mean, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).

jquery disable form submit on enter

If keyCode is not caught, catch which:

$('#formid').on('keyup keypress', function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 
    e.preventDefault();
    return false;
  }
});

EDIT: missed it, it's better to use keyup instead of keypress

EDIT 2: As in some newer versions of Firefox the form submission is not prevented, it's safer to add the keypress event to the form as well. Also it doesn't work (anymore?) by just binding the event to the form "name" but only to the form id. Therefore I made this more obvious by changing the code example appropriately.

EDIT 3: Changed bind() to on()

How to save image in database using C#

I think this valid question is already answered here. I have tried it as well. My issue was simply using picture edit (from DevExpress). and this is how I got around it:

  • Change the PictureEdit's "PictureStoreMode" property to ByteArray: it is currently set to "default" enter image description here
  • convert the control's edit value to bye: byte[] newImg = (byte[])pictureEdit1.EditValue;
  • save the image: this.tbSystemTableAdapter.qry_updateIMGtest(newImg);

Thank you again. Chagbert

Have border wrap around text

Try this and see if you get what you are aiming for:

_x000D_
_x000D_
<div id='page' style='width: 600px'>_x000D_
  <h1 style='border:2px black solid; font-size:42px; width:fit-content; width:-webkit-fit-content; width:-moz-fit-content;'>Title</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

MS-DOS Batch file pause with enter key

There's a pause command that does just that, though it's not specifically the enter key.

If you really want to wait for only the enter key, you can use the set command to ask for user input with a dummy variable, something like:

set /p DUMMY=Hit ENTER to continue...

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

Sometime this error also occur when you change the order of Component Function while passing to connect.

Incorrect Order:

export default connect(mapDispatchToProps, mapStateToProps)(TodoList);

Correct Order:

export default connect(mapStateToProps,mapDispatchToProps)(TodoList);

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Just Android studio run 'Run as administrator' it will work

Or verify your package name on google-services.json file

Can we import XML file into another XML file?

Mads Hansen's solution is good but to succeed in reading the external file in .NET 4 took some time to figure out using hints in the comments about resolvers, ProhibitDTD and so on.

This is how it's done:

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.DtdProcessing = DtdProcessing.Parse;
        XmlUrlResolver resolver = new XmlUrlResolver();
        resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
        settings.XmlResolver = resolver;
        var reader = XmlReader.Create("logfile.xml", settings);
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        foreach (XmlElement element in doc.SelectNodes("//event"))
        {
            var ch = element.ChildNodes;
            var count = ch.Count;
        }

logfile.xml:

<?xml version="1.0"?>
<!DOCTYPE logfile [
<!ENTITY events    
 SYSTEM "events.txt">
]>
<logfile>
&events;
</logfile>

events.txt:

<event>
    <item1>item1</item1>
    <item2>item2</item2>
</event>

QR Code encoding and decoding using zxing

For what it's worth, my groovy spike seems to work with both UTF-8 and ISO-8859-1 character encodings. Not sure what will happen when a non zxing decoder tries to decode the UTF-8 encoded image though... probably varies depending on the device.

// ------------------------------------------------------------------------------------
// Requires: groovy-1.7.6, jdk1.6.0_03, ./lib with zxing core-1.7.jar, javase-1.7.jar 
// Javadocs: http://zxing.org/w/docs/javadoc/overview-summary.html
// Run with: groovy -cp "./lib/*" zxing.groovy
// ------------------------------------------------------------------------------------

import com.google.zxing.*
import com.google.zxing.common.*
import com.google.zxing.client.j2se.*

import java.awt.image.BufferedImage
import javax.imageio.ImageIO

def class zxing {
    def static main(def args) {
        def filename = "./qrcode.png"
        def data = "This is a test to see if I can encode and decode this data..."
        def charset = "UTF-8" //"ISO-8859-1" 
        def hints = new Hashtable<EncodeHintType, String>([(EncodeHintType.CHARACTER_SET): charset])

        writeQrCode(filename, data, charset, hints, 100, 100)

        assert data == readQrCode(filename, charset, hints)
    }

    def static writeQrCode(def filename, def data, def charset, def hints, def width, def height) {
        BitMatrix matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, width, height, hints)
        MatrixToImageWriter.writeToFile(matrix, filename.substring(filename.lastIndexOf('.')+1), new File(filename))
    }

    def static readQrCode(def filename, def charset, def hints) {
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filename)))))
        Result result = new MultiFormatReader().decode(binaryBitmap, hints)

        result.getText()        
    }

}

ld.exe: cannot open output file ... : Permission denied

It may be your Antivirus Software.

In my case Malwarebytes was holding a handle on my program's executable:

enter image description here

Using Process Explorer to close the handle, or just disabling antivirus for a bit work just fine.

Stacked Tabs in Bootstrap 3

Left, Right and Below tabs were removed from Bootstrap 3, but you can add custom CSS to achieve this..

.tabs-below > .nav-tabs,
.tabs-right > .nav-tabs,
.tabs-left > .nav-tabs {
  border-bottom: 0;
}

.tab-content > .tab-pane,
.pill-content > .pill-pane {
  display: none;
}

.tab-content > .active,
.pill-content > .active {
  display: block;
}

.tabs-below > .nav-tabs {
  border-top: 1px solid #ddd;
}

.tabs-below > .nav-tabs > li {
  margin-top: -1px;
  margin-bottom: 0;
}

.tabs-below > .nav-tabs > li > a {
  -webkit-border-radius: 0 0 4px 4px;
     -moz-border-radius: 0 0 4px 4px;
          border-radius: 0 0 4px 4px;
}

.tabs-below > .nav-tabs > li > a:hover,
.tabs-below > .nav-tabs > li > a:focus {
  border-top-color: #ddd;
  border-bottom-color: transparent;
}

.tabs-below > .nav-tabs > .active > a,
.tabs-below > .nav-tabs > .active > a:hover,
.tabs-below > .nav-tabs > .active > a:focus {
  border-color: transparent #ddd #ddd #ddd;
}

.tabs-left > .nav-tabs > li,
.tabs-right > .nav-tabs > li {
  float: none;
}

.tabs-left > .nav-tabs > li > a,
.tabs-right > .nav-tabs > li > a {
  min-width: 74px;
  margin-right: 0;
  margin-bottom: 3px;
}

.tabs-left > .nav-tabs {
  float: left;
  margin-right: 19px;
  border-right: 1px solid #ddd;
}

.tabs-left > .nav-tabs > li > a {
  margin-right: -1px;
  -webkit-border-radius: 4px 0 0 4px;
     -moz-border-radius: 4px 0 0 4px;
          border-radius: 4px 0 0 4px;
}

.tabs-left > .nav-tabs > li > a:hover,
.tabs-left > .nav-tabs > li > a:focus {
  border-color: #eeeeee #dddddd #eeeeee #eeeeee;
}

.tabs-left > .nav-tabs .active > a,
.tabs-left > .nav-tabs .active > a:hover,
.tabs-left > .nav-tabs .active > a:focus {
  border-color: #ddd transparent #ddd #ddd;
  *border-right-color: #ffffff;
}

.tabs-right > .nav-tabs {
  float: right;
  margin-left: 19px;
  border-left: 1px solid #ddd;
}

.tabs-right > .nav-tabs > li > a {
  margin-left: -1px;
  -webkit-border-radius: 0 4px 4px 0;
     -moz-border-radius: 0 4px 4px 0;
          border-radius: 0 4px 4px 0;
}

.tabs-right > .nav-tabs > li > a:hover,
.tabs-right > .nav-tabs > li > a:focus {
  border-color: #eeeeee #eeeeee #eeeeee #dddddd;
}

.tabs-right > .nav-tabs .active > a,
.tabs-right > .nav-tabs .active > a:hover,
.tabs-right > .nav-tabs .active > a:focus {
  border-color: #ddd #ddd #ddd transparent;
  *border-left-color: #ffffff;
}

Working example: http://bootply.com/74926

UPDATE

If you don't need the exact look of a tab (bordered appropriately on the left or right as each tab is activated), you can simple use nav-stacked, along with Bootstrap col-* to float the tabs to the left or right...

nav-stacked demo: http://codeply.com/go/rv3Cvr0lZ4

<ul class="nav nav-pills nav-stacked col-md-3">
    <li><a href="#a" data-toggle="tab">1</a></li>
    <li><a href="#b" data-toggle="tab">2</a></li>
    <li><a href="#c" data-toggle="tab">3</a></li>
</ul>

Check if user is using IE

Update to SpiderCode's answer to fix issues where the string 'MSIE' returns -1 but it matches 'Trident'. It used to return NAN, but now returns 11 for that version of IE.

   function msieversion() {
       var ua = window.navigator.userAgent;
       var msie = ua.indexOf("MSIE ");
       if (msie > -1) {
           return ua.substring(msie + 5, ua.indexOf(".", msie));
       } else if (navigator.userAgent.match(/Trident.*rv\:11\./)) {
           return 11;
       } else {
           return false;
       }
    }

AES vs Blowfish for file encryption

I know this answer violates the terms of your question, but I think the correct answer to your intent is simply this: use whichever algorithm allows you the longest key length, then make sure you choose a really good key. Minor differences in the performance of most well regarded algorithms (cryptographically and chronologically) are overwhelmed by a few extra bits of a key.

File name without extension name VBA

Using the Split function seems more elegant than InStr and Left, in my opinion.

Private Sub CommandButton2_Click()


Dim ThisFileName As String
Dim BaseFileName As String

Dim FileNameArray() As String

ThisFileName = ThisWorkbook.Name
FileNameArray = Split(ThisFileName, ".")
BaseFileName = FileNameArray(0)

MsgBox "Base file name is " & BaseFileName

End Sub

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

I think jQuery cannot find the element.

First of all find the element

var rowTemplate= document.getElementsByName("rowTemplate");

or

var rowTemplate = document.getElementById("rowTemplate"); 

or

var rowTemplate = $('#rowTemplate');

Then try your code again

rowTemplate.html().replace(....)

When is the @JsonProperty property used and what is it used for?

Without annotations, inferred property name (to match from JSON) would be "set", and not -- as seems to be the intent -- "isSet". This is because as per Java Beans specification, methods of form "isXxx" and "setXxx" are taken to mean that there is logical property "xxx" to manage.

How to set the thumbnail image on HTML5 video?

<?php
$thumbs_dir = 'E:/xampp/htdocs/uploads/thumbs/';
$videos = array();
if (isset($_POST["name"])) {
 if (!preg_match('/data:([^;]*);base64,(.*)/', $_POST['data'], $matches)) {
  die("error");
 }
 $data = $matches[2];
 $data = str_replace(' ', '+', $data);
 $data = base64_decode($data);
 $file = 'text.jpg';
 $dataname = file_put_contents($thumbs_dir . $file, $data);
}
?>
//jscode
<script type="text/javascript">
 var videos = <?= json_encode($videos); ?>;
 var video = document.getElementById('video');
 video.addEventListener('canplay', function () {
     this.currentTime = this.duration / 2;
 }, false);
 var seek = true;
 video.addEventListener('seeked', function () {
    if (seek) {
         getThumb();
    }
 }, false);

 function getThumb() {
     seek = false;
     var filename = video.src;
     var w = video.videoWidth;//video.videoWidth * scaleFactor;
     var h = video.videoHeight;//video.videoHeight * scaleFactor;
     var canvas = document.createElement('canvas');
     canvas.width = w;
     canvas.height = h;
     var ctx = canvas.getContext('2d');
     ctx.drawImage(video, 0, 0, w, h);
     var data = canvas.toDataURL("image/jpg");
     var xmlhttp = new XMLHttpRequest;
     xmlhttp.onreadystatechange = function () {
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
         }
     }
     xmlhttp.open("POST", location.href, true);
     xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     xmlhttp.send('name=' + encodeURIComponent(filename) + '&data=' + data);
 }
  function failed(e) {
     // video playback failed - show a message saying why
     switch (e.target.error.code) {
         case e.target.error.MEDIA_ERR_ABORTED:
             console.log('You aborted the video playback.');
             break;
         case e.target.error.MEDIA_ERR_NETWORK:
             console.log('A network error caused the video download to fail part-way.');
             break;
         case e.target.error.MEDIA_ERR_DECODE:
             console.log('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
              break;
          case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
              console.log('The video could not be loaded, either because the server or network failed or because the format is not supported.');
              break;
          default:
              console.log('An unknown error occurred.');
              break;
      }


  }
</script>
//Html
<div>
    <video   id="video" src="1499752288.mp4" autoplay="true"  onerror="failed(event)" controls="controls" preload="none"></video>
</div>

Unique on a dataframe with only selected columns

Ok, if it doesn't matter which value in the non-duplicated column you select, this should be pretty easy:

dat <- data.frame(id=c(1,1,3),id2=c(1,1,4),somevalue=c("x","y","z"))
> dat[!duplicated(dat[,c('id','id2')]),]
  id id2 somevalue
1  1   1         x
3  3   4         z

Inside the duplicated call, I'm simply passing only those columns from dat that I don't want duplicates of. This code will automatically always select the first of any ambiguous values. (In this case, x.)

Why use double indirection? or Why use pointers to pointers?

One thing I use them for constantly is when I have an array of objects and I need to perform lookups (binary search) on them by different fields.
I keep the original array...

int num_objects;
OBJECT *original_array = malloc(sizeof(OBJECT)*num_objects);

Then make an array of sorted pointers to the objects.

int compare_object_by_name( const void *v1, const void *v2 ) {
  OBJECT *o1 = *(OBJECT **)v1;
  OBJECT *o2 = *(OBJECT **)v2;
  return (strcmp(o1->name, o2->name);
}

OBJECT **object_ptrs_by_name = malloc(sizeof(OBJECT *)*num_objects);
  int i = 0;
  for( ; i<num_objects; i++)
    object_ptrs_by_name[i] = original_array+i;
  qsort(object_ptrs_by_name, num_objects, sizeof(OBJECT *), compare_object_by_name);

You can make as many sorted pointer arrays as you need, then use a binary search on the sorted pointer array to access the object you need by the data you have. The original array of objects can stay unsorted, but each pointer array will be sorted by their specified field.

Why is a primary-foreign key relation required when we can join without it?

The main reason for primary and foreign keys is to enforce data consistency.

A primary key enforces the consistency of uniqueness of values over one or more columns. If an ID column has a primary key then it is impossible to have two rows with the same ID value. Without that primary key, many rows could have the same ID value and you wouldn't be able to distinguish between them based on the ID value alone.

A foreign key enforces the consistency of data that points elsewhere. It ensures that the data which is pointed to actually exists. In a typical parent-child relationship, a foreign key ensures that every child always points at a parent and that the parent actually exists. Without the foreign key you could have "orphaned" children that point at a parent that doesn't exist.

How can I detect if this dictionary key exists in C#?

Here is a little something I cooked up today. Seems to work for me. Basically you override the Add method in your base namespace to do a check and then call the base's Add method in order to actually add it. Hope this works for you

using System;
using System.Collections.Generic;
using System.Collections;

namespace Main
{
    internal partial class Dictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
    {
        internal new virtual void Add(TKey key, TValue value)
        {   
            if (!base.ContainsKey(key))
            {
                base.Add(key, value);
            }
        }
    }

    internal partial class List<T> : System.Collections.Generic.List<T>
    {
        internal new virtual void Add(T item)
        {
            if (!base.Contains(item))
            {
                base.Add(item);
            }
        }
    }

    public class Program
    {
        public static void Main()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1,"b");
            dic.Add(1,"a");
            dic.Add(2,"c");
            dic.Add(1, "b");
            dic.Add(1, "a");
            dic.Add(2, "c");

            string val = "";
            dic.TryGetValue(1, out val);

            Console.WriteLine(val);
            Console.WriteLine(dic.Count.ToString());


            List<string> lst = new List<string>();
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");

            Console.WriteLine(lst[2]);
            Console.WriteLine(lst.Count.ToString());
        }
    }
}

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

Insted of

drawer.setDrawerListener(toggle);

You can use

drawer.addDrawerListener(toggle);

enable/disable zoom in Android WebView

Ive modifiet Lukas Knuth's solution a little:

1) There's no need to subclass the webview,

2) the code will crash during bytecode verification on some Android 1.6 devices if you don't put nonexistant methods in seperate classes

3) Zoom controls will still appear if the user scrolls up/down a page. I simply set the zoom controller container to visibility GONE

  wv.getSettings().setSupportZoom(true);
  wv.getSettings().setBuiltInZoomControls(true);
  if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
    // Use the API 11+ calls to disable the controls
    // Use a seperate class to obtain 1.6 compatibility
    new Runnable() {
      public void run() {
        wv.getSettings().setDisplayZoomControls(false);
      }
    }.run();
  } else {
    final ZoomButtonsController zoom_controll =
        (ZoomButtonsController) wv.getClass().getMethod("getZoomButtonsController").invoke(wv, null);
    zoom_controll.getContainer().setVisibility(View.GONE);
  }

ASP.NET Identity DbContext confusion

If you drill down through the abstractions of the IdentityDbContext you'll find that it looks just like your derived DbContext. The easiest route is Olav's answer, but if you want more control over what's getting created and a little less dependency on the Identity packages have a look at my question and answer here. There's a code example if you follow the link, but in summary you just add the required DbSets to your own DbContext subclass.

Converting NumPy array into Python List structure?

tolist() works fine even if encountered a nested array, say a pandas DataFrame;

my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]

print(type(my_list),type(my_dt),type(new_list))

SQL: How to get the id of values I just INSERTed?

Rob's answer would be the most vendor-agnostic, but if you're using MySQL the safer and correct choise would be the built-in LAST_INSERT_ID() function.

How to get only the last part of a path in Python?

Here is my approach:

>>> import os
>>> print os.path.basename(
        os.path.dirname('/folderA/folderB/folderC/folderD/test.py'))
folderD
>>> print os.path.basename(
        os.path.dirname('/folderA/folderB/folderC/folderD/'))
folderD
>>> print os.path.basename(
        os.path.dirname('/folderA/folderB/folderC/folderD'))
folderC

How to create a MySQL hierarchical recursive query?

Something not mentioned here, although a bit similar to the second alternative of the accepted answer but different and low cost for big hierarchy query and easy (insert update delete) items, would be adding a persistent path column for each item.

some like:

id | name        | path
19 | category1   | /19
20 | category2   | /19/20
21 | category3   | /19/20/21
22 | category4   | /19/20/21/22

Example:

-- get children of category3:
SELECT * FROM my_table WHERE path LIKE '/19/20/21%'
-- Reparent an item:
UPDATE my_table SET path = REPLACE(path, '/19/20', '/15/16') WHERE path LIKE '/19/20/%'

Optimise the path length and ORDER BY path using base36 encoding instead real numeric path id

 // base10 => base36
 '1' => '1',
 '10' => 'A',
 '100' => '2S',
 '1000' => 'RS',
 '10000' => '7PS',
 '100000' => '255S',
 '1000000' => 'LFLS',
 '1000000000' => 'GJDGXS',
 '1000000000000' => 'CRE66I9S'

https://en.wikipedia.org/wiki/Base36

Suppressing also the slash '/' separator by using fixed length and padding to the encoded id

Detailed optimization explanation here: https://bojanz.wordpress.com/2014/04/25/storing-hierarchical-data-materialized-path/

TODO

building a function or procedure to split path for retreive ancestors of one item

Using external images for CSS custom cursors

I would put this as a comment, but I don't have the rep for it. What Josh Crozier answered is correct, but for IE .cur and .ani are the only supported formats for this. So you should probably have a fallback just in case:

.test {
    cursor:url("http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif"), url(foo.cur), auto;
}

DELETE ... FROM ... WHERE ... IN

The canonical T-SQL (SqlServer) answer is to use a DELETE with JOIN as such

DELETE o
FROM Orders o
INNER JOIN Customers c
    ON o.CustomerId = c.CustomerId
WHERE c.FirstName = 'sklivvz'

This will delete all orders which have a customer with first name Sklivvz.

How can I use Oracle SQL developer to run stored procedures?

There are two possibilities, both from Quest Software, TOAD & SQL Navigator:

Here is the TOAD Freeware download: http://www.toadworld.com/Downloads/FreewareandTrials/ToadforOracleFreeware/tabid/558/Default.aspx

And the SQL Navigator (trial version): http://www.quest.com/sql-navigator/software-downloads.aspx

Assigning out/ref parameters in Moq

Seems like it is not possible out of the box. Looks like someone attempted a solution

See this forum post http://code.google.com/p/moq/issues/detail?id=176

this question Verify value of reference parameter with Moq

Setting DEBUG = False causes 500 Error

I encountered the same issue just recently in Django 2.0. I was able to figure out the problem by setting DEBUG_PROPAGATE_EXCEPTIONS = True. See here: https://docs.djangoproject.com/en/2.0/ref/settings/#debug-propagate-exceptions

In my case, the error was ValueError: Missing staticfiles manifest entry for 'admin/css/base.css'. I fixed that by locally running python manage.py collectstatic.

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

jQuery is not JavaScript which is more easy to use in some cases.

Look at this example:

<textarea rows="10" cols="50" onclick="this.focus();this.select()">Text is here</textarea>

Source: CSS Tricks, MDN

How to calculate number of days between two dates

Try:

//Difference in days

var diff =  Math.floor(( start - end ) / 86400000);
alert(diff);

How to add additional fields to form before submit?

You can add a hidden input with whatever value you need to send:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="someName" value="someValue">');
    return true;
});

delete image from folder PHP

You can delete files in PHP using the unlink() function.

unlink('path/to/file.jpg');

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

You should write something like that :

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);

Why are elementwise additions much faster in separate loops than in a combined loop?

I cannot replicate the results discussed here.

I don't know if poor benchmark code is to blame, or what, but the two methods are within 10% of each other on my machine using the following code, and one loop is usually just slightly faster than two - as you'd expect.

Array sizes ranged from 2^16 to 2^24, using eight loops. I was careful to initialize the source arrays so the += assignment wasn't asking the FPU to add memory garbage interpreted as a double.

I played around with various schemes, such as putting the assignment of b[j], d[j] to InitToZero[j] inside the loops, and also with using += b[j] = 1 and += d[j] = 1, and I got fairly consistent results.

As you might expect, initializing b and d inside the loop using InitToZero[j] gave the combined approach an advantage, as they were done back-to-back before the assignments to a and c, but still within 10%. Go figure.

Hardware is Dell XPS 8500 with generation 3 Core i7 @ 3.4 GHz and 8 GB memory. For 2^16 to 2^24, using eight loops, the cumulative time was 44.987 and 40.965 respectively. Visual C++ 2010, fully optimized.

PS: I changed the loops to count down to zero, and the combined method was marginally faster. Scratching my head. Note the new array sizing and loop counts.

// MemBufferMystery.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
#include <time.h>

#define  dbl    double
#define  MAX_ARRAY_SZ    262145    //16777216    // AKA (2^24)
#define  STEP_SZ           1024    //   65536    // AKA (2^16)

int _tmain(int argc, _TCHAR* argv[]) {
    long i, j, ArraySz = 0,  LoopKnt = 1024;
    time_t start, Cumulative_Combined = 0, Cumulative_Separate = 0;
    dbl *a = NULL, *b = NULL, *c = NULL, *d = NULL, *InitToOnes = NULL;

    a = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    b = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    c = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    d = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    InitToOnes = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    // Initialize array to 1.0 second.
    for(j = 0; j< MAX_ARRAY_SZ; j++) {
        InitToOnes[j] = 1.0;
    }

    // Increase size of arrays and time
    for(ArraySz = STEP_SZ; ArraySz<MAX_ARRAY_SZ; ArraySz += STEP_SZ) {
        a = (dbl *)realloc(a, ArraySz * sizeof(dbl));
        b = (dbl *)realloc(b, ArraySz * sizeof(dbl));
        c = (dbl *)realloc(c, ArraySz * sizeof(dbl));
        d = (dbl *)realloc(d, ArraySz * sizeof(dbl));
        // Outside the timing loop, initialize
        // b and d arrays to 1.0 sec for consistent += performance.
        memcpy((void *)b, (void *)InitToOnes, ArraySz * sizeof(dbl));
        memcpy((void *)d, (void *)InitToOnes, ArraySz * sizeof(dbl));

        start = clock();
        for(i = LoopKnt; i; i--) {
            for(j = ArraySz; j; j--) {
                a[j] += b[j];
                c[j] += d[j];
            }
        }
        Cumulative_Combined += (clock()-start);
        printf("\n %6i miliseconds for combined array sizes %i and %i loops",
                (int)(clock()-start), ArraySz, LoopKnt);
        start = clock();
        for(i = LoopKnt; i; i--) {
            for(j = ArraySz; j; j--) {
                a[j] += b[j];
            }
            for(j = ArraySz; j; j--) {
                c[j] += d[j];
            }
        }
        Cumulative_Separate += (clock()-start);
        printf("\n %6i miliseconds for separate array sizes %i and %i loops \n",
                (int)(clock()-start), ArraySz, LoopKnt);
    }
    printf("\n Cumulative combined array processing took %10.3f seconds",
            (dbl)(Cumulative_Combined/(dbl)CLOCKS_PER_SEC));
    printf("\n Cumulative seperate array processing took %10.3f seconds",
        (dbl)(Cumulative_Separate/(dbl)CLOCKS_PER_SEC));
    getchar();

    free(a); free(b); free(c); free(d); free(InitToOnes);
    return 0;
}

I'm not sure why it was decided that MFLOPS was a relevant metric. I though the idea was to focus on memory accesses, so I tried to minimize the amount of floating point computation time. I left in the +=, but I am not sure why.

A straight assignment with no computation would be a cleaner test of memory access time and would create a test that is uniform irrespective of the loop count. Maybe I missed something in the conversation, but it is worth thinking twice about. If the plus is left out of the assignment, the cumulative time is almost identical at 31 seconds each.

What is the best data type to use for money in C#?

System.Decimal

The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations requiring large numbers of significant integral and fractional digits and no round-off errors. The Decimal type does not eliminate the need for rounding. Rather, it minimizes errors due to rounding.

I'd like to point to this excellent answer by zneak on why double shouldn't be used.

Eloquent ORM laravel 5 Get Array of ids

Just an extra info, if you are using DB:

DB::table('test')->where('id', '>', 0)->pluck('id')->toArray();

And if using Eloquent model:

test::where('id', '>', 0)->lists('id')->toArray();

Show whitespace characters in Visual Studio Code

It is not a boolean anymore. They switched to an enum. Now we can choose between: none, boundary, and all.

// Controls how the editor should render whitespace characters,
// posibilties are 'none', 'boundary', and 'all'.
// The 'boundary' option does not render single spaces between words.
"editor.renderWhitespace": "none",

You can see the original diff on GitHub.

What is the difference between JavaScript and ECMAScript?

ECMAScript is the language, whereas JavaScript, JScript, and even ActionScript 3 are called "dialects". Wikipedia sheds some light on this.

Add list to set?

I found I needed to do something similar today. The algorithm knew when it was creating a new list that needed to added to the set, but not when it would have finished operating on the list.

Anyway, the behaviour I wanted was for set to use id rather than hash. As such I found mydict[id(mylist)] = mylist instead of myset.add(mylist) to offer the behaviour I wanted.

PostgreSQL: role is not permitted to log in

The role you have created is not allowed to log in. You have to give the role permission to log in.

One way to do this is to log in as the postgres user and update the role:

psql -U postgres

Once you are logged in, type:

ALTER ROLE "asunotest" WITH LOGIN;

Here's the documentation http://www.postgresql.org/docs/9.0/static/sql-alterrole.html

Get HTML5 localStorage keys

in ES2017 you can use:

Object.entries(localStorage)

python max function using 'key' and lambda expression

Strongly simplified version of max:

def max(items, key=lambda x: x):
    current = item[0]
    for item in items:
        if key(item) > key(current):
            current = item
    return current

Regarding lambda:

>>> ident = lambda x: x
>>> ident(3)
3
>>> ident(5)
5

>>> times_two = lambda x: 2*x
>>> times_two(2)
4

Class extending more than one class Java?

Multiple Inheritance

Assume B and C are overriding inherited method and their own implementation. Now D inherits both B & C using multiple inheritance. D should inherit the overridden method.The Question is which overridden method will be used? Will it be from B or C? Here we have an ambiguity. To exclude such situation multiple inheritance was not used in Java.

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

CSS hide scroll bar if not needed

You can use overflow:auto;

You can also control the x or y axis individually with the overflow-x and overflow-y properties.

Example:

.content {overflow:auto;}
.content {overflow-y:auto;}
.content {overflow-x:auto;}

Is there a standardized method to swap two variables in Python?

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

Python docs: Evaluation order

That means the following for the expression a,b = b,a :

  • The right-hand side b,a is evaluated, that is to say, a tuple of two elements is created in the memory. The two elements are the objects designated by the identifiers b and a, that were existing before the instruction is encountered during the execution of the program.
  • Just after the creation of this tuple, no assignment of this tuple object has still been made, but it doesn't matter, Python internally knows where it is.
  • Then, the left-hand side is evaluated, that is to say, the tuple is assigned to the left-hand side.
  • As the left-hand side is composed of two identifiers, the tuple is unpacked in order that the first identifier a be assigned to the first element of the tuple (which is the object that was formerly b before the swap because it had name b)
    and the second identifier b is assigned to the second element of the tuple (which is the object that was formerly a before the swap because its identifiers was a)

This mechanism has effectively swapped the objects assigned to the identifiers a and b

So, to answer your question: YES, it's the standard way to swap two identifiers on two objects.
By the way, the objects are not variables, they are objects.

UITableView with fixed section headers

The headers only remain fixed when the UITableViewStyle property of the table is set to UITableViewStylePlain. If you have it set to UITableViewStyleGrouped, the headers will scroll up with the cells.

How to find numbers from a string?

This a variant of brettdj's & pstraton post.

This will return a true Value and not give you the #NUM! error. And \D is shorthand for anything but digits. The rest is much like the others only with this minor fix.

Function StripChar(Txt As String) As Variant
With CreateObject("VBScript.RegExp")
    .Global = True
    .Pattern = "\D"
    StripChar = Val(.Replace(Txt, " "))
End With
End Function

detect key press in python?

As OP mention about raw_input - that means he want cli solution. Linux: curses is what you want (windows PDCurses). Curses, is an graphical API for cli software, you can achieve more than just detect key events.

This code will detect keys until new line is pressed.

import curses
import os

def main(win):
    win.nodelay(True)
    key=""
    win.clear()                
    win.addstr("Detected key:")
    while 1:          
        try:                 
           key = win.getkey()         
           win.clear()                
           win.addstr("Detected key:")
           win.addstr(str(key)) 
           if key == os.linesep:
              break           
        except Exception as e:
           # No input   
           pass         

curses.wrapper(main)

How to remove item from list in C#?

You don't specify what kind of list, but the generic List can use either the RemoveAt(index) method, or the Remove(obj) method:

// Remove(obj)
var item = resultList.Single(x => x.Id == 2);
resultList.Remove(item);

// RemoveAt(index)
resultList.RemoveAt(1);

Add new item in existing array in c#.net

You can expand on the answer provided by @Stephen Chung by using his LINQ based logic to create an extension method using a generic type.

public static class CollectionHelper
{
    public static IEnumerable<T> Add<T>(this IEnumerable<T> sequence, T item)
    {
        return (sequence ?? Enumerable.Empty<T>()).Concat(new[] { item });
    }

    public static T[] AddRangeToArray<T>(this T[] sequence, T[] items)
    {
        return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray();
    }

    public static T[] AddToArray<T>(this T[] sequence, T item)
    {
        return Add(sequence, item).ToArray();
    }

}

You can then call it directly on the array like this.

    public void AddToArray(string[] options)
    {
        // Add one item
        options = options.AddToArray("New Item");

        // Add a 
        options = options.AddRangeToArray(new string[] { "one", "two", "three" });

        // Do stuff...
    }

Admittedly, the AddRangeToArray() method seems a bit overkill since you have the same functionality with Concat() but this way the end code can "work" with the array directly as opposed to this:

options = options.Concat(new string[] { "one", "two", "three" }).ToArray();

.htaccess redirect www to non-www with SSL/HTTPS

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

This worked for me after much trial and error. Part one is from the user above and will capture www.xxx.yyy and send to https://xxx.yyy

Part 2 looks at entered URL and checks if HTTPS, if not, it sends to HTTPS

Done in this order, it follows logic and no error occurs.

HERE is my FULL version in side htaccess with WordPress:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]


# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

$(...).datepicker is not a function - JQuery - Bootstrap

Not the right function name I think

$(document).ready(function() {

    $('.datepicker').datetimepicker({
        format: 'dd/mm/yyyy'
    });
});

Using LINQ to remove elements from a List<T>

Below is the example to remove the element from the list.

 List<int> items = new List<int>() { 2, 2, 3, 4, 2, 7, 3,3,3};

 var result = items.Remove(2);//Remove the first ocurence of matched elements and returns boolean value
 var result1 = items.RemoveAll(lst => lst == 3);// Remove all the matched elements and returns count of removed element
 items.RemoveAt(3);//Removes the elements at the specified index

Pycharm/Python OpenCV and CV2 install error

You are getting those errors because opencv and cv2 are not the python package names.

These are both included as part of the opencv-python package available to install from pip.

If you are using python 2 you can install with pip:

 pip install opencv-python

Or use the equivilent for python 3:

pip3 install opencv-python

After running the appropriate pip command your package should be available to use from python.

Detect end of ScrollView

We should always add scrollView.getPaddingBottom() to match full scrollview height because some time scroll view has padding in xml file so that case its not going to work.

scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            if (scrollView != null) {
               View view = scrollView.getChildAt(scrollView.getChildCount()-1);
               int diff = (view.getBottom()+scrollView.getPaddingBottom()-(scrollView.getHeight()+scrollView.getScrollY()));

          // if diff is zero, then the bottom has been reached
               if (diff == 0) {
               // do stuff
                }
            }
        }
    });

Adding an onclicklistener to listview (android)

You are doing

Object o = prestListView.getItemAtPosition(position);
String str=(String)o;//As you are using Default String Adapter

The o that you get back is not a String, but a prestationEco so you get a CCE when doing the (String)o

How can I clear previous output in Terminal in Mac OS X?

On Mac OS X Terminal, this functionality is already built in to the Terminal Application as menu View ? Clear Scrollback (the default is CMD + K).

So you can re-assign this as you like with Apple's Keyboard shortcuts. Just add a new shortcut for Terminal with the command "Clear Scrollback". (I use CMD + L, because it's similar to Ctrl + L to clear the current screen contents, without clearing the buffer.)

I am not sure how you would use this in a script (maybe AppleScript as others have pointed out).

WARNING: Can't verify CSRF token authenticity rails

Use jquery.csrf (https://github.com/swordray/jquery.csrf).

  • Rails 5.1 or later

    $ yarn add jquery.csrf
    
    //= require jquery.csrf
    
  • Rails 5.0 or before

    source 'https://rails-assets.org' do
      gem 'rails-assets-jquery.csrf'
    end
    
    //= require jquery.csrf
    
  • Source code

    (function($) {
      $(document).ajaxSend(function(e, xhr, options) {
        var token = $('meta[name="csrf-token"]').attr('content');
        if (token) xhr.setRequestHeader('X-CSRF-Token', token);
      });
    })(jQuery);
    

Using variable in SQL LIKE statement

If you are using a Stored Procedure:

ALTER PROCEDURE <Name>
(
    @PartialName VARCHAR(50) = NULL
)

SELECT Name 
    FROM <table>
    WHERE Name LIKE '%' + @PartialName + '%'

Normal arguments vs. keyword arguments

Using keyword arguments is the same thing as normal arguments except order doesn't matter. For example the two functions calls below are the same:

def foo(bar, baz):
    pass

foo(1, 2)
foo(baz=2, bar=1)

How to fit Windows Form to any screen resolution?

You can simply set the window state

this.WindowState = System.Windows.Forms.FormWindowState.Maximized;

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

Important Note

I had to COPY and untar java package in my docker image. When I compared the docker image size created using ADD it was 180MB bigger than the one created using COPY, tar -xzf *.tar.gz and rm *.tar.gz

This means that although ADD removes the tar file, it is still kept somewhere. And its making the image bigger!!

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

... or if you really want to use NOT IN you can use

SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email WHERE id IS NOT NULL)

Angular HttpClient "Http failure during parsing"

if you have options

return this.http.post(`${this.endpoint}/account/login`,payload, { ...options, responseType: 'text' })

SQL Developer is returning only the date, not the time. How do I fix this?

This will get you the hours, minutes and second. hey presto.

select
  to_char(CREATION_TIME,'RRRR') year, 
  to_char(CREATION_TIME,'MM') MONTH, 
  to_char(CREATION_TIME,'DD') DAY, 
  to_char(CREATION_TIME,'HH:MM:SS') TIME,
  sum(bytes) Bytes 
from 
  v$datafile 
group by 
  to_char(CREATION_TIME,'RRRR'), 
  to_char(CREATION_TIME,'MM'), 
  to_char(CREATION_TIME,'DD'), 
  to_char(CREATION_TIME,'HH:MM:SS') 
 ORDER BY 1, 2; 

How to get 2 digit year w/ Javascript?

The specific answer to this question is found in this one line below:

_x000D_
_x000D_
//pull the last two digits of the year_x000D_
//logs to console_x000D_
//creates a new date object (has the current date and time by default)_x000D_
//gets the full year from the date object (currently 2017)_x000D_
//converts the variable to a string_x000D_
//gets the substring backwards by 2 characters (last two characters)    _x000D_
console.log(new Date().getFullYear().toString().substr(-2));
_x000D_
_x000D_
_x000D_

Formatting Full Date Time Example (MMddyy): jsFiddle

JavaScript:

_x000D_
_x000D_
//A function for formatting a date to MMddyy_x000D_
function formatDate(d)_x000D_
{_x000D_
    //get the month_x000D_
    var month = d.getMonth();_x000D_
    //get the day_x000D_
    //convert day to string_x000D_
    var day = d.getDate().toString();_x000D_
    //get the year_x000D_
    var year = d.getFullYear();_x000D_
    _x000D_
    //pull the last two digits of the year_x000D_
    year = year.toString().substr(-2);_x000D_
    _x000D_
    //increment month by 1 since it is 0 indexed_x000D_
    //converts month to a string_x000D_
    month = (month + 1).toString();_x000D_
_x000D_
    //if month is 1-9 pad right with a 0 for two digits_x000D_
    if (month.length === 1)_x000D_
    {_x000D_
        month = "0" + month;_x000D_
    }_x000D_
_x000D_
    //if day is between 1-9 pad right with a 0 for two digits_x000D_
    if (day.length === 1)_x000D_
    {_x000D_
        day = "0" + day;_x000D_
    }_x000D_
_x000D_
    //return the string "MMddyy"_x000D_
    return month + day + year;_x000D_
}_x000D_
_x000D_
var d = new Date();_x000D_
console.log(formatDate(d));
_x000D_
_x000D_
_x000D_

Is there an easy way to reload css without reloading the page?

One more jQuery solution

For a single stylesheet with id "css" try this:

$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');

Wrap it in a function that has global scrope and you can use it from the Developer Console in Chrome or Firebug in Firefox:

var reloadCSS = function() {
  $('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
};

Why I cannot cout a string?

You need to include

#include <string>
#include <iostream>

Maximum length of HTTP GET request

GET REQUEST using the Chrome browser

Yes. There isn't any limit on a GET request.

I am able to send ~4000 characters as part of the query string using both the Chrome browser and curl command.

I am using Tomcat 8.x server which has returned the expected 200 OK response.

Here is the screenshot of a Google Chrome HTTP request (hiding the endpoint I tried due to security reasons):

RESPONSE

GET using the Chrome browser

What is 'PermSize' in Java?

lace to store your loaded class definition and metadata. If a large code-base project is loaded, the insufficient Perm Gen size will cause the popular Java.Lang.OutOfMemoryError: PermGen.

bundle install fails with SSL certificate verification error

same problem but with different gem here:

Gem::RemoteFetcher::FetchError: SSL_connect returned=1 errno=0 state=SSLv3 
read server certificate B: certificate verify failed 
(https://bb-m.rubygems.org/gems/builder-3.0.0.gem)
An error occured while installing builder (3.0.0), and Bundler cannot continue.
Make sure that `gem install builder -v '3.0.0'` succeeds before bundling.

temporarily solution: gem install builder -v '3.0.0' makes it possible to continue bundle install

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

You can covert numpy.ndarray to object using astype(object)

This will work:

>>> a = [np.zeros((224,224,3)).astype(object), np.zeros((224,224,3)).astype(object), np.zeros((224,224,13)).astype(object)]

How to install OpenSSL in windows 10?

Necroposting, but might be useful for others.

There's always the official page: [OpenSSL.Wiki]: Binaries which contains useful URLs.

I also want to mention: [GitHub]: CristiFati/Prebuilt-Binaries - Prebuilt-Binaries/OpenSSL

  • v1.0.2u is built with OpenSSL-FIPS 2.0.16
  • Artefacts are .zips that should be unpacked in "C:\Program Files" (please take a look at the Readme.md file, and also at the one at the repository root)

Test method is inconclusive: Test wasn't run. Error?

In my case [Test] methods were just private. S-h-a-m-e

css transition opacity fade background

It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.

If you want to fade to black(ish), you'll need a black container around the image. Something like:

.ctr {
    margin: 0; 
    padding: 0;
    background-color: black;
    display: inline-block;
}

and

<div class="ctr"><img ... /></div>

List all employee's names and their managers by manager name using an inner join

Select e.lastname as employee ,m.lastname as manager
  from employees e,employees m
 where e.managerid=m.employyid(+)

Save byte array to file

You can use:

File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO

If you have an enumerable and not an array, you can use:

File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq

Getting error "No such module" using Xcode, but the framework is there

I also encountered the same error a few days back. Here's how I resolved the problem:

The error is "module not found"

  • Create Podfile in your root project directory
  • Install cocoapods (a dependency manager for Swift and iOS projects)
  • Run pod install
  • Go to Project Build Settings:

    • Find Objective-c bridging Header under Swift compiler - Code Generation (If you don't find Swift compiler here, probably add a new Swift file to the project)
    • Drag and drop the library header file from left side to bridging header (see image attached)enter image description here
  • Create a new bridging header file: e.g TestProject-Bridging-Header.h and put under Swift Compiler ? Objective-C Generated Interface Header Name (ref, see the image above)

  • In TestProject-Bridging-Header.h file, write #import "Mixpanel/Mixpanel.h"
  • In your Swift file the code should be: Import Mixpanel (i.e name of library)

That's all.

How do you share constants in NodeJS modules?

I found the solution Dominic suggested to be the best one, but it still misses one feature of the "const" declaration. When you declare a constant in JS with the "const" keyword, the existence of the constant is checked at parse time, not at runtime. So if you misspelled the name of the constant somewhere later in your code, you'll get an error when you try to start your node.js program. Which is a far more better misspelling check.

If you define the constant with the define() function like Dominic suggested, you won't get an error if you misspelled the constant, and the value of the misspelled constant will be undefined (which can lead to debugging headaches).

But I guess this is the best we can get.

Additionally, here's a kind of improvement of Dominic's function, in constans.js:

global.define = function ( name, value, exportsObject )
{
    if ( !exportsObject )
    {
        if ( exports.exportsObject )
            exportsObject = exports.exportsObject;
        else 
            exportsObject = exports;        
    }

    Object.defineProperty( exportsObject, name, {
        'value': value,
        'enumerable': true,
        'writable': false,
    });
}

exports.exportObject = null;

In this way you can use the define() function in other modules, and it allows you to define constants both inside the constants.js module and constants inside your module from which you called the function. Declaring module constants can then be done in two ways (in script.js).

First:

require( './constants.js' );

define( 'SOME_LOCAL_CONSTANT', "const value 1", this ); // constant in script.js
define( 'SOME_OTHER_LOCAL_CONSTANT', "const value 2", this ); // constant in script.js

define( 'CONSTANT_IN_CONSTANTS_MODULE', "const value x" ); // this is a constant in constants.js module

Second:

constants = require( './constants.js' );

// More convenient for setting a lot of constants inside the module
constants.exportsObject = this;
define( 'SOME_CONSTANT', "const value 1" ); // constant in script.js
define( 'SOME_OTHER_CONSTANT', "const value 2" ); // constant in script.js

Also, if you want the define() function to be called only from the constants module (not to bloat the global object), you define it like this in constants.js:

exports.define = function ( name, value, exportsObject )

and use it like this in script.js:

constants.define( 'SOME_CONSTANT', "const value 1" );

MySQL select one column DISTINCT, with corresponding other columns

How about

`SELECT 
    my_distinct_column,
    max(col1),
    max(col2),
    max(col3)
    ...
 FROM
    my_table 
 GROUP BY 
    my_distinct_column`

Convert datetime value into string

Use DATE_FORMAT()

SELECT
  DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;

HTML <input type='file'> File Selection Event

That's the way I did it with pure JS:

_x000D_
_x000D_
var files = document.getElementById('filePoster');_x000D_
var submit = document.getElementById('submitFiles');_x000D_
var warning = document.getElementById('warning');_x000D_
files.addEventListener("change", function () {_x000D_
  if (files.files.length > 10) {_x000D_
    submit.disabled = true;_x000D_
    warning.classList += "warn"_x000D_
    return;_x000D_
  }_x000D_
  submit.disabled = false;_x000D_
});
_x000D_
#warning {_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
#warning.warn {_x000D_
 color: red;_x000D_
 transform: scale(1.5);_x000D_
 transition: 1s all;_x000D_
}
_x000D_
<section id="shortcode-5" class="shortcode-5 pb-50">_x000D_
    <p id="warning">Please do not upload more than 10 images at once.</p>_x000D_
    <form class="imagePoster" enctype="multipart/form-data" action="/gallery/imagePoster" method="post">_x000D_
        <div class="input-group">_x000D_
       <input id="filePoster" type="file" class="form-control" name="photo" required="required" multiple="multiple" />_x000D_
     <button id="submitFiles" class="btn btn-primary" type="submit" name="button">Submit</button>_x000D_
        </div>_x000D_
    </form>_x000D_
</section>
_x000D_
_x000D_
_x000D_

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

My exact problem was (Fatal error in launcher: Unable to create process using '"') on windows 10. So I navigated to the "C:\Python33\Lib\site-packages" and deleted django folder and pip folders then reinstalled django using pip and my problem was solved.

What is the correct JSON content type?

Content-Type: application/json - json
Content-Type: application/javascript - json-P
Content-Type: application/x-javascript - javascript
Content-Type: text/javascript - javascript BUT obsolete, older IE versions used to use as html attribute.
Content-Type: text/x-javascript - JavaScript Media Types BUT obsolete
Content-Type: text/x-json - json before application/json got officially registered.

jquery fill dropdown with json data

Here is an example of code, that attempts to featch AJAX data from /Ajax/_AjaxGetItemListHelp/ URL. Upon success, it removes all items from dropdown list with id = OfferTransModel_ItemID and then it fills it with new items based on AJAX call's result:

if (productgrpid != 0) {    
    $.ajax({
        type: "POST",
        url: "/Ajax/_AjaxGetItemListHelp/",
        data:{text:"sam",OfferTransModel_ItemGrpid:productgrpid},
        contentType: "application/json",              
        dataType: "json",
        success: function (data) {
            $("#OfferTransModel_ItemID").empty();

            $.each(data, function () {
                $("#OfferTransModel_ItemID").append($("<option>                                                      
                </option>").val(this['ITEMID']).html(this['ITEMDESC']));
            });
        }
    });
}

Returned AJAX result is expected to return data encoded as AJAX array, where each item contains ITEMID and ITEMDESC elements. For example:

{
    {
        "ITEMID":"13",
        "ITEMDESC":"About"
    },
    {
        "ITEMID":"21",
        "ITEMDESC":"Contact"
    }
}

The OfferTransModel_ItemID listbox is populated with above data and its code should look like:

<select id="OfferTransModel_ItemID" name="OfferTransModel[ItemID]">
    <option value="13">About</option>
    <option value="21">Contact</option>
</select>

When user selects About, form submits 13 as value for this field and 21 when user selects Contact and so on.

Fell free to modify above code if your server returns URL in a different format.

How to drop a PostgreSQL database if there are active connections to it?

In Linux command Prompt, I would first stop all postgresql processes that are running by tying this command sudo /etc/init.d/postgresql restart

type the command bg to check if other postgresql processes are still running

then followed by dropdb dbname to drop the database

sudo /etc/init.d/postgresql restart
bg
dropdb dbname

This works for me on linux command prompt

How do I "decompile" Java class files?

There are a few decompilers out there... A quick search yields:

  1. Procyon: open-source (Apache 2) and actively developed
  2. Krakatau: open-source (GPLv3) and actively developed
  3. CFR: open-source (MIT) and actively developed
  4. JAD
  5. DJ Java Decompiler
  6. Mocha

And many more.

These produce Java code. Java comes with something that lets you see JVM byte code (javap).

How can I change the color of my prompt in zsh (different from normal text)?

Try my favorite: put in

~/.zshrc

this line:

PROMPT='%F{240}%n%F{red}@%F{green}%m:%F{141}%d$ %F{reset}'

don't forget

source ~/.zshrc

to test the changes

you can change the colors/color codes, of course :-)

How to do a https request with bad certificate?

The correct way to do this if you want to maintain the default transport settings is now (as of Go 1.13):

customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client = &http.Client{Transport: customTransport}

Transport.Clone makes a deep copy of the transport. This way you don't have to worry about missing any new fields that get added to the Transport struct over time.

Javascript change date into format of (dd/mm/yyyy)

This will ensure you get a two-digit day and month.

function formattedDate(d = new Date) {
  let month = String(d.getMonth() + 1);
  let day = String(d.getDate());
  const year = String(d.getFullYear());

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return `${day}/${month}/${year}`;
}

Or terser:

function formattedDate(d = new Date) {
  return [d.getDate(), d.getMonth()+1, d.getFullYear()]
      .map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}

How to compile without warnings being treated as errors?

-Wall and -Werror compiler options can cause it, please check if those are used in compiler settings.

Format Instant to String

Instants are already in UTC and already have a default date format of yyyy-MM-dd. If you're happy with that and don't want to mess with time zones or formatting, you could also toString() it:

Instant instant = Instant.now();
instant.toString()
output: 2020-02-06T18:01:55.648475Z


Don't want the T and Z? (Z indicates this date is UTC. Z stands for "Zulu" aka "Zero hour offset" aka UTC):

instant.toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.663763


Want milliseconds instead of nanoseconds? (So you can plop it into a sql query):

instant.truncatedTo(ChronoUnit.MILLIS).toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.664

etc.

How to get JSON object from Razor Model object in javascript

After use codevar json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));

You need use JSON.parse(JSON.stringify(json));

How to load all the images from one of my folder into my web page, using Jquery/Javascript

Based on the answer of Roko C. Buljan, I have created this method which gets images from a folder and its subfolders . This might need some error handling but works fine for a simple folder structure.

var findImages = function(){
    var parentDir = "./Resource/materials/";

    var fileCrowler = function(data){
        var titlestr = $(data).filter('title').text();
        // "Directory listing for /Resource/materials/xxx"
        var thisDirectory = titlestr.slice(titlestr.indexOf('/'), titlestr.length)

        //List all image file names in the page
        $(data).find("a").attr("href", function (i, filename) {
            if( filename.match(/\.(jpe?g|png|gif)$/) ) { 
                var fileNameWOExtension = filename.slice(0, filename.lastIndexOf('.'))
                var img_html = "<img src='{0}' id='{1}' alt='{2}' width='75' height='75' hspace='2' vspace='2' onclick='onImageSelection(this);'>".format(thisDirectory + filename, fileNameWOExtension, fileNameWOExtension);
                $("#image_pane").append(img_html);
            }
            else{ 
                $.ajax({
                    url: thisDirectory + filename,
                    success: fileCrowler
                });
            }
        });}

        $.ajax({
        url: parentDir,
        success: fileCrowler
    });
}

jQuery multiple conditions within if statement

A more general approach:

if ( ($("body").hasClass("homepage") || $("body").hasClass("contact")) && (theLanguage == 'en-gb') )   {

       // Do something

}

What exactly does the "u" do? "git push -u origin master" vs "git push origin master"

The key is "argument-less git-pull". When you do a git pull from a branch, without specifying a source remote or branch, git looks at the branch.<name>.merge setting to know where to pull from. git push -u sets this information for the branch you're pushing.

To see the difference, let's use a new empty branch:

$ git checkout -b test

First, we push without -u:

$ git push origin test
$ git pull
You asked me to pull without telling me which branch you
want to merge with, and 'branch.test.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.

If you often merge with the same branch, you may want to
use something like the following in your configuration file:

    [branch "test"]
    remote = <nickname>
    merge = <remote-ref>

    [remote "<nickname>"]
    url = <url>
    fetch = <refspec>

See git-config(1) for details.

Now if we add -u:

$ git push -u origin test
Branch test set up to track remote branch test from origin.
Everything up-to-date
$ git pull
Already up-to-date.

Note that tracking information has been set up so that git pull works as expected without specifying the remote or branch.

Update: Bonus tips:

  • As Mark mentions in a comment, in addition to git pull this setting also affects default behavior of git push. If you get in the habit of using -u to capture the remote branch you intend to track, I recommend setting your push.default config value to upstream.
  • git push -u <remote> HEAD will push the current branch to a branch of the same name on <remote> (and also set up tracking so you can do git push after that).

How to properly validate input values with React.JS?

You can use npm install --save redux-form

Im writing a simple email and submit button form, which validates email and submits form. with redux-form, form by default runs event.preventDefault() on html onSubmit action.

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';

class LoginForm extends Component {
  onSubmit(props) {
    //do your submit stuff
  }


  render() {
    const {fields: {email}, handleSubmit} = this.props;

    return (
      <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
        <input type="text" placeholder="Email"
               className={`form-control ${email.touched && email.invalid ? 'has-error' : '' }`}
          {...email}
        />
          <span className="text-help">
            {email.touched ? email.error : ''}
          </span>
        <input type="submit"/>
      </form>
    );
  }
}

function validation(values) {
  const errors = {};
  const emailPattern = /(.+)@(.+){2,}\.(.+){2,}/;
  if (!emailPattern.test(values.email)) {
    errors.email = 'Enter a valid email';
  }

  return errors;
}

LoginForm = reduxForm({
  form: 'LoginForm',
  fields: ['email'],
  validate: validation
}, null, null)(LoginForm);

export default LoginForm;

Conditional formatting using AND() function

COLUMN() and ROW() won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.

For instance, if you want to use this conditional formating on a range begining on cell A1, you can try:

`COLUMN(A1)` and `ROW(A1)`

Excel will automatically adapt the conditional formating to the current cell.

Access localhost from the internet

You are accesing localhost, meaning you have a web server running on your machine. To access it from Internet, you need to assign a public IP address to your machine. Then you can access http://<public_ip>:<port>/. Port number is normally 80.

Making macOS Installer Packages which are Developer ID ready

A +1 to accepted answer:

Destination Selection in Installer

If domain (a.k.a destination) selection is desired between user domain and system domain then rather than trying <domains enable_anywhere="true"> use following:

<domains enable_currentUserHome="true" enable_localSystem="true"/>

enable_currentUserHome installs application app under ~/Applications/ and enable_localSystem allows the application to be installed under /Application

I've tried this in El Capitan 10.11.6 (15G1217) and it seems to be working perfectly fine in 1 dev machine and 2 different VMs I tried.

Git, fatal: The remote end hung up unexpectedly

PLESK Nginx and GIT I was getting this error on plesk git and while pushing a large repo with (who knows what) it gave me this error with HTTP code 413 and i looked into following Server was Plesk and it had nginx running as well as apache2 so i looked into logs and found the error in nginx logs

Followed this link to allow plesk to rebuild configuration with larger file upload.

I skipped the php part for git

After that git push worked without any errors.

How to plot two columns of a pandas data frame using points?

For this (and most plotting) I would not rely on the Pandas wrappers to matplotlib. Instead, just use matplotlib directly:

import matplotlib.pyplot as plt
plt.scatter(df['col_name_1'], df['col_name_2'])
plt.show() # Depending on whether you use IPython or interactive mode, etc.

and remember that you can access a NumPy array of the column's values with df.col_name_1.values for example.

I ran into trouble using this with Pandas default plotting in the case of a column of Timestamp values with millisecond precision. In trying to convert the objects to datetime64 type, I also discovered a nasty issue: < Pandas gives incorrect result when asking if Timestamp column values have attr astype >.

What is SuppressWarnings ("unchecked") in Java?

@SuppressWarnings annotation is one of the three built-in annotations available in JDK and added alongside @Override and @Deprecated in Java 1.5.

@SuppressWarnings instruct the compiler to ignore or suppress, specified compiler warning in annotated element and all program elements inside that element. For example, if a class is annotated to suppress a particular warning, then a warning generated in a method inside that class will also be separated.

You might have seen @SuppressWarnings("unchecked") and @SuppressWarnings("serial"), two of most popular examples of @SuppressWarnings annotation. Former is used to suppress warning generated due to unchecked casting while the later warning is used to remind about adding SerialVersionUID in a Serializable class.

Read more: https://javarevisited.blogspot.com/2015/09/what-is-suppresswarnings-annotation-in-java-unchecked-raw-serial.html#ixzz5rqQaOLUa

How to close existing connections to a DB

Short Answer:

You get "close existing connections to destination database" option only in "Databases context >> Restore Wizard" and NOT ON context of any particular database.

Long Answer:

Right Click on the Databases under your Server-Name as shown below:

and select the option: "Restore Database..." from it.

db

In the "Restore Database" wizard,

  1. select one of your databases to restore
  2. in the left vertical menu, click on "Options"

db1

Here you can find the checkbox saying, "close existing connections to destination database"

db3

Just check it, and you can proceed for the restore operation.

It automatically will resume all connections after completion of the Restore.

JQuery .on() method with multiple event handlers to one selector

Also, if you had multiple event handlers attached to the same selector executing the same function, you could use

$('table.planning_grid').on('mouseenter mouseleave', function() {
    //JS Code
});

After installation of Gulp: “no command 'gulp' found”

I actually have the same issue.

This link is probably my best guess:

nodejs vs node on ubuntu 12.04

I did that to resolve my problem:

sudo apt-get --purge remove node 
sudo apt-get --purge remove nodejs 
sudo apt-get install nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node

Rotating a point about another point (2D)

This is the answer by Nils Pipenbrinck, but implemented in c# fiddle.

https://dotnetfiddle.net/btmjlG

using System;

public class Program
{
    public static void Main()
    {   
        var angle = 180 * Math.PI/180;
        Console.WriteLine(rotate_point(0,0,angle,new Point{X=10, Y=10}).Print());
    }

    static Point rotate_point(double cx, double cy, double angle, Point p)
    {
        double s = Math.Sin(angle);
        double c = Math.Cos(angle);
        // translate point back to origin:
        p.X -= cx;
        p.Y -= cy;
        // rotate point
        double Xnew = p.X * c - p.Y * s;
        double Ynew = p.X * s + p.Y * c;
        // translate point back:
        p.X = Xnew + cx;
        p.Y = Ynew + cy;
        return p;
    }

    class Point
    {
        public double X;
        public double Y;

        public string Print(){
            return $"{X},{Y}";
        }
    }
}

Ps: Apparently I can’t comment, so I’m obligated to post it as an answer ...

Golang read request body

Inspecting and mocking request body

When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.

One option is to read the whole body using ioutil.ReadAll(), which gives you the body as a byte slice.

You may use bytes.NewBuffer() to obtain an io.Reader from a byte slice.

The last missing piece is to make the io.Reader an io.ReadCloser, because bytes.Buffer does not have a Close() method. For this you may use ioutil.NopCloser() which wraps an io.Reader, and returns an io.ReadCloser, whose added Close() method will be a no-op (does nothing).

Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.

Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!

Inspecting / modifying response body

If you also want to read the response body, then you have to wrap the http.ResponseWriter you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).

Here's a simple ResponseWriter wrapper, which just caches the data, so it'll be available after the subsequent handler returns:

type MyResponseWriter struct {
    http.ResponseWriter
    buf *bytes.Buffer
}

func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
    return mrw.buf.Write(p)
}

Note that MyResponseWriter.Write() just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write() method) and write the data immediately to the wrapped / embedded ResponseWriter. You may even modify the data. You have full control.

Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.

Full example

Putting the pieces together, here's a full working example:

func loginmw(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            log.Printf("Error reading body: %v", err)
            http.Error(w, "can't read body", http.StatusBadRequest)
            return
        }

        // Work / inspect body. You may even modify it!

        // And now set a new body, which will simulate the same data we read:
        r.Body = ioutil.NopCloser(bytes.NewBuffer(body))

        // Create a response wrapper:
        mrw := &MyResponseWriter{
            ResponseWriter: w,
            buf:            &bytes.Buffer{},
        }

        // Call next handler, passing the response wrapper:
        handler.ServeHTTP(mrw, r)

        // Now inspect response, and finally send it out:
        // (You can also modify it before sending it out!)
        if _, err := io.Copy(w, mrw.buf); err != nil {
            log.Printf("Failed to send out response: %v", err)
        }
    })
}

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

Seems like you want to move around. Try this:

ActiveSheet.UsedRange.select

results in....

enter image description here

If you want to move that selection 3 rows up then try this

ActiveSheet.UsedRange.offset(-3).select

does this...

enter image description here

Round up double to 2 decimal places

Use a format string to round up to two decimal places and convert the double to a String:

let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = String(format: "%.2f", currentRatio)

Example:

let myDouble = 3.141
let doubleStr = String(format: "%.2f", myDouble) // "3.14"

If you want to round up your last decimal place, you could do something like this (thanks Phoen1xUK):

let myDouble = 3.141
let doubleStr = String(format: "%.2f", ceil(myDouble*100)/100) // "3.15"

CSS3 100vh not constant in mobile browser

The following code solved the problem (with jQuery).

var vhHeight = $("body").height();
var chromeNavbarHeight = vhHeight - window.innerHeight;
$('body').css({ height: window.innerHeight, marginTop: chromeNavbarHeight });

And the other elements use % as a unit to replace vh.

Access is denied when attaching a database

With me - Running on window 8 - RIght click SQL Server Manager Studio -> Run with admin. -> attach no problems

How to define constants in ReactJS

If you want to keep the constants in the React component, use statics property, like the example below. Otherwise, use the answer given by @Jim

var MyComponent = React.createClass({
    statics: {
        sizeToLetterMap: {
            small_square: 's',
            large_square: 'q',
            thumbnail: 't',
            small_240: 'm',
            small_320: 'n',
            medium_640: 'z',
            medium_800: 'c',
            large_1024: 'b',
            large_1600: 'h',
            large_2048: 'k',
            original: 'o'
        },
        someOtherStatic: 100
    },

    photoUrl: function (image, size_text) {
        var size = MyComponent.sizeToLetterMap[size_text];
    }

How can I get city name from a latitude and longitude point?

Following Code Works Fine to Get City Name (Using Google Map Geo API) :

HTML

<p><button onclick="getLocation()">Get My Location</button></p>
<p id="demo"></p>
<script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>

SCRIPT

var x=document.getElementById("demo");
function getLocation(){
    if (navigator.geolocation){
        navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
    else{
        x.innerHTML="Geolocation is not supported by this browser.";
    }
}

function showPosition(position){
    lat=position.coords.latitude;
    lon=position.coords.longitude;
    displayLocation(lat,lon);
}

function showError(error){
    switch(error.code){
        case error.PERMISSION_DENIED:
            x.innerHTML="User denied the request for Geolocation."
        break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML="Location information is unavailable."
        break;
        case error.TIMEOUT:
            x.innerHTML="The request to get user location timed out."
        break;
        case error.UNKNOWN_ERROR:
            x.innerHTML="An unknown error occurred."
        break;
    }
}

function displayLocation(latitude,longitude){
    var geocoder;
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(latitude, longitude);

    geocoder.geocode(
        {'latLng': latlng}, 
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var add= results[0].formatted_address ;
                    var  value=add.split(",");

                    count=value.length;
                    country=value[count-1];
                    state=value[count-2];
                    city=value[count-3];
                    x.innerHTML = "city name is: " + city;
                }
                else  {
                    x.innerHTML = "address not found";
                }
            }
            else {
                x.innerHTML = "Geocoder failed due to: " + status;
            }
        }
    );
}

Angular.js How to change an elements css class on click and to remove all others

To me it seems like the best solution is to use a directive; there's no need for the controller to know that the view is being updated.

Javascript:

var app = angular.module('app', ['directives']);

angular.module('directives', []).directive('toggleClass', function () {
    var directiveDefinitionObject = {
        restrict: 'A',
        template: '<span ng-click="localFunction()" ng-class="selected"  ng-transclude></span>',
        replace: true,
        scope: {
            model: '='
        },
        transclude: true,
        link: function (scope, element, attrs) {
            scope.localFunction = function () {
                scope.model.value = scope.$id;
            };
            scope.$watch('model.value', function () {
                // Is this set to my scope?
                if (scope.model.value === scope.$id) {
                    scope.selected = "active";
                } else {
                    // nope
                    scope.selected = '';
                }
            });
        }
    };
    return directiveDefinitionObject;
});

HTML:

<div ng-app="app" ng-init="model = { value: 'dsf'}"> <span>Click a span... then click another</span>

<br/>
<br/>
<span toggle-class model="model">span1</span>

<br/><span toggle-class model="model">span2</span>

<br/><span toggle-class model="model">span3</span>

CSS:

.active {
     color:red;
 }

I have a fiddle that demonstrates. The idea is when a directive is clicked, a function is called on the directive that sets a variable to the current scope id. Then each directive also watches the same value. If the scope ID's match, then the current element is set to be active using ng-class.

The reason to use directives, is that you no longer are dependent on a controller. In fact I don't have a controller at all (I do define a variable in the view named "model"). You can then reuse this directive anywhere in your project, not just on one controller.

How can I remove the extension of a filename in a shell script?

As pointed out by Hawker65 in the comment of chepner answer, the most voted solution does neither take care of multiple extensions (such as filename.tar.gz), nor of dots in the rest of the path (such as this.path/with.dots/in.path.name). A possible solution is:

a=this.path/with.dots/in.path.name/filename.tar.gz
echo $(dirname $a)/$(basename $a | cut -d. -f1)

How to disable Django's CSRF validation?

If you just need some views not to use CSRF, you can use @csrf_exempt:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

You can find more examples and other scenarios in the Django documentation:

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

In my case, the prepare agent had a different destFile in configuration, but accordingly the report had to be configured with a dataFile, but this configuration was missing. Once the dataFile was added, it started working fine.

Compare two objects' properties to find differences?

Compare NET Objects can help you!

CompareLogic logic = new CompareLogic();
var compare = logic.Compare(obj1, obj2);
comparacao.Differences.ForEach(diff => Debug.Write(diff.PropertyName));
// Or formatted summary
Debug.Write(comparacao.DifferencesString);

jQuery UI DatePicker to show year only

check this out jquery calendar to show only year and month

or something like this

$("#datepicker").datepicker( "option", "dateFormat", "yy" );?

What is the inclusive range of float and double in Java?

Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.

You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

How to count days between two dates in PHP?

PHP has a date_diff() function to do this.

Redirecting to previous page after login? PHP

You can save a page using php, like this:

$_SESSION['current_page'] = $_SERVER['REQUEST_URI']

And return to the page with:

header("Location: ". $_SESSION['current_page'])

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:

http://[server]/[site]/[ListName]/[Folder]/[SubFolder]

To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

Spring Security with roles and permissions

To implement that, it seems that you have to:

  1. Create your model (user, role, permissions) and a way to retrieve permissions for a given user;
  2. Define your own org.springframework.security.authentication.ProviderManager and configure it (set its providers) to a custom org.springframework.security.authentication.AuthenticationProvider. This last one should return on its authenticate method a Authentication, which should be setted with the org.springframework.security.core.GrantedAuthority, in your case, all the permissions for the given user.

The trick in that article is to have roles assigned to users, but, to set the permissions for those roles in the Authentication.authorities object.

For that I advise you to read the API, and see if you can extend some basic ProviderManager and AuthenticationProvider instead of implementing everything. I've done that with org.springframework.security.ldap.authentication.LdapAuthenticationProvider setting a custom LdapAuthoritiesPopulator, that would retrieve the correct roles for the user.

Hope this time I got what you are looking for. Good luck.

When should we use mutex and when should we use semaphore

While @opaxdiablo answer is totally correct I would like to point out that the usage scenario of both things is quite different. The mutex is used for protecting parts of code from running concurrently, semaphores are used for one thread to signal another thread to run.

/* Task 1 */
pthread_mutex_lock(mutex_thing);
    // Safely use shared resource
pthread_mutex_unlock(mutex_thing);



/* Task 2 */
pthread_mutex_lock(mutex_thing);
   // Safely use shared resource
pthread_mutex_unlock(mutex_thing); // unlock mutex

The semaphore scenario is different:

/* Task 1 - Producer */
sema_post(&sem);   // Send the signal

/* Task 2 - Consumer */
sema_wait(&sem);   // Wait for signal

See http://www.netrino.com/node/202 for further explanations

How to get span tag inside a div in jQuery and assign a text?

Try this

$("#message span").text("hello world!");

function Errormessage(txt) {
    var elem = $("#message");
    elem.fadeIn("slow");
    // find the span inside the div and assign a text
    elem.children("span").text("your text");

    elem.children("a.close-notify").click(function() {
        elem.fadeOut("slow");
    });
}

Returning a stream from File.OpenRead()

You forgot to seek:

str.CopyTo(data);
data.Seek(0, SeekOrigin.Begin); // <-- missing line
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);

What to put in a python module docstring?

Think about somebody doing help(yourmodule) at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help in terms of amount of information). So if you have in x.py:

"""This module does blah blah."""

class Blah(object):
  """This class does blah blah."""

then:

>>> import x; help(x)

shows:

Help on module x:

NAME
    x - This module does blah blah.

FILE
    /tmp/x.py

CLASSES
    __builtin__.object
        Blah

    class Blah(__builtin__.object)
     |  This class does blah blah.
     |  
     |  Data and other attributes defined here:
     |  
     |  __dict__ = <dictproxy object>
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__ = <attribute '__weakref__' of 'Blah' objects>
     |      list of weak references to the object (if defined)

As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).

I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.

Change color of Back button in navigation bar

If you already have the back button in your "Settings" view controller and you want to change the back button color on the "Payment Information" view controller to something else, you can do it inside "Settings" view controller's prepare for segue like this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if segue.identifier == "YourPaymentInformationSegue"
    {
        //Make the back button for "Payment Information" gray:
        self.navigationItem.backBarButtonItem?.tintColor = UIColor.gray               
    }
}

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;
     position:absolute;
     top:0;
     right:0;
 }

jsFiddle example

TypeError: 'function' object is not subscriptable - Python

It is so simple, you have 2 objects with the same name and when you say: bank_holiday[month] python thinks you wanna run your function and got ERROR.

Just rename your array to bank_holidays <--- add a 's' at the end! like this:

bank_holidays= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   if month <1 or month > 12:
       print("Error: Out of range")
       return
   print(bank_holidays[month-1],"holiday(s) in this month ")

bank_holiday(int(input("Which month would you like to check out: ")))

symfony 2 No route found for "GET /"

I have also tried that error , I got it right by just adding /hello/any name because it is path that there must be an hello/name

example : instead of just putting http://localhost/app_dev.php

put it like this way http://localhost/name_of_your_project/web/app_dev.php/hello/ai

it will display Hello Ai . I hope I answer your question.

CAST to DECIMAL in MySQL

From MySQL docs: Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC:

In standard SQL, the syntax DECIMAL(M) is equivalent to DECIMAL(M,0)

So, you are converting to a number with 2 integer digits and 0 decimal digits. Try this instead:

CAST((COUNT(*) * 1.5) AS DECIMAL(12,2)) 

'git status' shows changed files, but 'git diff' doesn't

TL;DR

Line ending issue:

  1. Change autocrlf setting to default true. I.e., checkout Windows-style line endings on Windows and commit Linux-style line endings on remote git repo:
    git config --global core.autocrlf true
    
  2. On a Windows mahcine, change all files in the repo to Windows-style:
    unix2dos **
    
  3. Git add all modified files and modified files will go:
    git add .
    git status
    

Background

  • Platform: Windows, WSL

I occassionally run into this issue that git status shows I have files modified while git diff shows nothing. This is most likely issue of line endings. I finally figured out how it always happen and share here to see if it can help others.

Root Cause

The reason I encounter this issue often is that I work on a Windows machine and interact with Git in WSL. Switching between linux and Windows setting can easily cause this end-of-line issue. Since line ending format used in OS differs:

  • Windows: \r\n
  • OSX / Linux: \n

Common Practice

When you install Git on your machine, it will ask you to choose line endings setting. Usually, the common practice is to use (commit) Linux-style line endings on your remote git repo and checkout Windows-style on your Windows machine. If you use default setting, this is what git do for you. enter image description here

This means if you have a shell script myScript.sh and bash script myScript.cmd in your repo, the scripts both exist with Linux-style ending in your remote git repo, and both exist with Windows-style ending on your Windows machine.

I used to checkout shell script file and use dos2unix to change the script line-ending in order to run the shell script in WSL. This is why I encounter the issue. Git keeps telling me my modification of line-ending has been changed and asks whether to commit the changes.

Solution

Use default line ending settings and if you change the line endings of some files (like use the dos2unix or dos2unix), drop the changings. If line-endings changes already exist and you would like to get rid of it, try git add them and the changes will go.

PHP : send mail in localhost

It is configured to use localhost:25 for the mail server.

The error message says that it can't connect to localhost:25.

Therefore you have two options:

  1. Install / Properly configure an SMTP server on localhost port 25
  2. Change the configuration to point to some other SMTP server that you can connect to

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

  1. First, let's see what this does:

    Arrays.asList(ia)
    

    It takes an array ia and creates a wrapper that implements List<Integer>, which makes the original array available as a list. Nothing is copied and all, only a single wrapper object is created. Operations on the list wrapper are propagated to the original array. This means that if you shuffle the list wrapper, the original array is shuffled as well, if you overwrite an element, it gets overwritten in the original array, etc. Of course, some List operations aren't allowed on the wrapper, like adding or removing elements from the list, you can only read or overwrite the elements.

    Note that the list wrapper doesn't extend ArrayList - it's a different kind of object. ArrayLists have their own, internal array, in which they store their elements, and are able to resize the internal arrays etc. The wrapper doesn't have its own internal array, it only propagates operations to the array given to it.

  2. On the other hand, if you subsequently create a new array as

    new ArrayList<Integer>(Arrays.asList(ia))
    

    then you create new ArrayList, which is a full, independent copy of the original one. Although here you create the wrapper using Arrays.asList as well, it is used only during the construction of the new ArrayList and is garbage-collected afterwards. The structure of this new ArrayList is completely independent of the original array. It contains the same elements (both the original array and this new ArrayList reference the same integers in memory), but it creates a new, internal array, that holds the references. So when you shuffle it, add, remove elements etc., the original array is unchanged.

How do you find out the caller function in JavaScript?

Try the following code:

function getStackTrace(){
  var f = arguments.callee;
  var ret = [];
  var item = {};
  var iter = 0;

  while ( f = f.caller ){
      // Initialize
    item = {
      name: f.name || null,
      args: [], // Empty array = no arguments passed
      callback: f
    };

      // Function arguments
    if ( f.arguments ){
      for ( iter = 0; iter<f.arguments.length; iter++ ){
        item.args[iter] = f.arguments[iter];
      }
    } else {
      item.args = null; // null = argument listing not supported
    }

    ret.push( item );
  }
  return ret;
}

Worked for me in Firefox-21 and Chromium-25.

Where is the Keytool application?

keytool is a tool to manage (public/private) security keys and certificates and store them in a Java KeyStore file (stored_file_name.jks).
It is provided with any standard JDK/JRE distributions.
You can find it under the following folder %JAVA_HOME%\bin.

How do you test your Request.QueryString[] variables?

Well for one thing use int.TryParse instead...

int id;
if (!int.TryParse(Request.QueryString["id"], out id))
{
    id = -1;
}

That assumes that "not present" should have the same result as "not an integer" of course.

EDIT: In other cases, when you're going to use request parameters as strings anyway, I think it's definitely a good idea to validate that they're present.

How to set an image's width and height without stretching it?

Do I have to add an encapsulating <div> or <span>?

I think you do. The only thing that comes to mind is padding, but for that you would have to know the image's dimensions beforehand.

Check if a value exists in pandas dataframe index

Multi index works a little different from single index. Here are some methods for multi-indexed dataframe.

df = pd.DataFrame({'col1': ['a', 'b','c', 'd'], 'col2': ['X','X','Y', 'Y'], 'col3': [1, 2, 3, 4]}, columns=['col1', 'col2', 'col3'])
df = df.set_index(['col1', 'col2'])

in df.index works for the first level only when checking single index value.

'a' in df.index     # True
'X' in df.index     # False

Check df.index.levels for other levels.

'a' in df.index.levels[0] # True
'X' in df.index.levels[1] # True

Check in df.index for an index combination tuple.

('a', 'X') in df.index  # True
('a', 'Y') in df.index  # False

How to extract filename.tar.gz file

It happens sometimes for the files downloaded with "wget" command. Just 10 minutes ago, I was trying to install something to server from the command screen and the same thing happened. As a solution, I just downloaded the .tar.gz file to my machine from the web then uploaded it to the server via FTP. After that, the "tar" command worked as it was expected.

jQuery issue - #<an Object> has no method

For anyone else arriving at this question:

I was performing the most simple jQuery, trying to hide an element:

('#fileselection').hide();

and I was getting the same type of error, "Uncaught TypeError: Object #fileselection has no method 'hide'

Of course, now it is obvious, but I just left off the jQuery indicator '$'. The code should have been:

$('#fileselection').hide();

This fixes the no-brainer problem. I hope this helps someone save a few minutes debugging!

Mailx send html message

Well, the "-a" mail and mailx in Centos7 is "attach file" not "append header." My shortest path to a solution on Centos7 from here: stackexchange.com

Basically:

yum install mutt
mutt -e 'set content_type=text/html' -s 'My subject' [email protected] < msg.html

Ajax LARAVEL 419 POST error

I received this error when I had a config file with <?php on the second line instead of the first.

Difference between single and double quotes in Bash

Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \ escapes, etc.

Example:

$ echo "$(echo "upg")"
upg
$ echo '$(echo "upg")'
$(echo "upg")

The Bash manual has this to say:

3.1.2.2 Single Quotes

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

3.1.2.3 Double Quotes

Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.

The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

Send file via cURL from form POST in PHP

Here is some production code that sends the file to an ftp (may be a good solution for you):

// This is the entire file that was uploaded to a temp location.
$localFile = $_FILES[$fileKey]['tmp_name']; 

$fp = fopen($localFile, 'r');

// Connecting to website.
$ch = curl_init();

curl_setopt($ch, CURLOPT_USERPWD, "[email protected]:password");
curl_setopt($ch, CURLOPT_URL, 'ftp://@ftp.website.net/audio/' . $strFileName);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 86400); // 1 Day Timeout
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'CURL_callback');
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localFile));
curl_exec ($ch);

if (curl_errno($ch)) {

    $msg = curl_error($ch);
}
else {

    $msg = 'File uploaded successfully.';
}

curl_close ($ch);

$return = array('msg' => $msg);

echo json_encode($return);

How to reload a div without reloading the entire page?

Use this.

$('#mydiv').load(document.URL +  ' #mydiv');

Note, include a space before the hastag.

Find and Replace Inside a Text File from a Bash Command

You can use rpl command. For example you want to change domain name in whole php project.

rpl -ivRpd -x'.php' 'old.domain.name' 'new.domain.name' ./path_to_your_project_folder/  

This is not clear bash of cause, but it's a very quick and usefull. :)

Invoke native date picker from web-app on iOS/Android

You could use Trigger.io's UI module to use the native Android date / time picker with a regular HTML5 input. Doing that does require using the overall framework though (so won't work as a regular mobile web page).

You can see before and after screenshots in this blog post: date time picker

What is the difference between == and equals() in Java?

The difference between == and equals confused me for sometime until I decided to have a closer look at it. Many of them say that for comparing string you should use equals and not ==. Hope in this answer I will be able to say the difference.

The best way to answer this question will be by asking a few questions to yourself. so let's start:

What is the output for the below program:

String mango = "mango";
String mango2 = "mango";
System.out.println(mango != mango2);
System.out.println(mango == mango2);

if you say,

false
true

I will say you are right but why did you say that? and If you say the output is,

true
false

I will say you are wrong but I will still ask you, why you think that is right?

Ok, Let's try to answer this one:

What is the output for the below program:

String mango = "mango";
String mango3 = new String("mango");
System.out.println(mango != mango3);
System.out.println(mango == mango3);

Now If you say,

false
true

I will say you are wrong but why is it wrong now? the correct output for this program is

true
false

Please compare the above program and try to think about it.

Ok. Now this might help (please read this : print the address of object - not possible but still we can use it.)

String mango = "mango";
String mango2 = "mango";
String mango3 = new String("mango");
System.out.println(mango != mango2);
System.out.println(mango == mango2);
System.out.println(mango3 != mango2);
System.out.println(mango3 == mango2);
// mango2 = "mang";
System.out.println(mango+" "+ mango2);
System.out.println(mango != mango2);
System.out.println(mango == mango2);

System.out.println(System.identityHashCode(mango));
System.out.println(System.identityHashCode(mango2));
System.out.println(System.identityHashCode(mango3));

can you just try to think about the output of the last three lines in the code above: for me ideone printed this out (you can check the code here):

false
true
true
false
mango mango
false
true
17225372
17225372
5433634

Oh! Now you see the identityHashCode(mango) is equal to identityHashCode(mango2) But it is not equal to identityHashCode(mango3)

Even though all the string variables - mango, mango2 and mango3 - have the same value, which is "mango", identityHashCode() is still not the same for all.

Now try to uncomment this line // mango2 = "mang"; and run it again this time you will see all three identityHashCode() are different. Hmm that is a helpful hint

we know that if hashcode(x)=N and hashcode(y)=N => x is equal to y

I am not sure how java works internally but I assume this is what happened when I said:

mango = "mango";

java created a string "mango" which was pointed(referenced) by the variable mango something like this

mango ----> "mango"

Now in the next line when I said:

mango2 = "mango";

It actually reused the same string "mango" which looks something like this

mango ----> "mango" <---- mango2

Both mango and mango2 pointing to the same reference Now when I said

mango3 = new String("mango")

It actually created a completely new reference(string) for "mango". which looks something like this,

mango -----> "mango" <------ mango2

mango3 ------> "mango"

and that's why when I put out the values for mango == mango2, it put out true. and when I put out the value for mango3 == mango2, it put out false (even when the values were the same).

and when you uncommented the line // mango2 = "mang"; It actually created a string "mang" which turned our graph like this:

mango ---->"mango"
mango2 ----> "mang"
mango3 -----> "mango"

This is why the identityHashCode is not the same for all.

Hope this helps you guys. Actually, I wanted to generate a test case where == fails and equals() pass. Please feel free to comment and let me know If I am wrong.

Place input box at the center of div

Here's a rather unconventional way of doing it:

#inputcontainer
{
    display:table-cell; //display like a <td> to make the vertical-align work
    text-align:center; //centre the input horizontally
    vertical-align:middle; //centre the input vertically


    width:200px; //widen the div for demo purposes
    height:200px; //make the div taller for demo purposes
    background:green; //change the background of the div for demo purposes
}

It might not be the best way to do it, and margin? won't work, but it does the job. If you need to use margin, then you could wrap the div that displays as a table cell in another 'normal' div.

JSFiddle: http://jsfiddle.net/qw4QW/

Get random integer in range (x, y]?

Just add one to the result. That turns [0, 10) into (0,10] (for integers). [0, 10) is just a more confusing way to say [0, 9], and (0,10] is [1,10] (for integers).

SQL Server: Maximum character length of object names

Yes, it is 128, except for temp tables, whose names can only be up to 116 character long. It is perfectly explained here.

And the verification can be easily made with the following script contained in the blog post before:

DECLARE @i NVARCHAR(800)
SELECT @i = REPLICATE('A', 116)
SELECT @i = 'CREATE TABLE #'+@i+'(i int)'
PRINT @i
EXEC(@i)

How to Navigate from one View Controller to another using Swift

let objViewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.navigationController?.pushViewController(objViewController, animated: true)

Calculating the distance between 2 points

the algorithm : ((x1 - x2) ^ 2 + (y1 - y2) ^ 2) < 25

C# 30 Days From Todays Date

A bit late to this question, but I created a class with all the handy methods needed to create a fully functional time trial in C#. Rather than your application config, I write the expiry time to the Windows Application Data path, and that will also remain persistent even after the program has closed (it's also tricky to find the path for the average user).

Fully documented and simple to use, I hope someone finds it useful!

public class TimeTrialManager
{
    private long expiryTime=0;
    private string softwareName = "";
    private string userPath="";
    private bool useSeconds = false;

    public TimeTrialManager(string softwareName) {
        this.softwareName = softwareName;
        // Create folder in Windows Application Data folder for persistence:
        userPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\" + softwareName + "_prefs\\";
        if (!Directory.Exists(userPath)) Directory.CreateDirectory(Path.GetDirectoryName(userPath));
        userPath += "expiryinfo.txt";
    }

    // Use this method to check if the expiry has already been created. If
    // it has, you don't need to call the setExpiryDate() method ever again.
    public bool expiryHasBeenStored(){
        return File.Exists(userPath);
    }

    // Use this to set expiry as the number of days from the current time.
    // This should be called just once in the program's lifetime for that user.
    public void setExpiryDate(double days)  {
        DateTime time = DateTime.Now.AddDays(days);
        expiryTime = time.ToFileTimeUtc();
        storeExpiry(expiryTime.ToString() );
        useSeconds = false;
    }

    // Like above, but set the number of seconds. This should be just used for testing
    // as no sensible time trial would allow the user seconds to test the trial out:
    public void setExpiryTime(double seconds)   {
        DateTime time = DateTime.Now.AddSeconds(seconds);
        expiryTime = time.ToFileTimeUtc();
        storeExpiry(expiryTime.ToString());
        useSeconds = true;
    }

    // Check for this in a background timer or whenever else you wish to check if the time has run out
    public bool trialHasExpired()   {
        if(!File.Exists(userPath)) return false;
        if (expiryTime == 0)    expiryTime = Convert.ToInt64(File.ReadAllText(userPath));
        if (DateTime.Now.ToFileTimeUtc() >= expiryTime) return true; else return false;
    }

    // This method is optional and isn't required to use the core functionality of the class
    // Perhaps use it to tell the user how long he has left to trial the software
    public string expiryAsHumanReadableString(bool remaining=false) {
        DateTime dt = new DateTime();
        dt = DateTime.FromFileTimeUtc(expiryTime);
        if (remaining == false) return dt.ToShortDateString() + " " + dt.ToLongTimeString();
        else {
            if (useSeconds) return dt.Subtract(DateTime.Now).TotalSeconds.ToString();
            else return (dt.Subtract(DateTime.Now).TotalDays ).ToString();
        }
    }

    // This method is private to the class, so no need to worry about it
    private void storeExpiry(string value)  {
        try { File.WriteAllText(userPath, value); }
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }

}

Here is a typical usage of the above class. Couldn't be simpler!

TimeTrialManager ttm;
private void Form1_Load(object sender, EventArgs e)
{
    ttm = new TimeTrialManager("TestTime");
    if (!ttm.expiryHasBeenStored()) ttm.setExpiryDate(30); // Expires in 30 days time
}

private void timer1_Tick(object sender, EventArgs e)
{
    if (ttm.trialHasExpired()) { MessageBox.Show("Trial over! :("); Environment.Exit(0); }
}

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

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

{ "error_message" : "This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console: Learn more: https://code.google.com/apis/console", "results" : [], "status" : "REQUEST_DENIED" }

Enabling Directions API made me this error fixed

https://console.developers.google.com/apis/library/directions-backend.googleapis.com

https://console.developers.google.com/apis/library/directions-backend.googleapis.com

pointer to array c++

The parenthesis are superfluous in your example. The pointer doesn't care whether there's an array involved - it only knows that its pointing to an int

  int g[] = {9,8};
  int (*j) = g;

could also be rewritten as

  int g[] = {9,8};
  int *j = g;

which could also be rewritten as

  int g[] = {9,8};
  int *j = &g[0];

a pointer-to-an-array would look like

  int g[] = {9,8};
  int (*j)[2] = &g;

  //Dereference 'j' and access array element zero
  int n = (*j)[0];

There's a good read on pointer declarations (and how to grok them) at this link here: http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations

Where can I find MySQL logs in phpMyAdmin?

In phpMyAdmin 4.0, you go to Status > Monitor. In there you can enable the slow query log and general log, see a live monitor, select a portion of the graph, see the related queries and analyse them.

SQL Server query - Selecting COUNT(*) with DISTINCT

You have to create a derived table for the distinct columns and then query the count from that table:

SELECT COUNT(*) 
FROM (SELECT DISTINCT column1,column2
      FROM  tablename  
      WHERE condition ) as dt

Here dt is a derived table.

Convert a float64 to an int in Go

Correct rounding is likely desired.

Therefore math.Round() is your quick(!) friend. Approaches with fmt.Sprintf and strconv.Atois() were 2 orders of magnitude slower according to my tests with a matrix of float64 values that were intended to become correctly rounded int values.

package main
import (
    "fmt"
    "math"
)
func main() {
    var x float64 = 5.51
    var y float64 = 5.50
    var z float64 = 5.49
    fmt.Println(int(math.Round(x)))  // outputs "6"
    fmt.Println(int(math.Round(y)))  // outputs "6"
    fmt.Println(int(math.Round(z)))  // outputs "5"
}

math.Round() does return a float64 value but with int() applied afterwards, I couldn't find any mismatches so far.

MySQL: What's the difference between float and double?

Float has 32 bit (4 bytes) with 8 places accuracy. Double has 64 bit (8 bytes) with 16 places accuracy.

If you need better accuracy, use Double instead of Float.

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

It's because the virtual environment viarable has not been installed.

Try this:

sudo pip install virtualenv
virtualenv --python python3 env
source env/bin/activate
pip install <Package>

or

sudo pip3 install virtualenv
virtualenv --python python3 env
source env/bin/activate
pip3 install <Package>

How to search a specific value in all tables (PostgreSQL)?

Here's @Daniel Vérité's function with progress reporting functionality. It reports progress in three ways:

  1. by RAISE NOTICE;
  2. by decreasing value of supplied {progress_seq} sequence from {total number of colums to search in} down to 0;
  3. by writing the progress along with found tables into text file, located in c:\windows\temp\{progress_seq}.txt.

_

CREATE OR REPLACE FUNCTION search_columns(
    needle text,
    haystack_tables name[] default '{}',
    haystack_schema name[] default '{public}',
    progress_seq text default NULL
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
DECLARE
currenttable text;
columnscount integer;
foundintables text[];
foundincolumns text[];
begin
currenttable='';
columnscount = (SELECT count(1)
      FROM information_schema.columns c
      JOIN information_schema.tables t ON
        (t.table_name=c.table_name AND t.table_schema=c.table_schema)
      WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
        AND c.table_schema=ANY(haystack_schema)
        AND t.table_type='BASE TABLE')::integer;
PERFORM setval(progress_seq::regclass, columnscount);

  FOR schemaname,tablename,columnname IN
      SELECT c.table_schema,c.table_name,c.column_name
      FROM information_schema.columns c
      JOIN information_schema.tables t ON
        (t.table_name=c.table_name AND t.table_schema=c.table_schema)
      WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
        AND c.table_schema=ANY(haystack_schema)
        AND t.table_type='BASE TABLE'
  LOOP
    EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
       schemaname,
       tablename,
       columnname,
       needle
    ) INTO rowctid;
    IF rowctid is not null THEN
      RETURN NEXT;
      foundintables = foundintables || tablename;
      foundincolumns = foundincolumns || columnname;
      RAISE NOTICE 'FOUND! %, %, %, %', schemaname,tablename,columnname, rowctid;
    END IF;
         IF (progress_seq IS NOT NULL) THEN 
        PERFORM nextval(progress_seq::regclass);
    END IF;
    IF(currenttable<>tablename) THEN  
    currenttable=tablename;
     IF (progress_seq IS NOT NULL) THEN 
        RAISE NOTICE 'Columns left to look in: %; looking in table: %', currval(progress_seq::regclass), tablename;
        EXECUTE 'COPY (SELECT unnest(string_to_array(''Current table (column ' || columnscount-currval(progress_seq::regclass) || ' of ' || columnscount || '): ' || tablename || '\n\nFound in tables/columns:\n' || COALESCE(
        (SELECT string_agg(c1 || '/' || c2, '\n') FROM (SELECT unnest(foundintables) AS c1,unnest(foundincolumns) AS c2) AS t1)
        , '') || ''',''\n''))) TO ''c:\WINDOWS\temp\' || progress_seq || '.txt''';
    END IF;
    END IF;
 END LOOP;
END;
$$ language plpgsql;

What is difference between png8 and png24

You have asked two questions, one in the title about the difference between PNG8 and PNG24, which has received a few answers, namely that PNG24 has 8-bit red, green, and blue channels, and PNG-8 has a single 8-bit index into a palette. Naturally, PNG24 usually has a larger filesize than PNG8. Furthermore, PNG8 usually means that it is opaque or has only binary transparency (like GIF); it's defined that way in ImageMagick/GraphicsMagick.

This is an answer to the other one, "I would like to know that if I use either type in my html page, will there be any error? Or is this only quality matter?"

You can put either type on an HTML page and no, this won't cause an error; the files should all be named with the ".png" extension and referred to that way in your HTML. Years ago, early versions of Internet Explorer would not handle PNG with an alpha channel (PNG32) or indexed-color PNG with translucent pixels properly, so it was useful to convert such images to PNG8 (indexed-color with binary transparency conveyed via a PNG tRNS chunk) -- but still use the .png extension, to be sure they would display properly on IE. I think PNG24 was always OK on Internet Explorer because PNG24 is either opaque or has GIF-like single-color transparency conveyed via a PNG tRNS chunk.

The names PNG8 and PNG24 aren't mentioned in the PNG specification, which simply calls them all "PNG". Other names, invented by others, include

  • PNG8 or PNG-8 (indexed-color with 8-bit samples, usually means opaque or with GIF-like, binary transparency, but sometimes includes translucency)
  • PNG24 or PNG-24 (RGB with 8-bit samples, may have GIF-like transparency via tRNS)
  • PNG32 (RGBA with 8-bit samples, opaque, transparent, or translucent)
  • PNG48 (Like PNG24 but with 16-bit R,G,B samples)
  • PNG64 (like PNG32 but with 16-bit R,G,B,A samples)

There are many more possible combinations including grayscale with 1, 2, 4, 8, or 16-bit samples and indexed PNG with 1, 2, or 4-bit samples (and any of those with transparent or translucent pixels), but those don't have special names.

OnItemClickListener using ArrayAdapter for ListView

i'm using arrayadpter ,using this follwed code i'm able to get items

String value = (String)adapter.getItemAtPosition(position);

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
             String string=adapter.getItem(position);
             Log.d("**********", string);

        }
    });

git still shows files as modified after adding to .gitignore

The solutions offered here and in other places didn't work for me, so I'll add to the discussion for future readers. I admittedly don't fully understand the procedure yet, but have finally solved my (similar) problem and want to share.

I had accidentally cached some doc-directories with several hundred files when working with git in IntelliJ IDEA on Windows 10, and after adding them to .gitignore (and PROBABLY moving them around a bit) I couldn't get them removed from the Default Changelist.

I first commited the actual changes I had made, then went about solving this - took me far too long. I tried git rm -r --cached . but would always get path-spec ERRORS, with different variations of the path-spec as well as with the -f and -r flags.

git status would still show the filenames, so I tried using some of those verbatim with git rm -cached, but no luck. Stashing and unstashing the changes seemed to work, but they got queued again after a time (I'm a bity hazy on the exact timeframe). I have finally removed these entries for good using

git reset

I assume this is only a GOOD IDEA when you have no changes staged/cached that you actually want to commit.

How would you make a comma-separated string from a list of strings?

Here is an example with list

>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [i[0] for i in myList])) 
>>> print "Output:", myList
Output: Apple,Orange

More Accurate:-

>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList])) 
>>> print "Output:", myList
Output: Apple,Orange

Example 2:-

myList = ['Apple','Orange']
myList = ','.join(map(str, myList)) 
print "Output:", myList
Output: Apple,Orange

Wait until a process ends

You could use wait for exit or you can catch the HasExited property and update your UI to keep the user "informed" (expectation management):

System.Diagnostics.Process process = System.Diagnostics.Process.Start("cmd.exe");
while (!process.HasExited)
{
    //update UI
}
//done

Histogram using gnuplot?

I have found this discussion extremely useful, but I have experienced some "rounding off" problems.

More precisely, using a binwidth of 0.05, I have noticed that, with the techniques presented here above, data points which read 0.1 and 0.15 fall in the same bin. This (obviously unwanted behaviour) is most likely due to the "floor" function.

Hereafter is my small contribution to try to circumvent this.

bin(x,width,n)=x<=n*width? width*(n-1) + 0.5*binwidth:bin(x,width,n+1)
binwidth = 0.05
set boxwidth binwidth
plot "data.dat" u (bin($1,binwidth,1)):(1.0) smooth freq with boxes

This recursive method is for x >=0; one could generalise this with more conditional statements to obtain something even more general.

How can I create a product key for my C# application?

Who do you trust?

I've always considered this area too critical to trust a third party to manage the runtime security of your application. Once that component is cracked for one application, it's cracked for all applications. It happened to Discreet in five minutes once they went with a third-party license solution for 3ds Max years ago... Good times!

Seriously, consider rolling your own for having complete control over your algorithm. If you do, consider using components in your key along the lines of:

  • License Name - the name of client (if any) you're licensing. Useful for managing company deployments - make them feel special to have a "personalised" name in the license information you supply them.
  • Date of license expiry
  • Number of users to run under the same license. This assumes you have a way of tracking running instances across a site, in a server-ish way
  • Feature codes - to let you use the same licensing system across multiple features, and across multiple products. Of course if it's cracked for one product it's cracked for all.

Then checksum the hell out of them and add whatever (reversable) encryption you want to it to make it harder to crack.

To make a trial license key, simply have set values for the above values that translate as "trial mode".

And since this is now probably the most important code in your application/company, on top of/instead of obfuscation consider putting the decrypt routines in a native DLL file and simply P/Invoke to it.

Several companies I've worked for have adopted generalised approaches for this with great success. Or maybe the products weren't worth cracking ;)

How can I access each element of a pair in a pair list?

When you say pair[0], that gives you ("a", 1). The thing in parentheses is a tuple, which, like a list, is a type of collection. So you can access the first element of that thing by specifying [0] or [1] after its name. So all you have to do to get the first element of the first element of pair is say pair[0][0]. Or if you want the second element of the third element, it's pair[2][1].

Loop through a date range with JavaScript

If startDate and endDate are indeed date objects you could convert them to number of milliseconds since midnight Jan 1, 1970, like this:

var startTime = startDate.getTime(), endTime = endDate.getTime();

Then you could loop from one to another incrementing loopTime by 86400000 (1000*60*60*24) - number of milliseconds in one day:

for(loopTime = startTime; loopTime < endTime; loopTime += 86400000)
{
    var loopDay=new Date(loopTime)
    //use loopDay as you wish
}