Finding largest prime factor from inputted number This is my first C# console application. This program asks for an input of a number, and finds the highest prime factor of that number. Please review my code.

Have I used things right?
Is my code efficient?
Is there a better way to achieve this?

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

namespace Problems
{
    class Program
    {
        static int FindFactor(Int64 UserInput)
        {
            int LargestFactor = 0;
            Int64 Number = UserInput;

            for (int i = 2; i < Number; i++)
            {
                if (Number % i == 0)
                {
                    if (PrimeFactorCheck(i) == true)
                    {
                        LargestFactor = i;
                    }
                }
            }
            return LargestFactor;
        }
        static bool PrimeFactorCheck(int Number)
        {
            bool PrimeNumberValidity = true;

            for(int i = 2; i < Number; i++)
            {
                if (PrimeNumberValidity == true)
                {
                    if (Number % i == 0)
                    {
                        PrimeNumberValidity = false;
                    }
                }
                else
                {
                    i = Number;
                }
            }

            return PrimeNumberValidity;
        }
        static void Main(string[] args)
        {
            Console.Write("Hello, please enter a number to find the biggest prime factor of it: ");
             Int64 UserInput = Convert.ToInt64(Console.ReadLine());

            int Answer = FindFactor(UserInput);
            Console.WriteLine(Answer);
            Console.ReadKey();
        }
    }
}

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

namespace Problems
{

You can make this class static since it doesn't make sense to make instances of it.

    static class Program
    {

Local variables are usually not capitalized.

        static int FindFactor(Int64 userInput)
        {

The compiler can infer the type if you use var, so you won't have to repeat it.

            var largestFactor = 0L;
            var number = userInput;

            for (var i = 2; i < number; ++i)
            {

Use && instead of nested if-statements.

                if (number % i == 0 && IsPrimeFactor(i))
                {
                    largestFactor = i;
                }
            }

            return largestFactor;
        }

Usually you put a blank line between function definitions.

Functions returning Booleans are often called "IsBlaBla" instead of "BlaBlaCheck."

        static bool IsPrimeFactor(int number)
        {
            var primeNumberValidity = true;

            for(int i = 2; i < number; ++i)
            {
                if (primeNumberValidity && number % i == 0)
                {
                    primeNumberValidity = false;

You can exit the loop here because continuing is useless.

                    break;
                }
                else
                {
                    i = number;
                }
            }

            return primeNumberValidity;
        }

args is not used, so you can omit it.

        static void Main()
        {
            Console.Write("Hello, please enter a number to find the biggest prime factor of it: ");

            var userInput = Convert.ToInt64(Console.ReadLine());

            var answer = FindFactor(userInput);
            Console.WriteLine(answer);
            Console.ReadKey();
        }
    }
}

You can use LINQ to implement FindFactor in a functional fashion, rather than imperatively.

static int FindFactor(Int64 number) {
    return IEnumerable.Range(2, number - 2)
                      .Where(n => number % n == 0 && IsPrimeFactor(n))
                      .DefaultIfEmpty(0)
                      .Last();
}


Avoiding nested conditionals and comparing strings I have a web page with a set of icons that are grey by default:

If a user clicks one, it toggles green (.toggleClass('green')):

If a user clicks a green one, it toggles back to grey (.removeClass('green')).
Only one icon can be green at any given time, so if you have a green icon and you click a grey icon, the icon that was originally green will change to grey while the one you clicked would change to green.

Each of these icons corresponds to a section on the page.

If all the icons are grey, all the sections on the page are visible.

If one icon is green, only that icon's section is visible, the sections represented by the grey icons are hidden.

Here is the code that controls that behavior:
$(document).on 'click', '.toggler', ->
  icons = [$('#toggle-videos'),$('#toggle-images'),$('#toggle-words')]
  sections = [$('#videos'),$('#images'),$('#words')]
  if $(this).hasClass('green')
    $(this).toggleClass('green')
    i = 0
    while i < sections.length
      sections[i].show()
      i++
  else
    $(this).addClass('green')
    i = 0
    while i < icons.length
      if icons[i][0] != $(this)[0]
        icons[i].removeClass('green')
        sections[i].hide()
      else
        j = 0
        while j < sections.length
          if $(this).attr('id').indexOf(sections[j].attr('id')) != -1
            sections[j].show()
          j++
      i++

I feel it is very hard to understand what this code does simply by reading it.  I feel I am missing a simpler way to accomplish the following:

Associate an icon with a specific section on the page
Keep the green state of an icon associated with the visibility of a specific section on the page

My primary concerns with the code:

I have several nested if statements with nested while statements
I am checking the relationship between a section and an icon by checking if the icon.id has part of the string (this is the icon element and j is a counter):
if $(this).attr('id').indexOf(sections[j].attr('id')) != -1

Is this acceptable for javascript or is there a better way?

I would propose to use data attributes. E.g. icons have data-section-id attribute.

if $(this).hasClass('green') // all should become greynow
{
    $('div.section').show(); // show all sections
    $(this).removeClass('green');
}
else // we turn one sectio on
{
    $('div.section').hide(); // show all sections
    $('#'+ $(this).data('sectionId')).show(); // show a corresponding section
    $('li.icon').removeClass('green'); // turn all icons off
    $(this).addClass('green'); // turn current one on
}

But of course, that requires some changes in HTML structure.


Ruby script to load .xlsx files into a MySQL database I put together this Ruby script (1.9.3) to load data into MySQL from many .xlsx files that contain data entered by people. These files typically have many illegal characters and it has been difficult to handle the different errors. I have tried multiple rescue and character escaping approaches but now this method is not good and I have several more in the same class that are similar but load from different formats.

