Selection sort algorithm examination I had an algorithm test.

I was asked Selection sort algorithm to program.

I coded it in javascript and shown to examiner.

But he was not satisfied, he said its too complicated.

I think I have written correctly.

this is the code below,

function selectionSort(inputArray){
  var swapElementIndex = 0;
  var shouldSwap = false;
  var temp = 0;
  var minNum = 0;
  for(var i = 0;i < (inputArray.length - 1);i++){
    minNum = 0;
    for(var currentIndex = (i+1); currentIndex < inputArray.length; currentIndex++){

        if(inputArray[i] > inputArray[currentIndex]){
            if(minNum === 0){ // when first minimum element is found
                swapElementIndex = currentIndex;
                shouldSwap = true;
                minNum = inputArray[swapElementIndex];
            }else{// when we have an minimum element

                /* further check whether min element is less than the new found [min] element,
                   if yes set it as min element.
                */
                if(minNum > inputArray[currentIndex]){
                    minNum = inputArray[currentIndex];
                    swapElementIndex = currentIndex;
                    shouldSwap = true;
                    minNum = inputArray[swapElementIndex];
                }
            }
        }
    }

    if(shouldSwap === true){
        temp = inputArray[i];
        inputArray[i] = inputArray[swapElementIndex];
        inputArray[swapElementIndex] = temp;
        shouldSwap = false;
    }
  }

  return inputArray;
}

console.log(selectionSort([1,31,26,4,3,12]));
console.log(selectionSort([5,6,1,2,3,4]));

The output when I run is as follows,

rahul@rahul:~/myPractise/Algo$ node sorting.js
[ 1, 3, 4, 12, 26, 31 ]
[ 1, 2, 3, 4, 5, 6 ]
rahul@rahul:~/myPractise/Algo$

So you can see that its working fine.

Please tell me how can I improve my code

Yes, it could be simpler.

Special case for first value is not needed.
Some variables could be removed.
All variables initialization could be removed.

Below, you can see your code reviewed.

    function selectionSort(inputArray) {
      for (var i = 0; i < (inputArray.length - 1); i++) {
         var minNum = inputArray[i];
         var swapElementIndex = i;
         for (var currentIndex = i + 1; currentIndex < inputArray.length; currentIndex++) {
            if (inputArray[currentIndex] < minNum) {
                swapElementIndex = currentIndex;
                minNum = inputArray[swapElementIndex];
            }
        }
        if (i != swapElementIndex) {
            var temp = inputArray[i];
            inputArray[i] = inputArray[swapElementIndex];
            inputArray[swapElementIndex] = temp;
        }
     }
     return inputArray;
    }


C Socket API Call with Swift I have a small function in Objective-C which uses the C Socket API to check if the device has an active internet connection:

#include <netdb.h>

- (BOOL)isNetworkAvailable {
    char *hostname;
    struct hostent *hostinfo;
    hostname = "youtube.com";
    hostinfo = gethostbyname(hostname);
    if (hostinfo == NULL) {
        return NO;
    } else {
        return YES;
    }
}

I have rewritten this function in Swift, using an UnsafeMutablePointer type for the hostent struct:

func isNetworkAvailable() -> Bool {
    var hostinfo: UnsafeMutablePointer<hostent>
    let hostString: String = "youtube.com"
    var hostname = (hostString.cStringUsingEncoding(NSUTF8StringEncoding))!
    hostinfo = gethostbyname(hostname)
    if (hostinfo == nil) {
        hostinfo.destroy()
        return false
    } else {
        hostinfo.destroy()
        return true
    }
}

Is there a better way to check for network connectivity in Swift without using the C API?  How can I improve this function, possibly removing the need to manually retain and release an UnsafeMutablePointer?

Wrong memory management

gethostbyname() returns a pointer to an internal structure. You don't
have initialized that memory and don't own it, therefore you must not
call destroy().

Things that can be improved

var hostinfo: UnsafeMutablePointer<hostent>
// ...
hostinfo = gethostbyname(...)

can be combined to

let hostinfo = gethostbyname(...)

There is no need to declare the variable in advance, and the type
can be inferred automatically. Also you can define it as a constant
with let because it is not modified subsequently.

let hostString: String = "youtube.com"
var hostname = (hostString.cStringUsingEncoding(NSUTF8StringEncoding))!
let hostinfo = gethostbyname(hostname)

can be simplified to

let hostname = "youtube.com"
let hostinfo = gethostbyname(hostname)

because a Swift string is automatically converted to a C string when
passed to a C API taking a const char * parameter.

Finally, since the destroy() has been removed,

if (hostinfo == nil) {
    return false
} else {
    return true
}

can be simplified to

return hostinfo != nil

So your function is now

func isNetworkAvailable() -> Bool {
    let hostname = "youtube.com"
    let hostinfo = gethostbyname(hostname)
    return hostinfo != nil
}

BUT: This does not what you expect it to do!

gethostbyname() "only" resolves a host name to an IP address.
That does not necessarily involve any network communication, as
the local DNS resolver might have cached the information.

Better: Use the SCNetworkReachability framework.

From the documentation:

  The SCNetworkReachability programming interface allows an application
  to determine the status of a system's current network configuration
  and the reachability of a target host. A remote host is considered
  reachable when a data packet, sent by an application into the network
  stack, can leave the local device. Reachability does not guarantee
  that the data packet will actually be received by the host.

Other Resources:

Apple provides Objective-C sample code at https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html
A Swift wrapper can be found here: https://github.com/ashleymills/Reachability.swift
And perhaps you can use the code from https://stackoverflow.com/questions/25623272/working-with-c-structs-in-swift.


Last five non-zero digits of a factorial in base b This HackerRank problem (based on Project Euler problem 160) says:

  For any \$n\$, let \$f_b(n)\$ be the last five digits before the trailing zeroes in \$n!\$ written in base \$b\$.

  For example,

  \$9! = 362880\$ so \$f_{10}(9)=36288\$
  \$10! = 3628800\$ so \$f_{10}(10)=36288\$
  \$20! = 2432902008176640000\$ so \$f_{10}(20)=17664\$

  Input format

  First line of each file contains two numbers: \$b\$ (base) and \$q\$ (number of queries). \$q\$ lines follow, each with an integer \$n\$ written in base \$b\$.

  Constraints

  \$2 \le b \le 36\$
  \$1 \le q \le 10^5\$
  \$0 \le n \le 10^{18}\$
  Every character in \$n\$ is a valid digit in base \$b\$ (0-9, A-Z for values \$>9\$)

  Output Format

  Output \$q\$ lines. On each line print exactly 5 digits in base \$b\$ - the answer to the \$i\$-th query. If for some \$n\$, \$n!\$ contains fewer than 5 digits, put the corresponding number of leading zeroes before the answer.

I believe the code works:

def treeFactor(low, high):
    if low + 1 < high:
        mid = (high+low) // 2
        return treeFactor(low, mid) * treeFactor(mid + 1, high)
    if low == high:
        return low
    return low * high

