Finding all pairs of elements in an array that sum to a target value using multiple pointers (follow up) The previous question was not clear enough so I will try to clarify it more in this follow-up question.
I tried the multiple pointers technique to solve the problem that find pair of values that sums up to a target value.

We are assuming that:

the array is already sorted.
we are working with a static array of size 16 (testing purpose only).
we are not working with actual pointers; because we don't need them in this case (I think), I named the question on the algorithm's
name only.

#include <iostream>
#include <vector>
using namespace std;

struct result
 {
     int num1;
     int num2;
     result() {}

     result(int num1, int num2)
         : num1{ num1 }, num2{ num2 } {}
 };

 vector<result> mult_pt(int arr[], int target)
 {
     int p1 = 0;
     int p2 = 15;
     bool flag = false;
     vector<result> res;
     while (p1 <= p2)
     {
         if (arr[p1] + arr[p2] == target)
         {

             for (int k = 0; k < res.size() - 1; k++)
             {
                 if (res.size() == 0)
                     res.push_back(result(arr[p1], arr[p2]));
                 else if (res[k].num1 != arr[p1] && res[k].num2 != arr[p2])
                 {
                     flag = false;
                 }
                 else flag = true;
             }
             if(flag) res.push_back(result(arr[p1], arr[p2]));
             p1++;
         }
         else if (arr[p1] + arr[p2] < target)
         {
             p1++;
             continue;
         }
         else if (arr[p1] + arr[p2] > target)
         {
             p2--;
             for (int i = p1; i >=0; i--)
             {
                 if (arr[i] + arr[p2] == target)
                 {
                     res.push_back(result(arr[p1], arr[p2]));
                 }
                 else if (arr[i] + arr[p2] > target)
                 {
                     continue;
                 }
                 else break;
             }
         }
     }
     return res;
 }

int main ()
{
  int array[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
  vector <result> res = mult_pt(array, 19);
  for (int j = 0; j < res.size(); j++)
    {
        cout << "[ " << res[j].num1 << " , " << res[j].num2 << " ]" << endl;
    }
  return 0;
}

The output should be like:
[ 4 , 15 ]
[ 5 , 14 ]
[ 6 , 13 ]
[ 7 , 12 ]
[ 8 , 11 ]
[ 9 , 10 ]
[ 10 , 9 ]

You can check the previous post here.

using namespace std;
There are lot of good answers why you shouldn't use it. See here

Use std::pair<int, int>
Since your result struct is just acting as a container for two ints, consider using std::pair<int, int>

Don't hardcode values
Why do you want hardcode 16 as the array length? You can just pass it to the function as a parameter, or use std::array. Your code should be able to handle any number of elements.

while(p1 <= p2)
This is incorrect. This will allow the algorithm to run for single length arrays as well. For example, consider the array {7} and target value 14. Your code returns {7,7} as an answer. In fact, the rogue [10, 9] in your output is a direct result of this.

Comparison of signed and unsigned ints
If you turn on warnings -Wall -pedantic, you will see your compiler warn you about comparing signed and unsigned ints. For example, comparing k which is a signed int to res.size() - 1 which is an unsigned int.
In fact, you're quite lucky that the first time you encounter a valid pair, it's inserted into the result vector. res.size() - 1 wraps around to whatever the maximum value of vector<result>::size_type is (in my case, 18446744073709551615) which means k < res.size() - 1 is valid.
In fact, you don't even need this entire loop (see below).
Use curly braces consistently
Your use of curly braces is very inconsistent. As a general use, always use curly braces for your conditional statements. It looks cleaner and can help avoid subtle bugs.

Since you're using arr[p1] + arr[p2] quite a bit, better to use a variable to store the value.

if(res.size() == 0) is irrelevant because it's always gonna be false (ignoring that one case at the very beginning because it's poor code, not an edge case to be handled).

I'm still not quite sure what the flag variable is mean to do. All your inner loop is doing is looking at the second to last element in the res vector and comparing values. flag will never be true unless the second to last element in the res vector has elements matching arr[p1] and arr[p2].

You have needlessly complicated your algorithm (the inner loop inside of the else if block, for example).
In pseudocode, this algorithm can be written as:
while(p1 < p2)
      sum = array[p1] + array[p2]
      if sum == target
           insert into res vector
           p1++
           p2--
     else if sum < target
           p1++
    else
           p2--

You could use res.emplace_back(arr[p1], arr[p2]); instead of res.push_back(result(arr[p1], arr[p2]));. The former constructs the struct in-place, while the latter might invoke the move constructor.


Show and paginate only child categories with wordpress query I'm using this piece of code to show and paginate only child categories but this is horribly slow (49 queries in 9,799 seconds.).

Where did I make mistakes and how can I make this run faster?

<?php

$current_cat = get_query_var('cat');
$attributes = array('terms_per_page' => 20, 'taxonomy' => 'category');

// Sanitize and validate our inputs and set variables
$tpp = filter_var( $attributes['terms_per_page'], FILTER_VALIDATE_INT );
$taxonomy = filter_var( $attributes['taxonomy'], FILTER_SANITIZE_STRING );

// Make sure our taxonomy exists to avoid unnecessary work
if ( !taxonomy_exists( $taxonomy ) )
return false;

// Our taxonomy exists, lets continue
// Get the term count to calculate pagination.
$term_count = count( get_terms('category',array('hide_empty'=>'1','child_of' => $current_cat) ) );

// We have terms, now calculate pagination
$max_num_pages = ceil( $term_count / $tpp );
// Get current page number. Take static front pages into account as well
if ( get_query_var('paged')){
$paged = get_query_var('paged');
} elseif ( get_query_var('page')) {
$paged = get_query_var( 'page' );
} else {
$paged = 1;
}
// Calculate term offset
$offset = ( ( $paged - 1 ) * $tpp );

// We can now get our terms and paginate it
$args = array(
'number'     => $tpp, // Amount of terms to return
'offset'     => $offset, // The amount to offset the list by for pagination
'child_of'   => $current_cat,
'orderby'    => 'name',
'order'      => 'ASC',
'hide_empty' => '1',
);
// Set our variable to hold our string
$output = '';
$wpbtags = get_terms( $taxonomy, $args );

if ( ! empty($wpbtags)) {
foreach ($wpbtags as $category) {

//first get the current category ID
$cat_prefix = "category_";
$cat_id = $category->term_id;
//then i get the data from the database
$join_cat = $cat_prefix . $cat_id;
$cat_data = get_option($join_cat);?>

<a href="<?php echo get_category_link($category->term_id); ?>"     onclick="ga('send', 'event', 'ClickNav', 'cats', 'Cat - <?php echo $category-    >cat_name; ?>');">
<div class="one_fourth<?php echo ( ++$counter == 4 )?' last_column':''; ?> home-colour" title="<?php echo $category->name; ?>">

<?php if (!empty($cat_data['cat_img_url'])) : ?>

 <?php echo $category->name; ?>

<img class="res_img" src="<?php echo $cat_data['cat_img_url'] ;?>" alt="<?php echo $category->cat_name; ?>" width="310" height="209" />

<?php elseif (empty($cat_data['cat_img_url'])) :?>

 <?php echo $category->name; ?>

<img class="res_img" src="<?php echo get_stylesheet_directory_uri(); ?>/images/subcat-img-na.png" alt="Posts - <?php echo $category->cat_name; ?>"/>

<?php else : ?>
<?php endif; ?>

<?php } ?>

<?php /* COUNTS FOUR ADDS LAST COLUMN */ if ( $counter == 4 ) : ?>

<?php $counter = 0; endif; wp_reset_query(); ?>

<?php echo '
';
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $max_num_pages = (ceil( $term_count / $tpp))
) );

echo '
';
?>

<?php wp_reset_postdata(); ?>

<?php  /* IF THERE'S NOTHING TO SHOW */ } else {?>

// Show something if there is no posts here

<?php } ?>

The real problem here is that you are querying in loops (almost always a bad pattern) because you are relying on built-in Wordpress querying functions, rather than writing raw SQL to query all this data at once.

My guess is you can do a single query to get both the paginated results and the total number of rows without limit being applied (by using SQL_CALC_FOUND_ROWS).

You might consider opening StackOverflow question specifically about the multiple/slow query problems along with information on your database tables relevant to these queries to get a suggestion on how to write an appropriate query.

Outside of that, I find your code incredibly difficult to read, and while some of that might have to do with following style conventions in Wordpress (which really bad IMO), you should at least indent you code and place comments properly (i.e. not prepending comment on code lines).


DisjointSet with O(1) find and O(1) amortised union Does this code outperform the common implementation with path-compression and union-by-rank?  I'm still okay with a review.

GitHub

import java.util.*;

public class DisjointSet<E> {
    public static void main(String... args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();

        DisjointSet<String> set = new DisjointSet<>();

        for (int i = 0; i < n; i++) {
            String a = s.next();
            String b = s.next();
            set.union(a, b);
        }

        System.out.println(set);
    }

    /**
    * a map from each element to a reference to the set
    * that contains them. The reference is used so that many
    * map entries can be updated at once in O(1) without
    * the cost of iterating through each entry.
    * This occurs when performing the union. If we are merging
    * a set A and a set B then we would otherwise be required
    * to iterate through all of B's entries and point them to
    * A and then call A.addAll(B). By having a mutable reference
    * we skip the iteration and update all entries of B in O(1).
    */
    private HashMap<E, Ref<Set<E>>> map = new HashMap<>();

    /**
    * a set of references to subsets.
    * Just used for #toString().
    */
    private Set<Ref<Set<E>>> refs = new HashSet<>();

    /**
     * @time worst case O(n), amortised O(1)
     */
    public void union(E a, E b) {
        Ref<Set<E>> ra = map.get(a);
        Ref<Set<E>> rb = map.get(b);

        Set<E> sa = ra != null ? ra.value : null;
        Set<E> sb = rb != null ? rb.value : null;

        Set<E> t;

        if (sa == null && sb == null) {
            t = new HashSet<>();
            t.add(a);
            t.add(b);
        } else if (sa != null && sb != null) {
            t = sa.size() > sb.size() ? sa : sb;

            // addAll is worst-case O(n) but you have to add n items to be able to
            // experience that worst case, and all intermediate adds will be O(1),
            // so #union is amortised O(1)
            t.addAll(sa.size() > sb.size() ? sb : sa);
        } else {
            t = sa != null ? sa : sb;
            t.add(a);
            t.add(b);
        }

        Ref<Set<E>> ref = ra != null ? ra : rb != null ? rb : new Ref<>();

        ref.value = t;

        map.put(a, ref);
        map.put(b, ref);

        refs.remove(ra);
        refs.remove(rb);
        refs.add(ref);
    }

    /**
     * @param e the element whose (sub)set you would like to find.
     * @return the set that e belongs to or null if it is not present
     * @time O(1)
     */
    public Set<E> find(E e) {
        Ref<Set<E>> ref = map.get(e);
        return ref != null ? ref.value : null;
    }