I would love some code review to help make this more functional. This is a standalone Ruby script without Rails or activerecord. I am using the logger, rubyXL, and MySQL2 gems.

  def paid_adv_load_ppc
    begin
      Dir["#{@paid_adv_work_path}*.xlsx"].each do |file|
        if file =~ /(PPC)/ && file !~ /(~)/
          begin
            @file = file
            begin
              workbook = RubyXL::Parser.parse(file)
              data = workbook.worksheets[0]
              sheet1 = data.extract_data
              begin
                sheet1.each_with_index do |row,index|
                  if index > 0 && row[1] != nil
                    service = row[3].to_s.gsub(/['"]/, '')
                    impressions = row[9].to_i
                    clicks = row[10].to_i
                    cost = row[11].to_f
                    total = row[12].to_f
                    puts "index: #{index} row: #{row}"
                    @db.query("INSERT INTO ppc
                     (service,impressions,clicks,cost,total)
                     VALUES  ('#{service}',#{impressions},#{clicks},#{cost},#{total})  ")
                  end
                end
              rescue Exception => e
                @log.info("There is a problem loading row for index #{index} :#{row} because of #{e.message}")
                next
              end
            rescue Exception => e
              @log.info("There is a problem loading #{@file}: #{e.message}")
              next
            end
          end
          @log.info("Loaded file #{@file} into database")
          FileUtils.rm(@file)
        end
      end
    rescue Exception => e
      @log.warn("Unable to process the data feed: #{@file} because #{e.message}")
    end
  end

For starters, I'd break the script up into many more methods. If nothing else it'll avoid the "pyramid code" (all that nested indentation) you've got going on. But it should also make the code easier to understand, maintain and extend.

I'd also, as an overall approach, favor writing a file of INSERT statements, rather than inserting each row, one at a time. At least for testing, I'd highly recommend this. You can always read this file directly into mysql later. The point is that if, say, the first 2 rows get inserted fine, but the 3rd fails, you'll already have those first 2 row in the database, when you run the script again. And since the .xlsx files only get removed if everything works out, the same file may be imported several times - perhaps failing halfway several times - resulting in a bunch of doubled rows.

Speaking of files, I'd avoid completely removing the xlsx file once it's done. Probably better to move it or rename it, so you still have it, but it won't get read again. In general, just try to avoid destructive operations unless necessary.

Anyway, the code below is an attempt to break up your code. I haven't tried it, so don't just blindly run it or anything.

Moreover, I'm using RubyXL's get_table method here - I don't know if that's actually useful in your case. However, I imagine that the xlsx-files have a header row, since you always skip the first row. If those headers are sensical, you can use them to your advantage, and avoid the hard-coded (and opaque) column indices.

Some of the methods here have optional arguments that default to instance variables. I won't recommend that for production use; it's there for testing purposes. You can either make the arguments required, or you can remove the arguments, and rely on instance variables.

# Hash for translating xlsx columns to mysql columns
# The procs may not be necessary; get_table may handle conversion
COLUMN_TRANSLATIONS = {
  "Service"     => { column: "service",     proc: :to_s },
  "Impressions" => { column: "impressions", proc: :to_i },
  "Clicks"      => { column: "clicks",      proc: :to_i },
  "Cost"        => { column: "cost",        proc: :to_f },
  "Total"       => { column: "total",       proc: :to_f }
}.freeze

# Gets the relevant .xlsx-files
def xlsx_files(directory = @paid_adv_work_path)
  path = File.join(directory, "*(PPC)*.xlsx")
  files = Dir.glob(path)
  files.reject { |file| File.basename(file) =~ /^~/ }
end

# Use get_table to get structured data
def read_xlsx(file)
  workbook  = RubyXL::Parser.parse(file)
  worksheet = workbook.worksheets[0]
  worksheet.get_table(COLUMN_TRANSLATIONS.keys)[:table]
end

# Translate into a mysql-friendly format
def translate_table(table)
  table.map do |row|
    row.map do |column, value|
      lookup = COLUMN_TRANSLATIONS[name.to_s] # get_table uses symbol keys; we want strings
      value = value.send(lookup[:proc])
      [lookup[:column], value]
    end
  end
end

# Insert a row
def insert_rows(rows, connection = @db)
  columns = COLUMN_TRANSLATIONS.map { |name, info| info[:column] }
  rows.each do |row|
    columns = row.keys.join(", ")
    values  = row.values.map { |value| "'#{connection.escape(value)}'" }.join(", ")
    query = "INSERT INTO ppc (#{columns}) VALUES (#{values});"
    connection.query(query)
  end
end

# Put it together per-file
def import_xlsx_file(file, connection = @db)
  table = read_xlsx(file)
  rows  = translate_table(table)
  insert_rows(rows, connection)
end

# And all together now...
def import
  xlsx_files.each do |file|
    begin
      import_xlsx_file(file)
      # Handle file removal/renaming here
    rescue => e
      @log.info "Failed to import #{file}: #{e.message}"
    end
  end
end

An advantage of having the optional arguments is that you can swap out the database connection with a stand-in object, like:

class QueryLogger
  def initialize(logger)
    @logger = logger
  end

  def query(string)
    @logger.info(string)
  end
end

And try something like import_xlsx_file(some_file, QueryLogger.new(@log)) to log the queries instead of actually running them on the server.


Guessing Game: computer generated number between 1 and 100 guessed by user The required output is stated just before the main() function. Is there a better way to achieve it? I feel like I am repeating code unnecessarily but am unable to find a better way to get the result. Not squeezing the code too much, like one liners, but reasonably using better logic.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#Time to play a guessing game.

#Enter a number between 1 and 100: 62
#Too high. Try again: 32
#Too low. Try again: 51
#Too low. Try again: 56

#Congratulations! You got it in 4 guesses.

import random

def main():

    return 0

if __name__ == '__main__':
    main()

print("Time to play a guessing game.")

val = random.randint(1, 100)
guess = 0
count = 1

guess = input("\n\t\tEnter a number between 1 and 100: ")
guess = int(guess)

print("")
print("randint is", val)
print("")

if (guess == val):
    print("\nCongratulations! You got it in", count, "guesses.")

while(guess != val):

    if guess > val:
        print("Too high. Try again:", guess)
        guess = input("\n\t\tEnter a number between 1 and 100: ")
        guess = int(guess)
        count = count + 1
        if guess == val:
            print("\nCongratulations! You got it in", count, "guesses.")
            break

    elif guess < val:
        print("Too low. Try again:", guess)
        guess = input("\n\t\tEnter a number between 1 and 100: ")
        guess = int(guess)
        count = count + 1
        if guess == val:
            print("\nCongratulations! You got it in", count, "guesses.")
            break
    else:
        pass

print("")

The pythonic way to do count = count + 1 is count += 1
You don't need to repeat the 'guess again' part of the game twice:

if guess > val:
    print("Too high. Try again:", guess)
elif guess < val:
    print("Too low. Try again:", guess)
guess = int(input("\n\t\tEnter a number between 1 and 100: "))
count += 1
if guess == val:
    print("\nCongratulations! You got it in", count, "guesses.")
    break

You don't need to add the extra if statement because if guess != val, then the loop with break anyway:

while guess != val:
    if guess > val:
        print("Too high. Try again:", guess)
    elif guess < val:
        print("Too low. Try again:", guess)
    guess = int(input("\n\t\tEnter a number between 1 and 100: "))
    count += 1
print("Congratulations! You got it in", count, "guesses.")

I think print("randint is", val) was probably for testing purposes, but it's still in your code!
If you execute your program outside the command module (I'm not quite sure what it's called), the program will close immediately after it's finished; it's always best to give the user the choice of when to quit, so insert this at the end of your code:

input("Press enter to quit")

The first section is unneeded:

def main():`, `if __name__ == "__main__":

The first if statement is also unneeded:

if guess == val:

You don't need to define guess = 0 the first time.

So, all in all, my improvement of your code is:

import random
print("Time to play a guessing game.")
val = random.randint(1, 100)
count = 1
guess = int(input("\n\t\tEnter a number between 1 and 100: "))
while(guess != val):
    if guess > val:
        print("Too high. Try again:", guess)
    elif guess < val:
        print("Too low. Try again:", guess)
    guess = int(input("\n\t\tEnter a number between 1 and 100: "))
    count += 1
print("\nCongratulations! You got it in ", count, " guesses.")
input("Press enter to quit.")


Calculating minimum size of rectangle that contains two smaller ones My Rectangle class contains one vertex (x,y), its width a, and its height b; the opposite vertex will be (x+a,y+b). I had a task to take 2 rectangles and compute the minimal 3rd rectangle to contain 2 smaller ones.  How can I simplify this code?

Rectangle operator+(Rectangle &o){
    double x1 = x, x2 = o.Gx(), y1 = y, y2 = o.Gy(), a1 = a, a2 = o.Ga(), b1 = b, b2 = o.Gb();
    double retx, rety, reta, retb;
    if (x2 > x1){
        retx = x1;
        if (x1 + a1 <= x2)
            reta = a1 + a2 + x2 - (x1 + a1);
        else if (x1 + a1 > x2 + a2)
            reta = a1;

        else
            reta = x2 + a2 - x1;
    }
    else{
        retx = x2;
        if (x1 <= x2 + a2)
            reta = x1 + a1 - x1;
        else if (x2 + a2 > x1 + a1)
            reta = a2;
        else
            reta = a1 + a2 + x1 - (x2 + a2);
    }
    if (x1 == x2 && a1 > 0 && a2 > 0){
        retx = x1;
        if (a1 > a2)
            reta = a1;
        else
            reta = a2;
    }

    if (y2 > y1){
        rety = y1;
        if (y1 + b1 <= y2)
            retb = b1 + b2 + y2 - (y1 + b1);
        else if (y1 + b1 > y2 + b2)
            retb = b1;

        else
            retb = y2 + b2 - y1;
    }
    else{
        rety = y2;
        if (y1 <= y2 + b2)
            retb = y1 + b1 - y1;
        else if (y2 + b2 > y1 + b1)
            retb = b2;
        else
            retb = b1 + b2 + y1 - (y2 + b2);
    }
    if (y1 == y2 && b1 > 0 && b2 > 0){
        rety = y1;
        if (b1 > b2)
            retb = b1;
        else
            retb = b2;
    }
    return Rectangle(retx,rety,reta,retb);
}

For the moment, I'm assuming a typical graphics system with the origin at the top left. At the very least, the variable names I've used depend upon that to really make any sense. Anyway, I believe the logic you want can be embodied in code something like this (please forgive the sexist variable names):

Rectangle operator+(Rectangle &o) {
    double my_left = std::min(x, x + a);
    double his_left = std::min(o.x, o.x + o.a);
    double left = std::min(my_left, his_left);

    double my_right = std::max(x, x + a);
    double his_right = std::max(o.x, o.x + o.a);
    double right = std::max(my_right, his_right);

    double my_top = std::min(y, y + b);
    double his_top = std::min(o.y, o.y + o.b);
    double top = std::min(my_top, his_top);

    double my_bottom = std::max(y, y + b);
    double his_bottom = std::max(o.y, o.y + o.b);
    double bottom = std::max(my_bottom, his_bottom);

    return Rectangle(left, top, right - left, bottom - top);
}

If you can be sure that a and b are non-negative, you can simplify that quite a bit to just:

Rectangle operator+(Rectangle &o) {
    double left = std::min(x, o.x);
    double right = std::max(x + a, o.x + o.a);
    double top = std::min(y, o.y);
    double bottom = std::max(y + b, o.y + o.b);

    return Rectangle(left, top, right - left, bottom - top);
}

As for the rest of the code, I see two obvious things. First of all, the variable names aren't particularly helpful. I guess I can sort of keep things like x1 and x2 straight, but only just.

Second, the logic strikes me as almost a complete mess. I guess I can understand what it needs to do, and if I was willing to spend enough time on it I could verify that it works correctly--but it's not immediately obvious to me at first glance, and it would take some fairly exhaustive (and exhausting) analysis to be sure that it works for every possible case, not to mention being sure exactly how it works.

There's also one final caveat I feel obliged to add: an IEEE floating point number can be set to a NaN, which means all comparisons to that value will return false (even if (a == a) will yield false). If either of your rectangles contains a NaN, all of these will produce garbage results.


stringByAppendingString: vs. stringWithFormat: I am refactoring code which contains many lines of NSString* image = [@"ipad_" stringByAppendingString:imageOrigName]; and wondered which is more optimized:

stringByAppendingString:

or

stringWithFormat:

In the first, you take one NSString object and concatenate another onto its tail.  In the second, you can use a formatter:

NSString* image = [NSString stringWithFormat:@"ipad_%@", imageOrigName];

The result is the same, but for optimization purposes, which is better?

For the above example, I would expect that a simple concatenation would be faster than having it parse the string for '%' symbols, find a matching type (NSString for the %@), and do all its background voodoo.

However, what happens when we have (sloppily written?) code which contains multiple stringByAppendingStrings?

NSString* remainingStr = [NSString stringWithFormat:@"%d", remaining];
NSString* msg = "You have ";
msg = [msg stringByAppendingString:remainingStr];
msg = [msg stringByAppendingString:@" left to go!"];
if (remaining == 0)
    msg = [msg stringByAppendingString:@"Excellent Job!"];
else
    msg = [msg stringByAppendingString:@"Keep going!"];

Here, a single stringWithFormat (or initWithFormat if we use [NSString alloc]) would seem to be the smarter path:

NSString* encouragementStr = (remaining == 0 ? @"Excellent Job!" : @"Keep going!");
NSString* msg = [NSString stringWithFormat:@"You have %d left to go! %@", remaining, encouragementStr];

Thoughts? Sites/blogs that you've found that helps answer this?

The only way to know is to measure it.

And, of course, the only reason to measure it is if it actually matters;  if you have a real world performance issue that can be tracked to this code.

If not, don't worry about it.

However, there are a few issues to consider:

every append* is going to cause an allocation and memory copying, those are expensive
every *WithFormat: is going to cause a string to be parsed (and there will be allocations/copying)
all of this is likely entirely moot unless you are doing this 10s of thousands of times often.   If you are, it begs the question as to why?

And, finally, note that this kind of string manipulation is going to make localization more difficult.


Quicksort Without Recursion Am teaching myself about sorting techniques and trying my hand at a quicksort implementation. I found a lot of examples based on recursion but didn't want to go that route in a language that doesn't support tail-call optimization.

public static class ListExtensions
{
    public static void InsertionSort<T>(this IList<T> values, int startIndex, int endIndex, IComparer<T> comparer) {
        var left = startIndex;
        var right = 0;
        var temp = default(T);

        while (left < endIndex) {
            right = left;
            temp = values[++left];

            while ((right >= startIndex) && (0 < comparer.Compare(values[right], temp))) {
                values[(right + 1)] = values[right--];
            }

            values[(right + 1)] = temp;
        }
    }
    public static void InsertionSort<T>(this IList<T> values, IComparer<T> comparer) {
        InsertionSort(values, 0, (values.Count - 1), comparer);
    }
    public static void InsertionSort<T>(this IList<T> values) {
        InsertionSort(values, Comparer<T>.Default);
    }
    public static void QuickSort<T>(this IList<T> values, int startIndex, int endIndex, IComparer<T> comparer, IRandomNumberGenerator randomNumberGenerator) {
        var range = (startIndex, endIndex);
        var stack = new Stack<(int, int)>();

        do {
            startIndex = range.startIndex;
            endIndex = range.endIndex;

            if ((endIndex - startIndex + 1) < 31) {
                values.InsertionSort(startIndex, endIndex, comparer);

                continue;
            }

            var pivot = values.SampleMedian(startIndex, endIndex, comparer, randomNumberGenerator);
            var left = startIndex;
            var right = endIndex;

            while (left <= right) {
                while (0 > comparer.Compare(values[left], pivot)) { left++; }
                while (0 > comparer.Compare(pivot, values[right])) { right--; }

                if (left <= right) {
                    values.Swap(left++, right--);
                }
            }

            if (startIndex < right) {
                stack.Push((startIndex, right));
            }

            if (left < endIndex) {
                stack.Push((left, endIndex));
            }
        }
        while (stack.TryPop(out range));
    }
    public static void QuickSort<T>(this IList<T> values, IComparer<T> comparer, IRandomNumberGenerator randomNumberGenerator) {
        QuickSort(values, 0, (values.Count - 1), comparer, randomNumberGenerator);
    }
    public static void QuickSort<T>(this IList<T> values) {
        QuickSort(values, Comparer<T>.Default, FastRandom.Default);
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static T SampleMedian<T>(this IList<T> values, int startIndex, int endIndex, IComparer<T> comparer, IRandomNumberGenerator randomNumberGenerator) {
        var left = randomNumberGenerator.NextInt32(startIndex, endIndex);
        var middle = randomNumberGenerator.NextInt32(startIndex, endIndex);
        var right = randomNumberGenerator.NextInt32(startIndex, endIndex);

        if (0 > comparer.Compare(values[right], values[left])) {
            Swap(values, right, left);
        }

        if (0 > comparer.Compare(values[middle], values[left])) {
            Swap(values, middle, left);
        }

        if (0 > comparer.Compare(values[right], values[middle])) {
            Swap(values, right, middle);
        }

        return values[middle];
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static void Swap<T>(this IList<T> values, int xIndex, int yIndex) {
        var temp = values[xIndex];

        values[xIndex] = values[yIndex];
        values[yIndex] = temp;
    }
}

All in all there is not much to comment. I like the iterative mechanism with the stack. Trying other collections (linked list, dictionary, hashset etc.) doesn't seem to improve the performance.

One could argue that it would be nice to have the partition part in a dedicated function to improve readability, but again the algorithm isn't that hard to understand.

The really improvement of performance comes from the use of InsertionSort() when the range is smaller than 31 - and that magic number seems to be the right limit. And Insertion Sort seems to be the right choice over other simple algorithms like Selection Sort.

The performance gain from SampleMedian() is little or absent for smaller data sets, but is significant for larger (> 10000) - compared to let it return values[startIndex] or values[startIndex + (endIndex - startIndex) / 2].

All in all a well designed algorithm optimized in respect to performance.

A minor thing in SampleMedian():

I don't like:

if (0 > comparer.Compare(values[right], values[left]))

but rather:

if (comparer.Compare(values[right], values[left]) < 0)

but that's a matter of habit.

Of course you should check if the arguments are valid (values != null, startIndex < endIndex etc.)


Readability vs. maintainability: nested functions What are the pros and cons of each option, considering long-term implications (increasing the number of functions / parameters, other developers taking over, etc.)?
Option 1: removes the need to pass foo and bar to each method, but will create nested functions that are hard to follow.
const myFunction = ({foo, bar}) => {
  const results = []

  const function1 = () => {
    return foo + bar;
  }

  const function2 = () => {
    return foo * bar;
  }

  const res1 = function1();
  const res2 = function2();

  results.push(res1, res2);
}

Option 2: you pass the parameters to each function, but remove the nesting, which in my opinion makes it more readable.
const function1 = ({foo, bar}) => {
  return foo + bar;
}

const function2 = ({foo, bar}) => {
  return foo * bar;
}

const myFunction = ({foo, bar}) => {
  const results = []

  const res1 = function1({foo, bar});
  const res2 = function2({foo, bar});

  results.push(res1, res2);
}

I would prefer to know how to improve my functional approaches here. Thank you!

Option 1
The nested function is not bad (depending on the situation). Of course, they bring more complexity and reduces extensibility. But in some cases, you wish to bundle some function that works with the main function output (well, it's not very different from the class).
Of course you should return object instead of the list for the usage convenience:
const myFunction = ({foo, bar}) => {
  return {
    function1() {
        return foo + bar
    },
    function2() {
        return foo * bar;
    }
  }
}
myFunction().function1()

To sum up, this design can simplify usage in some cases. However, the worst thing about this pattern is that these functions are not extendible and you can't use partial functionality (like using only function1). In most cases, I recommend avoiding this unless you are writing a library/helper function and which to simplify usage by attaching other chain function to the main output (fetch is a good example).

Option 2
Regarding the second option, it works fine as long as your function is not too complex and you don't have too many parameters. You can partially solve the issue with a lot of parameters using TypeScript (because you can statically describe them).
However, if possible I recommend changing logic a bit. Instead of requiring all parameters why don't you require the output of functions? Then you can have multiple functions which return different output + you can also write your own implementation for one part. This option opens a way for unlimited possibilities.
Example:
const myFunction = ({foo, bar}) => {
    return [
        foo,
        bar
    ]
}

myFunction({
    foo: function1(),
    bar: function1(),
})

// You can "extend" this function:
myFunction({
    foo: function1(),
    bar: myCustomFunction(),
})


Pretty printing of the numpy ndarrays Following this idea for pretty printing of numpy ndarrays, I have developed a very primitive prototype:

def ndtotext(A, w=None, h=None):
    if A.ndim==1:
        if w == None :
            return str(A)
        else:
            s ='['+' '*(max(w[-1],len(str(A[0])))-len(str(A[0]))) +str(A[0])
            for i,AA in enumerate(A[1:]):
                s += ' '*(max(w[i],len(str(AA)))-len(str(AA))+1)+str(AA)
            s +='] '
    elif A.ndim==2:
        w1 = [max([len(str(s)) for s in A[:,i]])  for i in range(A.shape[1])]
        w0 = sum(w1)+len(w1)+1
        s= u'\u250c'+u'\u2500'*w0+u'\u2510' +'\n'
        for AA in A:
            s += ' ' + ndtotext(AA, w=w1) +'\n'
        s += u'\u2514'+u'\u2500'*w0+u'\u2518'
    elif A.ndim==3:
        h=A.shape[1]
        s1=u'\u250c' +'\n' + (u'\u2502'+'\n')*h + u'\u2514'+'\n'
        s2=u'\u2510' +'\n' + (u'\u2502'+'\n')*h + u'\u2518'+'\n'
        strings=[ndtotext(a)+'\n' for a in A]
        strings.append(s2)
        strings.insert(0,s1)
        s='\n'.join(''.join(pair) for pair in zip(*map(str.splitlines, strings)))
    return s

for example:

shape = 4, 5, 3
C=np.random.randint(10000, size=np.prod(shape)).reshape(shape)
print(ndtotext(C))

┌┌────────────────┐┌────────────────┐┌────────────────┐┌────────────────┐┐
│ [9298 4404 1759]  [5426 3488 9267]  [8884 7721  579]  [6872 4226 1858] │
│ [6723  271 8466]  [9885 6760 8949]  [ 295 7422 5659]  [5322 4239 7446] │
│ [7156 6077 9390]  [2712 6379 2832]  [6956  626 5534]  [ 142 4090 6390] │
│ [9377 9033 1953]  [8986 3791 4538]  [2466 8572  662]  [1528 8922 9656] │
│ [1449 7319 3939]  [7350 9619  928]  [7542 4704 1477]  [ 980 6037  869] │
└└────────────────┘└────────────────┘└────────────────┘└────────────────┘┘

I would appreciate it if you could review this code and let me know how I can improve it.

I hope to see:

possible mistakes or cases to break the code
how to make it faster, more performant, pythonic
how to extend it to higher dimensions

P.S. For those who follow up this idea I have integrated everythin here in this Jupyter Notebook

If A.ndim is not in 1, 2, 3, your code tries to return a non-existing string s. It would be better to be explicit about what your code supports atm:

def ndtotext(A, w=None, h=None):
    ...
    else:
        raise NotImplementedError("Currently only 1 - 3 dimensions are supported")
    return s

While we are at the point of having your code be clear about what is happening, you should add a docstring explaining what your code does:

def ndtotext(A, w=None, h=None):
    """Returns a string to pretty print the numpy.ndarray `A`.

    Currently supports 1 - 3 dimensions only.
    Raises a NotImplementedError if an array with more dimensions is passed.

    Describe `w` and `h`.
    """
    ...

Next, Python has an official style-guide, PEP8, which programmers are encouraged to follow. One of the things it recommends is surrounding operators with spaces (which I fixed in the rest of the code) and using lower_case for variables and functions (which I left as is for now).

Now, let's come to your actual code:

You calculate some values multiple times (like str(A[0])), save those to a variable.
If you want to compare to None, use is (since it is a singleton).
No else needed after an if...return (this is a matter of personal style, I prefer not having the additional level of indentation).
Use str.rjust to add enough whitespace in front of your strings. You could also use str.format for this, but it looks less nice.
Your w has a weird structure, with the width of the first column being the last entry and the rest starting at zero.
Give the unicode values names. And then add functions to draw a line of specified length.
String addition is costly and slow. Try to consistently use building a list and str.joining it.

UPPER_LEFT = u'\u250c'
UPPER_RIGHT = u'\u2510'
LOWER_LEFT = u'\u2514'
LOWER_RIGHT = u'\u2518'
HORIZONTAL = u'\u2500'
VERTICAL = u'\u2502'

def upper_line(width):
    return UPPER_LEFT + HORIZONTAL * width + UPPER_RIGHT

def lower_line(width):
    return LOWER_LEFT + HORIZONTAL * width + LOWER_RIGHT

def left_line(height):
    return "\n".join([UPPER_LEFT] + [VERTICAL] * height + [LOWER_LEFT])

def right_line(height):
    return "\n".join([UPPER_RIGHT] + [VERTICAL] * height + [LOWER_RIGHT])

def ndtotext(A, w=None, h=None):
    """Returns a string to pretty print the numpy.ndarray `A`.

    Currently supports 1 - 3 dimensions only.
    Raises a NotImplementedError if an array with more dimensions is passed.

    Describe `w` and `h`.
    """
    if A.ndim == 1:
        if w is None:
            return str(A)
        s = " ".join([str(value).rjust(width) for value, width in zip(A, w)])
        return '[{}]'.format(s)
    elif A.ndim == 2:
        widths = [max([len(str(s)) for s in A[:, i]]) for i in range(A.shape[1])]
        s = "".join([' ' + ndtotext(AA, w=widths) + ' \n' for AA in A])
        w0 = sum(widths) + len(widths) - 1 + 2 # spaces between elements and corners
        return upper_line(w0) + '\n'  + s + lower_line(w0)
    elif A.ndim == 3:
        h = A.shape[1]
        strings = [left_line(h)]
        strings.extend(ndtotext(a) + '\n' for a in A)
        strings.append(right_line(h))
        return '\n'.join(''.join(pair) for pair in zip(*map(str.splitlines, strings)))
    raise NotImplementedError("Currently only 1 - 3 dimensions are supported")

This can probably be even more compactified, but I think it is a good start.

Example usage:

x = np.arange(12)

print(ndtotext(x))
[ 0  1  2  3  4  5  6  7  8  9 10 11]

print(ndtotext(x.reshape(3, 4)))
┌───────────┐
 [0 1  2  3]
 [4 5  6  7]
 [8 9 10 11]
└───────────┘

print(ndtotext(x.reshape(3, 2, 2)))
┌┌─────┐┌─────┐┌───────┐┐
│ [0 1]  [4 5]  [ 8  9] │
│ [2 3]  [6 7]  [10 11] │
└└─────┘└─────┘└───────┘┘


Binary trees exercise I'm not sure about this code but it feels ugly to me. It is a solution to this.

package main

import ("golang.org/x/tour/tree"; "fmt"; "reflect"; "sort")

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    if t != nil {
        ch <- t.Value
        Walk(t.Left, ch)
        Walk(t.Right, ch)
    }
}

func WalkTest(t *tree.Tree, ch chan int) []int {
    go Walk(t, ch)
    var testSlice []int
    for i := 0; i <10; i++ {
        testSlice = append(testSlice, <- ch)
    }
    return testSlice
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    var t1Slice []int
    var t2Slice []int
    ch1 := make(chan int, 10)
    ch2 := make(chan int, 10)
    go Walk(t1, ch1)
    go Walk(t2, ch2)
    for i := 0; i < 10; i++ {
        t1Slice = append(t1Slice, <- ch1)
        t2Slice = append(t2Slice, <- ch2)
    }
    sort.Ints(t1Slice); sort.Ints(t2Slice)
    return reflect.DeepEqual(t1Slice, t2Slice)
}

func main() {
    // Test the walk function
    walkTestTree := tree.New(1)
    walkTestCh := make(chan int, 10)
    walkTest := WalkTest(walkTestTree, walkTestCh)
    if len(walkTest) != 10 {
        panic("Walk test failed")
    }
    fmt.Println("Walk test ok!")

    // test the Same function
    testTree1 := tree.New(1)
    testTree2 := tree.New(1)
    sameTest := Same(testTree1, testTree2)
    if !sameTest {
        panic("same test failed")
    }
    fmt.Println("Same test passed")

    aTree := tree.New(1)
    bTree := tree.New(1)
    fmt.Println(Same(aTree, bTree))
}

The ugly

  Not sure about this code but it feels ugly to me...

I agree :-)

The WalkTest function and other code that uses it is not pretty.
This is not part of the exercise,
not really well done, so practically it's just noise.
It's not well done, because all it does is put values from the tree into a slice, return it, and then main checks that the length is 10.
What does that mean? It's not a useful test.

I'm not a fan of variables for one-time use without justification.
For example these:

testTree1 := tree.New(1)
testTree2 := tree.New(1)
sameTest := Same(testTree1, testTree2)
if !sameTest {
  panic("same test failed")
}

I would find the above easier to read without the one-time variables:

if !Same(tree.New(1), tree.New(1)) {
    panic("got false; expected true (same trees)")
}

Magic

In this code, why should the length of walkTest be 10?

walkTestCh := make(chan int, 10)
walkTest := WalkTest(walkTestTree, walkTestCh)
if len(walkTest) != 10 {
  panic("Walk test failed")
}

You create a buffered channel with size 10.
But why buffered, and why 10?
Then WalkTest does something,
but just be reading this code,
we have no clue that 10 has any special significance.
Yet we expect the returned walkTest slice to have length of 10.

This could would have made a lot more sense if WalkTest took a count parameter. Then it would be reasonable to expect that a slice returned by WalkTest(tree, ch, 123) should have length = 123.

Variable declarations

In this code, t1Slice and t2Slice are declared at the top,
but only used much later.

var t1Slice []int
var t2Slice []int
ch1 := make(chan int, 10)
ch2 := make(chan int, 10)
go Walk(t1, ch1)
go Walk(t2, ch2)
for i := 0; i < 10; i++ {
  t1Slice = append(t1Slice, <-ch1)
  t2Slice = append(t2Slice, <-ch2)
}

It would be better to declare them right before you need them:

ch1 := make(chan int, 10)
ch2 := make(chan int, 10)
go Walk(t1, ch1)
go Walk(t2, ch2)

var t1Slice []int
var t2Slice []int
for i := 0; i < 10; i++ {
    t1Slice = append(t1Slice, <-ch1)
    t2Slice = append(t2Slice, <-ch2)
}

Performance

The exercise includes a link to the documentation of Tree,
from where you can find the source code too.
As it turns out,
the random binary tree is actually built as a binary search tree.
The consequence of that is in this case if you traverse the nodes in in-order, you will get sorted values:

func Walk(t *tree.Tree, ch chan int) {
    if t == nil {
        return
    }
    Walk(t.Left, ch)
    ch <- t.Value
    Walk(t.Right, ch)
}

With that, testing the equivalence becomes simpler and more efficient,
without needing intermediary slices, and sort.Ints and reflect.DeepEqual:

func Same(t1, t2 *tree.Tree) bool {
    ch1 := make(chan int)
    ch2 := make(chan int)
    go Walk(t1, ch1)
    go Walk(t2, ch2)

    // as per the spec, a tree.Tree has 10 elements
    size := 10
    for i := 0; i < size; i++ {
        if <-ch1 != <-ch2 {
            return false
        }
    }
    return true
}

The "specs" I'm referring to is this btw:

  The function tree.New(k) constructs a randomly-structured binary tree holding the values k, 2k, 3k, ..., 10k.

Formatting

There is a standard formatting in Go,
enforceable by the go fmt command.
Simply run this command on your code,
or use the Format button on the playground or on the tour.


Thoughts on using curly-brackets-less while loop with a try/catch? I need to fetch data from an server that isn't always reliable and unfortunately fixing that is out of my hands. My team determined we would attempt the request up to 3 times.

So I thought of using a try-catch inside the while loop but didn't like the extra indentation for no good reason and thought to remove the braces from the while loop.

async function doAjax() {
  const data = { /* stuff */ }
  const retryLimit = 2;
  let retryCount = 0;
  let found = false;

  while (!found && retryCount <= retryLimit) try {
    let serverResponse = await $.get("url", data);
    // Do stuff
  } catch (err) {
    retryCount++;
  }

  // Do more stuff
}

I know my team won't be against this, but I still got curious if there's a consensus or some reason in favor/against writing code this way. Thoughts?

I would not do this. It breaks too far from any typical convention for very little gain.

I'm personally against omitting braces at all; except in very narrow circumstances. I've seen many questions on stack overflow that stem from people omitting braces and not being able to figure out why "only certain lines are running".

This also appears to look like a new language construct and feels a little jolting at first. It takes an extra second to realize what's going on.

Considering how short the lines are, indentation shouldn't be a problem; and even if it is, there are other ways of addressing that problem. I would write this in the standard way

async function doAjax() {
  const data = { /* stuff */ }
  const retryLimit = 2;
  let retryCount = 0;
  let found = false;

  while (!found && retryCount <= retryLimit) {
    try {
      let serverResponse = await $.get("url", data);
      // Do stuff

    } catch (err) {
      retryCount++;
    }
  }

  // Do more stuff
}

If you like playing around with making code read interestingly and creating language constructs, I recommend playing around with a language with Clojure (or another lisp). Doing experimental things with the syntax is a little more expected in a language like that.


Find the smallest regular number that is not less than N (Python) This is from an answer to my own StackOverflow question on how to efficiently find a regular number that is greater than or equal to a given value.

I originally implemented this in C# but translated it to Python because I guessed (correctly) that it would be shorter and would eliminate a third-party library dependency.

I am a Python newbie though - This is the longest Python program I have ever written.  So I would like to know:

Is there a convention for indicating what version of the language you are targeting (like require <version> in perl?)  This program only works in 2.6.
Instead of the priority queue, is there a better way to generate the odd regular numbers?  I know it is possible to implement lazy lists in Python but they are not in 2.6 are they?
Any other idioms/naming conventions I am missing?

from itertools import ifilter, takewhile
from Queue import PriorityQueue

def nextPowerOf2(n):
    p = max(1, n)
    while p != (p & -p):
        p += p & -p
    return p

# Generate multiples of powers of 3, 5
def oddRegulars():
    q = PriorityQueue()
    q.put(1)
    prev = None
    while not q.empty():
        n = q.get()
        if n != prev:
            prev = n
            yield n
            if n % 3 == 0:
                q.put(n // 3 * 5)
            q.put(n * 3)

# Generate regular numbers with the same number of bits as n
def regularsCloseTo(n):
    p = nextPowerOf2(n)
    numBits = len(bin(n))
    for i in takewhile(lambda x: x <= p, oddRegulars()):
        yield i << max(0, numBits - len(bin(i)))

def nextRegular(n):
    bigEnough = ifilter(lambda x: x >= n, regularsCloseTo(n))
    return min(bigEnough)

from itertools import ifilter, takewhile
from Queue import PriorityQueue

def nextPowerOf2(n):

Python convention says that function should be named with_underscores

    p = max(1, n)
    while p != (p & -p):

Parens not needed.

        p += p & -p
    return p

I suspect that isn't the most efficient way to implement this function. See here for some profiling done on various implementations. http://www.willmcgugan.com/blog/tech/2007/7/1/profiling-bit-twiddling-in-python/

# Generate multiples of powers of 3, 5
def oddRegulars():
    q = PriorityQueue()

So this is a synchronized class, intended to be used for threading purposes. Since you aren't using it that way, you are paying for locking you aren't using.

    q.put(1)
    prev = None
    while not q.empty():

Given that the queue will never be empty in this algorithm, why are you checking for it?

        n = q.get()
        if n != prev:
            prev = n

The prev stuff bothers me. Its ugly code that seems to distract from your algorithm. It also means that you are generating duplicates of the same number. I.e. it would be better to avoid generating the duplicates at all.

            yield n
            if n % 3 == 0:
                q.put(n // 3 * 5)
            q.put(n * 3)

So why don't you just push n * 3 and n * 5 onto your queue?

# Generate regular numbers with the same number of bits as n
def regularsCloseTo(n):
    p = nextPowerOf2(n)
    numBits = len(bin(n))

These two things are basically the same thing. p = 2**(numBits+1).  You should be able to calculate one from the other rather then going through the work over again.

    for i in takewhile(lambda x: x <= p, oddRegulars()):
        yield i << max(0, numBits - len(bin(i)))

I'd have a comment here because its tricky to figure out what you are doing.

def nextRegular(n):
    bigEnough = ifilter(lambda x: x >= n, regularsCloseTo(n))
    return min(bigEnough)

I'd combine those two lines.

  Is there a convention for indicating what version of the language you are targeting (like > require  in perl?) This program only works in 2.6.

Honestly, much programs just fail when trying to use something not supported in the current version of python.

  I know it is possible to implement lazy lists in Python but they are not in 2.6 are they?

Lazy lists? You might be referring to generators. But they are supported in 2.6, and you used one in your code.


Testing a list of proxies for validity concurrently I have a class that tests a list of proxies for validity concurrently, which I have created in 2 different ways, one utilizing Parallel.ForEach and the other using a TPL Dataflow ActionBlock.

I am just wondering which is one is preferred, and if I am overlooking something important.  As a side note, I created the Dataflow version because I want to be able to queue proxy tests, with the Parallel.ForEach version I could probably achieve that but it would take more code and some refactoring.

I still need some add some functionality to these methods. I realize the 'tests' parameter isn't being used.

Parallel.ForEach version:

public class ProxyTester
{
    public async Task ValidateProxiesAsync(IEnumerable<Proxy> proxies, IEnumerable<ProxyJudge> judges, IEnumerable<ProxyTest> tests)
    {
        await Task.Run(async () =>
        {
            foreach (var proxy in proxies)
            {
                proxy.Status = ProxyStatus.Queued;
            }
            await proxies.ProcessWithParallelAsync(new Action<Proxy>((proxy =>
            {
                proxy.Status = ProxyStatus.Testing;
                proxy.Status = proxy.TestValidity(judges.ElementAt(0));
            })));
        });
    }
}

ProcessWithParallelAsync Extension method:

public static async Task ProcessWithParallelAsync<T>(this IEnumerable<T> list, Action<T> action, int maxConcurrency = 100)
{
    await Task.Run(() => {
        var options = new ParallelOptions();
        options.MaxDegreeOfParallelism = maxConcurrency;
        Parallel.ForEach(list, options, action);
    });
}

TPL Dataflow version (supports queuing):

class ProxyTester2
{

    private ActionBlock<(Proxy, IProxyTest)> actionBlock;

    public ProxyTester2()
    {
        actionBlock = new ActionBlock<(Proxy proxy, IProxyTest test)>(tup =>
        {
            tup.proxy.Status = ProxyStatus.Testing;
            tup.proxy.Status = tup.proxy.TestValidity(tup.test);
        }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 100 });
    }

    public void QueueProxyTest(Proxy proxy, IProxyTest test)
    {
        proxy.Status = ProxyStatus.Queued;
        actionBlock.Post((proxy, test));
    }

    public void QueueProxyTests(IEnumerable<Proxy> proxies, IEnumerable<ProxyJudge> judges, IEnumerable<ProxyTest> tests)
    {
        foreach (var proxy in proxies)
        {
            QueueProxyTest(proxy, judges.ElementAt(0));
        }
    }
}

You are starting two Task in ValidateProxiesAsync - one in the method and another in the extension method.  Really seems it should be one Task.

Also judges is an IEnumerable that you are constantly doing ElementAt.  Should either do First and store that value for each call or pass in an IList or Array is that's what it really is if you need to access it by element

As for Parallel.ForEach vs TPL DataFlow I think that depends on if you are building a data flow mesh (TPL DataFlow) or just want to process items in Parallel only (Parallel.ForEach)


Given a sequence of words, print all anagrams together Given an array of words, print all anagrams together. For example, if
  the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output
  may be “cat tac act dog god”.

My idea is to sort individual words firstly. And then sort the array of words.
In this way, the anagrams will be together. The following is my code:

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

typedef struct word_with_ind
{
    char* word;
    int ind;
}*word_with_ind_ptr;

int comp_char(const void* x, const void* y)
{
    char* c1 = (char*)x;
    char* c2 = (char*)y;

    return *c1 - *c2;
}

int comp_str(const void* x, const void* y)
{
    const word_with_ind_ptr w1 = (word_with_ind_ptr)x;
    const word_with_ind_ptr w2 = (word_with_ind_ptr)y;

    return strcmp(w1->word, w2->word);
}

void destroy(word_with_ind_ptr x, int size)
{
    for(int i = 0; i < size; ++i)
    {
        free(x[i].word);
    }
    free(x);
}

void print_anagrams_together(char* word[], int size)
{
    //make a copy of the original word array. And sort
    //the individual words
    word_with_ind_ptr x = (word_with_ind_ptr)malloc(sizeof(struct word_with_ind)*size);
    for(int i = 0; i < size; ++i)
    {
        x[i].ind = i;
        x[i].word = (char*)malloc(sizeof(char)*(strlen(word[i])+1));
        strcpy(x[i].word, word[i]);
        qsort(x[i].word, strlen(x[i].word), sizeof(char), comp_char);
    }

    //sort the array of words
    qsort(x, size, sizeof(struct word_with_ind), comp_str);

    //print result
    for(int i = 0; i < size; ++i)
    {
        printf("%s\n", word[x[i].ind]);
    }

    //free memory
    destroy(x, size);

}

int main()
{
    char* word[] = {"cat", "dog", "tac", "god", "act"};
    int size = sizeof(word)/sizeof(word[0]);
    print_anagrams_together(word, size);

    getchar();
    return 0;
}

FiHopZz, your concept seems fine.   A few comments:

in general, don't typedef pointers. It is confusing.
your functions are not const-correct. In other words they cast const values
to non-const values.  The compiler will warn you of this if you enable
warnings.
I prefer pointers to be declared like this: char *p, not char* p.
Consider char* a, b if in doubt (b is not a pointer but looks as if it
should be).
all local functions should be declared static
print_anagrams_together should take a const word array and a size_t size
(destroy should also take size_t not int)
don't cast the return from malloc and note that malloc can fail.
sizeof(char) is 1 by definition.
use strdup to copy a word, not malloc.  strdup can also fail.
you took the length of the string twice, once in the malloc call and once
in the qsort call.
you also used strcpy on a string of which you already knew the
length. memcpy is better (but remember to copy length+1).
print_anagrams_together is arguably better broken into several
sub-functions: copy_words, sort_words, print_words.  Well done for making
destroy as function.  This  would be renamed destroy_words for symmetry.
arguably, copy_words and sort_words above could be combined.  This is how
your loop is written, with a word copied and then sorted in the same loop.
This is clearly slightly more efficient, but in some way it does not appeal
to me.  For a start what do you call it? - copy_and_sort_words is rather
ugly. But also a copy_words that just duplicates the array is easily tested;
one that duplicates it and modifies it is not.  These are perhaps not
considerations that belong to a simple program such as this, but they are
worth beaaring in mind for more complicated tasks.
comments should be useful. Yours are mainly noise.  If nothing needs
saying, say nothing.
the word array in main should be const
the size in main should be const size_t, not int
main should have a parameter list

Don't take my comments on breaking your print_anagrams_together into separate
functions too seriously. It is not a big function and it is easily understood.
Breaking it apart would probably make the program worse.  However, for bigger
or more complicated applications, having several loops in the same function
in my opinion often indicates a lack of proper subdivision.  Just my opinion
though and others may differ.

Note also that although I say that malloc/strdup can fail, they are of course
unlikely to fail in a small program like this.  You might say that it is
pointless testing for NULL pointers when you know they will probably be okay.
The only thing you can sensibly do is to print an error and exit anyway
(perror("malloc"); exit(EXIT_FAILURE);).  But it is a good discipline always
to check the return values of functions that can fail.  Just do it.


Find the Nth number divisible by only 2,3,5, or 7 I recently participated in a small friendly competition and this was one of the questions:

  A number whose only prime factors are 2, 3, 5 or 7 is called a humble
  number. The first 20 humble numbers are: 1, 2, 3, 4, 5, 6, 7, 8, 9,
  10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, ...

  Given n, find the nth humble number.

  Example

  n = 1: 1; n = 11: 12; n = 22: 30

  [input] integer: positive integer n

  [output] integer: The nth humble number.

  There should be a O(N) solution!

Here's my solution:

def humbleNumber(n):
    curr = 0
    i = 0
    dp = {}
    while i < n:
        curr += 1
        if ishumble(curr, dp):
            dp[curr] = True
            i += 1
        else:
            dp[curr] = False
    return curr

def ishumble(x,dp):
    if x == 1:
        return True
    acc = [2,3,5,7]
    for i in acc:
        if x % i == 0:
            if (x/i) in dp:
                return dp[x/i]
            return ishumble(x / i) #i don't believe this ever get's called
    return False

I believe that this solution is \$O(N)\$. I am iterating up to \$n\$, and at each step, I am calling a constant-time helper function. The helper function ishumble(x, dp) will check if the current number x is a humble number. We are able to do this in constant time because we are guaranteed that if x % i == 0, then (x/i) is in dp! So I believe that the return ishumble(x / i) line is actually never called.

Therefore, this solution is in \$O(N)\$. Is my analysis correct? Is there a better solution?

No, not \$O(n)\$. Not even close. I'll get back to this later though. First, the code:

It's a little difficult to tell what your loop logic is. curr is getting incremented each time, but i isn't... whereas typically we'd use i as a loop index. I'd propose using i as the loop index, and then keeping a humble number count named count (or num_humbles or something):

count = 0
dp = {}
for i in itertools.count(start=1):
    if ishumble(i, dp):
        dp[i] = True
        count += 1
        if count == n:
            return i
    else:
        dp[i] = False

You are also correct in this comment:

  #i don't believe this ever get's called

That'll happen in the case where x is divisible by one of our primes, but we somehow haven't seen x/p yet. But we are iterating in order, so you're guaranteed that y in dp for all y<x. So you can simplify that block to:

if x % i == 0:
    return dp[x/i]

Though if you reread that statement again, you'll see that there's no need for dp to be a dictionary. You can just make it a list.

Split things up

Rather than having one function that does both generate the humble numbers and return the nth one, you can split them up. Have one function that generates the humble numbers:

def humble_numbers():
    dp = {}
    for i in itertools.count(start=1):
        if ishumble(i, dp):
            dp[i] = True
            yield i
        else:
            dp[i] = False

And another function that returns the nth one. Actually, that part is a snap using the nth recipe:

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

So the solution becomes:

def humbleNumber(n):
    return nth(humble_numbers(), n)

Note that now that we separated out the original idea into "generate the numbers" and "get the nth one" as separate, we can just play around with the generating functions.

Runtime

Your algorithm is deceptively easy to analyse. For each number we check, we do at most 4 modulo operations, at most 1 dictionary lookup, and 1 dictionary insertion. That's all reasonable and obviously super cheap. But, are we doing one cheap operation per \$n\$? NO, we're not, but it's easy to fall into that trap. Because we're not iterating up to \$n\$... we're iterating up to the \$n\$th humble number. Thus, the runtime is really \$O(H(n))\$.

And humble numbers get really sparse. Here's an unnecessarily prettified table for what the growth rate looks like:

+---------+---------------------------------------+
|       N |                                  H(N) |
+---------+---------------------------------------+
|      10 |                                    12 |
|     100 |                                   480 |
|    1000 |                                387072 |
|   10000 |                           63248102400 |
|  100000 |                 123098144531250000000 |
| 1000000 | 4157518627998641643389868083057746290 |
+---------+---------------------------------------+

Your runtime complexity grows commensurately with the second column. According to Wikipedia, that means your algorithm is something on the order of \$O(e^{\sqrt[4]{n}})\$?

A better approach

Rather than checking every individual number (which leads to terrible runtime complexity), we can build numbers up from the bottom. The numbers we want are basically \$2^a3^b5^c7^d\$, for all \$a,b,c,d\$. Of course, that's difficult to iterate over (how do you know which one to do next?). But a different way of writing that is each humble number is either 2x, 3x, 5x, or 7x some previous humble number. And that's easy to iterate over:

def humble_numbers2():
    primes = (2,3,5,7)
    result = [1]
    yield 1

    def make_multiple(_p):
        return (_p * result[i] for i in itertools.count())

    iters = map(make_multiple, primes)
    merged = heapq.merge(*iters)
    for k,_ in itertools.groupby(merged):
        result.append(k)
        yield k

The key is heapq.merge, which joins sorted iterables (which we know ours are). Basically we're on the fly creating the lists: 2*humble numbers, 3*humble numbers, 5*humble numbers, and 7*humble numbers - which are all humble numbers - and then using itertools.groupby to drop the duplicates (because, e.g., 14 is both 2x the 7th humble number and 7x the 2nd humble number)

This approach is \$O(n)\$. We are only performing constant operations to determine the next humble number. Which, when in doubt, we can always very by timing how long it takes to find the Nth humble number 10 times (after making the modifications I proposed to your solution):

+------+----------------+-----------------+
|  N   | humble_numbers | humble_numbers2 |
+------+----------------+-----------------+
| 100  |         0.003s |          0.002s |
| 1000 |         2.890s |          0.028s |
| 2000 |        53.332s |          0.059s |
| 3000 |       384.589s |          0.091s |
| 4000 |      1730.465s |          0.123s | #ok, I only ran this one once
+------+----------------+-----------------+


Calling a script with a setuid set I wanted to launch a bash script (read: bash not sh script) as a root not as the user calling it, however bash ignore setuid on scripts, so I chose to write a very small script that takes a script/arguments and call it with setuid set.

This worked well and I went even further to verify that the script has setuid set on, executable and setuid() called on the owner of the file and not as root, to avoid any misuse of the program and I ended up with the program below.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char **argv)
{
  char *command;
  int i, file_owner, size = 0;
  struct stat status_buf;
  ushort file_mode;

  // Check argc
  if (argc < 2) {
    printf("Usage: %s <script> [arguments]\n", argv[0]);
    return 1;
  }

  // Make sure the script does exist
  if(fopen(argv[1], "r") == NULL) {
    printf("The file %s does not exist.\n", argv[1]);
    return 1;
  }

  // Get the attributes of the file
  stat(argv[1], &status_buf);

  // Get the permissions of the file
  file_mode = status_buf.st_mode;

  // Make sure it's executable and it's setuid
  if(file_mode >> 6 != 567) {
    printf("The file %s should be executable and should have setuid set, please chmod it 0106755.\n", argv[1]);
    return 1;
  }

  // Get the owner of the script
  file_owner = status_buf.st_uid;

  // setuid
  setuid(file_owner);

  // Generate the command
  for (i = 1; i < argc; i++) {
    size += strlen(argv[i]);
  }
  command = (char *) malloc( (size + argc + 11) * sizeof(char) );
  sprintf(command, "/bin/bash %s", argv[1]);
  if (argc > 2) {
    for (i = 2; i < argc; i++) {
      sprintf(command, "%s %s", command, argv[i]);
    }
  }

  // Execute the command
  system(command);

  // free memory
  free(command);

  return 0;
}

The exercise was not only to solve my problem, but it was also a way to get more into C, so what do you suggest? Is there anything I should improve?

Check for errors in stat, setuid, fork, and execvp, to name a few.  If the exec fails in the child you should call exit.
Do you really want the p in execvp?  This is not guaranteed to be the same as the argv[1] you just stat-ed.  If argv[1] is ls your stat will look for a file at ./ls and it will likely find the program in /bin.  I would use execve and either do that PATH lookup yourself or simply omit that part and require the user to specify a full path for something in PATH (eg. /bin/ls instead of just ls).
The stat + observe state + exec thing is a race condition.  Another process can change the attributes on the file in that timing window.  This may or may not be important to you.  Given that this is a security-ish program I would say it may very well be.
Instead of returning 0, you might want to return the child process's exit code (which you can get with waitpid.)  You might also want to return nonzero when the functions I mention in #1 fail.  This way a shell script or something calling you programmatically can determine success or failure.


Converting std::chrono::time_point to/from std::string Consider these functions that allow to convert std::chrono::time_point to/from std::string with a predefined date-time format.

constexpr size_t log10(size_t xx) { return xx == 1 ? 0 : 1 + log10(xx/10); }

template < typename Double, size_t Precision = std::numeric_limits<Double>::digits10, typename TimePoint >
requires (TimePoint::period::den % 10 != 0) && std::is_floating_point_v<Double> && Precision <= std::numeric_limits<Double>::digits10
inline bool toString(const TimePoint& timePoint, std::string& str)
{
    Double seconds = timePoint.time_since_epoch().count();
    (seconds *= TimePoint::period::num) /= TimePoint::period::den;
    auto zeconds = std::modf(seconds,&seconds);
    time_t tt = seconds;
    std::ostringstream oss;
    oss << std::put_time(std::localtime(&tt), "%Y-%m-%d %H:%M:")
        << std::setw(Precision+3) << std::setfill('0') << std::fixed << std::setprecision(Precision) << (tt%60)+zeconds;
    return oss && (str = oss.str(), true);
}

template < typename TimePoint > requires (TimePoint::period::den % 10 == 0)
inline bool toString(const TimePoint& timePoint, std::string& str)
{
    uint64_t feconds = timePoint.time_since_epoch().count() * TimePoint::period::num;
    time_t tt = feconds / TimePoint::period::den;
    std::ostringstream oss;
    oss << std::put_time(std::localtime(&tt), "%Y-%m-%d %H:%M:%S.")
        << std::setw(log10(TimePoint::period::den)) << std::setfill('0') << feconds % TimePoint::period::den;
    return oss && (str = oss.str(), true);
}

template < typename TimePoint >
bool fromString(TimePoint& timePoint, const std::string& str)
{
    std::istringstream iss(str);
    std::tm tm{};
    if (!(iss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S")))
        return false;
    timePoint  = {};
    timePoint += std::chrono::seconds(std::mktime(&tm));
    if (iss.eof())
        return true;
    if (iss.get() != '.')
        return false;
    std::string zz;
    if (!(iss >> zz))
        return false;
    static_assert(std::chrono::high_resolution_clock::period::num == 1 && std::chrono::high_resolution_clock::period::den % 10 == 0);
    zz.resize(log10(std::chrono::high_resolution_clock::period::den),'0');
    size_t zeconds = 0;
    try { zeconds = std::stoul(zz); } catch (const std::exception&) { return false; }
    timePoint += std::chrono::high_resolution_clock::duration(zeconds);
    return true;
}

with usage:

        std::string str;
        auto now = std::chrono::system_clock::now();
        toString(now,str); std::cerr << "==== " << str << std::endl;
        using DD = std::chrono::duration<size_t,std::ratio<2,3>>;
        using TP = std::chrono::time_point<std::chrono::system_clock,DD>;
        toString<double>(TP(DD(0)),str); std::cout << "==== " << str << std::endl;
        toString<double>(TP(DD(1)),str); std::cout << "==== " << str << std::endl;
        toString<double>(TP(DD(2)),str); std::cout << "==== " << str << std::endl;
        toString<double>(TP(DD(3)),str); std::cout << "==== " << str << std::endl;

        std::chrono::system_clock::time_point tp;
        str = "2017-Mar-01";                          fromString(tp,str); toString(tp,str); std::cerr << "---- " << str << std::endl;
        str = "1969-Dec-31 19:00:00.666666666666667"; fromString(tp,str); toString(tp,str); std::cerr << "---- " << str << std::endl;

Any suggestions to make them faster, c-functions free or more compact?

As the objective is to do conversions with a predefined date-time format the std::locale support of std::ostringstream and std::istringstream is useless and it is a significant slowdown. But how can I avoid this?

Headers and typenames

We're missing

#include <chrono>
#include <cmath>
#include <cstdint>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

And we consistently misspell the types std::size_t, std::time_t, std::uint64_t.

A name collision

On systems that define a global log10 as well as std::log10, there's ambiguity on the calls to our log10.  I suggest using a name that conveys intent, such as digits() (even that's a bit risky - it would be better in a private namespace).  It costs nothing to make it terminate if passed 0 as argument, too:

static constexpr std::size_t feconds_width(std::size_t x)
{
    return x <= 1 ? 0 : 1 + feconds_width(x/10);
}

Interface consistency

The two alternative forms for toString() need to be instantiated differently, depending on the timepoint's denominator value.  If we make Double default to double, then both can be called without explicit template arguments.

Incidentally, did you measure a performance difference between the two implementations that proved a benefit?  If so, it's worth quantifying that in a comment so that future readers understand that it's worthwhile having both versions.

Document the assumption

This code only works when converting to or from TimePoint classes which have the same epoch as std::time_t.

Prefer to return values over status codes

Rather than returning a status code, I'd prefer to throw an exception when conversion fails; then the return value can be used directly.  Failure in toString() seems especially unlikely - I think the only possible cause is running out of room in the output string and being unable to allocate more.

if (!oss) throw std::runtime_error("timepoint-to-string");
return oss.str();

If you really dislike exceptions, it's still easier on the caller to return a std::optional rather than return a boolean and modify a reference argument.

Be careful with negative times

If tt<0, then tt%60 can be negative.  That's not what we want.  However, since we create a std::tm, we can read seconds from that:

auto tm = std::localtime(&tt);
if (!tm) throw std::runtime_error(std::strerror(errno));
oss << std::put_time(tm, "%Y-%b-%d %H:%M:")
    << std::setw(Precision+3) << std::setfill('0')
    << std::fixed << std::setprecision(Precision)
    << tm->tm_sec+zeconds;

Peek the '.' instead of reading it

If we leave '.' in the input stream, we can read that as part of a floating-point value:

double zz;
if (iss.peek() != '.' || !(iss >> zz))
    throw std::invalid_argument("decimal");
using hr_clock = std::chrono::high_resolution_clock;
std::size_t zeconds = zz * hr_clock::period::den / hr_clock::period::num;
timePoint += hr_clock::duration(zeconds);

Test cases seem inconsistent with the code

The test cases use month names, which require a %b conversion, not %m.
We could do with a few more test cases.

Consider a streamable wrapper

If your main use-case is to stream dates in and out, it may be better to bypass returning a string, and instead create an object that knows how to stream directly to a std::ostream.  As I don't know if that's your intended use, I won't demonstrate that.

Simplified code

#include <cerrno>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>

template<typename Double = double,
         std::size_t Precision = std::numeric_limits<Double>::digits10,
         typename TimePoint>
    requires std::is_floating_point_v<Double>
          && Precision <= std::numeric_limits<Double>::digits10
inline std::string toString(const TimePoint& timePoint)
{
    auto seconds = Double(timePoint.time_since_epoch().count())
        * TimePoint::period::num / TimePoint::period::den;
    auto const zeconds = std::modf(seconds,&seconds);
    std::time_t tt(seconds);
    std::ostringstream oss;
    auto const tm = std::localtime(&tt);
    if (!tm) throw std::runtime_error(std::strerror(errno));
    oss << std::put_time(tm, "%Y-%b-%d %H:%M:")
        << std::setw(Precision+3) << std::setfill('0')
        << std::fixed << std::setprecision(Precision)
        << tm->tm_sec+zeconds;
    if (!oss) throw std::runtime_error("timepoint-to-string");
    return oss.str();
}

template<typename TimePoint>
TimePoint fromString(const std::string& str)
{
    std::istringstream iss{str};
    std::tm tm{};
    if (!(iss >> std::get_time(&tm, "%Y-%b-%d %H:%M:%S")))
        throw std::invalid_argument("get_time");
    TimePoint timePoint{std::chrono::seconds(std::mktime(&tm))};
    if (iss.eof())
        return timePoint;
    double zz;
    if (iss.peek() != '.' || !(iss >> zz))
        throw std::invalid_argument("decimal");
    using hr_clock = std::chrono::high_resolution_clock;
    std::size_t zeconds = zz * hr_clock::period::den / hr_clock::period::num;
    return timePoint += hr_clock::duration(zeconds);
}

int main()
{
    using std::chrono::system_clock;
    auto now = system_clock::now();
    std::clog << "==== " << toString(now) << std::endl;
    using DD = std::chrono::duration<std::size_t,std::ratio<2,3>>;
    using TP = std::chrono::time_point<std::chrono::system_clock,DD>;
    for (int i = 0;  i <= 3;  ++i)
        std::clog << "==== " << toString(TP(DD(i))) << std::endl;

    for (std::string s: { "2017-May-01 00:10:15", "2017-May-01 00:10:15.25",
                "2017-Mar-01", "1969-Dec-31 19:00:00.666666666666667",
                "2018", // underspecified - but succeeds as 2017-12-31
                "1752-May-5",   // out of range
                "not a date",
                })
    {
        try {
            std::clog << "---- "
                      << toString(fromString<system_clock::time_point>(s))
                      << std::endl;
        } catch (const std::exception& e) {
            std::cerr << e.what() << std::endl;
        }
    }
}


jQuery function to select user specified text within a div I'm very new to jQuery, and have recently converted one JavaScript function to jQuery. This function is part of a small utility that mimics click and drag for selection of text. Complete code is available on my github repo. Following is the screenshot of the utility.

The purpose of the code is to allow user to select text by entering the desired text in target text input, hitting the select button calls the getSelection function to select the target text within sentence div.

JavaScript

getSelection = function(){
  sentence = document.getElementById("sentence");
  target= document.getElementById("target");
  selection = window.getSelection();
  range = document.createRange();
  index = sentence.innerHTML.indexOf(target.value);
  range.setStart(sentence.firstChild,index);
  range.setEnd(sentence.firstChild,(index + target.value.length));
  selection.removeAllRanges();
  selection.addRange(range);
}

jQuery

$(document).ready(function(){
  $("#getSelection").click(function(){
    sentence = $("#sentence")[0];
    target= $("#target")[0];
    selection = window.getSelection();
    range = document.createRange();
    index = sentence.innerHTML.indexOf(target.value);
    range.setStart(sentence.firstChild,index);
    range.setEnd(sentence.firstChild,(index + target.value.length));
    selection.removeAllRanges();
    selection.addRange(range);
  });
});

Additional Info

Question: Having little knowledge of jQuery I'm concerned whether I'm doing everything right? Please let me know.

Current solution

DOM queries

Whenever you call getSelection you select the same two elements again and again. You can simply store them in variables for re-use outside of the function. Also you never use the element #sentence itself, so you can actually store its textNode:

var textNode = document.getElementById('sentence').firstChild,
    source = document.getElementById('source');

I also renamed target to source as it represents the "source" of the selection. But this might be arguable.

You can even store the selection and range in variables:

var selection = document.getSelection(),
    range = document.createRange();

Cases

You don't handle these cases:

empty value or value not found
case sensitivity in both the value and the text
multiple occurrences of the value

If no value is given or no match is found, you should deselect any text. You could also present a message to the user:

if (0 === value.length || -1 === start) {
    selection.removeAllRanges();
    return;
}

Being case sensitive could be by design, but it would be great if I could type this and it would select the text This in the beginning of the sentence.

Your solution always selects the first occurrence of the string. Multiple ranges are only supported by Firefox and apparently by Edge, see MDN Selection.addRange(). So, this is by design. But it would be nice if the button's wording would reflect that:

  Select first occurence

Getting text using innerHTML

You're using innerHTML to get the content of the div element. We have stored the textNode already. You can simply use nodeValue instead, as it is way faster than innerHTML in Webkit browsers. It's about the same in Firefox:

textNode.nodeValue.indexOf(value);

Updated function

Taking everything into account, this could be the final function:

getSelectionText = function() {
    var value = source.value.toLowerCase(),
        start = textNode.nodeValue.toLowerCase().indexOf(value);

    selection.removeAllRanges();

    if (0 === value.length || -1 === start) {
        return;
    }

    range.setStart(textNode, start);
    range.setEnd(textNode, start + value.length);

    selection.addRange(range);
}

jQuery

I'm not sure, why you're trying to rewrite this code using jQuery. Let's assume it's an exercise to get to know jQuery better.

The thing is, you're creating a lot of overhead, as you'll see next.

DOM queries

If you follow through and create jQuery objects of all DOM elements, the selectors will look like this:

var textNode = $("#sentence").contents().first(),
    source = $('#source');

jQuery optimizes selectors, so this should end in a call to getElementById(). But calling contents().first() is overhead to a simple .firstChild.

Getting text the jQuery way

Use .val() for form elements and .text() for other nodes:

var value  = source.val().toLowerCase(),
    start = textNode.text().toLowerCase().indexOf(value);

.text() wil definitely be slower than the native options discussed before.

Other changes

Well actually you have only one change left. You have to pass the real node to the range methods instead of the jQuery object:

range.setStart(textNode[0], start);
range.setEnd(textNode[0], start + value.length);

Adding everything into the anonymous function

I would not advise to place everything into the anonymous function of the event handler. What if you need to call the function from another place? Keep it as is and bind the function call, for example like:

$("#getSelection").click(getSelectionText);

Updated function

getSelectionText = function() {
    var value  = source.val().toLowerCase(),
        start = textNode.text().toLowerCase().indexOf(value);

    selection.removeAllRanges();

    if (0 === value.length || -1 === start) {
        return;
    }

    range.setStart(textNode[0], start);
    range.setEnd(textNode[0], start + value.length);

    selection.addRange(range);
}

Final thoughts

I guess you can see, that there's no actual benefit from switching to jQuery for this particular task:

The code is not getting easier to read or maintain.
You create a lot of overhead.
You still have to access the contained native DOM element often.
You have additional weight of 87 KB for the compressed library.


Max sum of abs difference in array I am just trying to understand the algorithm of the problem statement

  Given an array, we need to find the maximum sum of absolute difference of any permutation of the given array.

Here is my implementation after following the algorithm mentioned in the link

static int sumOfMaxAbsDiff(int[] arr) {
    Arrays.sort(arr);
    int len = arr.length;
    int[] temp = new int[len];
    int sum = 0;
    for (int i = 0, j = 1, k = 0; i < len / 2; i++, j++, k++) {
      temp[k] = arr[i];
      temp[++k] = arr[len - j];
    }
    if (len % 2 != 0) { // Odd numbered length
      temp[len - 1] = arr[len / 2]; // copy the middle element of arr to last place in temp
    }
    // Now accumulate sum
    for (int i = 0; i + 1 < len; i++) {
      sum += Math.abs(temp[i] - temp[i + 1]);
    }
    // max abs diff at last index - NOT sure of this
    sum += Math.abs(temp[len - 1] - temp[0]); // assuming array size is >= 2
    return sum;
  }

I know why we have to sort, as we are trying to find max diff, it's obviously the least-highest
If we arrange the sequence as firstSmallest, firstLargest, and so on for a given input arr [1,2,4,8]
it would be [1,8,2,4]
Now, checking the max diff in forward direction, max diff at each index, it would be 7,6,2,?

2 questions

For odd numbered length arr [1,2,3,4,8] why place middle at the end of arr?
And, for last index, why do we have to find abs difference between val at last index and first index?

Is there is any better and clear algorithm to think about or links to apply for this

For odd numbered length arr [1,2,3,4,8] why place middle at the end of
  arr?

The middle element in an odd numbered array, is the next highest element to be paired up.  But since it is also the next lower element it doesn't have a pair, so it gets added by itself.

  And, for last index, why do we have to find abs difference between val
  at last index and first index?

To my mind, the problem states 'maximum sum of absolute difference of any permutation'. The permutation of the lowest number on the high side of the sorted array and the lowest number wouldn't get added to the max sum otherwise.

  Is there is any better and clear algorithm to think about

I believe there is.  The idea of calculating the differences on the fly and adding to the max sum directly, has merit.  It just needed tweaking a bit.  Heres some working code for that concept:

static int MaxSumDifference2(int []a, int n) {
    Arrays.sort(a);
    int maxSum = 0;
    int low = 0;
    int high = a.length - 1;
    for(;low < high; ++low, --high){
        maxSum += a[high] - a[low] + a[high] - a[low + 1];
    }
    maxSum += a[low] - a[0];
    return maxSum;
}


Method to Retrieve Data from a MySQL Database I have a method that retrieves information relating to a Contact that was made between two Companies. I am looking to improve my code in any way and am intrigued in hearing any recommendations you may have on how this method can be improved. I use it throughout my program but modify it according to the DataModel I am attempting to load.

string constr = ConfigurationManager.ConnectionStrings["sqlString"].ConnectionString;
using (var sqlCon = new MySqlConnection(constr))
{
    sqlCon.Open();
    using (var myQuery = sqlCon.CreateCommand())
    {
        myQuery.CommandText = @"SELECT DISTINCT contacts.contactID, contacts.companyID,
        companies.name, contacts.donestatus, contacts.telephone, employees.ID, employees.name,
        people.ID, people.firstname, people.lastname,
        contacts.contractID, contacts.date, contacts.time,
        presets.presettext, contacts.enteredby, contacts.description
        FROM contacts
        LEFT OUTER JOIN companies ON contacts.companyID = companies.ID
        LEFT OUTER JOIN employees ON contacts.employeeID = employees.ID
        LEFT OUTER JOIN people ON contacts.personID = people.ID
        JOIN presets ON contacts.type = presets.presetIDFoxPro
        WHERE presets.presetreferencefoxpro = 8
        AND contacts.date > @date
        ORDER BY contacts.date DESC";
        myQuery.Parameters.AddWithValue("@date", date);
        using (var myReader = myQuery.ExecuteReader())
        {
            var listOfContacts = new ObservableCollection<ContactModel>();
            while (myReader.Read())
            {
                var details = new ContactModel
                {
                    ID = Convert.ToInt32(myReader[0]),
                    CompanyID = DBNullCheck(myReader[1]),
                    CompanyName = myReader[2].ToString().Trim(),
                    DoneStatus = Convert.ToInt32(myReader[3]),
                    Telephone = myReader[4].ToString().Trim(),
                    EmployeeID = DBNullCheck(myReader[5]),
                    EmployeeName = myReader[6].ToString().Trim(),
                    PersonID = DBNullCheck(myReader[7]),
                    PersonName = myReader[8].ToString().Trim() + " " + myReader[9].ToString().Trim(),
                    ContractID = DBNullCheck(myReader[10]),
                    Date = Convert.ToDateTime(myReader[11]),
                    Time = Convert.ToDateTime(myReader[12]),
                    TypeOfContact = myReader[13].ToString().Trim(),
                    EnteredBy = myReader[14].ToString().Trim(),
                    Notes = myReader[15].ToString(),
                };
                listOfContacts.Add(details);
            }
            return listOfContacts;
        }
    }
}

I would be happy if you could recommend improvements to my C# code or my MySQL statement alike.

In my review I assume you cannot use EF or alike...

I don't see any particular really bad practices here but there are a few minor things that make me uncomfortable when I look at your code. As the important things are correct (everything is disposed and you use parameters to prevent sql injection) there is not much left to review. But hey! this a good news ;-)

The my-prefix ;-) It doesn't hurt but it doesn't look professional either. You know everything there is yours so there's no need to emphasize it with my.

Try to name things by what they really are instead of giving them misleading names. If you do sqlCon.CreateCommand() then name the variable command or cmd not a query. It isn't one. Your sql is a query and it would be fine to name it like so.

Returning an ObservableCollection is a questionable practice. I suggest to use a List instead and update the real observable collection with the new data.

The listOfContacts. It's a collection and for collections we usually just use a plural noun. In this case just contants would be enough.

The reader[0] & magic numbers. You should use constants here like reader[Column.ID]. It looks much better now, doesn't it?

class Column
{
    public const int ID = 0;
    ...
}

PersonName = myReader[8].ToString().Trim() + " " + myReader[9].ToString().Trim(),

PersonName or FullName should be a readonly property of the ContactModel and it should have two normal properties for the first and last names. Your repository shouldn't care and know how to build a person name. It should just pass the data to the ContactModel.


Ping multiple sites via Python Here is a simple script that I am using to ping 50 sites at a time and check if they are up or not. If not, save the down time with error in MongoDB.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from urllib.request import urlopen, Request
from threading import Thread
from time import sleep, time
import datetime
import queue
import pymongo

''' A Simple script to  ping multiple sites at a time
and capture the down sites
'''
__author__ = "Aamir khan"
__version__ = 1.1

_MAX_CONNECTIONS = 50
counter = 0
downsites = []
now = datetime.datetime.utcnow  # time stamp

# DO NOT ON BOTH AT THE SAME TIME
_DEBUG = False
_MONITOR = True

def getcollection(db='websites', colname='website_urls'):
    return pymongo.MongoClient().get_database(db).get_collection(colname)

# to save downsites in db
ds = getcollection(colname="downsites")

# fetch urls from db
if _DEBUG:
    print("Fetching Urls")
    urls = getcollection().find()
    print("%d Urls Fetched" % urls.count())
    print("pulling urls to the queue")
    q = queue.Queue(urls.count())
    for url in urls:
        url = url['url']
        q.put(url)
    print("pulled urls to the queue")
    print("The size of the Queue is %d" % q.qsize())
else:
    urls = getcollection().find()
    q = queue.Queue(urls.count())
    for url in urls:
        url = url['url']
        q.put(url)

del urls

def inc_counter():
    global counter
    # lock.acquire()
    counter += 1
    # lock.release()

def monitor():
    total = q.qsize()
    if total > 0:
        while counter < total:
            print("%d Request sent" % counter)
            sleep(1)
        print("Total {}/{} Request Sent".format(counter, total))
        assert counter == total

def ping(uri):
    req = Request(uri, headers={
        "User-Agent": ("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0)"
                       " Gecko/20100101 Firefox/51.0")
    })
    req.get_method = lambda: 'HEAD'

    try:
        with urlopen(req) as r:
            res = r.getcode(), uri, now()
    except Exception as e:
        res = str(e), uri, now()
    finally:
        if _DEBUG:
            err, uri, last_check = res
            print("Requesting = ", uri, "Request Method = ", req.get_method(),
                  "\nstatus = ", err, "time", last_check)
            print("-----" * 10)
        if _MONITOR:
            inc_counter()
            sleep(1)
        sleep(0.5)  # sleep a while to release the workload from cpu
    return res

def process(url):
    err, uri, last_check = ping(url)
    if err != 200:
        ds.insert_one({"Error": err.strip('<>'),
                       "url": uri, "last_checked": last_check})

def worker():
    while True:
        url = q.get()
        if url is None:
            break
        process(url)
        q.task_done()

if __name__ == '__main__':
    workers = []

    if _MONITOR:
        Thread(target=monitor).start()  # start monitoring reqest/sec
        start_time = time()

    for i in range(_MAX_CONNECTIONS):
        t = Thread(target=worker)
        t.start()
        workers.append(t)

    # block until all tasks are done
    q.join()

    # poision kill
    for i in range(_MAX_CONNECTIONS):
        q.put(None)

    # wait for all the threads to join
    for w in workers:
        w.join()

    if _MONITOR:
        print("Time taken %f (sec)" % (time() - start_time))

Questions:

Can I make use of better threading techniques?
Can I eliminate the duplication of code while _DEBUG is on line 35 to 54?
I would love/prefer to see a functional version of this program.
How can I improve the performance? (my target is to ping 1000000 sites under an hour)

The question is tagged python-3.x; this answer assumes 3.2 or higher.

Threading

You can dramatically simplify the code by using a framework for concurrency and
queueing. Specifically, instead of spawning a fixed number of concurrent
threads and managing a queue, your code will be simpler by using an Executor subclass from concurrent.futures (see
https://docs.python.org/3/library/concurrent.futures.html)

Remove the worker function, the queue management logic (including the poison
kill), and create something like this in your if __name__ == '__main__'
block:

import concurrent.futures as futures
urls = [url['url'] for url in ds.getcollection().find()]
with futures.ThreadPoolExecutor(max_workers=32) as executor:
    executor.map(process, urls)

Note the with statement implicitly calls executor.shutdown(wait=True), so
the block is essentially synchronous. And once the iterable is drained, the
executor manages clean up.

Functional

This pattern is inherently more functional, though I would not say it's "pure"
functional.  The map() method applies your function process to each of the
items in the associated iterable, spreading the load across available threads
(or processes) in the pool.

DEBUG duplication

To address the _DEBUG duplication issue (or generally any selective print() output), in similar situations I use a logger:

log = logging.getLogger(__name__)
log.addHandler(logging.StreamHandler(sys.stdout)

if _DEBUG:
    log.setLevel(logging.DEBUG)
else:
    log.setLevel(logging.INFO)

Then, that section becomes:

log.debug("Fetching Urls")
urls = getcollection().find()
log.debug("%d Urls Fetched" % urls.count())
log.debug("pulling urls to the queue")
q = queue.Queue(urls.count())
for url in urls:
    url = url['url']
    q.put(url)
log.debug("pulled urls to the queue")
log.debug("The size of the Queue is %d" % q.qsize())

With no leading if _DEBUG:. Note, though, that if you go with the executor, the queue goes away as well. Play with the levels that work for your needs.

Performance

Honestly, there is not a lot you'll be able to do here above what you are
already doing - your main bottleneck is going to be I/O. For 1m sites in 1
hour, you should be averaging close to 280 requests a second. Play around with
your concurrency (there is a tipping point where too many threads will actually
slow things down) - on an 8 core machine w/ 64 workers, I was only hitting about 100 sites in 1.4 seconds.

Additional notes:

Note that many sites won't return 200 for HEAD requests, so you might consider
a list of "acceptable" codes, which will likely include 301 and 302
You don't need the sleep() calls in the worker function.