def convert(num,b,numerals="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
    return ((num == 0) and numerals[0]) or (convert(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])

def removeZ(ans):
    while ans[-1] == "0":
        ans = ans[:-1]
    return ans[-5:]

b, q = raw_input().split(" ")
b = int(b)
q = int(q)

for _ in xrange(q):
    ans = int(str(raw_input()), 10)
    if ans < 2:
        print "1"
    else:
        ans = treeFactor(1, ans)
        ans = convert(ans, b)
        ans = removeZ(ans)
        k = len(ans)
        if k < 5:
            ans = (5 - k * "0").join(ans)
        print ans

However, it doesn't run fast enough to pass the tests. I changed the factorial method and tried to cut down on str() conversions, using xrange() and so on, but it still isn't efficient enough. Can you see any bottlenecks, or methods that could be improved further (without the use of specialist packages like NumPy).

(on a slight side note, would it be possible to perform the factorial method on numbers without converting them to base 10, while maintaining efficiency?)

Note that the constraint in this problem is \$n \leq 10^{18}\$. In other words, the factorials you are calculating can be as large as \$10^{18}!\approx 10^{1.7\cdot 10^{18}}\$. In other words, if you aren't running into a time limit, you will most likely run into a memory limit.

Your function treeFactor calculates:

\$10000!\$ in 0.06 seconds
\$100000!\$ in 2.57 seconds
\$200000!\$ in 9.34 seconds
\$400000!\$ in 29.73 seconds
\$1000000!\$ in 129.58 seconds

In other words, even \$1000000!\$ can't be calculated within the time limit. Futher, \$(10^7)!\$ will probably take at least an hour, \$(10^8)!\$ will probably take several days. Even with a lot of optimizations to calculating factorials, it isn't going to make it, unfortunately. Further, I can't think of a faster method now (I tried a few things, but I got recursion limit exceeded).

For this problem, you only need the last five non-zero digits. For this, you'll need to do a few things with modular arithmetic. Only read the text under the spoiler if you want more hints.

   For example, create an array with the five last non-zero digits. Take away all factors that cause a factor of the base \$b\$. Also, note that multiplying by a number larger than \$10^5\$ is the same as multiplying by the same number modulo \$10^5\$.

I will not write the solution for you. This problem is quite hard - considering that only four people solved it out of over a hundred attempts. I do not know whether this solution is fast enough (also because there is no time limit specified, and because I didn't code it), but it should at least run within a couple of minutes, if you optimalize enough. The calculation of \$10^{18}!\$ can't be done with any method in any reasonable time.


Nicely tabulate a list of strings for printing I have a list of strings of variable lengths, and I want to pretty-print them so they are lining up in columns.  I have the following code, which works as I want it to currently, but I feel it is a bit ugly.  How can I simplify it/make it more pythonic (without changing the output behaviour)?

For starters I think I could probably use the alignment '<' option of the str.format stuff if I could just figure out the syntax properly...

def tabulate(words, termwidth=79, pad=3):
  width = len(max(words, key=len))
  ncols = max(1, termwidth // (width + pad))
  nrows = len(words) // ncols + (1 if len(words) % ncols else 0)
  #import itertools
  #table = list(itertools.izip_longest(*[iter(words)]*ncols, fillvalue=''))  # row-major
  table = [words[i::nrows] for i in xrange(nrows)]                          # column-major
  return '\n'.join(''.join((' '*pad + x.ljust(width) for x in r)) for r in table)

A slightly more readable version:

def tabulate(words, termwidth=79, pad=3):
    width = len(max(words, key=len)) + pad
    ncols = max(1, termwidth // width)
    nrows = (len(words) - 1) // ncols + 1
    table = []
    for i in xrange(nrows):
        row = words[i::nrows]
        format_str = ('%%-%ds' % width) * len(row)
        table.append(format_str % tuple(row))
    return '\n'.join(table)

Most notably, I've defined width to include padding and using string formatting to generate a format string to format each row ;).


Review of singlely linked list C I posted a couple of weeks ago with a double linked list.  It was recommended that I rewrite the code as a singlely linked list and replace the recursive parts with loops.

I've gone ahead and made several edits and was hoping to get another critique of the code.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct file {
    int fd;
    struct file *next;
};

struct file *create_head(void) {
    struct file *first_link = malloc ( sizeof *first_link );
    return first_link;
}

void insert(struct file *node, int val) {
    while (node->next != NULL) {
        node = node->next;
    }
    struct file *tail = malloc ( sizeof *tail );
    node->next = tail;
    tail->fd = val;
    tail->next = NULL;
}

int delete(struct file *node, int val) {
    struct file *prev;
    while (node->fd != val) {
        if(!(node->next)) {
            return 1;
        }
        else {
            prev = node;
            node = node->next;
        }
    }
    prev->next = node->next;
    free(node);
    return 0;
}

int locate(struct file *node, int val) {
    while (node->fd != val) {
        if (!(node->next)) {
            return 1;
        }
        else {
            node = node->next;
        }
    }
    printf ("Value %d in list\n", val);
    return 0;
}

void dump(struct file *node) {
    while (node->next) {
        printf ("Node: %d\n", node->fd);
        node = node->next;
    }
    printf ("Node: %d\n", node->fd);
}

int get_choice(void) {
    int choice;
    int val;
    struct file *head = NULL;
    while ( true ) {
        printf ("\n[Choices - Insert=1, Delete=2, Locate=3, Dump=4, Exit=5]\n");
        printf ("\nEnter selection: ");
        scanf("%d", &choice);
        switch (choice) {
            case (1):
                printf ("Enter value: ");
                scanf ("%d", &val);
                if (!(head)) {
                    head = create_head();
                    head->fd = val;
                    head->next = NULL;
                }
                else {
                    insert(head, val);
                }
                break;
            case (2):
                if (head) {
                    printf ("Enter value: ");
                    scanf ("%d", &val);
                    if (head->fd == val && head->next == NULL) {
                        head = NULL;
                    }
                    else if (head->fd == val && head->next != NULL) {
                        free (head);
                        head = head->next;
                    }
                    else if (delete(head, val) == 1) {
                        printf ("Value %d not in list\n", val);
                    }
                }
                else {
                    printf ("List is empty!\n");
                }
                break;
            case (3):
                if (head) {
                    printf ("Enter value: ");
                    scanf ("%d", &val);
                    if (locate(head, val) == 1) {
                        printf ("Value %d not in list\n", val);
                    }
                }
                else {
                    printf ("List is empty!\n");
                }
                break;
            case (4):
                if (head) {
                    dump(head);
                }
                else {
                    printf ("Nothing to dump!\n");
                }
                break;
            case (5):
            return 0;
        }
    }
}

int main(void) {
    printf ("\nSingle Linked List: \n");
    get_choice();
    return 0;
}

Stylistic/Function

Your list holds values of type int yet you named the node type very specific in relation to file descriptors which will be a bit weird if you make a list of lets say prime numbers you want to operate on. Consider renaming your node type to something more generic rather than file (especially sincere there is a FILE type in <stdio.h>)
Your insert method actually doesn't insert an element, it appends it to the end so it should be named append.
delete doesn't work when the node you want to delete is head. I know you handle that case separately in get_choice but it's still bad that the caller has to know that fact. It also clutters the code with lots of special handling.
dump is a bit weird: It skips the first one, then prints all following nodes in order and then prints the first one. So while it prints out all nodes I'd say it's still unexpected from a usage point of view.
None of your methods can deal with the fact if NULL is being passed in.
If you typedef your structs then you can save some typing work.

Structural/Design

Your list does not have a nice API to use. You can see that in get_choice which is cluttered with handling of many special cases.
Some methods like insert (size/length would be a different candidate) are inefficient as you have to iterate the entire list first. You could avoid that by keeping a separate tail pointer.

I suggest you create a list object which holds head, tail and possibly length of the list and all your methods should operate on an object of that list type rather than nodes. Something along these lines:

typedef struct node_
{
    int value;
    struct node *next;
} node;

typedef struct list_
{
    struct node *head;
    struct node *tail;
    int length;
} list;

And then define some methods to operate on:

// creates a new empty list
list *new_list()
{
}

// deletes the list and all the nodes
void delete_list(list *l)
{
}

// appends new value to the list
void append(list *l, int value)
{
}

// insert a value at a given position
void insert(list *l, int value, int position)
{
}

// deletes the first node with the given value from the list
// return 1 if node found and deleted, 0 otherwise
int delete_item(list *l, int value)
{
}

// returns the first node with the given value or NULL if not found
node *find(list *l, int value)
{
}

// prints the content of the list
void print_list(list *l)
{
}

Your get_choice method would then look like this:

int get_choice(void) {
    int choice;
    int val;
    list *myList = new_list();
    while ( true ) {
        printf ("\n[Choices - Insert=1, Delete=2, Locate=3, Dump=4, Exit=5]\n");
        printf ("\nEnter selection: ");
        scanf("%d", &choice);
        switch (choice) {
            case (1):
                printf ("Enter value: ");
                scanf ("%d", &val);
                append(myList, val);
                break;
            case (2):
                if (myList->length > 0) {
                    printf ("Enter value: ");
                    scanf ("%d", &val);
                    if (!delete_item(myList, val))
                    {
                        printf ("Value %d not in list\n", val);
                    }
                }
                else {
                    printf ("List is empty!\n");
                }
                break;
            case (3):
                if (myList->length > 0) {
                    printf ("Enter value: ");
                    scanf ("%d", &val);
                    if (find(myList, val) == NULL) {
                        printf ("Value %d not in list\n", val);
                    }
                }
                else {
                    printf ("List is empty!\n");
                }
                break;
            case (4):
                if (myList->length > 0) {
                    print_list(myList);
                }
                else {
                    printf ("Nothing to dump!\n");
                }
                break;
            case (5):
            return 0;
        }
    }
}


Finding the percentage of even numbers in an array I wrote a method which computes the ratio of even to odd numbers in an array. I know it's a simple piece of code, but I wanted to see if you have any feedback for improving it.

public double percentEven(int[] a) {
if(a.length <= 1) {
    return 0.0;
}
double even = 0.0;
for(int i = 0; i < a.length; i++) {
    if(a[i] % 2 == 0) {
        even++;
    }
}
return (double) (even / a.length) * 100;
}

If the array contains zero elements, or zero even elements, return 0.

Potential bug: What if the array contains a single element, and it is even?

if(a.length <= 1) {
    return 0.0;
}

That's what happens.

Easy fix, change to:

if(a.length == 0) {

Your indentation is slightly screwed up, but that might just be a copy-paste error.

double even should be int even.

You could use a for-each loop,

for (int i : a) {
    if(i % 2 == 0) {

int[] a could be named int[] array or int[] values or int[] input.

When using even as an int, use the following return statement to cast only even to a double, which will then make it use double division and not int division:

return (double) even / a.length * 100;

Alternatively you could use:

return even * 100.0 / a.length;

But I think return (double) even / a.length * 100; is better.


Beheading of knights, who survives? We have a round table of n knights, where n is some positive
  integer. These have failed to satisfy the expectations of the mad king
  and are sentenced to death. However as an act of mercy he goes around
  the table killing every other knight (starting with the second)
  until only one knight remains.

  The question is: which seat do you need to pick to survive?

I wrote the primitive code below to tackle this problem:

while True:
    temp_num = input("Enter the number of knights: ")
    try:
        temp_num = int(temp_num)
        if temp_num <= 0:  # if not a positive int print message and ask for input again
            print("Sorry, the number of knights must be a positive integer, try again")
        else:
            knights_num = temp_num
            break
    except ValueError:
        print("That's not an integer!")
# else all is good, val is >=  0 and an integer

# Create a table of knights and a temp table
knights_table = [i for i in range(1,knights_num+1)]
knights_temp_table = list(knights_table)

i = 1
while len(knights_temp_table)>1:
# print("Knights =",knights_temp_table , "(",knights_temp_table[i],")")
    knights_temp_table.pop(i)
    i = (i+1)%len(knights_temp_table)
print( "The knight who survived was no.",knights_temp_table[0] )

The code runs fine and outputs the expected values n=60> 57 and n=16 > 1
However from the code it is not clear why it works. So i had some questions below

Could the table of knights be made using a generator?
Is a code using try knights_temp_table[i+1] and knights_temp_table[i+2] and then iterating over the list for the exceptions clearer?
Could one implement a linked list to make the code clearer instead of modulo?

I know the code is very simple and the problem I solved almost trivial. However any suggestions is much appreaciated since I am a semi-begginer / novice at python.
 * Are there any other general suggestions to improve the code, or running speed?

Those poor knights.... what did they do to deserve that?

But, there is a mathematical treat that allows this problem to be solved in O(1) time, and space.

What does that mean? Well, it means that solving the problem for 1 knight takes just as long (and just as much memory) as solving it for 10, or 1000, or 1000000000000000 knights. How is this possible?

There's a pattern that emerges when you study this problem. If there is 1 knight, then knight 1 survives. If there's 2, then knight 1 survives, and, if we map this out for say the first 32 knights, we get:

1 -> 1
2 -> 1
3 -> 3
4 -> 1
5 -> 3
6 -> 5
7 -> 7
8 -> 1
9 -> 3
10 -> 5
11 -> 7
12 -> 9
13 -> 11
14 -> 13
15 -> 15
16 -> 1
17 -> 3
18 -> 5
19 -> 7
20 -> 9
21 -> 11
22 -> 13
23 -> 15
24 -> 17
25 -> 19
26 -> 21
27 -> 23
28 -> 25
29 -> 27
30 -> 29
31 -> 31
32 -> 1

Note that, at the powers-of-2, the surviving knight skips back to knight 1. Also, between the powers, the surviving knight increments by 2 (and is always odd).

The pattern is also easy to enumerate - find the largest power of 2 that's less than (or equal to) the count. Find how many knights there are after that power, double it, and add one.

It would look like this:

import math

def low_power(input):
    return 1 << int(math.floor(math.log(input, 2)))

def survivor(count):
    return 1 + 2 * (count - low_power(count))

So, calling survivor(16) will return 1. survivor(60) returns 57.

But, you can do crazy numbers now too, like survivor(98765432123456789) is 53415676171057707

See this code running on ideone: Knights

Note that you have now confirmed you are using Python 3.4. Python 3.1 introduced the bit_length() method. This makes the determination of the power much easier (from a programming perspective - bitlength can be thought of as an implementation of the log2):

def low_power(input):
    return 1 << (input.bit_length() - 1)

The same code running bit_length in python 3 is shown here in ideone (also contains correct parenthesis for python 3 print statements).


Using Task.Run(..) in a .NET property Summary

I have a normal class which has a normal property but that property has access to an async backing field.

I'm not sure if this is the best/acceptable way to access the asyc method for this backing field.

Details

I've got a C# library that helps testing the .NET HttpClient class.

This class has a property public HttpContent HttpContent which is access two private backing fields which some code uses later on.

One of these private backing fields is populated via an async method. This, being a property, isn't async.

When the value of this property is set, I extract the actual string content from it by calling the method _httpContent.ReadAsStringAsync() and also remember a reference to this instance via a class-global variable.

The actual code in question is this

private string _httpContentSerialized;

....

_httpContentSerialized = _httpContent == null
    ? "*"
    : Task.Run(_httpContent.ReadAsStringAsync).Result;

As such, I'm not sure if the code I have (which seems to work, mind you) is the best way to do this and I'm hoping someone can review this (as opposed to asking on SO for a 'how to do this' answer).

Extra Info to consider:

Being a library I have no idea how/where my library will be consumed/used:

A console app?
An ASP.NET app?

With this in mind, I'm not sure if the code I have written is acceptable and won't cause deadlocks for a .NET application.

Other suggestions have been to use _httpContent.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();

Here's some more of the code:

public class HttpMessageOption
{
    private HttpContent _httpContent;
    private string _httpContentSerialized;

    public HttpContent HttpContent
    {
        get { return _httpContent; }
        set
        {
            _httpContent = value;
            _httpContentSerialized = _httpContent == null
                ? "*"
                : Task.Run(_httpContent.ReadAsStringAsync).Result;
        }
    }
}

You have just literally lost the async part of your ReadAsStringAsync method. By calling the Result property of your Task object, you will block your calling thread since it is going to wait for the async thread to return with the result of the operation. The Result property is just like the Wait method.

You should use await instead of Result or Wait, since:

Result and Wait will encapsulate your Exception into an AggregateException.
You could easily encounter a deadlock situation. You shouldn't block on async code normally.

However, without Result and Wait you simply cannot make a property safely async. It is not supported in C#, only methods, lambda expressions or anonymous methods can use await. Properties should perform fast and non-blocking operations. If you want to perform a long running activity, don't make it a property (or just call a synchronous method in the setter).

private HttpContent Content;
private string SerializedContent;

public async Task SetHttpContent(HttpContent Content)
{
    this.Content = Content;
    SerializedContent = await Content.ReadAsStringAsync();
}

// ...

await SetHttpContent(new object);


Find prime positioned prime number This is a question from programming contest. This contest is already over.

Now, all the prime numbers are arranged sequentially in ascending order. i.e:- 2, 3, 5,7...and so on. Now, your task is to calculate those prime numbers which are present at a prime position. For example, 2 is present at position 1 which is not a prime number while 3 is present at position 2 which is a prime number, hence 3 is the first prime positioned number. Now, these primed positioned prime numbers are numbered is ascending order such that:

first prime positioned number is 3. So, it is given number 1.

second prime positioned number is 5. So, it is given number 2.

and so on. Now, we are given 2 numbers n and m which denotes the nth and mth prime positioned numbers. Now, your task is to calculate the multiplication of prime positioned number present at nth and mth position. Since the answer may be large, output the answer modulo 109 + 7.

INPUT

First line contains an integer t denoting the number of test cases. The next t lines contains two integers n and m separated by space, denoting the prime positioned numbers which are given numbers n and m.

OUTPUT

A single integer (one per line) for each test t, that is the answer to the question.

CONSTRAINTS

1<= t <=106

1<= n,m <=10000

My approach:

For each test case read 'n' and 'm'. Then calculate nthPrime for 'n' and 'm'.Then again calculate nthPrime for result each result and finally multiply both the answers. This is working for small input but for large inputs it is taking more time.

import java.util.Scanner;

public class Sum {

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    int t=scanner.nextInt();

    while(t-- >0){
        int n=scanner.nextInt();
        int m=scanner.nextInt();
        int first=nthPrime(nthPrime(n));
        int second=nthPrime(nthPrime(m));

        System.out.println(first*second);
    }

}

private static int nthPrime(int n) {
    // TODO Auto-generated method stub
    int candidate,count;
    for(candidate=2,count=0;count<n;candidate++){
        if(isPrime(candidate)){
            count++;
        }
    }
    return candidate-1;
}

private static boolean isPrime(int n) {
    // TODO Auto-generated method stub
    int m=(int) (Math.sqrt(n)+1);
    for(int i=2;i<m;i++){
        if(n%i==0){
            return false;
        }
    }
    return true;
}

}

How to increase time and space efficiency of this program?

Time Limit: 1 sec(s) for each input file.

Memory Limit:   256 MB

Source Limit:   2 KB

Knowing the time limit helps determine what kind of effort is needed to make the code fast enough:

simple trial division
trial division with wheeled striding through candidates and divisors
trial division with memoised divisor primes and wheeled striding through candidates
Sieve of Eratosthenes
odds-only Sieve of Eratosthenes
segmented odds-only Sieve of Eratosthenes
segmented odds-only Sieve of Eratosthenes with presieving

Each complication makes the code significantly faster, but also more complex. So how fast is fast enough?

Generally speaking, the primes up to any given k should only be computed once total instead of twice for each query. Also, given the fact that the query count limit is much higher than the piddling small numbers of primes involved (10000) it makes sense to compute all of them in one go, which is much more efficient and much less complicated than writing some logic that can extend the current list of prime-indexed primes up to some number k when it is too short.

The high number on queries also makes it imperative to benchmark the code for parsing inputs and producing outputs, since that can easily dominate the total program runtime. SPOJ's INOUTEST - and the same or similar tasks at other sites - can be a good guide there.

I've had several such tasks where my submissions clocked times of several seconds or even TLE, even though the raw problem-solving part took only a few milliseconds to run. Writing a dedicated input parser and (batched) output converter cut runtime by two orders of magnitude or more.

Based on my experience recently solving problems of similar structure and magnitude (SPOJ's TDPRIMES and TDKPRIME) I would recommend using a segmented odds-only Sieve of Eratosthenes for building the list of prime-indexed primes in one go. That gives you the best performance for the least amount of complications. It would be possible to speed up your trial division by several orders of magnitude but then it would be more complex than the sieving solution, and the sieve would still blow it out of the water despite using simpler code.

I tried quite a few approaches and strategies, and perhaps my experiences can help you avoid going down some blind alleys.

Recommendation: use an odds-only sieve with bool array that is the same size as your CPU's L1 cache, e.g. 32 KiByte.

Using packed bits in a byte array would allow sieving eight times as much per cache-sized window, and extraction of primes from the sieve would be much more efficient. However, the overhead of indexing (sieve[j>>3] |= 1 << (j&7) instead of a simple sieve[j] = true) means that the sieving using byte[] took slightly longer overall in my tests than sieving plus extraction using bool[], even though the bool code had to sieve eight times as many windows. I was able to make byte[] 30% faster than bool[] but the effort required was essentially the same as that for a modulo 30 wheel, tripling the total size of the source code. Using the stock bitsets of C# (BitArray) and C++ (std::vector<bool>) was an unmitigated performance disaster; the whole program took several times as long to run just because of their mind-boggling inefficiency.

Recommendation: use functions that focus on a specific part of the job and that do whole batches at a time with maximum efficiency.

For example, I found it much faster to extract all primes from a sieved window and then pick out every hundredth from that, instead of integrating the 'take only every 100th prime' bit into the code that extracts primes from the sieve. The reason is focus and simplified looping/branching structures. Modern CPU don't like unpredictable branches at all and levy heavy taxes on them in the form of wait cycles. Better factoring also makes it easier to try different approaches for different sub tasks, for example via function pointers or delegates that can be switched at runtime. And it makes it easier to compose new, completely different solutions from the existing bits and pieces.

For example, instead of complicating - and thus slowing down - the sieve code by the logic for memoising the small handful of primes needed for sieving, I used a separate function for that purpose. Here is the pseudocode (of a hashish persuasion):

internal static List<ushort> small_odd_primes_up_to (int n)
{
    Trace.Assert(3 <= n && n <= ushort.MaxValue + 1);

    // the '- 1' comes straight from the reversing the conversion formula n = (b << 1) + 1;
    // it ensures that even n get treated the same as the immediately preceding odd number
    // instead of tagging an unnecessary bit onto the end of the array
    int max_bit = (n - 1) >> 1;

    // the '- 1' comes from the number-to-bit conversion again and is not related to the sqrt
    int sqrt_n_bit = (int)(Math.Sqrt(n) - 1) >> 1;
    var sieve = new bool[max_bit + 1];

    for (int i = 3 >> 1; i <= sqrt_n_bit; ++i)
        if (!sieve[i])
            for (int p = (i << 1) + 1, j = p * p >> 1; j <= max_bit; j += p)
                sieve[j] = true;

    // 3 needs to be handled separately because of the mod 3 stepping in the for loop
    var result = new List<ushort>()  {  3  };

    for (int i = 5 >> 1, d = 1; i <= max_bit; i += d, d ^= 3)
        if (!sieve[i])
            result.Add((ushort)((i << 1) + 1));

    return result;
}

In your case it would have to deliver only the 1168 odd sieve primes, i.e. those not greater than sqrt(1366661) where 1366661 is the 104729th prime and the 10000th prime-indexed prime. This means that the optimisations it contains - odds-only sieving, plus skipping multiples of 3 when reading out the sieved primes - are not really necessary for the problem at hand. However, I've used that function unchanged in almost all code challenges related to primes, and there's no reason to fiddle with tried and trusted code. Basically, it's about the simplest possible code that can do the job, with only a few sleight-of-hand optimisations. I've shown it to provide a contrast to the design of the main sieving logic, which adds quite a few complications.

For example, here's the hashish pseudocode of a function that gets handed a sieved window by the segmented sieve function, extracts all primes from it into a cache, and then adds every Kth prime from the cache to the list of results (which is a property of the class):

// phase and result[] are static class fields

internal static int[] cache = new int[MAX_PRIMES_PER_SIEVE];

internal static void sieve_to_array_post_filtered (bool[] sieve, int window_base, int window_bits)
{
    // get things into step for the mod 3 loop stepping on top of the mod 2 wheel
    // (the loop is anchored at residue 1)

    int i = 0, k = 0;

    switch (window_base % 3)
    {
        case 0:
        {
            i = 1;  goto case 2;
        }

        case 2:
        {
            if (!sieve[i])
                if (i < window_bits)
                    cache[k++] = window_base + (i << 1);

            ++i;  break;
        }
    }

    for (int e = window_bits - 5; i < e; i += 6)
    {
        if (!sieve[i])
            cache[k++] = window_base + (i << 1);

        if (!sieve[i + 2])
            cache[k++] = window_base + (i << 1) + 4;

        if (!sieve[i + 3])
            cache[k++] = window_base + (i << 1) + 6;

        if (!sieve[i + 5])
            cache[k++] = window_base + (i << 1) + 10;
    }

    for ( ; i < window_bits; ++i)
        if (!sieve[i])
            cache[k++] = window_base + (i << 1);

    for (i = K - phase - 1; i < k; i += K)
        result[result_size++] = cache[i];

    phase = (phase + k) % K;
}

Most of this does the exactly same job as the 2nd for loop in the earlier function, but much faster. The main loop uses mod 3 stepping on top of the odds-only sieve, twice unrolled. The loop after that cleans up leftovers, and the final loop extracts every Kth prime, with phase coordinating the correct counting from one sieve window to the next. This is from the TDPRIMES task where every 100th prime was to be printed; adapting the logic to the requirements of finding prime-indexed primes is trivial.

This example shows how the tiny 2nd loop of the first function got blown up quite lot by the tricks required for achieving performance goals. The code is significantly faster than all other variations I tried, and I tried an awful lot of them (because I'm currently learning the hashish language). The speed is made possible by batched operation, focussing on a single job, and reusing buffers; the loop for extracting the Kth prime was essentially tacked on to the end of the function without disturbing anything. That was required because the sieving function simply invokes this via a process_sieve delegate that is supposed to do whatever is necessary with the freshly sieved primes.

To complete the picture, here's the pseudo code of the segmented sieving logic. It's essentially a normal Sieve of Eratosthenes that sieves the target range in cache-sized increments, remembering the working offsets for each prime from one iteration to the next and pumping the sieved primes out via the process_sieve delegate to make place for a new batch.

internal static void process ()
{
    const int N = 100000000;
    var small_odd_primes = small_odd_primes_up_to((int)Math.Sqrt(N)).ToArray();
    var offset = new int[small_odd_primes.Length];

    // ... some preparatory stuff elided (e.g. setting presieve_pattern and presieve_modulus) ...

    int window_base = 3, n = N - (~N & 1), last_prime_index = small_odd_primes.Length - 1;

    for (int i = first_sieve_prime_index; i <= last_prime_index; ++i)
    {
        int prime = small_odd_primes[i], start = prime * prime;

        offset[i] = (start - window_base) >> 1;
    }

    var sieve = new bool[1 << 15];

    for (int bits_to_sieve = ((n - window_base) >> 1) + 1; bits_to_sieve > 0; )
    {
        int window_bits = Math.Min(bits_to_sieve, sieve.Length);

        Buffer.BlockCopy(presieve_pattern, (window_base >> 1) % presieve_modulus, sieve, 0, window_bits);

        for (int i = first_sieve_prime_index; i <= last_prime_index; ++i)
        {
            int p = small_odd_primes[i], j = offset[i];

            for ( ; j < window_bits; j += p)
                sieve[j] = true;

            offset[i] = j - window_bits;
        }

        process_sieve(sieve, window_base, window_bits);

        window_base += window_bits << 1;
        bits_to_sieve -= window_bits;
    }
}

Obviously you'd use N = 1366661 instead of 10^8, and the logic for copying the presieved pattern would be replaced by a simple call to Array.Clear. However, I left the presieve logic in place to show where it fits into the overall scheme, because this simple trick can add quite a performance boost. The reason is that the smallest few primes have the shortest strides and thus have to make many more hops in any window than the rest taken together, and blasting a suitable bit pattern over the sieve is much faster. Without presieving you'd use 0 as first_sieve_prime_index, naturally.

In any case this should make clear that the logic of a segmented sieve can be very simple indeed.

Using a delegate like process_sieve instead of fixed-function code has the added advantage that it simplifies unit testing. I.e. write a delegate that extracts and stores all primes, which can then be checked against any other prime source.

To put things into perspective: my SPOJ TDPRIMES submission from which the pseudo code was taken (printing every 100th prime up to 100,000,000) clocked 190 milliseconds on SPOJ (C#). The time for sieving the first 10,000 prime-indexed primes with this approach should be on the order of a millisecond.


Using semaphore in C This is my first time using semaphores and I was wondering if I implemented them to the best of their abilities in my code....

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include<semaphore.h>
#include <math.h>

#define NR_THREAD 2

int sum=0;
unsigned int seed;
sem_t sem0;

void* func0(void *param) {
    int tmp;
    int i;
    for(i=0; i<10; i++) {
        sem_wait (&sem0);
        tmp=sum;
        tmp++;
        if(rand_r(&seed)%2) {
            printf("sleeping for 1 sec\n");
            sleep(1);
        } else {
            printf("sleeping for 2 sec\n");
            sleep(2);
        }
        sem_post (&sem0);
        sem_wait (&sem0);
        sum=tmp;
        if(rand_r(&seed)%2) {
            printf("sleeping for 1 sec\n");
            sleep(1);
        } else {
            printf("sleeping for 2 sec\n");
            sleep(2);
        }
        sem_post (&sem0);
    }

    return (void*)0;
}

int main() {
    int i;
    int error;
    pthread_t *tid;
    pthread_attr_t attr;

    seed=(unsigned int)time(NULL);

    if((tid=(pthread_t*)calloc(NR_THREAD, sizeof(pthread_t)))==NULL) {
        fprintf(stderr, "calloc() failed\n");
        exit(1);
    }
    sem_init(&sem0, 0, 1);
    if(sem_init(&sem0, 0, 1)==-1) {
        perror("Failed to sem_init() sem0");
        exit(1);
    }

    pthread_attr_init(&attr);
    for(i=0; i<NR_THREAD; i++) {
        if((error=pthread_create(&tid[i], &attr, func0,
            (void*)0))) {
            fprintf(stderr, "pthread_create() failed: %d %d\n",
                i, error);
            tid[i]=pthread_self();
        }
    }

    for(i=0; i<NR_THREAD; i++) {
        if(pthread_equal(pthread_self(), tid[i]))
            continue;

        if((error = pthread_join(tid[i], NULL))) {
            fprintf(stderr, "pthread_join() failed: %d %d\n",
                i, error);
        }
    }

    printf("Final sum= %d\n", sum);

    free(tid);

    if(sem_destroy(&sem0)==-1) {
        perror("Failed to sem_destroy() sem0");
        exit(2);
    }

    return 0;
}

It runs and gets the correct answer, but I was wondering if there were better places to put them or not. Also, I'm getting a warning, I'm receiving an implicit declaration warning on if(rand_r(&seed)%2) { and I'm not sure how to go about fixing this problem.

This is a demo in which two threads each sleep 10 times.

I presume that you expected the result to be 20. Unfortunately this code may produce anything from 2 to 20.

Here is a scenario how 2 can be produced:

thread 1 grabs the semaphore (its tmp becomes 1)
thread 1 posts the semaphore in the mid-loop

thread 2 grabs the semaphore (sum is still 0)
thread 2 runs the loop for 9 times (sum becomes 9)
thread 2 posts the semaphore at the loop end

thread 1 takes over and completes its first loop
sum becomes 1
thread 1 posts the semaphore at the loop end

thread 2 takes over; its tmp becomes 2
thread 2 posts the semaphore in the mid-loop

thread 1 takes over and runs to completion

thread 2 (its tmp still 2) completes the second half of the loop
sum becomes 2

In your code the threads sleep while holding the semaphore (so sleeping is pretty much irrelevant). Contexts may only switch in the tiny window between sem_post and sem_wait. Most likely it never happens (scheduler doesn't have to switch threads), which explains why you are getting 20. Try to increase the window, say

    sem_post();
    sleep();
    sem_wait();

and see what happens.


Monte Carlo Simulation of P-Value I'm testing Python 3 code to perform a Monte Carlo simulation based on the result of an statistical test.

I currently have the result of the statistical test in a pandas dataframe, like this.

Dataframe A
+-----+-------+
| id  | f_res |
+-----+-------+
|   1 | 4.22  |
|   2 | 5.25  |
|   3 | 3.3   |
|   4 | 2.5   |
|   5 | 1.9   |
|   6 | 9.3   |
+-----+-------+

So my idea is; for each row in f_res, pass that value to a function and extract multiple values from a Noncentral chi-squared distribution, ask how many of this extracted values are greater than the original and divide this by the total of values analyzed.

I'm working with numpy to generate the array of values, and I have this working code.

import numpy as np
import pandas as pd

total_sample = 100

def monte_carlo(x, tot_sample):
    gen_dist = np.random.noncentral_chisquare(df=1, nonc=x, size=tot_sample)
    compare = gen_dist > x
    return np.divide(np.sum(compare), tot_sample)

df = pd.DataFrame(np.random.randint(0,10, 625527), columns=[['A']])
b = np.array(df.values)
g = np.vectorize(monte_carlo)

x = g(b, total_sample)

I know that the use of np.vectorize is not good for speed, because behind curtains is a for loop, but currently I don't understand another method for applying a function element wise in numpy.

Currently analyzing a dataframe of 625.000 items and with a total sample of 100, it takes approx 20 s. line_profiler shows the following.

Total time: 19.909 s
File: test3.py
Function: test at line 6

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     6                                           @profile
     7                                           def monte_carlo(x, tot_sample):
     8    625528     33866564     54.1     58.2      gen_dist = np.random.noncentral_chisquare(df=1, nonc=x, size=tot_sample)
     9    625528      4621263      7.4      7.9      compare = gen_dist > x
    10    625528     19704575     31.5     33.9      return np.divide(np.sum(compare), tot_sample)

So, using numpy or pandas or both, is there any way I could improve this
in execution time and syntax?

The final idea is to return a numpy array with the simulated p-values to append it to the original dataframe.

As you mentioned, by calling np.vectorize on your monte_carlo function and applying it to your dataset b, you are essentially running a for loop over each element individually.

np.random.noncentral_chisquare takes either a float or an array of floats for its noncentrality parameter, so you could vectorize your function call by generating your entire distribution in 1 call then applying the rest of the function to the entire matrix at once.

def monte_carlo2(x, tot_sample):
    gen_dist = np.random.noncentral_chisquare(df=1, nonc=x, size=(x.shape[0],total_sample))
    compare = gen_dist > x
    return np.divide(np.sum(compare, axis=1), tot_sample)

x2 = monte_carlo2(b, total_sample)

This passes your f_res data in as a vector, b, instead of 1 element at a time, generates a distribution with nonc= [b0, b1, b2, ..., bN]. This results in a gen_dist matrix of size (625527, 10) or (len(b), total_sample). b is a vertical vector, so the comparison will apply it across each row, then you just need to sum your comparison over each row (axis=1).

You could probably speed it up more by only generating one distribution per unique value of f_res, but depending on what percentage of your values are unique this may not be worth it, and I assume you want a new random sample each time.

With your original function I get a timeit of:

  15.2 s ± 125 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

And with the vectorized version I get:

  8.84 s ± 50.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


Using properties efficiently in inheritance I have a class called Mailer which has some properties like this

public static string Cname
{
   get
   {
      return HttpUtility.HtmlDecode(HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request["cname"]));
   }
   set
   {
      HttpUtility.HtmlDecode(HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request["cname"]));
   }
}

I am inheriting this property from another class called EventRegistrationReplyMail
like this

public class EventRegistrationReplyMail :Mailer

and using Cname property inside this class. I doubt whether this is the correct way of doing things or not. I am just a beginner in OOP concepts, so please spare me if I am doing anything completely stupid.

Accessors in C#
You should read on accessors in C# - your setter does not do what it should - it should set the value if Cname. If this has no meaning (you can't change the value of Cname - you should drop the set altogether.
Correct use of accessors:

public string Name
{
   get
   {
      return name;
   }
   set
   {
      name = value;
   }
}

For read only properties:

public static string Cname
{
   get
   {
      return HttpUtility.HtmlDecode(HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request["cname"]));
   }
}

Inheritance and static members
You are asking about efficiency in inheriting properties. I don't know what do you mean by "efficiently inheriting", but static members are not really inherited, you simply get some allowance from calling them in the inherited class...

  Inheritance in .NET works only on instance base. Static methods are
  defined on the type level not on the instance level. That is why
  overriding doesn't work with static methods/properties/events...

Use of properties
When using properties, you imply state of the object you are writing the property on (in this case - Mailer class). From looking at your code, it does not look like its the class's state, but rather a calculation made.
A better choice would be to write it as a utility method, which makes it clear that you are calculating something in it:

public static string ExtractCNameFromCurrentRequest() {
    return HttpUtility.HtmlDecode(
       HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request["cname"]));
}

Or you could use an extension method, which will result in a cool usage syntax, and make clear from where you are extracting the CName:

public static class HttpContextExtension {
    public static string GetCName(this HttpContext context) {
        return HttpUtility.HtmlDecode(context.Server.UrlDecode(context.Request["cname"]));
    }
}

And its usage will be:

string cname = HttpContext.Current.GetCName();


Using phantom types to represent amounts and exchange rates of currencies I posted the following snippet to StackOverflow, and someone said there was much to be improved.

{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}

class (Show a) => Currency a where unphantom :: a

data USD = USD deriving Show
data EUR = EUR deriving Show

instance Currency USD where unphantom = USD
instance Currency EUR where unphantom = EUR

data Amount a where
  Amount :: Currency a => Float -> Amount a
instance Show (Amount a) where
  show (Amount x) = show x ++ show (unphantom :: a)

data Rate a b where
  Rate :: (Currency a, Currency b) => Float -> Rate a b
-- ...

Having to define an unphantom function for each currency is a bit annoying but I don't really see a way around it. Also, note that my use of Float to represent monetary values is just a placeholder.

How can I improve this code?

You could rely on the fact the types describing your currencies are Enumerable and you can therefore always generate the appropriate token based on the type of an expression. You would write something like this:

{-# LANGUAGE ScopedTypeVariables #-}

module Currency where

data USD = USD deriving (Show, Enum)
data EUR = EUR deriving (Show, Enum)

currencyRep :: Enum a => a
currencyRep = toEnum 0

newtype Amount a = Amount { value :: Float }

instance (Enum a, Show a) => Show (Amount a) where
  show v = show (value v) ++ " " ++ show (currencyRep :: a)

newtype Rate a b = Rate { rate :: Float }

convert :: Rate a b -> Amount a -> Amount b
convert k v = Amount (rate k * value v)

-- example:
main :: IO ()
main = putStrLn $ show (Amount 3 :: Amount EUR)

Now you can really talk about phantom types: Amount does not carry around a representation of the currency being used and both Amount and Rate are newtypes meaning that they will be optimized away.

Question: Is there a typeclass of singletons out there? It'd be cleaner than using Enum (though relying on deriving is pretty useful) if we had something like this:

class Singleton a where
  unique :: a


Recursive XML2JSON parser I made a Python function that takes an XML file as a parameter and returns a JSON.
My goal is to convert some XML get from an old API to convert into Restful API.

This function works, but it is really ugly. I try to clean everything, without success.

Here are my tests:

    def test_one_node_with_more_than_two_children(self):
        xml = ''
        expected_output = {
            "a": {
                "@id": "0",
                "@name": "foo",
                "b": [
                    {
                        "@id": "00",
                        "@name": "moo"
                    },
                    {
                        "@id": "01",
                        "@name": "goo"
                    },
                    {
                        "@id": "02",
                        "@name": "too"
                    }
                ]
            }
        }
        self.assertEqual(expected_output, self.parser.convertxml2json(xml))

And my function:

from xml.dom.minidom import parseString, Node

class Parser(object):

    def get_attributes_from_node(self, node):
        attributes = {}
        for attrName, attrValue in node.attributes.items():
            attributes["@" + attrName] = attrValue
        return attributes

    def convertxml2json(self, xml):
        parsedXml = parseString(xml)
        return self.recursing_xml_to_json(parsedXml)

    def recursing_xml_to_json(self, parsedXml):
        output_json = {}
        for node in parsedXml.childNodes:
            attributes = ""
            if node.nodeType == Node.ELEMENT_NODE:
                if node.hasAttributes():
                    attributes = self.get_attributes_from_node(node)

                if node.hasChildNodes():
                    attributes[node.firstChild.nodeName] = self.recursing_xml_to_json(node)[node.firstChild.nodeName]

                if node.nodeName in output_json:
                    if type(output_json[node.nodeName]) == dict:
                        output_json[node.nodeName] = [output_json[node.nodeName]] + [attributes]
                    else:
                        output_json[node.nodeName] = [x for x in output_json[node.nodeName]] + [attributes]
                else:
                    output_json[node.nodeName] = attributes
        return output_json

Can someone give me some tips to improve this code?
def recursing_xml_to_json(self, parsedXml) is really bad.
I am ashamed to produce it :)

There is a structural issue with your code: the recursive function works at two levels. 1) It constructs a dict representing a node, and 2) it does some work in constructing the representation for the children. This makes it unnecessarily complicated. Instead, the function should focus on handling one node, and delegate the creation of child nodes to itself via recursion.

You seem to have requirements such as:

A node that has no children nor attributes converts to an empty string. My implementation: return output_dict or ""
Multiple children with same nodeName convert to a list of dicts, while a single one converts to just a dict. My implementation makes this explicit by constructing lists first, then applying this conversion: v if len(v) > 1 else v[0]
A node with children but no attributes raises a TypeError. I suspect this is an oversight and did not reproduce the behavior.

Note that (2) means that a consumer of your JSON that expects a variable number of nodes must handle one node as a special case. I don't think that is good design.

def get_attributes_from_node(self, node):
    attributes = {}
    if node.attributes:
        for attrName, attrValue in node.attributes.items():
            attributes["@" + attrName] = attrValue
    return attributes

def recursing_xml_to_json(self, node):
    d = collections.defaultdict(list)
    for child in node.childNodes:
        if child.nodeType == Node.ELEMENT_NODE:
            d[child.nodeName].append(self.recursing_xml_to_json(child))

    output_dict = self.get_attributes_from_node(node)
    output_dict.update((k, v if len(v) > 1 else v[0])
                       for k, v in d.iteritems())

    return output_dict or ""


Create dummy variables in dataframe using for loop and apply lambda I like to compute dummy variables based on the existing values in a dataframe and a dictionary with certain "cut off" points. I wonder whether I need to get rid of the for loop in the example below. And if so, how?
The second answer in this Stackoverflow post compellingly urges to avoid looping through dataframes. In my real dataset (about 20.000 rows and 50 columns/variables) the "apply lambda" for the rows indeed performs much better than a for loop (which after a few hours still wasn't finished). Yet, the for loop for the columns doesn't really give a problem with time and it is handy to automatically name the variables.
Here is an example dataset
import pandas as pd
# create df
dict={'file':['a', 'b', 'c'],'t_0':[1.5, 2.5, 3.5], 't_1':[0.5, 1.5, 0]}
df=pd.DataFrame(dict,index=['0', '1', '3'])
print(df)
# create dictionary with cut off points for dummy variable
d = dict={'t_0_cut_off':1, 't_1_cut_off':2}
print(d)

And here the for loop and apply lambda function which I use to compute the dummy variables.
for column in df.columns[-2:]:
    df[f'{column}_result']=df[f'{column}'].apply(lambda x: 1 if x> d[f'{column}_cut_off'] else 0)
df

The results look like this (and appear as I expect)
  file  t_0  t_1  t_0_result  t_1_result
0    a  1.5  0.5           1           0
1    b  2.5  1.5           1           0
3    c  3.5  0.0           1           0

df.apply is essentially a loop and can be slower than vectorized methods.  Here is a proposal without using apply:
First, we can rename the keys in the dictionary to match the column names in the dataframe:
d1 = {k.rsplit('_',2)[0]: v for k, v in d.items()}
#{'t_0': 1, 't_1': 2}

Next step is make a subset of your dataframe, since you are interested in second and subsequent columns; for this, use df.iloc. Then, using df.assign, we can assign the values from the dictionary in the columns we are interested in and compare them with the original values using df.gt, then convert the boolean value to int using df.astype . Finally, we can df.join it back to the original dataframe and use rsuffix argument to rename the columns to add "_result"
sub_df = df.iloc[:,1:] #subsets the dataframe leaving the first column out
out = df.join(sub_df.gt(sub_df.assign(**d1)).astype(int) , rsuffix='_result')

Final code looks like:
d1 = {k.rsplit('_',2)[0]: v for k, v in d.items()}
sub_df = df.iloc[:,1:]
out = df.join(sub_df.gt(sub_df.assign(**d1)).astype(int) , rsuffix='_result')
print(out)

  file  t_0  t_1  t_0_result  t_1_result
0    a  1.5  0.5           1           0
1    b  2.5  1.5           1           0
3    c  3.5  0.0           1           0


Finding an exact "phrase" with a given string (as typed/in order) <?php
    function filterExactPhrase($input, $phrase)
    {
        $phrase = explode("\t", $phrase);
        $phrases = count($phrase);

        for($i = 0; $i < $phrases;)
        {
            if(preg_match("/(" . $phrase[$i] . ")\b/", $input))
            {
                $out[] = ['INPUT' => $input, 'FOUND' => 1,
                'VALUEofFOUND' => $phrase[$i]];
            } else {
                $out[] = 'Not found';
            }
            $i++;
        }
        print_r($out);
    } //end function

    $this->filterExactPhrase("this is a test, foobar", "foobar");

Calling the function like this yields

Array ( [0] => Array ( [INPUT] => this is a test, foobar [FOUND] => 1 [VALUEofFOUND] => foobar ) )

Giving the function foo as $input instead of foobar yields

$this->filterExactPhrase("this is a test, foo", "foobar");

Array ( [0] => Not found )

I thought this was quite interesting to find as I was looking for a solution to find a very specific phrase with spaces, in a extensively long, log file to remove from it.

Basically, Alex has already made some good suggestions (especially the bit about using \b). However, your function will fail in certain cases like this one:

//looking for chars like *, +, ? and such
filterExactPhrase("some *markdown* string", "*markdown*");

The string could contain special regex chars (. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -), or the delimiter you use:

//this is operator error (regex + markup don't mix)
filterExactPhrase('
foobar
', '
');

Yes, it's evil, but people still seem hellbent on using regex's to consume markup, so your code should either check and throw an exception if it's used to do that, or you should defend against it. The example above will generate an error, because the string
 is concatenated into the regex raw, so you end up with this:

/\b(
)\b/
/\b(</ -> faulty regex
hi>\b/ -> unknown and invalid flags

Another thing to think of is that people, once they find out the function uses a regex, will start passing regular expressions instead of a string to it. Kind of like people entering SQL wildcards in search forms (stuff like foo%).

filterExactPhrase("some string with words and 123 numbers", "[\w\d]+");

So how do you go about this? simple: preg_quote filters the input for you, and escapes whatever chars need escaping. Basically, all I'm trying to say is change this:

$numFound = preg_match_all("/\b(" . $phrase . ")\b/", $input);

to this:

$escaped = preg_quote($phrase, '/');//second param is the delimiter
$numFound = preg_match_all("/\b(" . $phrase . ")\b/", $input);

Now chars like + or * are escaped properly, and so are the delimiters.

The other thing I'd suggest is to remove the print_r from your function/method. I realize that it's probably there for debugging purposes, but still: a function/method does one thing. In this case its job is to process a piece of string, and find exact matches of another string. Whether or not that data should be shown (displayed, echoed or printed or whatever) is not a call this method should make. It's not aware of output buffers, headers that might be set later on, so it shouldn't forcibly generate output.

For all you know, I might want to call this method, store the data somewhere, and send something entirely different to the output stream. In short: a function/method should return data, not print/echo it
This dogma doesn't apply for methods in a renderer component or view class, of course. But it holds true for data-processing code units


Efficient way in Swift to trim an array Let's say I have a struct…

struct Person {
   let isMale: Bool
   let name: String
}

and an array of Person structs. I want to trim all the men (isMale == true) from the start and end of the array (similarly to how you'd trim whitespace from the start & end of a string)…

func trimMen(people: [Person]) -> [Person]

    var trimmedPeople: [Person] = people

    while trimmedPeople.first?.isMale {
        trimmedPeople.removeFirst()
    }
    while trimmedPeople.last?.isMale {
        trimmedPeople.removeLast()
    }
    return trimmedPeople
}

Is there a more efficient way to do it?

Following implementation provides generic solution, which mimics other foundation methods like filter, map etc. Though extends Array instead of SequenceType.

Main benefit from this solution comparing to the original provided by Ashley Mills is that it does not mutate an array.

extension Array {

    func trim(@noescape predicate: (Element) throws -> Bool) rethrows -> [Element] {
        guard let
            start = try (indexOf { try !predicate($0) }),
            end = try (reverse().indexOf { try !predicate($0) }) else {
                return []
        }
        return Array(self[start..<end.base])
    }

}

Usage Example:

persons.trim { $0.isMale }


Optimizing jQuery addclass / removeclass on scroll I have a scroll event and add class and remove classes for different elements. As you can see the code is a bit big. Is this method ok or is there a more efficient one?

I mean, you can see that there are no child elements. I could use .siblings() for some but, as you can see, I also serve unique classes.

Any idea? I know it looks bad but I think it is the only way.

 $(document).ready(function () {
        $(window).scroll(function () {
            var scroll = $(window).scrollTop();

            if (scroll >= 50) {
                $("nav ul li").addClass("list-mini");
                $("nav").addClass("nav-mini");
                $("nav ul li a").addClass("nav-recolor");
                $("nav img").removeClass("zoomOutLeft");
                $("nav img").addClass("zoomInUp");
                $("nav img").addClass("logo-mini-active");
                $("nav ul").addClass("margin-transition");
                $("ul").addClass("ul-active");
                $("nav ul li a span").addClass("text-removed");
                $("nav ul li a").addClass("nav-font");
                $("nav ul li a span").addClass("transition-02s");
                $(".fa-shopping-cart").addClass("fa-shopping-cart-mini");
                $(".fa-globe").addClass("fa-globe-mini");
                $(".fa-info").addClass("fa-info-mini");
                $(".fa-circle-o-notch").addClass("fa-circle-o-notch-mini");
                $(".fa-envelope-o").addClass("fa-envelope-o-mini");
            } else {
                $("nav ul").removeClass("margin-transition");
                $("nav ul li").removeClass("list-mini");
                $("nav").removeClass("nav-mini");
                $("nav ul li a").removeClass("nav-recolor");
                $("nav img").removeClass("zoomInUp");
                $("nav img").addClass(" zoomOutLeft");
                $("ul").removeClass("ul-active");
                $("nav ul li a span").removeClass("text-removed");
                $("nav ul li a").removeClass("nav-font");
                $("nav ul li a span").removeClass("transition-02s")
                $(".fa-shopping-cart").removeClass("fa-shopping-cart-mini");
                $(".fa-globe").removeClass("fa-globe-mini");
                $(".fa-info").removeClass("fa-info-mini");
                $(".fa-circle-o-notch").removeClass("fa-circle-o-notch-mini");
                $(".fa-envelope-o").removeClass("fa-envelope-o-mini");
            }
        });
    });

You shouldn't be doing so much manipulation of the classes. Instead, you could just add or remove a scrolled-down class to the <body> element. Then specify the rest of the changes using pure CSS.  (For example, you would have a body.scrolled-down nav { … } rule.)


Hmm, a thoughtful library I've been writing far too many routines in JavaScript that get a record from a an object or array based off a matching property, much like jQuery does with DOM elements. Since all the good names are taken, I called it Hmm.

I went with the philosophy that if I don't need it yet, I wont provide for it.

var Hmm = (function()
{ //A snippet/library to find records in table-like JS arrays

  function getNamedValue( o , name  )
  { //Name can have dots, 'car.tire.brand.name' should get the expected
    var parts = name.split(".");
    while( parts.length && o ){
      o = o[parts.shift()];
    }
    return o;
  }

  function unique( )
  { //Assuming `this` is an array, will copy all unique entries of `this` to a returned new array
    var array = [], map = {}, json;
    this.forEach( function( value ){
      if( value instanceof Object ){
        json = JSON.stringify( value );
        if( !map[json] ){
          array.push( value );
          map[json] = true;
        }
      }
      else if( !~array.indexOf( value ) ){
        array.push( value );
      }
    });
    return array;
  }

  function Hmm( data )
  { //data could be a string -> treat as JSON, parse it
    //data could be an object, or a string that got converted to an object -> convert to array
    //data could be an array ( original or through conversion ) -> leave as is
    this.data = data instanceof Object ? data : JSON.parse( data );
    this.data = this.data instanceof Array ? this.data  : [ this.data  ];
  }

  Hmm.prototype.index = function( name )
  { //Name can have dots, 'car.tire.brand.name' should get the expected
    //Generates an index object
    var index = {} , i;

    this.data.forEach( function( value )
    {
      var key   = getNamedValue( value , name ),
          keys  = key instanceof Array ? key : [key];
      for( i = 0 ; i < keys.length ; i++ )
      {
        key = keys[i];
        index[key] = index[key] || [];
        index[key].push( value );
      }
    });
    return index;
  };

  Hmm.prototype.uniqueIndex = function( name )
  { //Create an index, point each index to the first of possible values
    var index = this.index( name );
    Object.keys( index ).forEach( function(key){
      index[key] = index[key][0];
    });
    return index;
  };

  Hmm.prototype.collect = function( name )
  { //Collect all the values for a given property name
    var values = this.data.map( function ( o ) {
      return getNamedValue( o , name );
    });
    values.unique = unique;
    return values;
  };

  Hmm.prototype.toString = function()
  { //More for jsbin than anything else
    return JSON.stringify( this.data );
  };

  return Hmm;

}());

//Some tests

var foods = [

  { name : 'potatoes' , calories : 100 , allergens : [] , storage : 'ambient' },
  { name : 'pistachio ice cream' , calories : 1000 , allergens : ['nuts','milk'] , storage : 'frozen'  },
  { name : 'chocolate ice cream' , calories : 1200 , allergens : ['milk'] , storage : 'frozen' },
  { name : '2% fat milk' , calories : 600 , allergens : ['milk'] , storage : 'chilled' }
];

var hmm = new Hmm( foods );

console.log( hmm.collect('name') );                 //Collect all names
console.log( hmm.collect('allergens') );            //
console.log( hmm.collect('allergens').unique() );
console.log( hmm.collect('allergens.0') );
console.log( hmm.collect('allergens.0').unique().sort() );
console.log( hmm.index('name') );
console.log( hmm.index('name').potatoes );
console.log( hmm.index('allergens').milk );
console.log( hmm.uniqueIndex('name') );
console.log( hmm.uniqueIndex('name').potatoes );
console.log( hmm.index('allergens') );
console.log( hmm.index('allergens.0') ); //Index on the first allergy

It's very nice. What few qualms I have are a result of me looking really hard for things to have qualms about (furrowing my brow and going "hmm", basically).

Anyway, some thoughts:

Your unique function relies on the assumption that there are no circular references in the object passed to JSON.stringify. It's probably a fair assumption, but an assumption nonetheless. Also, from a specification standpoint, JSON representation of objects doesn't impose or guarantee any ordering of properties. I highly doubt it'll ever be an issue anywhere, but it could mean that identical objects will have different JSON representations, and unique would thus include both those objects.
Similarly edge-case'y: Your instanceof usage is vulnerable to the usual cross-frame pitfalls.
The !~array.indexOf( value ) trick is a bit arcane. It's neat, but I don't think I've actually seen it used anywhere - except in some other code you posted :)
A === -1 comparison isn't nearly as cool, but it wouldn't cause me to go "huh?". In other words: I like it, but I wouldn't call it obvious or idiomatic.
That curly-brace-on-new-line style just rubs me the wrong way, but you know what you're doing, so I'll spare you the "automatic semi-colon insertion" speech :)

On a more overall note: Like jQuery, it might be useful to always return a Hmm-wrapped array, instead of only adding unique to the array returned by collect. Of course it'd be quite a different API.


Simple Question about Numeric Operations I have a question that may be easily answered, but the answer evades me.  In regards to numeric operations, how come when I code this:

double celsius = 30;
double fahrenheit = (celsius + 32.0) / (5/9);

I get an answer:

fahrenheit = infinity;

But, when I code this:

double fahrenheit = (celsius + 32.0) / (5.0/9);  // with a decimal place after 5 or 9

The answer comes out correctly as 111.6?

Shouldn't the (5/9) automatically become a double without the decimal, or am I incorrect?

Division by zero gets you infinity.

Note that (5/9) is an int expression, and resolves to int 0!

To fix things, make your literals doubles :

double celsius = 30d;
double fahrenheit = (celsius + 32.0d) / (5d/9d);


Calculating longest increasing sub-sequence recursively I have trouble understanding recursion, so I'm trying to implement algorithms using it. I wrote this code that calculates the length of the longest increasing sub-sequence. How can I improve this?

int _lis(int arr[], int n){
  if(n==0) return 1;

  int m=1, temp;
  for(int i=0; i<n; i++){
    if(arr[i]<arr[n]){
        temp= 1 + _lis(arr, i);
        if(temp > m)
            m=temp;    //   m = max(m, 1 + _lis(arr, i));
    }
  }
  return m;
}

int LIS(int arr[], int n){
  int temp, m=0;

  for(int i=0; i<n; i++){
    temp = _lis(arr, i);
    if(temp>m)
        m= temp;
  }
  return m;
}

Examples:

{3, 1, 2, 5, 1, 6} returns 4. (LIS : 1, 2, 5, 6)
{ 10, 22, 9, 33, 21, 50, 41, 60 } returns 5. (LIS : 10, 22, 33, 50, 60)

Time complexity

Your recursive solution works, but the time complexity is not optimal.  In the worst case where the array is sorted in increasing order, the time complexity appears to be \$O(n!)\$, because for each length you recurse on every length less than it.

What you need to do is to avoid recomputing solutions you've already found.  If you used some kind of memoization (i.e storing answers you've already found), you should be able to reduce the problem to time complexity \$O(n^2)\$.  For example, if you already computed _lis(arr, 5), then the next time you need to compute it, you should be able to just reuse the previous answer instead of recomputing it the recursive way.  All you would need to do is have an array of size n to store your results as you compute them.


Base 10 to Base 2-36 converter After a conversation with my math teacher about a base algebra (base 43 using all the algebra symbols) and finding it more than the 30 min of work I was looking for, I decided to make this instead.

import math

letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

def print_bases(base: int, num: int) -> None:
    new_num = []
    div = num
    while div != 0:
        if len(str(div % base)) > 1:
            new_num.insert(0, letters[((div % base) - 10)])
        else:
            new_num.insert(0, str(div % base))
        div = math.floor(div / base)
    new_num = "".join(new_num)
    print(f"{num} in base {base} is {new_num}")

while True:
    while True:
        try:
            num = int(input("Please enter a number in base 10: "))
            break
        except (NameError, ValueError):
            print("Please use numbers only")
    for base in range(35):
        print_bases(base + 2, num)

As this was made for fun I forgot to add any comments (doing that is still new for me), so I hope it makes sense. My main problem is I want to know if I can get rid of letters. Also print_bases seems messy and I wonder if that can be cleaned up. Any other small fixes would be appreciated.

;)

Since letters is a list of characters (1 length strings) you logistically have made letters a string. And so you can simplify writing it as a string rather than a list of characters.

letters = "ABCDE..."

You can remove the need to define letters by using string.ascii_uppercase.
It's good to see some type hints. Good job!
I would suggest changing your function to only take in the base and the number, and return a new number, rather than print it.
You don't need to use math.floor you have a couple of alternate options:

Use int - int(div / base).
Use the floordiv operator - div // base.

Rather than using div % base and math.floor(div / base) you can use divmod to divide and get the modulo in one command.
Rather than using list.insert I would recommend using list.append and then using reversed.

This is because inserting at the start of a list in Python has to move every other item from the beginning of the list to the end of the list. Append on the other hand only needs to append to the end of the list and it doesn't have to touch the rest of the list.

I also find it cleaner to just use .append.
The check len(str(div % base)) > 1 would be better described as (div % base) >= 10. This is as we're working with numbers - /, %, divmod - and so thinking of the value as a number is easier.
If you change letters to string.digits + string.ascii_uppercase then you can remove the need for the if.
I suggest you change the order of your function's arguments, so it's inline with other base conversion functions. num then base.
It's Pythonic to have constants be UPPER_SNAKE_CASE and so letters should be all caps.

There's a lot of points above, but for a beginner your code is good. Good job!

import string

LETTERS = string.digits + string.ascii_uppercase

def to_base(num: int, base: int) -> str:
    new_num = []
    while num != 0:
        num, mod = divmod(num, base)
        new_num.append(LETTERS[mod])
    return "".join(reversed(new_num))

while True:
    while True:
        try:
            num = int(input("Please enter a number in base 10: "))
            break
        except (NameError, ValueError):
            print("Please use numbers only")
    for base in range(2, 37):
        new_num = to_base(num, base)
        print(f"{int(new_num, base)} in base {base} is {new_num}")


Changing placeholder text with CSS only I am building one of those contact forms that are conversational. I have code that works but I don't think it is optimal (at the bottom). The form looks like:

The code is live on this codepen

The problem I was solving was that the placeholder text on one of them is very large and would either break into two lines or if I gave it a fixed width, it would break the layout of smaller mobile phones. Yes, I understand the the very simple solution would be to propose a change to the copy for any instance, but going on the fact that it cannot be done, how would I solve swapping the text based on the device width.

My proposed solution was to reduce the text on mobile. Since there they are more flexible with the mobile product, I can make these changes, but the desktop needs to comply with the PSD.

HTML

<input type="text" id="org" name="" placeholder="ORGANIZATION OR COMPANY NAME">

CSS

#org{
  display: block;
  width: 96%;
  margin: 0 auto;
}
@media only screen and (min-width: 768px) {
  #org{
    display: inline-block;
    width: 360px;
  }
}

It needs to be at least 360px to match the PSD for desktop.

One other option that I have is if I have entirely different inputs, would that work? like

<input type="text" id="org" class="orgm" name="" placeholder="ORG/COMPANY">
<input type="text" id="org" class="orgd" name="" placeholder="ORGANIZATION OR COMPANY NAME">

.orgm { //mobile
    display: block;
}
.orgd {
    display: none;
}
@media only screen and (min-width: 768px) {
  .orgm{
      display: none;
      width: 96%;
      margin: 0 auto;
  }
  .orgd {
      display: inline-block;
      width: 360px;
      margin: 0;
  }
}

I think that you are mistaking the purpous of the placeholder attribute.

A label element should be used to indicate what the field is for and a placeholder should provide an example of the format to use.

When you use a seperate label you have much more flexability in how you style it. You can use a "label as placeholder" pattern, where you place the
label on top of the input so it appeares to be the placeholder. You would have to move the label when the input is focused.

In the snippet below I have created two lable's for the input. It would be very easy to show and hide based on a media query.

Organization or Company Name
Org/Company
<input type="text" id="org" name="" placeholder="Code Review">


Fibonacci sequence and nth number with reduce() const generateFibonnaciSequence = (n) => {
    return [
        (arr = new Array(n).fill(1).reduce((arr, _, i) => {
            arr.push(i <= 1 ? 1 : arr[i - 2] + arr[i - 1]);
            return arr;
        }, [])),
        arr[n - 1],
    ];
};

const [fibonacciSequence, fibonacciNthNumber] = generateFibonnaciSequence(n);

My idea is to return an array holding fibonacci sequence up to n in index 0 and fibonnaci's n-th value in index 1. Can someone help me with a prettier way of constructing this function. I'd like to avoid holding the array in temp arr variable if possible, but still use a single expression for return statement.

A short review;

I prefer fat arrow syntax => for inline functions
Its a good exercise to code this with reduce but it is definitely not the best option for production code. (That would be a non-recursive old skool loop)
The modern approach to Fibonacci numbers has them start with [0,1,1] not [1,1]
If you have control over what the function returns, then I would just return the sequence. It is trivial for the caller to get the last value in the array

Please find below a counter proposal, I like that it support both the old and new style sequence.

function buildFibonnaciSequence(n){
  const start = [0,1];
  //Recursion exit lane
  if(n <= 1){
    return [start.slice(0,n+1), start[n]];
  }
  //Recurse
  const priorSequence = buildFibonnaciSequence(n-1);
  //Build return value
  const nValue = priorSequence[0][n-2] + priorSequence[0][n-1];
  return [[...priorSequence[0], nValue], nValue];
}

console.log(buildFibonnaciSequence(0));
console.log(buildFibonnaciSequence(1));
console.log(buildFibonnaciSequence(5));
console.log(buildFibonnaciSequence(45));


Map markers on a canvas that pop up boxes when clicked Here's a working version of my code - http://jsfiddle.net/sambenson/g3qsa/#base
How can this be improved upon?

$(function(){
    var box = {},
        island = {},
        canvas = {};

    box.el = $('#box');
    canvas.el = $('#arrow');

    function go(el){
        if(box.el.css('visibility') == 'hidden'){
            reset_name();
            $('.island').addClass('inactive');

            box.top = box.el.offset().top;
            box.corner = {};
            box.corner.left = box.el.offset().left;
            box.corner.right = box.corner.left + box.el.width();

            island.el = el;
            island.top = island.el.offset().top;
            island.left = island.el.offset().left;

            island.el.removeClass('inactive').addClass('active');

            canvas.width = island.left - box.corner.left;
            canvas.height = island.top - box.top;

            canvas.el.css({
                top: box.top,
                left: box.corner.left
            }).attr({
                width: canvas.width,
                height: canvas.height
            });

            var context = canvas.el[0].getContext('2d');

            context.beginPath();
            context.moveTo(0, 0);
            context.lineTo(box.el.width(), 0);
            context.lineTo(canvas.width, canvas.height);
            context.closePath();

            context.fillStyle = "#eaeaea";
            context.fill();

            box.el.css('visibility', 'visible');
            canvas.el.show();
        }
        else {
            close();
        }
    }

    function reset_name(){
        $('#name_holder').text('').css({
            top: -9999,
            left: -9999
        })
    }

    function close(){
        $('.island').removeClass('inactive active');
        box.el.css('visibility', 'hidden');
        canvas.el[0].width = canvas.el[0].width;
        canvas.el.hide();
    }

    $('.island').hover(function(){
        if(box.el.css('visibility') == 'hidden'){
            var t = $(this),
                name = t.text(),
                holder = $('#name_holder');
                top = t.offset().top - 60;
                left = t.offset().left - 50;

            holder.css({
                top: top,
                left: left
            }).text(name);
        }
    }, function(){ reset_name(); })
    .click(function(){ go($(this)); })

    $('.close').click(function(){
       close();
    })

})

Could it be made faster?
Could it be made more efficient?

My comments are more just on style as opposed to performance:

Instead of using :

if(box.el.css('visibility') == 'hidden'){

it's more readable to use :

if(box.el.is(":hidden")){

And similarly, instead of using :

box.el.css('visibility', 'visible');

you can use :

box.el.hide();

A note on this one though, these are not exactly equivalent because hide actually sets display: none.  In this case though I believe that's fine.

And one final comment, it's a good practice to name variables which contain jQuery objects with a $ at the beginning.  This allows you to know that the variable is already a jQuery object without going back in the code to check and avoids accidentally creating jQuery objects out of objects that were already jQuery objects.

So something like this:

var t = $(this),
    name = t.text()

would become this:

var $t = $(this),
    name = $t.text()


Macro that does some kind of duplicate check This macro pulls in two workbooks, one being a template with saved formulas already, and the other containing data with thousands of rows...I need to increase the speed because the process takes more than 15 minutes.

Sub WbtoWb4()

Dim Wb1 As Workbook
Dim Wb2 As Workbook

With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
Set Wb1 = Workbooks.Open("")
Set Wb2 = Workbooks.Open("")

Wb1.Sheets("CDGL Data").Copy After:=Wb2.Sheets("STS")
Wb1.Close False

With Application
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
End With

Sheets("CDGL Data").Select
Range("AQ:BB").EntireColumn.Delete

Range("A1").AutoFilter Field:=32, Criteria1:=Sheets("DataSources").Range("B4").Value
ActiveSheet.UsedRange.Offset(1, 0).SpecialCells _
(xlCellTypeVisible).Copy

Sheets("CDGL").Select
Range("B2").PasteSpecial Paste:=xlPasteValues

With Sheets("CDGL")
rows_c1 = .Cells(Rows.Count, "G").End(xlUp).Row
Sheets("Duplicate Check").Range("A1:C" & rows_c1).Value = Sheets("CDGL").Range("H2:J" & rows_c1).Value

rows_c2 = .Cells(Rows.Count, "K").End(xlUp).Row
Sheets("Duplicate Check").Range("D1:G" & rows_c2).Value = Sheets("CDGL").Range("L2:O" & rows_c2).Value

rows_c3 = .Cells(Rows.Count, "AI").End(xlUp).Row
Sheets("Duplicate Check").Range("H1:H" & rows_c3).Value = Sheets("CDGL").Range("AJ2:AJ" & rows_c3).Value
End With

Sheets("Duplicate Check").Select
Set rng = Range("A1", Range("H1").End(xlDown))
rng.RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6, 7, 8), Header:=xlNo

With Sheets("CDGL")
Sheets("Rec").Range("B6").Resize(.Cells(.Rows.Count, "G").End(xlUp).Row - 1, 3).Value = Sheets("Duplicate Check").Range("A1:C" & .Cells(.Rows.Count, "A").End(xlUp).Row).Value
 Sheets("Rec").Range("E6").Resize(.Cells(.Rows.Count, "D").End(xlUp).Row - 1, 4).Value = Sheets("Duplicate Check").Range("D1:G" & .Cells(.Rows.Count, "A").End(xlUp).Row).Value
 Sheets("Rec").Range("I6").Resize(.Cells(.Rows.Count, "H").End(xlUp).Row - 1, 1).Value = Sheets("Duplicate Check").Range("H1:H" & .Cells(.Rows.Count, "A").End(xlUp).Row).Value
End With

Application.DisplayAlerts = False
Sheets("Duplicate Check").Delete

ActiveWorkbook.SaveAs Filename:=""
ActiveWorkbook.Close
End Sub

Lowest-Hanging VBA Performance Fruit

You have

With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With

But you only have it in force for part of your Sub. If you move this

With Application
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
End With

To the very end of your Sub, you should instantly see a big improvement.

In addition, you should set Application.Calculate to xlCalculationManual at the start, and set it back to xlCalculationAutomatic at the end. That's the other big performance drain.

Always Reset anything you disable

Whenever you change an Application.Thing setting, that change will persist as long as Excel remains open. This:

Application.DisplayAlerts = False

is never set back to True. Once your Sub ends, if your user accidentally clicks the close button, Excel will close without prompting them to save their work first. Because alerts are disabled.


Many interfaces and lots of inheritance vs few interfaces and less inheritance? I have a Visual Studio Solution which has a bunch of Projects in it. One of these projects is called "Services" and is basically the junction point between all remaining projects. When I built it originally I made it as generic as possible so I can expand on it. At the time I only had to work with Entity Framework backed implementations of it, but now I've added QuickBooks to the mix as well. It mostly worked out well, but I saw the need to refactor and redesign bits and pieces of it. To that end I've spent most of yesterday doing that and I have new code that takes care of the weirdness I had before, but, I find myself using lots of interfaces and lots of inheritance and I'm not exactly comfortable with it. For example here's my "DbService" implementations:

public class DbService<TEntity> :
    Service<TRepository>,
    IDbQueryableService<TEntity>,
    IQueryableService<TEntity> {}

public class DbService<TEntity, TKey> :
    DbService<TEntity>,
    IDbGettableService<TEntity>,
    IGettableService<TEntity, TKey>,
    IRemovableService<TEntity, TKey>,
    IRestorableService<TEntity, TKey> {}

public class DbService<TEntity, TEntityFormItem, TKey> :
    DbService<TEntity, TKey>,
    IAddableService<TEntityFormItem, TKey>,
    IUpdatableService<TEntityFormItem, TKey> {}

public class DbService<TEntity, TEntityFormItem, TEntityListItem, TKey> :
    DbService<TEntity, TEntityFormItem, TKey>,
    IDbListableService<TEntityListItem>,
    IListableService<TEntityListItem> {}

public class DbService<TEntity, TEntityFormItem, TEntityListItem, TEntitySelectItem, TKey> :
    DbService<TEntity, TEntityFormItem, TEntityListItem, TKey>,
    IDbSelectableService<TEntitySelectItem>,
    ISelectableService<TEntitySelectItem> {}

This is very similar to my current code and allows me to only inherit from a base class that has the functionality I want. For example, if a TEntity can be listed, but doesn't need to be displayed as a select list, then I'll inherit from the fourth DbService. This way I know I can upgrade or downgrade my inheritance as I need to. That being said, it itself has a lot of inheritance between base classes and interfaces. There's six levels of base class inheritance and 12 interfaces.

So, this morning I tried to bring it all together a little bit and came up with this:

public class DbService2<TEntity, TEntityListItem, TEntitySelectItem, TKey> :
    Service<TRepository>,
    IDbReadableService<TEntity, TEntityListItem, TEntitySelectItem>,
    IReadableService<TEntity, TEntityListItem, TEntitySelectItem, TKey> {}

public class DbService2<TEntity, TEntityFormItem, TEntityListItem, TEntitySelectItem, TKey> :
    DbService2<TEntity, TEntityListItem, TEntitySelectItem, TKey>,
    IWritableService<TEntity, TEntityFormItem, TKey> {}

Now this version obviously reduces the depth of inheritance on the base classes to three and the interfaces to three, but, it forces me in a position where some inheriting TEntity services will not be using all of the features so I'd have to use placeholders to fill in some of the TEntity* parameters and that feels like it will end up dirtier in the long run than the first code sample.

Also, I do realize that I'm using lots of generic parameters, but it works for my needs and this not being a publicly exposed API, I'm OK with it.

So, my question for you fine folks is, am I being too zealous in trying to reduce the base class and interface inheritances or am I OK to continue as is, which has worked so far (referring to the original code I was refactoring which is very close to the first example)? Visual Studio gives the first example a maintainability index of 86.5% (average), and 82.5% (average) for the second example, so if I follow VS assessment, I should continue with the first example?

Zealous nitpicking...

am I being too zealous in trying to reduce the base class and interface inheritances

Careful with wording here: a type inherits from a base class, and implements an interface. Interfaces aren't inherited, they're implemented. Subtle, but important distinction.

My two cents...
Looking at the base class in the first snippet:

public class DbService<TEntity> :
    Service<TRepository>,
    IDbQueryableService<TEntity>,
    IQueryableService<TEntity> {}

Can you spot the code smell?
What's the difference between these two interfaces?

    IDbQueryableService<TEntity>
    IQueryableService<TEntity>

You're not listing any of these interfaces, but just from the names one can tell that IQueryableService<TEntity> and IDbQueryableService<TEntity> probably overlap in functionality: they're both queryable services.
Leaky abstractions
What you have here is a leaky abstraction: you're making an abstraction (/interface), but the implementation is leaking into the abstraction - whether the data is coming from a database, from a web service, or from text files, shouldn't matter; you want an abstraction for something that can be queried... and IQueryableService<TEntity> seems to accomplish that. IDbQueryableService<TEntity> is leaking a database implementation of an IQueryableService<TEntity>.
IDbQueryableService<TEntity> is redundant and should be removed.
Same goes for IDbGettableService<TEntity>, which is leaking a database implementation of IGettableService<TEntity, TKey>, at least so it seems from the interfaces' names.
Consistency in design
Where's IDbRemovableService<TEntity>? Where's IDbAddableService<TEntity>? Where's IDbUpdatableService<TEntity>? Why aren't these operations paired with a non-IDbSomething interface like the queryable and gettable stuff?

I would have lots of other questions about why you need to have a TEntityListItem (among other things), but there's really not enough context in your question to pursue any further without assuming what your implementations do, and what methods your interfaces expose.
I suggest you post another question with your actual code, so reviewers can actually go over your code and make sound recommendations. Just reviewing class names and interfaces without even having the interface members, is pretty hard.
I would venture to say that I highly doubt you need that many generic type parameters, but without knowing more about your code all I can do is say "I don't like this"; whether it's a private API or publicly exposed to client code doesn't matter: it's code that you need to maintain and understand, now and in the future - I don't care what Visual Studio thinks the "maintainability index" is (especially when anything between 20 and 100 is "green"). Having 12 different interfaces that, together, seem to be doing what a single repository could do, doesn't feel right. In fact, the first impression I got was "boy this is over-engineered". And I'm sure the impression wouldn't go away by looking at your actual code.