    /**
     * @time O(n)
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();

        for (Ref<Set<E>> ref : refs) {
            builder.append(ref.value);
            builder.append('\n');
        }

        return builder.toString();
    }

    private class Ref<R> {
        private R value;

        Ref(R r) {
            value = r;
        }

        public Ref() {

        }
    }
}

Union is \$O(\log n)\$, not \$O(1)\$

Consider a case where 1024 elements are initially added to their own set.  Then do 512 unions of pairwise neighbors to make 512 sets of 2 elements each.  This requires 512 copies in the "addAll" step, because half the elements are moved to a new set.  Then do 256 unions of pairwise neighboring sets to make 256 sets of 4 elements each.  This also requires 512 copies, because again half of all elements are moved to a new set.  Continue to do unions in passes, where each pass you end up with 2x the number of sets as before.  In the end, you will need 10 passes, and each pass will require 512 elements to be moved.

As you can see from the above, with N=1024, you end up with N unions taking N * log N copies, or on average log N copies per union.


Convert seconds to hours/minutes/seconds and pretty print I'm self taught in python 3, and I frequently keep track of how long my scripts have been running using the time library.

import time
startTime = time.time()

#The main body of script...

print('The script finished in {0} seconds'.format(time.time() - startTime)

However this can be unhelpful if the script has been running for some time, an example output being:

'The script has been running for 4323.580279111862 seconds'

I wrote a function which takes a float variable and prints the time in a more readable way. I convert the seconds to integer to get rid of the 12 decimal places, and I can pass a boolean value which changes the wording of the print to indicate that the script is still running or has finished.

def printRuntime(seconds,finished=False):
    seconds = int(seconds)
    status = 'has been running for'
    if finished == True:
        status = 'finished in'

    if seconds < 60:
        print('The script {} {} seconds'.format(status,seconds))
        return
    elif seconds < 3600:
        minutes = seconds // 60
        seconds = seconds - 60*minutes
        print('The script {} {} minutes & {} seconds'.format(status,minutes,seconds))
        return
    else:
        hours = seconds // 3600
        minutes = (seconds - 3600*hours) // 60
        seconds = seconds - 3600*hours - 60*minutes
        print('The script {} {} hours, {} minutes & {} seconds'.format(status,hours,minutes,seconds))
        return

import time
startTime = time.time()

#The main body of script...

printRuntime(time.time() - startTime)

Since I'm self taught I have no real idea about best practice. I feel like there must be a more concise way of doing this, what mistakes am I making?

There is a built-in timeit module which is quite convenient for measuring execution times, but, if we were to improve this particular solution, I would switch to using divmod as suggested by Brandon here, utilize short if/else version for the status definition and join the time value parts with a comma filtering non-zero values only.

Something along these lines:

seconds = int(seconds)
status = 'has been running for' if not finished else 'finished in'

minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)

periods = [('hours', hours), ('minutes', minutes), ('seconds', seconds)]
time_string = ', '.join('{} {}'.format(value, name)
                        for name, value in periods
                        if value)

print('The script {} {}'.format(status, time_string))


Using AbstractFactory I am a newcomer to design patterns. I read some articles about the abstract factory pattern, and wrote the following simple example:

public interface ParserFactory {
   List<ITransport> getBusList();
   List<ITransport> getTrainList();
   List<ITransport> getPlaneList();
}

public abstract class XMLParserFactory implements ParserFactory{ }
public abstract class CSVParserFactory implements ParserFactory{ }

public class DOMTransportParser extends XMLParserFactory{

    public List<ITransport> getBusList(){ return null;  }
    public List<ITransport> getTrainList(){ return null; }
    public List<ITransport> getPlaneList(){ return null; }
 }

 public class CSVTransportParser extends CSVParserFactory{

    public List<ITransport> getBusList(){   return null; }
    public List<ITransport> getTrainList(){ return null; }
    public List<ITransport> getPlaneList(){ return null; }
 }

}

Is anything wrong with this code? Can it be improved? Do I understand the abstract factory pattern correctly?

This isn't really an Abstract Factory. Going on the theme of what you've got above (although I'm not sure what trains, planes and buses have to do with parsing!), an Abstract Factory would look something like the following:

public interface Parser
{
    List<ITransport> getBusList();
    List<ITransport> getTrainList();
    List<ITransport> getPlaneList();
}

public interface ParserFactory
{
    Parser getParser();
}

public class XMLParser implements Parser
{
     //Implementation of Constructors and Interface methods from Parser
}

public class CSVParser implements Parser
{
     //Implementation of Constructors and Interface methods from Parser
}

public class XMLParserFactory implements ParserFactory
{
    public Parser getParser()
    {
        return new XMLParser();
    }
}

public class CSVParserFactory implements ParserFactory
{
    public Parser getParser()
    {
        return new CSVParser();
    }
}

This is then used in some way like the following:

public class Main
{
    //Note: Using a String is for illustrative purposes only. Ideally
    //it should be using some system or file setting. Half the point
    //of this pattern is that the caller doesn't know what kind of
    //object they are getting back (which probably doesn't make too much
    //sense for parsers, really).
    public static ParserFactory createParserFactory(String type)
    {
        if(type.equals("XML") {
            return new XMLParserFactory();
        } else {
            return new CSVParserFactory();
        }
    }

    public Main(ParserFactory factory)
    {
        Parser parser = factory.getParser();
        List<ITransport> bus = parser.getBusList();
    }

    public static void main(String[] args)
    {
        new Main(createParserFactory("XML"));
    }

So what's the point of all this (it's quite a lot of code, after all). Well, firstly, it insulates the caller from knowledge of the concrete type. They don't know what kind of Parser they're getting back, the implementation details are hidden from them. Secondly, it localizes all object creation through a single point, which means client code will need very minimal updates when things change. For example, say we want to add a new kind of Parser - let's say a JSONParser - to our code. Then we create a factory and parser like we did previously:

public class JSONParser implements Parser
{ // Implementation details
}

public class JSONParserFactory implements ParserFactory
{
    public Parser getParser() { return new JSONParser(); }
}

Then we simply add it to our getParserFactory method:

    public static ParserFactory createParserFactory(String type)
    {
        if(type.equals("XML") {
            return new XMLParserFactory();
        }
        else if(type.equals("JSON") {
            return new JSONParserFactory();
        } else {
            return new CSVParserFactory();
        }
    }

Note that any client code will be calling createParserFactory() and then getParser from that - so ideally, if they want to switch in a JSONParser, the only thing that needs to change in their code is the call to createParserFactory("JSON").

Hopefully this has cleared things up a little bit (and not confused you too much).


Building a list - why is this code inefficient? I'm attempting this code challenge.

Here's my code modified to handle one simple example test case:

string = "bcdefghij"
l = string.size

result = []

permutations = string.split('').permutation.to_a

l.times do
  permutations.each {|p| result << p.sort.join}
  permutations.map! {|p| p[1..-1]}
end

puts result.uniq.sort

It produces the correct result but it's way too slow. I've played around with benchmarking and it looks like the slowest part of the code is this line:

permutations.each {|p| result << p.sort.join}

Can I speed this code up somehow? Or am I thinking about the original problem all wrong?

RESULT

Thanks to Nat's answer below I came up with this:

string = "bcdefghij".split('')
l = string.length

result = []
(1..l).each {|i| result += string.combination(i).to_a}
puts result.map{|r| r.join}.sort

Benchmarks

Before: 6.480000   0.310000   6.790000 (  6.794669)

After: 0.000000   0.000000   0.000000 (  0.003087)

It's inefficient because you're doing a lot of work to create a factorial l, iterating over it l times, each time REDOING all the work of sorting and joining each permutation, and then throwing away most of the results!

Here are some suggestions:

You don't need to extend permutations into an array in memory (loose the to_a), a generator is generally more efficient to iterate over.
You don't need to sort and join the permutations again for every length, this is probably the biggest waste of time. Once they've been sorted and joined you can uniqify them then and then create shorter strings from them (which will need uniqifying again but this will be less work).
Finally, if instead you split and sort the input string at the beginning then you can use the combination function to generate only valid combinations for each length.


Reverse word by word efficiency I have a method that reverse each word in a string. I want to know how I can increase it's performance and memory efficiency. Ideas I had in mind were simply using char[] instead of strings being that strings are immutable and each time I concatenate the Strings, I am creating a new String object which is not efficient at all.

Example:

hi there cow  --> ih ereht woc

Code:

public static String reverseWord(String str) {
    int len = str.length();
    String strResult = "";
    String strBuffer = "";
    for (int i = 0; i < len; i++) {
        if (str.charAt(i) != ' ') {
            strBuffer = str.charAt(i) + strBuffer;
        }
        else if (str.charAt(i) == ' ') {
            strResult += strBuffer + " ";
            strBuffer = "";
        }
    }
    strResult += strBuffer;
    return strResult;
}

Ideas I had in mind were simply using char[] instead of strings being that strings are immutable and each time I concatenate the Strings, I am creating a new String object which is not efficient at all.

Yes, that will be faster. Go ahead and write it :-)
Instead of Strings like strResult and strBuffer you could use StringBuilders (although using char is probably faster). StringBuilder is mutable and would be faster than using Strings. StringBuilder also supports insert(offset, char) but also has a reverse method.
I'd rename  strResult to result (to avoid Hungarian notation) and strBuffer to the more descriptive currentWord.

if (str.charAt(i) != ' ') {
    ...
}
else if (str.charAt(i) == ' ') {
    ...
}

The following is the same, you don't need the second, inverted condition:

if (str.charAt(i) != ' ') {
    ...
} else {
    ...
}

You might want to use a more another check for spaces. Currently it handles tabs (\t) as normal characters and

"hi\tthere\tcow"

will be

"woc\tereht\tih"

Here is a slightly improved version with StringBuilders:

public static String reverseWord(String str) {
    int len = str.length();
    StringBuilder result = new StringBuilder();
    StringBuilder currentWord = new StringBuilder();
    for (int i = 0; i < len; i++) {
        if (str.charAt(i) != ' ') {
            currentWord.insert(0, str.charAt(i));
        } else {
            result.append(currentWord).append(" ");
            currentWord.setLength(0);
        }
    }
    result.append(currentWord);
    return result.toString();
}


Algorithms to find statistical information of an array I was working on a program that creates an array, then gives statistical information about that array such as std dev, median, mode average etc.

I have written a method for each statistical value, however I am not too sure that they are efficient, particularly the getMode() method.

I would be really happy if you helped me to make these methods memory efficient and fast as possible. Thanks, here are my methods:

private static int getMode(int[] x) {

    int max_mode = 0;
    int count = 0, count_max = 0;
    for (int i = 0; i < x.length; i++) {
        for (int j = 0; j < x.length; j++) {
            if (x[i] == x[j]) {
                count++;
            }
        }
        if (count >= count_max) {
            count_max = count;
            max_mode = x[i];
        }
        count = 0;
    }
    return max_mode;
}

private static double getMedian(int[] x) {
    int[] sorted = x;
    sort(sorted);
    double median;
    if (sorted.length % 2 == 0) {
        median = sorted[(sorted.length / 2 - 1 + sorted.length / 2) / 2];
        median += 0.5;
    } else {
        median = sorted[sorted.length / 2];
    }

    return median;

}

private static int[] sort(int[] x) {
    int temp;
    int[] sorted = x;
    for (int i = 1; i < sorted.length; i++) {
        for (int j = 0; j < sorted.length; j++) {
            if (sorted[i] < sorted[j]) {
                temp = sorted[i];
                sorted[i] = sorted[j];
                sorted[j] = temp;
            }
        }
    }
    return sorted;
}

private static double getAverage(int[] x) {
    double sum = 0;
    double avg;
    for (int i = 0; i < x.length; i++) {
        sum += x[i];
    }
    avg = sum / x.length;
    return avg;

}

private static int getSum(int[] x) {
    int sum = 0;
    for (int i = 0; i < x.length; i++) {
        sum += x[i];
    }
    return sum;
}

private static int getMax(int[] x) {
    int tempmax = 0, realmax = 0;
    for (int i = 0; i < x.length; i++) {
        for (int j = 0; j < x.length; j++) {
            if (x[i] > x[j]) {
                tempmax = x[i];
            }

        }
        if (tempmax > realmax) {
            realmax = tempmax;
        }
        tempmax = 0;
    }
    return realmax;
}

private static int getMin(int[] x) {
    int templow = 0, reallow = 0;
    for (int i = 0; i < x.length; i++) {
        for (int j = 0; j < x.length; j++) {
            if (x[i] < x[j]) {
                templow = x[i];
            }
        }
        if (templow <= reallow) {
            reallow = templow;
        }
        templow = 0;
    }
    return reallow;
}

private static double getStdDev(int[] x) {
    double sum = 0;
    double avg = getAverage(x);
    for (int i = 0; i < x.length; i++) {
        sum += (x[i] - avg) * (x[i] - avg);
    }
    return Math.sqrt(sum / (x.length - 1));
}

Glaring Deficiencies

Let me venture here that your getMedian method is slower than your getMode method. Thanks to your sort. You use a naive bubble-sort, which is \$O(n^2)\$. It can be done using \$O(n\log(n))\$ using quicksort (for practical input), mergesort, heapsort, etc. However, you can get the best of all worlds by just using the static method sort() from java.util.Arrays. It will get you an implementation of mergesort or Timsort, both very fast compared to bubble sort.
About getAverage. You recalculate the sum in a loop where you already have a getSum method. Use that.
You have really inconsistent return types in some places, especially getSum and getMedian.
In getMedian, int[] sorted = x; probably doesn't do what you want it to do, which is create a copy of the argument array which you can sort. Try using int[] sorted = Arrays.copyOf(x, x.length); instead, which will do the required deep copy instead of a reference assignment.

I disagree with @coderodde's approach. You should get what you ask for when computing statistics. You should not incur costs which you do not deserve. That is, if you want to get the average of all the elements in an array, you should not have to pay the overhead of sorting it and calculating the median.

Algorithmic improvements

In getMin and getMax, set the default value of the accumulator variable to the first element of the array, i.e., arr[0], and start the loop at 1 instead of 0. It makes more sense. Or, better, use Streams, they have these methods in-built.
Use @coderodde's idea for calculating mode, as that is \$O(n+n\log(n)) = O(n\log(n))\$, whereas yours is currently \$O(n^2)\$ in the worst case. That is, his way is faster.

Note, however, that your mode calculation algorithm is a bit problematic; for an input set {1, 1, 2, 4, 4}, your code will return 4, though for a multimodal set it would be mathematically appropriate to return the first mode, i.e., 1 here.

I have managed to fashion a faster approach to the problem, involving only partially sorting and partitioning the array, however, this works correctly only for unimodal sets (and works in a mathematically correct fashion for multimodal sets). I use the naive approach to get all the modes of a multimodal set.

In my code it appears that I need \$O(n)\$ additional space due to the Set<Mode> used for maintaining multimodal data, but for unimodal data, this is unnecessary and it can be made to work in \$O(n\log(n))\$ time and \$O(1)\$ additional space.

I make both pieces of code return a double[] (in the former case, a single-element array even for multimodal sets), for API consistency.
Use a selection algorithm, such as the Floyd-Rivest Algorithm for calculating the median in linear time, instead of the best-case \$O(n\log(n))\$ when using sorting.
Use a numerically stable one-pass algorithm like Welford's Method to get the variance / standard deviation.

Ideas

You should name getAverage to getArithmeticMean, as that is the more appropriate statistical term here.
As regards the above, you could try implementing a getGeometricMean, which would be calculated as follows:

\$GM = \sqrt[n]{\prod\limits_{i=1}^n x_i}\$

Or, the \$n\$th root of the product of \$n\$ numbers.

Suggestions

Java 8's Streams would help a lot here.
Declare your method parameters final. That way, the caller will not have to worry about you changing their data out from under their feet (it's not especially helpful with arrays, but even so).
Try using the for-each loop where you don't need explicit indexing, rather just the elements in sequence, e.g. in getMode.
Try to fail-fast: throw exceptions when you encounter exceptional conditions, like being supplied an empty array (java.util.NoSuchElementException seems to be a good fit for this use case).

New Code:

Note that this is not one of the best examples when it comes to coding in Java, but take a look at it anyway (there are comments when the going gets tough). There are usually 2 versions of each method, one utilizing your original idea, the other utilizing a faster algorithm. The naive versions have UnOpt suffixed to their names. Except in the case of getMode as noted above, both versions are semantically equivalent. In case of the Floyd-Rivest algorithm used in select, there are some magic numbers, you can look at the linked Wikipedia article for details.

import java.util.*;
import java.util.stream.*;
import static java.lang.Math.*;
public class Stats{
    private static double[] unbox(Collection<Double> collection){
        return collection.stream().mapToDouble(Double::doubleValue).toArray();
    }

    public static double[] getModesUnOpt(final double[] x) {
        Set<Double> modes = new HashSet<>(x.length);
        long count = 0, countMax = 0;
        for (final double v : x) {
            count = Arrays.stream(x).filter(y -> y == v).count();
            if (count >= countMax) {
                if(count > countMax){
                    countMax = count;
                    modes.clear();
                }
                modes.add(v);
            }
            count = 0;
        }
        return unbox(modes);
    }

    public static double getModeUnOpt(final double[] x) {
        return getModes(x)[0];
    }

    private static class Mode{
        public double Value = 0.0;
        public int Count = 0;
    }

    public static class Pair<L, R>{
        public final L left;
        public final R right;
        public Pair(L left, R right){
            this.left = left;
            this.right = right;
        }
    }

    public static double getMode(final double[] x){
        return getModes(x)[0];
    }

    public static double[] getModes(final double[] x){
        return findModePartialSortRecursive(x, 0, x.length, new Mode(), new HashSet<>()).right.stream().mapToDouble(y -> y.Value).toArray();
    }

    private static Pair<Mode, Set<Mode>> findModePartialSortRecursive(final double[] array, int begin, int end, Mode best, Set<Mode> modes){
        int pivotIndex = (int) (begin + (random() * (end - begin)));
        Mode mode = best;
        double pivot = array[pivotIndex];
        int left = begin, right = end - 1, pos = left;
        Pair<Mode, Set<Mode>> data = new Pair<>(best, modes);
        while (pos <= right){
            if (array[pos] < pivot){
                array[left++] = array[pos++];
            }
            else if (array[pos] > pivot){
                swap(array, right, pos);
                --right;
            }
            else{
                ++pos;
            }
        }
        int pivotCount = right - left + 1;
        for (int i = left; i <= right; i++){
            array[i] = pivot;
        }
        if (pivotCount >= mode.Count){
            if(pivotCount > mode.Count){
                mode.Value = pivot;
                mode.Count = pivotCount;
            }
            modes.add(mode);
            data.left = mode;
            data.right = modes;
        }
        int leftCount = left - begin;
        if (leftCount > mode.Count){
            data = findModePartialSortRecursive(array, begin, left, mode, modes);
        }
        int rightCount = end - right - 1;
        if (rightCount > mode.Count){
            data = findModePartialSortRecursive(array, right + 1, end, mode, modes);
        }
        return data;
    }

    public static void swap(double[] array, int i, int j){
        double temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    /**
     * Uses the Floyd-Rivest Algorithm for a quickselect with median-optimized pivot selection.
     * Modifies the input array such that array[k] is the (k - left + 1)th smallest element in the array.
     */
    public static double select(double[] array, int left, int right, int k){
        while(right > left){
            // use select recursively to sample a smaller set of size s
            // the arbitrary constants 600 and 0.5 are used in the original
            // version to minimize execution time
            if(right - left > 600){
                double n = right - left + 1;
                double i = k - left + 1;
                double z = log(n);
                double s = 0.5 * exp(2.0 * z/3.0);
                double sd = 0.5 * sqrt(z * s * (n - s)/n) * signum(i - n/2);
                int newLeft = (int)max(left, k - i * s/n + sd);
                int newRight = (int)min(right, k + (n - i) * s/n + sd);
                select(array, newLeft, newRight, k);
            }
            // partition the elements between left and right around t
            double t = array[k];
            int i = left;
            int j = right;
            swap(array, left, k);
            if(array[right] > t){
                swap(array, right, left);
            }
            while(i < j){
                swap(array, i, j);
                ++i;
                --j;
                while(array[i] < t){
                    ++i;
                }
                while(array[j] > t){
                    --j;
                }
            }
            if(array[left] == t){
                swap(array, left, j);
            }
            else{
                ++j;
                swap(array, j, right);
            }
            // adjust left and right towards the boundaries of the subset
            // containing the (k - left + 1)th smallest element
            if(j <= k){
                left = j + 1;
            }
            if(k <= j){
                right = j - 1;
            }
        }
        return array[k];
    }

    public static double getMedian(final double[] x){
        if(x.length == 0){
            throw new NoSuchElementException("Median of an empty array cannot be found");
        }
        int halfLength = x.length / 2, endIndex = x.length - 1;
        //calculate a generic median
        double median = select(Arrays.copyOf(x, x.length), 0, endIndex, halfLength);
        if((x.length % 2) == 1){
            //length is odd, only 1 middle element to consider
            return median;
        }
        //length is even, 2 median elemnts to consider.
        return (median + select(Arrays.copyOf(x, x.length), 0, endIndex, halfLength - 1)) / 2.0;
    }

    public static double getMedianUnOpt(final double[] x) {
        if(x.length == 0){
            throw new NoSuchElementException("Median of an empty array cannot be found");
        }
        double[] sorted = Arrays.copyOf(x, x.length);
        Arrays.sort(sorted);
        double median;
        if (sorted.length % 2 == 0) {
            //length is even, 2 median elemnts to consider.
            median = sorted[(sorted.length / 2 - 1 + sorted.length / 2) / 2] + 0.5;
        } else {
            //length is odd, only 1 middle element to consider
            median = sorted[sorted.length / 2];
        }
        return median;
    }

    public static double getArithmeticMean(final double[] x) {
        return Arrays.stream(x).average().getAsDouble();
    }

    public static double getGeometricMean(final double[] x) {
        return Arrays.stream(x).reduce((a, b) -> a * b).getAsDouble();
    }

    public static double getSum(final double[] x) {
        return Arrays.stream(x).sum();
    }

    public static double getMin(final double[] x){
        return Arrays.stream(x).min().getAsDouble();
    }

    public static double getMax(final double[] x){
        return Arrays.stream(x).max().getAsDouble();
    }

    /**
     * Uses Welford's method for calculating variance in 1 pass.
     */
    public static double getVariance(final double[] x){
        if(x.length == 0){
            throw new NoSuchElementException("Variance of an empty array cannot be found");
        }
        int n = 0;
        double mean = 0.0, M2 = 0.0;
        for(double y : x){
            ++n;
            double delta = y - mean;
            mean += delta / n;
            M2 += delta * (y - mean);
        }
        return M2 / (n - 1);
    }

    public static double getStandardDeviation(final double[] x){
        if(x.length == 0){
            throw new NoSuchElementException("Standard Deviation of an empty array cannot be found");
        }
        return sqrt(getVariance(x));
    }

    public static double getStandardDeviationUnOpt(final double[] x) {
        if(x.length == 0){
            throw new NoSuchElementException("Standard Deviation of an empty array cannot be found");
        }
        double sumDiffs = 0;
        double avg = getArithmeticMean(x);
        for (int i = 0; i < x.length; i++) {
            sumDiffs += (x[i] - avg) * (x[i] - avg);
        }
        return sqrt(sumDiffs / (x.length - 1));
    }
}


Preventing unwanted access I have some code that is helping to protect some online surveys. The surveys have an incentive in the form of an Amazon voucher or cash (which is manually/semi-automatically distributed post-survey) so as you can imagine, we get a lot of people attempting to get multiple vouchers, or undesirable respondents mainly from China.

Of course the main way to prevent this, is to send out unique links to a set of pre-recruited people, however this isn't always an option and hence the need for some kind of protection.

Here is the code, I've removed 2 SQL insert queries to reduce the size of this post:

$countryCode = sanitise($_SERVER["HTTP_CF_IPCOUNTRY"]);
$allowedCountries = getAllowedCountries($projectID); // array('GB', 'US', 'SE');

if(in_array($countryCode, $allowedCountries)) {

    // Count records with matching ip for this project, >=1 TRUE, 0 FALSE
    $isBlocked = checkForBlockedIP($projectID, $ip);

    if($isBlocked == TRUE) {

        header("Location: error.php?blocked");

    } else {

        // Count records with matching ip for this project, >=1 TRUE, 0 FALSE
        $isDuplicate = checkForDuplicateResponse($projectID, $ip);

        if ($isDuplicate == TRUE) {

            //<Removed>
            // Store identifying data into dup_attempts table
            // and block ip from further attempts

            header("Location: error.php?duplicate");

        } else {

            // Create redirect link and send user to it

            $redirectLink = $projectLink . $userID;
            header("refresh:3; url=" . $redirectLink . "");

        }

    }

}

I'm posting this here, because I'm not a professional developer and I don't know if I'm taking the right approach here. Perhaps my approach as a whole is wrong.

I'm allowing only certain countries to participate, checking for a duplicate IP (per project) and if one is found, then I'm storing it in a table for duplicate attempts and adding the IP to a blacklist for that project.

I agree with the comment above about IP-based restriction perhaps not being the best approach here, or at least not using it as the only means to detect duplicates.

I think GeoIP is reasonable for blocking at a country level (though certainly not foolproof).

I think IP address might be a reasonable component to duplicate detection.  You could also add other duplicate detection mechanisms including:

User ID (which is something you seem to have but are not using - I would think this would be most authoritative piece of information if there is authentication/login attached to this user ID)
setting a cookie
inspecting user agent
setting value in browser localStorage and then have browser add to request (localStorage is a little harder for a typical user to clear out than cookies)

With regards to the code itself, you should get in the practice of inverting conditions when you have large blocks of code nested in a conditional (or really just in general to provide clear, early exit paths from a section of code).

For example:

if(!in_array($countryCode, $allowedCountries)) {
    // set location header and exit
}
if (checkForBlockedIP($projectID, $ip)) {
    // set location header and exit
}
if (checkForDuplicateResponse($projectID, $ip)) {
    // set location header and exit
}
// happy path code follows

There is no reason for your else blocks at all here from what I can tell.  As a general rule of thumb, the less nested code and code branches you have, the less prone your code is to bugs, so you should actively look to design away such constructs where possible.


Object Oriented Graph Hierarchy with Depth First Search I would like to receive review on my code. It has only depth first search (DFS) and bidirected graph  is the only member of the hierarchy. I added name member for the BiGraph to make it easier to debug in the future, because there might be several BiGraph instances. Also, I would like the review to primarily focus on names of the functions'. I couldn't come with better names. The last thing is performing DFS. I think there are too many indirections, so, could you please suggest some relaxations? Any other suggestions are appreciated.

The call to make DFS is achieved through calling areConnected which calls implementation. Implementation resets the history of the last DFS, and then calls traverse which actually performs DFS and fills the isvVisited bool array, which indicates all vertices which were visited.

Graph.h

#pragma once
#include <vector>

class Graph
{
public:
    Graph()=default;

    void addAdjacent(int fvertex, int svertex) { addAdjacentImpl(fvertex, svertex); }
    const std::vector<bool>&  areConnected(int sourcevertex) { return areConnectedImpl(sourcevertex); }
    void print() { printImpl(); }
    virtual ~Graph()=default;

private:
    virtual void printImpl() const = 0;
    virtual void addAdjacentImpl(int fvertex, int svertex) = 0;
    virtual const std::vector<bool>& areConnectedImpl(int sourcevertex) = 0;
    virtual void traverse(int sourcevertex) = 0;
};

BiGraph.h

#pragma once
#include "graph.h"
#include <vector>
#include <string>

class BiGraph :public Graph
{
    std::vector<std::vector<int> > graph;
    int maxVertexCount;
    std::string name;
    std::vector<bool> isVisited;
public:
    BiGraph(int maxVertexCount_, std::string name_);

    ~BiGraph();
private:
    virtual void printImpl() const override;
    virtual void addAdjacentImpl(int fVertex, int sVertex) override;
    virtual const std::vector<bool>& areConnectedImpl(int sourcevertex) override;
    virtual void traverse(int sourceVertex) override;
};

BiGraph.cpp

#include "BiGraph.h"
#include <exception>
#include <iostream>

void ZeroBoolArray(std::vector<bool>& arr)
{
    for (auto &x : arr)
    {
        x = false;
    }
}

BiGraph::BiGraph(int maxvertexcount_, std::string name_):graph(maxvertexcount_), maxVertexCount(maxvertexcount_), name(name_), isVisited(maxVertexCount)
{

}

void BiGraph::addAdjacentImpl(int fVertex, int sVertex)
{
    if (fVertex > maxVertexCount)
    {
        throw std::out_of_range(name + ": trying to add vertex which doesn't exist");
    }
    graph[fVertex].push_back(sVertex);
    graph[sVertex].push_back(fVertex);
}

void BiGraph::traverse(int sourceVertex)
{
    if (isVisited[sourceVertex])
        return;
    isVisited[sourceVertex] = true;
    for (auto& x:graph[sourceVertex])
    {
        traverse(x);
    }
}

const std::vector<bool>& BiGraph::areConnectedImpl(int sourceVertex)
{
    ZeroBoolArray(isVisited);
    traverse(sourceVertex);
    return isVisited;
}

BiGraph::~BiGraph()
{

}

void BiGraph::printImpl() const
{
    for (size_t i = 0; i < graph.size(); i++)
    {
        std::cout << i << ": ";
        for (size_t j = 0; j < graph[i].size(); j++)
        {
            std::cout << j << ' ';
        }
        std::cout << std::endl;
    }
}

GraphFactory.h

#pragma once
#include "graph.h"
#include <memory>
#include <string>

class GraphFactory
{
public:
    GraphFactory()=default;

    std::unique_ptr<Graph> getBiGraph(int size, std::string name);

    ~GraphFactory()=default;
};

GraphFactory.cpp

#include "GraphFactory.h"
#include "BiGraph.h"

std::unique_ptr<Graph> GraphFactory::getBiGraph(int size, std::string name)
{
    return std::make_unique<BiGraph>(size, name);
}

General
Depth first search generally applies to trees (because it has a depth, no cycles). You have implemented a general purpose graph (which can contain cycles and thus is not a tree (and does not have a depth).
Code Review
Pragmas are compiler specific. They are fine if you use them taking this into context.
#pragma once

This pragma is basically useless as it is non portable. Use the appropriate include guards unless you want to be locked into your current compiler only.
Not sure why you need to make isVisitied a member.
class BiGraph :public Graph
{
    std::vector<bool> isVisited;

The only reason you seem to need it was because areConnected() returns it by reference.
const std::vector<bool>&  areConnected(int sourcevertex)

I assume you did this to save the cost of copying the vector out. This is a false optimization. C++ is highly optimized and it is unlikely that a return by value would be copied out. The compiler has aggrissive RVO/NRVO optimization that would build the result at the destionation. In C++11 move semantics are introduced and compliment the RVO/NRVO optimization and in the few cases were they can not be built in place move semantics kick in and the content is moved optimally out of the method.
So declare this function
const std::vector<bool>  areConnected(int sourcevertex) const;

The specialization std::vector<bool> is broadly considered a mistake. It is optimized for size (unlike nearly everything else in C++ which is optimized for speed).
Because it optimized for size it has several drawbacks and does not act like a normal std::vector<> (which is why it is normally avoided). Now if you think you need to optimize for size then fair enough but normally people prefer to use std::vector<char>
Simpler Issues
Sure.
void ZeroBoolArray(std::vector<bool>& arr)

But if you fix the code as I suggeste above you don't need this function.
There is a simpler way to write this:
for (auto &x : arr)
{
    x = false;
}

// Easier to write as:
x = std::vector<bool>(x.size());   // Might be slightly more expensive.

Please one variable per line. This includes initializee list.
// This is unreadable
BiGraph::BiGraph(int maxvertexcount_, std::string name_):graph(maxvertexcount_), maxVertexCount(maxvertexcount_), name(name_), isVisited(maxVertexCount)
{

}

// Rewrite as:
BiGraph::BiGraph(int maxvertexcount_, std::string name_)
    : graph(maxvertexcount_)
    , maxVertexCount(maxvertexcount_)
    , name(name_)
    , isVisited(maxVertexCount)
{}
// PS I hate the trailing `_` there is no need to have it.
// If you re-write as:
BiGraph::BiGraph(int maxvertexcount, std::string name)
    : graph(maxvertexcount)
    , maxVertexCount(maxvertexcount)
    , name(name)
    , isVisited(maxVertexCount)
{}
// this works just as well and is unambiguous.

Why only check fVertex?
void BiGraph::addAdjacentImpl(int fVertex, int sVertex)
{
    if (fVertex > maxVertexCount)
    {
        throw std::out_of_range(name + ": trying to add vertex which doesn't exist");
    }

You should probably also check sVertex. But unless you explicitly want that error message you don't need the test; just use at() method.
void BiGraph::addAdjacentImpl(int fVertex, int sVertex)
{
    graph.at(fVertex).push_back(sVertex);
    graph.at(sVertex).push_back(fVertex);
}

Also you don't check if the vertex has already been added.
Sure this works fine. But it would be better to use the Visitor Pattern.
void BiGraph::traverse(int sourceVertex)

We covered this function above:
const std::vector<bool>& BiGraph::areConnectedImpl(int sourceVertex)

// I would write as:
const std::vector<char> BiGraph::areConnectedImpl(int sourceVertex) const
{
    std::vector<char>  isVisited.
    traverse(sourceVertex, isVisited);
    return isVisited;
}

If your destructor does nothing then don't declare it. The compiler generated version will work perfectly well.
BiGraph::~BiGraph()

Sure: This printImpl() seems easy enough. But it could be improved.
void BiGraph::printImpl() const

Rather than assume you will print to std::cout take a parameter for the output stream to be used. It can default to std::cout but this gives you the flexability to use other streams (like files/string streams etc).
Also in C++ it is standard to define an output operator to print an object.
Prefer "\n" over std::endl. The std::endl will also flush the stream which will usually make the code sub optimal. The stream is already flushed automatically if needed and if not needed will flush at optimal points so there is no need to manually force a flush.
Prefer the range based for loop if you don't need the index (currently your j loop is wrong (you should print the value at each index).
void BiGraph::printImpl(std::ostream& str = std::cout) const
{
    for (size_t i = 0; i < graph.size(); i++)
    {
        str << i << ": ";
        for (auto j: graph[i])
        {
            str << j << ' ';
        }
        str << "\n";
    }
}
std::ostream& operator<<(std::ostream^ str, Graph const& g)
{
    g.print(str);
    return str;
}


Properly disposing of a WCF connection using IDisposable This is a follow up question to this question:

https://stackoverflow.com/questions/4573526/what-could-be-causing-a-cannot-access-a-disposed-object-error-in-wcf

I have created a WCF service and it is up and running. When I used it, I was closing the connection after each time I got a response in a finally.

Trying to use the client for a second time, I got the exception of the linked question - can not access a disposed object. I tried implementing the IDisposable pattern without closing the connection every time.

1) First of all - Did I implement the dispose pattern correctly?

the code (it's short, don't worry):

I got a singleton class which is responsible for the service communication in which it creates the client class:

public class WebService : IDisposable
{
    // Flag: Has Dispose already been called?
    bool disposed = false;
    private MyWebServiceContractClient client;
    private static readonly Lazy<WebService> webServiceHandler = new Lazy<WebService>(() => new WebService());

    private WebService()
    {
        client = new MyWebServiceContractClient();
    }

    public static WebService Instance
    {
        get
        {
            return webServiceHandler.Value;
        }
    }

    public double GetAnswer()
    {
        try
        {
            if (!(client.State == CommunicationState.Opened) && !(client.State == CommunicationState.Opening))
            {
                client.Open();
            }
            //do some work
            return answer;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return -1;
        }
        finally
        {
           // here i would normally call client.Close(); but now im not
        }
    }

    public void Dispose()
    {
        // Dispose of unmanaged resources.
        Dispose(true);
        // Suppress finalization.
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            client.Close();
        }

        disposed = true;
    }
}

2) If I'm only closing the connection in the dispose method, doesn't it mean I'm always keeping the connection alive? Isn't it a waste of resources and even a security risk to just keep it open?

The adviced way to call a service endpoint when the connection is not an open stream, is to have the lifecycle of you client in line with the operation you are calling.

So rather than storing an instance of the client..

private WebService()
    {
        client = new MyWebServiceContractClient();
    }

You should create a client on demand. To work around the known issue on Dispose, a solid solution is available.

public double GetAnswer()
    {
        try
        {
            using (new MyWebServiceContractClient()) {

                //do some work
                return answer;
            } // <- there is a known issue here: https://stackoverflow.com/questions/573872/what-is-the-best-workaround-for-the-wcf-client-using-block-issue
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return -1;
        }
    }


Optimize Arraylist function call I am using the following to retrieve some user info based on IP address. ClientLocation() returns an array with city, state and coordinates.

My concern with this is the function is called whenever I want to retrieve different array values. How can this be optimized so that the function is called once, but still retrieve multiple array values.

Public Function ClientLocation() As Object

    Dim Result As ArrayList = New ArrayList
    Dim XMLDoc As XmlDocument = New XmlDocument()
    Dim APIKey = "apikey"
    Dim GetXML = "url in xml"

    Try
        XMLDoc.Load(GetXML)
        Dim XMLResponse As XmlNodeList = XMLDoc.SelectNodes("Response")
        For Each Item As XmlNode In XMLResponse
            Result.Add(Item("cityName").InnerText & ", " & Item("regionName").InnerText)
            Result.Add(Item("latitude").InnerText & "," & Item("longitude").InnerText)
            Return (Result)
        Next
    Catch err As Exception
        Result.Add("Not Available")
        Result.Add("Not Available")
        Return (Result)
    End Try

    Return Nothing
End Function

Calling function

Dim UserProfile As ProfileCommon = Profile.GetProfile(User.Identity.Name)

UserProfile.Location = ClientLocation.Item(0)
UserProfile.Coordinates = ClientLocation.Item(1)
UserProfile.Save()

Assuming you have an xml structure that would be similar to:

<Responses>
    <Response>
        <Item>
            <cityname>abc</cityname>
            <regionname>def</regionname>
            <latitude>101.2345</latitude>
            <longitude>34.3456</longitude>
        </Item>
        <Item>
            <cityname>ghi</cityname>
            <regionname>jkl</regionname>
            <latitude>101.2345</latitude>
            <longitude>34.3456</longitude>
        </Item>
        <Item>
            <cityname>mno</cityname>
            <regionname>pqr</regionname>
            <latitude>101.2345</latitude>
            <longitude>34.3456</longitude>
        </Item>
        <Item>
            <cityname>stu</cityname>
            <regionname>vwx</regionname>
            <latitude>101.2345</latitude>
            <longitude>34.3456</longitude>
        </Item>
    </Response>
</Responses>

You could use the XMLSerializer class to deserialize the whole file all at once, by creating a class to contain the data:

Public Class Responses
    Public Class Item
        Dim cityname As String = ""
        Dim regionname As String = ""
        Dim latitude As Double = 0.0
        Dim longitude As Double = 0.0
    End Class
    <XmlArrayAttribute("Response")>
    Dim items As New List(Of Item)
End Class

Getting the data would be as simple as:

XMLDoc.Load(GetXML)
Dim result As Responses = CType(New XmlSerializer(GetType(Responses)) _
.Deserialize(New StringReader(XMLDoc.OuterXml)), Responses)

You would access the data through the items field of result:

result.items(0).cityname


Reducing repetition of sequence-like properties I have a class that is a wrapper for memory positions of a hardware device.

I need to data-bind each of this positions, so I created a class with hardcoded properties, one for each position, so that I can bind a WPF DataGrid to it.

Problem is: given the sequential nature of the positions, the code became quite repetitive.

Model(.cs):

public class TabelaMemoria
{

    public string Nome { get; private set; }

    int Numero { get; set; }
    MiotoolWrapper _device;

    public TabelaMemoria(MiotoolWrapper deviceWrapper, string nome, int numero)
    {
        _device = deviceWrapper;
        Nome = nome;
        Numero = numero;
    }

    public float A1
    {
        get { return getVal(0); }
    }

    public float B1
    {
        get { return getVal(1); }
    }

    public float A2
    {
        get { return getVal(2); }
    }

    public float B2
    {
        get { return getVal(3); }
    }

    public float A3
    {
        get { return getVal(4); }
    }

    public float B3
    {
        get { return getVal(5); }
    }

    public float A4
    {
        get { return getVal(6); }
    }

    public float B4
    {
        get { return getVal(7); }
    }

    private float getVal(int p)
    {
        return _device.GetCalibrationValue(Numero, p);
    }

}

View(.xaml):

<DataGrid
    ItemsSource="{Binding Memorias}"  <!-- of type IEnumerable<TabelaMemoria> -->
    AutoGenerateColumns="False"
    ColumnWidth="Auto">

    <DataGrid.RowHeaderStyle>
        <Style TargetType="DataGridRowHeader">
            <Setter Property="Content" Value="{Binding Nome}"/>
        </Style>
    </DataGrid.RowHeaderStyle>
    <DataGrid.Columns>
        <DataGridTextColumn Header="A1" Binding="{Binding A1}" Width="100"/>
        <DataGridTextColumn Header="B1" Binding="{Binding B1}" Width="100"/>
        <DataGridTextColumn Header="A2" Binding="{Binding A2}" Width="100"/>
        <DataGridTextColumn Header="B2" Binding="{Binding B2}" Width="100"/>
        <DataGridTextColumn Header="A3" Binding="{Binding A3}" Width="100"/>
        <DataGridTextColumn Header="B3" Binding="{Binding B3}" Width="100"/>
        <DataGridTextColumn Header="A4" Binding="{Binding A4}" Width="100"/>
        <DataGridTextColumn Header="B4" Binding="{Binding B4}" Width="100"/>
    </DataGrid.Columns>
</DataGrid>

I don't have VS on my laptop, but perhaps an enum might make it a bit simpler?

(Heads up: You might need to make a few changes to get this to work)

Model

public class TabelaMemoria {
    public string Nome { get; private set; }

    int Numero { get; set; }
    MiotoolWrapper _device;

    public TabelaMemoria(MiotoolWrapper deviceWrapper, string nome, int numero)
    {
        _device = deviceWrapper;
        Nome = nome;
        Numero = numero;
    }

    public enum Position{
        A1=0,
        B1,
        A2,
        B2,
        A3,
        B3,
        A4,
        B4
    }

    public float getval(Position p){
        return _device.GetCalibrationValue((int)p);
    }
}

View.xaml

<DataGrid.Columns x:Name="grdColumns"/>

View.Xaml.cs

public View{
    public View(){
        InitializeComponent();
        InitializePositions();
    }

    private void InitializePositions(){
        foreach (Position p in Enum.GetValues(typeof(Position))) {
            DataGridTextColumn dgrid = new DataGridTextColumn();
            dgrid.Width = 100;
            dgrid.Header = p.ToString();
            dgrid.Text = (int)p;
        }
    }
}

Now if you add anymore positions, just add it to the enum and it should automatically be picked up. I know it screws up the binding, but I wasn't sure what your specific use case was.

If nothing else, perhaps this will get your gears spinning on a better solution.
Good luck, mate!


Simple grid system made out of CSS columns I have been researching and experimenting with HTML5 and CSS3. I was aiming to create a very simple but efficient tiled gallery / grids. So some sort of grid system that I can layout anything inside.

Below is what I have created, what are your opinions? I also have a question, why the distributing of the images change from browser to another?  Is there a way to control it?

Here is a working Fiddle.

HTML:

CSS:
/*Grids System*/
 .grids {
    width: 100%;
    overflow: hidden;
    -webkit-column-count: 3;
    -moz-column-count: 3;
    column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-gap: 10px;
    column-gap: 10px;
}
.grids.twoGrids {
    -webkit-column-count: 2;
    -moz-column-count: 2;
    column-count: 2;
}
.grids.fourGrids {
    -webkit-column-count: 4;
    -moz-column-count: 4;
    column-count: 4;
}
.grids .gridElement {
    margin-bottom: 10px;
    overflow: hidden;
    -webkit-backface-visibility: hidden;
    -moz-backface-visibility: hidden;
    -ms-backface-visibility: hidden;
}
.grids .gridElement:last-child {
    margin-bottom: 0;
}
.grids .gridElement img {
    min-width: 100%;
}

There are a few good reasons why no one uses the multi-column module for "grids".

They are rigid

There are only 2 options for the column-span property: none or all.  Want to have elements spanning 2 columns?  Too bad.  Also, last time I checked, Mozilla does not support the column-span property.

They are unpredictable

Each browser has its own algorithm for determining how to generate the columns.  If you read the specification, column-count is not a guarantee that you will get the specified number of columns:

  describes the optimal number of columns into which the content of the element will be flowed. Values must be greater than 0. If both ‘column-width’ and ‘column-count’ have non-auto values, the integer value describes the maximum number of columns.

From: http://www.w3.org/TR/css3-multicol/#column-count

The emphasis is mine: in an ideal situation, you'll get the exact number of columns you've specified.  If the browser's algorithm decides that there's not enough room for that many, it will give you less.

Controlling where breaking occurs is a nuisance

Since you're using images for testing, you're not seeing the problem.  Using columns on a parent container doesn't just control how the children flow, but all descendant elements.  What this means is that your gridElement will frequently span multiple columns in an effort to equalize the height of the columns.  You can specify where breakage occurs (or shouldn't occur) on the descendant elements like so:

.foo {
  -webkit-column-break-inside: avoid; /* Deprecated property name for Webkit (Blink too?) */
  page-break-inside: avoid; /* Non-standard property name for Mozilla */
  break-inside: avoid;
}

http://codepen.io/cimmanon/pen/CcGlE

TL;DR

This system is designed with text in mind, not grids.  I predict that if you were to pursue this further, you'll end up being dissatisfied due to the limitations of the module as it is currently specified.  If you're just planning to use this with images, my last point above does not apply.


Creating automatic resizing of subelements in WPF I currently have this code:

<Window x:Class="Listener.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="600" Width="800" Loaded="Window_Loaded" WindowStyle="None" AllowsTransparency="True" Background="Transparent" MouseDown="Window_MouseDown" KeyDown="Window_KeyDown" ResizeMode="CanResizeWithGrip">
    <Grid Margin="30" x:Name="bgBorder">
        <Grid Margin="0" Background="#555555" x:Name="mainWindow" MouseDown="mainWindow_MouseDown">
            <Grid Margin="2,2,2,2" Height="80" Background="#779999" x:Name="topControl" VerticalAlignment="Top">
            </Grid>
            <Grid Margin="2,84,238,2" Background="#557777" x:Name="playListControl">
            </Grid>
            <Grid Margin="2,84,2,2" Width="234" Background="#668888" x:Name="optionsControl" HorizontalAlignment="Right">
            </Grid>
        </Grid>
    </Grid>
</Window>

A borderless window where the 3 sub panels get resized according to their margin and alignment.

Is this the correct way of doing this?

And on a side node, I plan on creating some sort of border resize and not use

ResizeMode="CanResizeWithGrip"

This was just used for testing.

I would say no. If you want to create grid-like layout, you should declare columns and rows, and specify how wpf should stretch those. For example like this:

<Grid Margin="30" x:Name="bgBorder">
    <Grid Background="#555555" x:Name="mainWindow" MouseDown="mainWindow_MouseDown">
        <Grid.RowDefinitions>
            <!-- frist row will stretch to fit the content -->
            <RowDefinition Height="Auto"/>
            <!-- second row will fill all available space -->
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid Margin="2" Grid.Row="0" Height="80" Background="#779999" x:Name="topControl"/>
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <!-- first column will fill all available space -->
                <ColumnDefinition Width="*"/>
                <!-- second column will stretch to fit the content -->
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>

            <Grid Grid.Column="0" Margin="2" Background="#557777" x:Name="playListControl"/>
            <Grid Grid.Column="1" Margin="2" Width="234" Background="#668888" x:Name="optionsControl"/>
        </Grid>
    </Grid>
</Grid>

You should really do some reading on how things are done in wpf, this HTML-ish layout you are trying to create won't work.


C# - name separation & last name in upper to Camel I had an xls file with lots of full names in the following form at work:
+----------------------------+--------------+-----+-----+
|        [Full name]         | [More data]  |[...]|[...]|
+----------------------------|--------------------------+
|   Cristiano RONALDO        |     ...      | ... | ... |
+----------------------------+--------------+-----+-----+
|   Carol SEVILLA            |     ...      | ... | ... |
+----------------------------|--------------+-----+-----+
|   Ronald Chris MAC DONALDS |     ...      | ... | ... |
+----------------------------|--------------+-----+-----+

some of the data will still be input this way but I want to add a column for last name and let it clear that I don't need the last name in upper case anymore, so I separated name from last name, and then changed the last name to camel case, notice that last names can have many words like "Mc Donalds Rodriguez" (it happens) so I solved it as follows
public static string GetLastNameFromFullName(string fullName)
{
    var lastName = "";
    foreach (var ch in fullName)
    {
        lastName += ch;
        if (char.IsLower(ch))
        {
            lastName = "";
        }
    }
    return lastName.TrimStart();
}

public static string GetCameledLastName(string lastNames)
{
    string[] lastNamesArr = lastNames.Split(' ');
    var lastNamesCameled = "";

    foreach (string lastNameUpper in lastNamesArr)
    {
        lastNamesCameled += lastNameUpper[0];
        for (int i = 1; i < lastNameUpper.Length; i++)
        {
            lastNamesCameled += char.ToLower(lastNameUpper[i]);
        }
    }
    return lastNamesCameled;
}

public static string GetNameWithoutLastName(string fullName)
{
    var possibleLastName = false;
    char possibleLastNameChar = ' '; //just initialized
    var name = "";
    foreach (var ch in fullName)
    {
        if (char.IsUpper(ch))
        {
            possibleLastNameChar = ch;
            if (possibleLastName)
            {
                break;
            }
            possibleLastName = true;
        }
        else
        {
            if (possibleLastName)
            {
                name += possibleLastNameChar;
            }
            name += ch;
            possibleLastName = false;
        }
    }
    return name;
}
private void Form1_Load(object sender, EventArgs e)
{
    var path = @"../../file.txt"; //dumped from xls file
    string contents = File.ReadAllText(path);

    using (StreamReader reader = new StreamReader(path, Encoding.GetEncoding("iso-8859-1"))) //some names had ñ or accented characters
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            var fullName = "";
            foreach (char ch in line)
            {
                if (ch == '\t')
                {
                    //The columns in the xls file were divided by tab characters
                }
                else
                {
                    fullName += ch;
                }
            }
            var lastName = GetLastNameFromFullName(fullName);
            Console.WriteLine("Name: " + GetNameWithoutLastName(fullName));
            Console.WriteLine("Last name: " + GetCameledLastName(lastName));
        }
    }
}

I think my code could be a lot better.
UPDATE: please note that while it is true that cases like "Cinthia del Río" is an actual name that is not considered in this way, it will be converted to "Cinthia Del Rio" because in the xls file it would be in a single column as "Cinthia DEL RIO", and of course it is impossible for the algorithm to know that "DEL" should actually be "del" even though it is perfectly OK for a last name's word to start with a lower case.

Well, I don't know if your code could be better or faster but the code could be a lot shorter by using some Linq-"magic".
Your code could use some level of input-parameter-validation because the methods in question are public which means anybody who uses these methods can pass whatever he/she wants, even null which would blow each method and would expose implementation details.
I don't know if the requirement is meant to be that passing Ronald Chris MAC DONALDS returns as lastname MacDonalds but for me this doesn't sound correct.
Instead of splitting the fullname twice and then splitting the lastname again, you should consider to just pass a string[] to the methods.
You could consider to have one public method where you pass the fullname and get a Tuple<string, string> so you would need only one parameter validation because you can make the other methods private.
Because a lastname contains only UpperCase letters we can take the passed string[] and take each string in this array which contains only upper-case letters, we will leave the first char because it allready is uppercase and take the remaining chars as lower-case chars. Last we join them using a space char like so
private static string GetLastName(string[] nameParts)
{
    return string.Join(" ", nameParts.Where(s => s.All(c => char.IsUpper(c)))
                                     .Select(s => s[0] + s.Substring(1).ToLowerInvariant()));
}

For the firstname we know that not all chars are upper-case chars. So we take each string inside the passed array and check if any char is a lower-case char, and then join the found strings by using a space char like so
private static string GetFirstName(string[] nameParts)
{
    return string.Join(" ", nameParts.Where(s => s.Any(c => char.IsLower(c))));
}

Last but not least we need to call these 2 methods after some proper validation like so
public static Tuple<string, string> GetNormalizedNames(string fullName)
{
    if (fullName == null) { throw new ArgumentNullException(nameof(fullName)); }
    if (string.IsNullOrWhiteSpace(fullName)) { return Tuple.Create("", ""); }

    var nameParts = fullName.Split(' ');

    return Tuple.Create(GetFirstName(nameParts), GetLastName(nameParts));
}

which we then call like so
var firstNameLastNameTuple = GetNormalizedNames(fullName);
Console.WriteLine("Name: " + firstNameLastNameTuple.Item1);
Console.WriteLine("Last name: " + firstNameLastNameTuple.Item2);

The whole code is now easier to read and therefor easier to maintain. Sure linq is only syntactic sugar and won't be faster than iterating over the chars by "hand" but the benefit is less and easier to read code.


Ternary tree preoder traversal (recursive implementation) Problem statement:

  Print out to console the ternary tree preorder traversal. Suppose that the tree can have at most 3 children, left, middle and right. Preorder traversal is to visit the middle child first, and then left, and then right. Every node has integer value.

My introduction of Algorithm

I was asked to write a simple recursive algorithm two years ago at the end of an important meeting. I like the algorithm, so I reviewed the algorithm and wrote a short C# solution today.

I am planning to study a few of short C# courses by myself on pluralsight.com called "defensive code in C#", "Code Contracts", "Provable Code", learn to write better C# code in next 2 weeks. I am learning C# right now.

I am trying to get some critics on my practice today.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TernaryTreePreorderTraversal
{
    class TernaryTree
    {
        static void Main(string[] args)
        {
            RunTestcase();
        }

        /*
         * Ternary tree:
         *      1
         *    / | \
         *   3  2  5
         *  /|  |
         * 4 33 22
         */
        public static void RunTestcase()
        {
            var root = new TernaryTree(1);

            root.Middle = new TernaryTree(2);
            root.Left   = new TernaryTree(3);
            root.Right  = new TernaryTree(4);

            root.Middle.Middle = new TernaryTree(22);
            root.Left.Middle   = new TernaryTree(33);
            root.Right = new TernaryTree(5);

            TernaryTree.PreOrderTraversal(root);

            // manually verify the console output is 1 2 22 3 33 4 5
        }

        public TernaryTree Left   { get; set; }
        public TernaryTree Right  { get; set; }
        public TernaryTree Middle { get; set; }
        public int Data { get; set; }

        public TernaryTree(int val)
        {
            Data = val;
        }

        public static void PreOrderTraversal(TernaryTree node)
        {
            if (node == null)
            {
                return;
            }

            Console.WriteLine(node.Data);

            PreOrderTraversal(node.Middle);
            PreOrderTraversal(node.Left);
            PreOrderTraversal(node.Right);
        }
    }
}

Class Definition

First of all, I would separate the class definition from the actual use case. The challenge wants you to walk nodes with integer data, but a next challenge may ask you to use a string instead. Don't let the use case stipulate the class definition. Let's make a generic class to make the tree reusable for more scenarios.

public class TernaryTree<T>
{
    public T Data { get; set; }
    public TernaryTree<T> Left { get; set; }
    public TernaryTree<T> Right { get; set; }
    public TernaryTree<T> Middle { get; set; }
}

DRY Code

You then present a method PreOrderTraversal which combines walking the tree with outputting data for this use case. It's a pitty the flow is not split from the use case. We would have to rewrite that flow for every single use case like this. Let's keep it DRY.

We want to have a non specific flow for traversing the tree pre-order, middle, left, then right.

public IEnumerable<TernaryTree<T>> WalkPreOrder()
{
    yield return this;
    foreach (var descendant in Middle?.WalkPreOrder())
    {
        yield return descendant;
    }
    foreach (var descendant in Left?.WalkPreOrder())
    {
        yield return descendant;
    }
    foreach (var descendant in Right?.WalkPreOrder())
    {
        yield return descendant;
    }
}

Use Case

And now we can reuse that method for our use case. This code should not be part of TernaryTree but rather of our unit test, or container class for the challenge:

 static void Print(TernaryTree<int> tree)
 {
     foreach (var node in tree.WalkPreOrder())
     {
         Console.WriteLine(node.Data);
     }
 }

Unit Tests

I noticed a comment in your code // manually verify the console output is 1 2 22 3 33 4 5. You can avoid manually checking the outcome by writing unit tests.

What's Next?

Since you can set any node to any of the child positions, you might introduce cycles. Suppose you set node.Left = node, this would be a cycle because of a self-to-child reference. As a challenge, you should try to figure out how to prevent cycles.

public TernaryTree Left   { get; set; }
public TernaryTree Right  { get; set; }
public TernaryTree Middle { get; set; }


Implement a queue using two stacks I tried to implement a queue using two stacks. I saw there are questions about this topic, but in my example, I used build-in stack from java. My question is, can someone give me some advice to make my code more efficient or better (in turn of class structure, for-loop, etc)?

This is for practising and understanding how the data structure works (Queue and stack). The main idea is to use two stacks and act as a single queue. The way I implement this problem is by assigning one stack to store odd number of elements and another one to store even number of elements. Example: if there are 3 elements, the first and the third element goes to the oddStack, the second element goes to evenStack.

import java.util.Stack;

public class twoStacksInOneQueue {

private Stack <Integer> oddStack;
private Stack <Integer> evenStack;
private int counter;// count added element
private int shift;//count internal movement from one stack to another.
/**
 Constructor
 */
public twoStacksInOneQueue()
{
    counter = 1;
    shift = 0;
    oddStack = new Stack<Integer>();
    evenStack = new Stack <Integer>();
}
/**
 add element to queue according to amount of elements.
 if there are 3 element, the 3rd element is put into odd stack.
 */
public void addToQueue(int num)
{
    if(counter % 2 == 0)
    {
        evenStack.push(num);
        System.out.println("evenStack: " +  num);
    }
    else
    {
        oddStack.push(num);
        System.out.println("oddStack: " +  num);
    }
    counter++;
}

/**
 remove an element from queue according to amount of elements
 */
public int removeFromQueue()
{
    int temp;
    int result = 0;

    if(counter == 0)//empty queue
    {
        System.out.println("The Queue is empty!");
    }
    else if (counter % 2 == 0) //if there are even elements
    {
        while(!evenStack.empty())//loop while not empty
        {
            //move the entire stack to another to get the bottom of the stack
            temp = evenStack.pop();
            oddStack.push(temp);
            shift++;
        }
        result = oddStack.pop();//the previous bottom of the moved stack
        System.out.println("result From even: "+result);

        while (shift-1  > 0)//move the moved stack back. -1 because of the popped element above
        {
            temp = oddStack.pop();
            evenStack.push(temp);
            shift--;
        }
        counter--;
    }
    else //if there are odd elements
    {
        while(!oddStack.empty())
        {
            temp = oddStack.pop();
            evenStack.push(temp);
            shift++;
        }
        result = evenStack.pop();

        System.out.println("result from odd: "+result);
        while (shift-1 > 0)
        {
            temp = evenStack.pop();
            oddStack.push(temp);
            shift--;
        }
        counter--;
    }
    shift = 0;//reset internal moved counter.
    return result;
}

public static void main (String [] arg)
{
   twoStacksInOneQueue myQueue = new twoStacksInOneQueue();
    for (int i = 0; i< 4; i++)
    {
        myQueue.addToQueue(i+1);
    }

    myQueue.removeFromQueue();
    myQueue.removeFromQueue();
    myQueue.removeFromQueue();
    myQueue.removeFromQueue();
}

Improving your solution

private Stack <Integer> oddStack;
private Stack <Integer> evenStack;

I'd replace these with an array.

private Stack<Integer>[] stacks = (Stack<Integer>[])new Stack[2];

Then you don't have to keep converting from numbers to names when you use them.

private int counter;// count added element

You don't need this, as Stack has a size method.

private int shift;//count internal movement from one stack to another.

You never use this outside of a single method.  Rather than creating an object field, just use a local variable.

public twoStacksInOneQueue()
{
    counter = 1;
    shift = 0;
    oddStack = new Stack<Integer>();
    evenStack = new Stack <Integer>();
}

This gets simpler.

public twoStacksInOneQueue()
{
    stacks[0] = new Stack<Integer>();
    stacks[1] = new Stack<Integer>();
}

No need for the other two here.

public void addToQueue(int num)
{
    if(counter % 2 == 0)
    {
        evenStack.push(num);
        System.out.println("evenStack: " +  num);
    }
    else
    {
        oddStack.push(num);
        System.out.println("oddStack: " +  num);
    }
    counter++;
}

And this becomes just

public void addToQueue(int num)
{
    int index = ((stacks[0].size() + stacks[1].size()) % 2;
    stacks[index].push(num);
    System.out.println(((index == 0) ? "evenStack: " : "oddStack: ") +  num);
}

Note that this would only be one line if it weren't for printing the stack information.

    int temp;
    int result = 0;

    if(counter == 0)//empty queue
    {
        System.out.println("The Queue is empty!");
    }

I wouldn't declare temp until later, and I would return from the empty case (or throw an exception).

    if (stacks[0].empty() && stacks[1].empty())
    {
        System.out.println("The Queue is empty!");
        return 0;
    }

I'll put result back later.

        while (shift-1  > 0)//move the moved stack back. -1 because of the popped element above

You are doing an extra math operation on every iteration of the loop.  But you don't have to do so.  Either

        while (shift > 1)//move the moved stack back. 1 because of the popped element above

Or

        shift--; //move the moved stack back. -1 because of the popped element above
        while (shift > 0)

The latter might be more efficient on some platforms, since comparisons are often implemented as subtractions and comparisons to 0.

    else if (counter % 2 == 0) //if there are even elements
    {
        while(!evenStack.empty())//loop while not empty
        {
            //move the entire stack to another to get the bottom of the stack
            temp = evenStack.pop();
            oddStack.push(temp);
            shift++;
        }
        result = oddStack.pop();//the previous bottom of the moved stack
        System.out.println("result From even: "+result);

        while (shift-1  > 0)//move the moved stack back. -1 because of the popped element above
        {
            temp = oddStack.pop();
            evenStack.push(temp);
            shift--;
        }
        counter--;
    }
    else //if there are odd elements
    {
        while(!oddStack.empty())
        {
            temp = oddStack.pop();
            evenStack.push(temp);
            shift++;
        }
        result = evenStack.pop();

        System.out.println("result from odd: "+result);
        while (shift-1 > 0)
        {
            temp = evenStack.pop();
            oddStack.push(temp);
            shift--;
        }
        counter--;
    }
    shift = 0;//reset internal moved counter.

This seems longer than it needs to be.

    int index = ((stacks[0].size() + stacks[1].size()) % 2;
    int result = removeLast(stacks[index], stacks[1 - index]);

    System.out.println(((index == 0) ? "result From even: " : "result from odd: ") + result);

    return result;

Again, if it weren't for the output requirement, we could have returned directly.

And then just define a method for removeLast:

public static int removeLast(Stack<Integer> stack, Stack<Integer> temp)
{
    int snapshot = temp.size();

    while (!stack.empty())
    {
        temp.push(stack.pop());
    }

    int result = temp.pop();

    while (temp.size() > snapshot)
    {
        stack.push(temp.pop());
    }

    return result;
}

Rather than explicitly counting how many elements we shift, now we just reduce temp back to its original size.

Because we defined a method for this, we only have to write this logic once.  We call the method with different arguments rather than duplicating the logic.

The thing is though that this method has you moving half the elements twice on every removal.  We can do better.  On average, we only need to move one element per removal.

An alternative solution

class StackQueue {

    private Stack<Integer> backward = new Stack<>();
    private Stack<Integer> forward = new Stack<>();

    public void enqueue(int item) {
        backward.add(item);
    }

    public int dequeue() {
        if (forward.empty()) {
            if (backward.empty()) {
                // throwing an exception would likely be better
                return 0;
            }

            do {
                forward.push(backward.pop());
            } while (!backward.empty());
        }

        return forward.pop();
    }

}

This gives constant time enqueue operations and on average gives constant time dequeue operations.  When I say "on average", I mean that it moves each element from backward to forward once per removal.  However, on a particular operation, it moves either 0 or all of them.


reversing a string test cases I am trying to create a method that reverses a string that will handle every case. So far the cases I have come up with are

""
"abcdef"
"abbbba"
null

I haven't been able to handle these conditions however

escape characters

"\n"
"\t"

Not sure how to make \n or \t into a string

special characters such as

áe

code:

public static String reverseStr(String str) {
    if ( str == null ) {
          return null;
    }
    int len = str.length();
    if (len <= 0) {
        return "";
    }
    char[] strArr = new char[len];
    int count = 0;
    for (int i = len - 1; i >= 0; i--) {
        strArr[count] = str.charAt(i);
        count++;
    }
    return new String(strArr);
}

There is a good overview of string reversal algorithms in this answer. It should explain how special characters like é can be handled. I don't see what's your problem with "\n" and "\t". These are strings already.


Faster way to intersect arrays I need to intersect lots of arrays with each other. Those arrays are like:
$a = array(4 => true, 10 => true, 18 => true...);
$b = array(6 => true, 10 => true, 73 => true...);
$c = array(106 => true, 293 => true, 297 => true...);

In PHP there is a function array_intersect_key, which intersects keys; it works fine but it's not very efficient. There is also another function array_intersect, which intersects values, and is much slower than array_intersect_key because it's O (n^2) instead of O (n) (array_intersect_key).
The problem with array_intersect_key is that it does lots of pre computation before executing the intersection, like ordering the arrays, verifying data types... at every call but I don't need that because my arrays are already ordered and contain only numbers. So I came up with this function:
function array_intersect_key_custom($a,$b) {

    $intersection = array();

    foreach ($a as $chave1 => $valor1) {

        if (isset($b[$chave1])) {

            $intersection [$chave1] = true;

        }

    }

    return $intersection;

}

This function runs a little faster than any other alternative I came up, but it's still too slow. Is there any code optimization, mathematical operation, matrix operation... that I can do in order to make this code run faster?

I tried hard but I couldn't find anything faster than the native array_intersect_key. It runs 30-50% faster than your function in my tests. Tried with PHP 7.0 and this array generator for test data:
function randomArr($size, $max) {
  $res = [];
  for ($i = 0 ; $i<$size; $i++) {
    $r = random_int(1, $max);
    if (!isset($res[$r])) {
      $res[$r] = true;
    }
    else {
      $i = $i-1;
    }
  }
  ksort($res);
  return $res;
}

Try with 10 Mio entries and $max=100000000 and I'd be really surprised if your function was faster. Maybe the densitiy of your arrays plays a role?
However, I found one little optimization for your function: If you don't require the result to have the form [3 => true, 7 => true, 23 => true, ...], but you can work with [0 => 3, 1 => 7, 2 => 23, ...] as well, it's a bit faster to just push the intersection keys onto the result array: $intersection[] = $chave1;. But this only saved me at most 10%.


Shell script to detect router slider status I have an openwrt router (TP-Link MR3040) and on boot I have it check the slider (AP, WISP, 3G/4G mode). The goal was to have it execute the current "slider status" vs the old one, or do nothing if it's the same (before reboot). I just want a critique on making it more elegant.

#!/bin/sh

test=$(cat /root/logs/sliderstatus)
status=""
if grep -qe "sw1.*in  hi" /sys/kernel/debug/gpio ; then
        if grep -qe "sw2.*in  hi" /sys/kernel/debug/gpio ; then

                # AP
                logger "Configure AP"
                status="AP"

        else
                # WISP
                logger "Configure WISP"
                status="CLIENT"
        fi
else

        # 3G
        logger "Configure 3G"
        status="CUSTOM"

fi

if [ $status != $test ] ; then

case $status in

CLIENT) echo "status is client, executing now"
        #sh /root/scripts/shell/CLIENT_MODE.sh &
        ;;

AP) echo "status is AP, executing now"
        #sh /root/scripts/shell/AP_MODE.sh &
        ;;

CUSTOM) echo  "status is CUSTOM, executing now"
        ;;

*) echo "ERROR status does not match ERROR"
        ;;

esac

elif [ $status == $test ] ; then

        echo " Status: $status and Slider $test are the same"

else
        echo "You shouldn't have seen this"

fi

First of all, there are so many pitfalls associated with /bin/sh programming that I prefer to write all except the most trivial scripts in a language like perl, python or even awk. I realize that availability is a concern, but all of those languages are pretty standard now.

If you write the script in a better scripting language you can get rid of the duplicate call to grep which is one thing that I presume bothers you about the code.

If you must write in /bin/sh, then run your code through one of the following static analyzers to help you find potential coding problems:

http://www.shellcheck.net
checkbashisms on Debian / Ubuntu systems

For instance, ShellCheck found these issues:

if [ $status != $test ] ; then
                ^---- should use "$test"

elif [ $status == $test ] ; then
               ^---- == not supported in POSIX sh

In perl your script would look like this:

#!/usr/bin/env perl

use strict;
use warnings;
use File::Slurp;

my $test = read_file( '/root/logs/sliderstatus' );
chomp $test;

my ($found1, $found2);
open(my $fh, "</sys/kernel/debug/gpio");
while (<$fh>) {
  if (m/\(sw1\s*\)\s+in\s+hi/) { $found1 = 1 }
  if (m/\(sw2\s*\)\s+in\s+hi/) { $found2 = 1 }
}
close($fh);

my ($status, $script);
if ($found1 && $found2) {
  $status = "AP";
  $script = "/root/scripts/shell/AP_MODE.sh";
} elsif ($found1) {
  $status = "CLIENT";
  $script = "/root/scripts/shell/CLIENT_MODE.sh";
} else {
  $status = "CUSTOM";
  # don't set $script
}

if ($status ne $test) {
  print "Status is $status, executing now.\n";
  if ($script) {
    system("$script &");
  }
} else {
  print "Status $status and slider $test are the same.\n";
}

It's still basically the same code, but has these advantages:

It only reads /sys/kernel/debug/gpio once
It's a lot safer
It's easier to express more complex logic
You have more versatile data structures available to you - e.g. real arrays and hash maps.

Finally, I have a question about your patterns for sw1 and sw2. What does the output of /sys/kernel/debug/gpio look like? Presumably the inputs are number something like sw1, sw2, sw3, etc. Could there be a sw10? There should be a delimiter in the output you can use to make sure you are matching the full switch number.


Calculating the volume of a tetrahedron Here's my function for calculating the volume of a tetrahedron. I've tried to comment well and perform a few checks on the types of the objects passed to it. Can the comments be improved?

I'd also like an opinion about my method for checking the object types. Is it better to use assert for this?

# eg9-tetrahedron.py
import numpy as np

def tetrahedron_volume(vertices=None, sides=None):
    """
    Return the volume of the tetrahedron with given vertices or sides. If
    vertices are given they must be in a NumPy array with shape (4,3): the
    position vectors of the 4 vertices in 3 dimensions; if the six sides are
    given, they must be an array of length 6. If both are given, the sides
    will be used in the calculation.

    Raises a ValueError if the vertices do not form a tetrahedron (for example,
    because they are coplanar, colinear or coincident). This method implements
    Tartaglia's formula using the Cayley-Menger determinant:
              |0   1    1    1    1  |
              |1   0   s1^2 s2^2 s3^2|
    288 V^2 = |1  s1^2  0   s4^2 s5^2|
              |1  s2^2 s4^2  0   s6^2|
              |1  s3^2 s5^2 s6^2  0  |
    where s1, s2, ..., s6 are the tetrahedron side lengths.

    Warning: this algorithm has not been tested for numerical stability.

    """

    # The indexes of rows in the vertices array corresponding to all
    # possible pairs of vertices
    vertex_pair_indexes = np.array(((0, 1), (0, 2), (0, 3),
                                    (1, 2), (1, 3), (2, 3)))
    if sides is None:
        # If no sides were provided, work them out from the vertices
        if type(vertices) != np.ndarray or vertices.shape != (4,3):
            raise TypeError('Invalid vertex array in tetrahedron_volume():'
                             ' vertices must be a numpy array with shape (4,3)')
        # Get all the squares of all side lengths from the differences between
        # the 6 different pairs of vertex positions
        vertex1, vertex2 = vertex_pair_indexes[:,0], vertex_pair_indexes[:,1]
        sides_squared = np.sum((vertices[vertex1] - vertices[vertex2])**2,
                               axis=-1)
    else:
        # Check that sides has been provided as a valid array and square it
        if type(sides) != np.ndarray or sides.shape != (6,):
            raise TypeError('Invalid argument to tetrahedron_volume():'
                             ' sides must be a numpy array with shape (6,)')
        sides_squared = sides**2

    # Set up the Cayley-Menger determinant
    M = np.zeros((5,5))
    # Fill in the upper triangle of the matrix
    M[0,1:] = 1
    # The squared-side length elements can be indexed using the vertex
    # pair indices (compare with the determinant illustrated above)
    M[tuple(zip(*(vertex_pair_indexes + 1)))] = sides_squared

    # The matrix is symmetric, so we can fill in the lower triangle by
    # adding the transpose
    M = M + M.T

    # Calculate the determinant and check it is positive (negative or zero
    # values indicate the vertices to not form a tetrahedron).
    det = np.linalg.det(M)
    if det <= 0:
        raise ValueError('Provided vertices do not form a tetrahedron')
    return np.sqrt(det / 288)

"The most Pythonic way to check the type of an object is... not to check it." The pythonic way to do this is to assume that the calling code/user is sensible enough to pass an object which can be handled by the callee. This allows for subclass items or simply any object with the correct properties to be used in the code.

For maintainability you should:

use self explanatory names such as numpy, matrix, determinant etc.,
use descriptively named constants for any magic numbers such as 288,
split the function into one for sides and one for vertices (one may end up calling the other or they may both call a third, internal function for the final calculation),
run the code through pep8 and possibly a cyclomatic complexity checker like radon, and
in general, go through all comments, and for every comment see if you can refactor the code to make the comment unnecessary. For example, instead of "Set up the Cayley-Menger determinant" create a function get_cayley_menger_determinant.