Different path for grid move (part 3) This is a continued discussion from (Different path for grid move (part 2)) to optimize for space complexity (using only cur list, other than a cur and another pre lists), and since it is new code and I make a new post.

  Given a m * n grids, and one is allowed to move up or right, find the different number of paths between two grid points.

My major idea is, if move r steps right, u steps up, we can find (1) solutions for r-1 steps right and u steps up, then combine with one final right step (2) solutions for r steps right and u-1 steps up, then combine with one final up step.

Source code in Python 2.7,

def grid_move_v2(rights, ups):
    cur = [1] * (ups + 1)
    for r in range(1, rights+1):
        for u in range(1, ups+1):
            cur[u] = cur[u] + cur[u-1]
    return cur[-1]

if __name__ == "__main__":
    print grid_move_v2(2,3)
    print grid_move_v2(4,2)

Since you never use r you can shift it down by one and call it _ (the customary unused variable in Python).

def grid_move_v2(rights, ups):
    cur = [1] * (ups + 1)
    for _ in range(rights):
        for u in range(1, ups+1):
            cur[u] = cur[u] + cur[u-1]
    return cur[-1]


Create all possible character combinations of any size I am trying to create all possible character combinations of a given word.  For example, “laptop” will include the following possible combinations:

l
la
lap
lapt
lapto
laptop
lp
lpa
lpat
lpato
lpatop

Here is what I have tried:

#!/usr/bin/env python
import argparse
import sys

def parse_args(argv):
    """parsing argument"""
    parser = argparse.ArgumentParser()
    parser.add_argument('-input', dest='input', type = str,
                         required = True,
                         help = "please provide string")
    args = parser.parse_args(argv)
    return args

def get_patt(patt, patt_index, new_pat):
    print new_pat
    for i in range(patt_index, len(patt), 1):
        new_pat = new_pat + patt[i]
        print new_pat
def main(args):
    f_pat = ""
    input = args.input
    for k in range(0, len(input), 1):
        for i in range(0, len(input), 1):
            f_pat =  input[i]
            for j in range(i+1, len(input), 1):
                f_pat = f_pat + input[j]
                get_patt(input, j+1, f_pat)
        input = args.input[k:] + args.input[:k]
        print "Input String", input

if __name__ == "__main__":
    args =parse_args(sys.argv[1:])
    main(args)

Improvements

Use either argparse or sys.argv because this feels just wierd,
and kind of surprised it worked at all. I'd recommend sticking with argparse
Secondly, be sure to check out the itertools module from python, because what you are looking for are basicly permutations of a word.

New code

import argparse
from itertools import permutations

def main(string):
    for idx in range(1, len(string)+1):
        print(list(''.join(p) for p in permutations(string, idx)))

def parse_args():
    """parsing argument"""
    parser = argparse.ArgumentParser()
    parser.add_argument('-input', dest='input', type = str,
                         required = True,
                         help = "please provide string")
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_args()
    main(args.input)


Palindrome algorithm in C# I had an interview yesterday where I had to write an algorithm on the whiteboard for working out if a value is a Palindrome in C#. The pressure got to me a bit but I've written my version of it in Visual Studio this evening.

 private bool Ispalindrome(string args)
        {
            var index = 0;
            var reverseArray = args.ToCharArray();

            do
            {
                if(index == args.Length)
                    return true;

                index++;
                var startingChars = args.Substring(0, index);
                var stringbuilder = new StringBuilder();

                for (var i = 0; i < index; i++)
                {
                    stringbuilder.Append(reverseArray[reverseArray.Length-i-1]);
                }

                if (startingChars != stringbuilder.ToString())
                    _isPalindrone = false;

            } while (_isPalindrone);
            return _isPalindrone;
        }

Doe anyone have any recommendations on how to make this more efficient?

You are making it harder than it needs to be.

You just need to compare one character at a time:

private static bool IsPalindrome(string s)
{
    if (string.IsNullOrEmpty(s))
        return false;
    char[] chars = s.ToLower().ToCharArray();
    for (int i = 0; i < chars.Length / 2; i++)
        if (chars[i] != chars[chars.Length - 1 - i])
            return false;
    return true;
}

Or:

private static bool IsPalindrome(string s)
{
    if (string.IsNullOrEmpty(s))
        return false;
    char[] chars = s.ToLower().ToCharArray();
    for (int i = 0, j = chars.Length - 1 ; i < j; i++, j--)
        if (chars[i] != chars[j])
            return false;
    return true;
}


Submitting form jQuery checkboxlist In my requestForm submit function I have this logic that checks three checkboxes and then displays the label with an error message. Is there better logic? I would be happy for any kind of feedback since this is quite critical a part of my application.
$("#requestForm").submit(function (e) {
            e.stopPropagation();
            e.preventDefault();

        var checked_sourcecheckboxes = $("#sources input[type=checkbox]:checked");
        if (checked_sourcecheckboxes.length == 0) {
            $("#lblSourcesError").show();
            return false;
        }
        else {
            $("#lblSourcesError").hide();
        }
        var checked_academicformatcheckboxes = $("#academicFormatsRow input[type=checkbox]:checked");
        if (checked_academicformatcheckboxes.length == 0) {
            $("#lblacademicFormatError").show();
            return false;
        }
        else {
            $("#lblacademicFormatError").hide();
        }
        var checked_academicmediaformatcheckboxes = $("#academicMediaFormatRow input[type=checkbox]:checked");
        if (checked_academicmediaformatcheckboxes.length == 0) {
            $("#lblacademicmediaFormatError").show();
            return false;
        }
        else {
            $("#lblacademicmediaFormatError").hide();
        }
})

Main Question

Is there better logic?

Repeated code
The first thing that I see with this code, which perhaps you see also, is that it is quite repetitive - select a list of checkboxes to see if any are checked - if none are checked then show an error message and return, otherwise hide any affiliated error message. This violates the Don't Repeat Yourself principle. It can be remedied by abstracting the common logic - e.g. putting the  the selectors into a mapping:
var SELECTOR_ERROR_MAPPING = {
    "#sources input[type=checkbox]:checked": "#lblSourcesError",
    "#academicFormatsRow input[type=checkbox]:checked": "lblacademicFormatError",
    //...more entries
};

Then use a loop to iterate over the mapping, checking each selector - e.g. using Array.every():
return Object.keys(SELECTOR_ERROR_MAPPING).every(function(selector) {
    var errorSelector = SELECTOR_ERROR_MAPPING[selector];

    var showError = !$(selector).length;
    $(errorSelector).toggle(showError, errorSelector);
    return !showError;
});

Those last three lines of the inner function could be placed into a separate function if desired, which would allow for better modularization/atomization and testing.
demo

var SELECTOR_ERROR_MAPPING = {
  "#sources input[type=checkbox]:checked": "#lblSourcesError",
  "#academicFormatsRow input[type=checkbox]:checked": "#lblacademicFormatError",
  "#academicMediaFormatRow input[type=checkbox]:checked": "#lblacademicmediaFormatError",
  //...more entries
};
$("#requestForm").submit(function(e) {
  e.stopPropagation();
  e.preventDefault();

  var allValid = Object.keys(SELECTOR_ERROR_MAPPING).every(function(selector) {
    var errorSelector = SELECTOR_ERROR_MAPPING[selector];

    var showError = !$(selector).length;
    $(errorSelector).toggle(showError, errorSelector);
    return !showError;
  });
  console.log('result', allValid);
  return allValid;
})
.error {
  color: red;
}

<form id="requestForm">

 Source

    Audi
      <input type="checkbox" name="source" value="Audi" />

    BMW
      <input type="checkbox" name="source" value="BMW" />

Please select a source

 Formats

    College
      <input type="checkbox" name="source" value="college" />

    University
      <input type="checkbox" name="source" value="university" />

Please select a format

 Media Formats

    DVD
      <input type="checkbox" name="source" value="DVD" />

    Blue-ray
      <input type="checkbox" name="source" value="blueray" />

Please select a media format

  <button>Submit</button>
</form>

Modern browsers support client-side validation using the required attribute on input elements1 and it is supported for checkbox inputs2 but apparently setting a custom message for checkboxes still involves writing some JavaScript3.
HTML layout
As one comment suggested, the dependence on the id attribute could be decreased - For example, if the location of the error message element was consistent within each section -e.g. a sibling of the list of checkbox inputs. Another solution might be to have each section of checkboxes and error message contained by a parent element with a consistent class name- then the JavaScript could loop over those container elements looking to see if the checkbox elements have any checked- if not, then display the error message.
Other review points
ES6
With modern JavaScript, consider using newer EcmaScript-2015 (AKA ES6) features, like for...of loops, the keywords let and const instead of var, etc.
jQuery
Also consider whether you really need jQuery because it may be the case it can be replaced with “vanilla JS” features. For example, to select elements with a CSS selector use document.querySelectorAll() and to add an event listener for the form submission, use the addEventListener() method after selecting that form element - e.g. with document.getElementById('requestForm'), document.forms[0] unless it isn't the first form, etc..
Loose comparisons
In the original code the length property of the jQuery objects was compared with 0 using loose equality - i.e. ==. A good habit and recommendation of many style guides is to use strict equality operators (i.e. ===, !==) whenever possible. The problem with loose comparisons is that it has so many weird rules one would need to memorize in order to be confident in its proper usage.
The suggested code above and below simplified this by using !$(checkboxSelector).length;
demo

const SELECTOR_ERROR_MAPPING = {
  "#sources input[type=checkbox]:checked": "#lblSourcesError",
  "#academicFormatsRow input[type=checkbox]:checked": "#lblacademicFormatError",
  "#academicMediaFormatRow input[type=checkbox]:checked": "#lblacademicmediaFormatError",
  //...more entries
};
document.forms[0].addEventListener('submit', e => {
  e.stopPropagation();
  e.preventDefault();

  for (const [selector, errorSelector] of Object.entries(SELECTOR_ERROR_MAPPING)) {
    const showError = !document.querySelectorAll(selector).length;
    document.querySelector(errorSelector).classList.toggle('hidden', !showError);
    if (showError) {
      return false;
    }
  }
});
.error {
  color: red;
}
.hidden {
  display: none;
}

<form id="requestForm">

 Source

    Audi
      <input type="checkbox" name="source" value="Audi" />

    BMW
      <input type="checkbox" name="source" value="BMW" />

Please select a source

 Formats

    College
      <input type="checkbox" name="source" value="college" />

    University
      <input type="checkbox" name="source" value="university" />

Please select a format

 Media Formats

    DVD
      <input type="checkbox" name="source" value="DVD" />

    Blue-ray
      <input type="checkbox" name="source" value="blueray" />

Please select a media format

  <button>Submit</button>
</form>


Java Quicksort Algorithm I am trying to work on writing readable code and reducing the amount of redundant code I write. I find this hard to do especially when it comes to algorithms. So, I wrote a quicksort program to practice.

Is there any way I can improve this? I know in terms of efficiency it could be better (instead of taking the leftmost as the pivot, I could choose a pivot in the middle of the array). However, is there a way I could have declared or initialized things better or could I have used a more efficient method of checking different cases?

 package quicksort;

/**
 * @date December 4, 2015
 */
public class Quicksort {

   // private static int[] intArray = new int[]{4, 8, 1, 6, 3, 7, 2, 5};
   private static int[] intArray = new int[]{11,10,9,8,7,6,5,4,3,2,1};
    //private final static int[] intArray = new int[]{1,2,3,4,5};

    /**
     * @purpose This method partitions the array and subarrays based on the current pivot point
     * @param pivot
     * @param leftPointer
     * @param rightPointer
     */
private static void partition(int pivot, int leftPointer, int rightPointer) {

    while (leftPointer <= rightPointer) {
        if (pivot < intArray[rightPointer]) {
            rightPointer--;
        } else if (pivot > intArray[rightPointer]) {
            intArray[leftPointer] = intArray[rightPointer];
            intArray[rightPointer] = pivot;
            leftPointer++;
        } else if (intArray[leftPointer] > pivot) {
            intArray[rightPointer] = intArray[leftPointer];
            intArray[leftPointer] = pivot;
            rightPointer--;
        } else {
            leftPointer++;
        }

    }
    for (int x = 0; x <= intArray.length - 1; x++) {
        System.out.print(intArray[x] + " ");
    }
    System.out.println();

}

/**
 * @purpose This method recursively runs the partition method for the array and subarrays
 * @param pivot
 * @param leftPointer
 * @param rightPointer
 */
private static void quicksort(int pivot, int leftPointer, int rightPointer) {

    while (rightPointer != 0) {
        partition(intArray[0], 0, rightPointer);
        rightPointer--;
    }

    while (leftPointer != intArray.length - 1) {
        leftPointer++;
        partition(intArray[leftPointer], leftPointer, intArray.length - 1);
    }

}

/**
 * @purpose Runs the Quicksort class
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int leftPointer = 0;
    int rightPointer = intArray.length - 1;
    int pivot = intArray[0];
    quicksort(pivot, leftPointer, rightPointer);

}

}

There is a bug in the code. If you try to sort

4, 3, 1, 2, 0

you get

0, 2, 1, 3, 4


Cron expression validator for Apache Quartz Not too long ago, I had to create a cron expression for a route in Apache Camel. I had a bit of a struggle to find the right expression. So I made a small program to output the n next valid dates returned by the expression. I planned to add more feature like instead of making a blind Sysout, you could create a file with your dates.

In my application, a cron expression correspond to the definition of this class. It's use to fire an event for a Camel route. You will set a Quartz endpoint to your route and use a cron expression to express at which interval it should start. Some example :

  0 0/5 12-18 ? * MON-FRI

This cron expression translated to a more human format would be : every five minutes starting at 12pm (noon) to 6pm on weekdays. (this cron is taken from the quartz documentation).

For this particular cron, my program (with an numberOfdates set to 5) would output :

  Fri Sep 19 12:05:00 EDT 2014
  Fri Sep 19 12:10:00 EDT 2014
  Fri Sep 19 12:15:00 EDT 2014
  Fri Sep 19 12:20:00 EDT 2014
  Fri Sep 19 12:25:00 EDT 2014

The application is really basic. I take two arguments, the cron expression and the numbers of date you want outputted.

Feel free to cover any aspect. I had particular problem with the naming of my classes and variables. There isn't much code at the moment, but my naming and the way I verify arguments worry me a bit.

It's a public repo on GitHub

CronTester

import java.util.Date;
import java.util.List;

public class CronTester {

    /**
     * The application take two arguments :
     * The first argument is the cron expression surrounded by " : "* * * * * *"
     * The second argument is the number of dates you want to verify. It's a simple Integer.
     * @param args
     */
    public static void main(String[] args) {
        if(args.length > 2) {
            throw new IllegalArgumentException("You should only provide 2 arguments. \"[cronExpression]\" [numberOfDates]");
        } else if (args.length != 2) {
            throw new IllegalArgumentException("You need to provide 2 arguments in the following form : \"[cronExpression]\" [numberOfDates]");
        }

        final String expression = args[0];
        final int numberOfDates;

        try {
            numberOfDates = Integer.parseInt(args[1]);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("The second argument need to be a valid integer.");
        }

        final CronDateCreator dateCreator = new CronDateCreator(expression);
        List<Date> result = dateCreator.createValidTimeDatesFromNow(numberOfDates);

        for(Date expected : result) {
            System.out.println(expected);
        }

    }

}

CronDateCreator

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.quartz.CronExpression;

public class CronDateCreator {

    private CronExpression cron;

    public CronDateCreator(String cronExpressionRaw) {
        try {
            this.cron = new CronExpression(cronExpressionRaw);
        } catch (ParseException e) {
            throw new IllegalArgumentException("The cron expression supplied is not a valid cron expression.",e);
        }
    }

    public List<Date> createValidTimeDates(Date startingDate, int numberOfDates) {
        Date nextValidDate = cron.getNextValidTimeAfter(startingDate);
        List<Date> results = new ArrayList<>();

        for (int i = 0; i < numberOfDates; i++) {
            results.add(nextValidDate);
            nextValidDate = cron.getNextValidTimeAfter(nextValidDate);
        }

        return results;
    }

    public List<Date> createValidTimeDatesFromNow(int numberOfDates) {
        return createValidTimeDates(new Date(), numberOfDates);
    }

}

In terms of overall hierarchy here, the CronTester class is just 'fluff' and does not do anything except provide an main method. The interesting class is: CronDateCreator.
CronDateCreator is a very lightweight class. It essentially does nothing that requires it to be a class... it wraps a String value in a CronExpression, is that CronExpression reused for anything?
It strikes me that the standard use-case for this class would be:
CronDateCreator cdc = new CronDateCreator(input);
List<Date> dates = cdc.createValidTimeDatesFromNow(numberOfDates);

and then the cdc will be forgotten.
Is this a case of where a static method is maybe all you need?
Something like:
public static List<Date> createValidTimeDatesFromNow(String expression, int numberOfDates) {
    ....
}

Just a thought...
Date
Now, about the Date return values.
Date is a much maligned class in Java. It has so many nuances, issues, and tweaks that it was initially 'forked' and rewritten as JodaTime in an open source library, then, in Java8, they have pulled the best from JodaTime, and incorporated some other compatibility and functionality changes, and created the new java.time.* package.
Any code written to support Java8 or newer should essentially abandon Date, and work with Instant  instead.
You should use your class/static methods to translate the Dates back to Instants, and go from there.
Actual code:
Your method here could be neatened up a lot:

public List<Date> createValidTimeDates(Date startingDate, int numberOfDates) {
    Date nextValidDate = cron.getNextValidTimeAfter(startingDate);
    List<Date> results = new ArrayList<>();

    for (int i = 0; i < numberOfDates; i++) {
        results.add(nextValidDate);
        nextValidDate = cron.getNextValidTimeAfter(nextValidDate);
    }

    return results;
}

For a start, you know how large the ArrayList will be, so set the size on the constructor:
List<Date> results = new ArrayList<>(numberOfDates);

Then, your loop logic is off... how about the following?:
public List<Date> createValidTimeDates(Date startingDate, final int numberOfDates) {
    List<Date> results = new ArrayList<>(numberOfDates);

    for (int i = 0; i < numberOfDates; i++) {
        startingDate = cron.getNextValidTimeAfter(startingDate);
        results.add(startingDate);
    }
    return results;
}


Want to know vulnerabilities in below program finding minimum positive number greater than 0 that doesn't occur in array Below program find a minimum positive number that is greater than 0, it doesn't occur in the array. My solution actually works fulfil performance-wise. However, Codelity has given 55% only, I m trying to understand what is the potential issues with below code?

For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.

#include <stdio.h>

#define ARRAY_SIZE(a) sizeof(a) / sizeof(a[0])

int solution(int A[], int N) {
    // write your code in C99 (gcc 6.2.0)
    int i=0, j=0, k=0;
    int result = 1, tmp = 0;

    for(i=0; i < N; i++) {
        for(j=i+1; j < N; j++) {
            if(A[j] < A[i]) {
                tmp = A[i];
                A[i] = A[j];
                A[j] = tmp;
            }
        }
    }

    for (i = 0; i < N; i++) {
        printf("%d\n", A[i]);
    }

    for ( k = 0; k < N; k++) {
        if (A[k] == result)
            result += 1;
        if (A[k] > result)
            break;
    }

    return result;
}

int main(void) {
    int a[] = {1,3,6,4,1,2};
    int ret = solution(a, ARRAY_SIZE(a));
    printf("Smallest positive integer: %d\n", ret);
    return 0;
}

At first glance, your code looks quite verbose. Seeing as it was an assignment for some type of class, I'm also assuming that points would've been deducted for you doing something that is considered bad practice. With this in mind, let's go through the code:

    int i=0, j=0, k=0;
    int result = 1, tmp = 0;

    for(i=0; i < N; i++) {
        for(j=i+1; j < N; j++) {
            if(A[j] < A[i]) {
                tmp = A[i];
                A[i] = A[j];
                A[j] = tmp;
            }
        }
    }

    for (i = 0; i < N; i++) {
        printf("%d\n", A[i]);
    }

In C99, declaring all variables at the start of the function isn't required. Variables like i, j, and k should be block scoped.

You're also sorting your array in a function that is called solution. The name isn't very descriptive, and given how that function returns an integer, I wouldn't expect it to actually change the array I'm passing.

Your solution function has a single point of return. That's fine, if that's what you were asked to do. However, generally speaking, most people prefer to return early. It simplifies the code, and reduces the total number of else's quite a lot.

You're missing some checks. An array, once passed to a function, decays into a pointer. I'd write the function as int solution(int *in, int size), and if I wanted to be paranoid about safety, I'd check for in == NULL and make sure size is non-negative. Then again, the size of the array is obtained through the sizeof operator, which actually yields a value of type size_t. Perhaps it makes sense to change your function argument to accept a size_t instead of an int? size_t is unsigned, so no need to check for negative values there...

You're sorting the array in ascending order. Understandable, of course, but why aren't you using qsort? It's better practice to write functions that only do 1 thing. Your solution function handles sorting, prints some debug output, and then sets about searching the lowest missing positive integer. Let's assume, for now, that changing the array that's being passed is not an issue, I'd break things up into 2 functions and write this:

static
int sort_ascending(const void *a, const void *b) {
    int av = *(int *)a, bv = *(int *)b;

    if (av == bv)
        return 0;
    if (av > bv)
        return 1;
    return -1;
}

static
int get_missing(int *in, size_t size) {
    // let's make sure the pointer can be dereferenced:
    if (in == NULL)
        return -1; // -1 is a common error value to return
    // first, sort the array
    qsort(in, size, sizeof *in, sort_ascending);

    // now let's just iterate over the array and find the answer
    // note, we're iterating until the NEXT TO LAST element, because we access in[i+1] in the body
    for (int i = 0; i < size-1; i++) {
        int v = in[i]+1; // the lowest possible value based on in[i]
        // if v is positive, and smaller than the next value in the array
        // we're done, and we can return
        if (v > 0 && v < in[i+1])
            return v;
    }
    // we didn't return from the loop. The lowest value is in[size-1]+1, if it's positive:
    int last = in[size-1]+1;
    if (last > 0)
        return last;
    // the highest value in the array was still negative, so the lowest positive missing value is 1
    return 1;
}

The last bit (getting the last value from the input, adding 1 and returning) is something that I'd probably leave at the end, but some might choose to perform this check before iterating the array. If the last (highest) value in the array is still negative, the loop is just a waste of time. The function then would look like this:

static
int get_missing(int *int, size_t size) {
    if (in == NULL || size == 0)
        return -1;
    qsort(in, size, sizeof *in, sort_ascending);

    if (in[size-1] <= 0) // highest value is 0 or less
        return 1;

    for (int i = 0; i < size -1; i++) {
        int v = in[i]+1;
        if (v > 0 && v < in[i+1])
            return v;
    }
}

As you can see, the function is a lot smaller, and fairly easy to read. The thing I don't like about checking the last element in the array before iterating is that it means the last return in the function is kind of "hidden" in a loop body. That may be personal preference, and if the input array is potentially huge, it's likely to be more efficient to preform that check. Then again, using qsort_r and passing in a pointer to an int allows you to count the number of negative values in the array, and that way you can start the iteration at the correct offset right away, but that's premature optimization. Let's get back to the matter at hand.

What was changed:

So far, we've changed:

Sorting separated out in a separate function, and using qsort rather than a nested loop
Checking for zero and NULL array
Returning early
Have error values returned in case the input is invalid (a -1)

What we still haven't addressed is the side-effect your function has. The input array is altered. This is considered bad practice (unless it's well documented, and is done for a clear reason). The way I'd solve it is by creating a copy:

static
int get_missing(const int *in, size_t size) {
    if (in == NULL || size == 0)
       return -1;
    // allocate memory for copy of input array
    int *temp = malloc(size * sizeof *in);
    if (temp == NULL)
        return -1;
    // copy the array
    memcpy(temp, in, size * sizeof *temp);

    // from here on, we use the copy
    qsort(temp, size, sizeof *temp, sort_ascending);
    if (temp[size-1] <= 0) {
        free(temp); // free memory
        return 1;
    }

    for (int i = 0; i < size -1; i++) {
        int v = temp[i]+1;
        if (v > 0 && v < temp[i+1]) {
            free(temp);
            return v;
        }
    }
}

Now if we do something like:

int main( void ) {
    int arr[] = int a[] = {1,3,6,4,1,2};
    int ret = get_missing(arr, ARRAY_SIZE(arr));
    for (int i=0; i < ARRAY_SIZE(arr); i++)
        printf("arr[%d] = %d\n", i, arr[i]);
    printf("Lowest positive int not in arr is %d\n", ret);
    return 0;
}

You'll see that the original array was not altered. The get_missing function now also communicates that clearly to:

int get_missing(const int *in, size_t size);

Looking at this, I know right away this function will return an int, accepts a pointer (decayed array), and will not change the argument (as it's const). I am expected to pass in a size value, which cannot be negative.

Putting it all together:

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

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))

static
int sort_callback(const void* a, const void* b) {
    int av = *((int *)a), bv = *(int *)b;

    if (av == bv)
        return 0;
    if (av < bv)
        return -1;
    return 1;
}

static
int get_missing_sideeffect(int *arr, int size) {
    qsort(arr, size, sizeof *arr, sort_callback);

    for (int i = 0; i < size-1; i++) {
        int next = arr[i] +1;
        if (next > 0 && arr[i+1] > next)
            return next;
    }

    int last = arr[size-1];
    if (last <= 0)
        last = 0;

    return last+1;
}

static
int get_missing(const int *in, size_t size) {
    if (in == NULL || size == 0)
       return -1;

    int *temp = malloc(size * sizeof *in);
    if (temp == NULL)
        return -1;

    memcpy(temp, in, size * sizeof *in);

    qsort(temp, size, sizeof *temp, sort_callback);
    if (temp[size-1] <= 0) {
        free(temp);
        return 1;
    }

    for (int i = 0; i < size -1; i++) {
        int v = temp[i]+1;
        if (v > 0 && v < temp[i+1]) {
            free(temp);
            return v;
        }
    }
}

int main(void) {
    int a[] = {1,3,6,4,1,2};
    int ret1 = get_missing(a, ARRAY_SIZE(a));
    // prints out a unchanged
    for (int i = 0; i < ARRAY_SIZE(a); i++)
        printf("a[%d] = %d\n", i, a[i]);
    int ret2 = get_missing_sideeffect(a, ARRAY_SIZE(a));

    printf("Smallest positive integer: %d -> %d\n", ret1, ret2);

    // shows a was changed due to side-effect
    for (int i = 0; i < ARRAY_SIZE(a); i++)
        printf("a[%d] = %d\n", i, a[i]);

    return 0;
}

As chux correctly pointed out: the version I posted here could've resulted in integer overflow. To fix this problem, it's a simple matter of returning 0 to indicate an error, and an unsigned int in all other cases (if the input has all ints up to (and including) INT_MAX).

Another issue I've realised is that the code wouldn't return a value like 1, if the input looked something like {2, 3, 4, 5}, whereas clearly, the smallest positive int missing from the array is 1. For these reasons, I'll write a final version of get_missing here:

static
unsigned int get_missing(const int *in, size_t size) {
    if (in == NULL || size == 0)
       return 0;

    int *temp = malloc(size * sizeof *in);
    if (temp == NULL)
        return 0;

    memcpy(temp, in, size * sizeof *in);

    qsort(temp, size, sizeof *temp, sort_callback);

    // lowest value in temp > 1, or highest value is zero or less
    if (temp[0] > 1 || temp[size-1] <= 0) {
        free(temp);
        return 1;
    }

    unsigned int v = 0;
    for (int i = 0; i < size -1; i++) {
        v = temp[i]+1u;
        if (v > 0 && v < temp[i+1]) {
            free(temp);
            return v;
        }
    }
    return v;
}

So I've added the check to make sure we return 1 if the input starts with 2 or more. I've changed the function to return an unsigned int (which means you have to print the output using printf("Return value %ud\n", ret);). Lastly, I'm also declaring v outside of the for loop. The last return statement won't ever be reached, but when I compiled the code in its original form (gcc -std=c99 main.c -o missing -Wall), the compiler spits out a warning.


Dynamic Controller Creation in Rails I have overrode Rails' ActionDispatch::Routing::RouteSet::Dispatcher.controller_reference method to check if a controller exists by checking for the required constants and then creating them based upon a controller with the same name in the Generic namespace.

The problem w/ my code is that it is using begin/rescue, it won't work w/ deeply namespaced controllers, and it's rather verbose.

Can anyone provide some improvements to this code?

class ActionDispatch::Routing::RouteSet::Dispatcher

  private

  def controller_reference(controller_param)
    const_name = @controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller"

    obj = Object
    const_name.split('::').each do |cn|
      begin
        obj =  obj.const_get(cn)
      rescue
        if obj == Object
          obj =  obj.const_set(cn, Class.new(ApplicationController))
        else
          puts "Creating #{obj}::#{cn} based on Generic::#{cn}"
          obj =  obj.const_set(cn, Class.new("Generic::#{cn}".constantize))
        end
      end
    end

    ActiveSupport::Dependencies.constantize(const_name)
  end

end

Disclaimer: this should be a comment, my reputation at the moment does not allow me to comment your question

What about exploiting const_missing?
https://apidock.com/ruby/Module/const_missing

I used it in an app to declare ActiveRecord models at runtime. If you are interested in this approach I suggest you to namespace all Dynamic controllers i.e.

module Dyn
  def self.const_missing(sym)
    # Declare class Dyn::MyDynamicController
    # without overriding or patching Rails classes
  end
end


Shortening calculator project code I was told to create a calculator design on AWT, which is also my first project on AWT.  I wrote the program and submitted it.  I was then told that my program contains around 70 lines of code, and I should try to write less code.  How can I shorten this code?

import java.awt.*;
class Demo{
    Frame f;
    TextField tf;
    Button add,sub,mul,div,find,zero,num1,num2,num3,num4,num5,num6,num7,num8,num9;
    Button num0,decimal,per;
    Demo(String s)
    {
        f=new Frame(s);
        tf=new TextField("0");
        tf.setBounds(20, 40, 205, 40);
        f.add(tf);
        add=new Button("+");
        sub=new Button("-");
        div=new Button("/");
        mul=new Button("x");
        find=new Button("=");
        zero=new Button("C");
        num1=new Button("1");
        num2=new Button("2");
        num3=new Button("3");
        num4=new Button("4");
        num5=new Button("5");
        num6=new Button("6");
        num7=new Button("7");
        num8=new Button("8");
        num9=new Button("9");
        num0=new Button("0");
        per=new Button("%");
        decimal=new Button(".");
        mul.setBounds(125,100,50,40);
        add.setBounds(70,100,50,40);
        sub.setBounds(15, 100, 50, 40);
        div.setBounds(180, 100, 50, 40);
        find.setBounds(180,250,50,88);
        zero.setBounds(180, 150, 50, 40);
        num9.setBounds(15,150,50,40);
        num8.setBounds(70,150,50,40);
        num7.setBounds(125,150,50,40);
        num6.setBounds(15,200,50,40);
        num5.setBounds(70,200,50,40);
        num4.setBounds(125,200,50,40);
        num3.setBounds(15,250,50,40);
        num2.setBounds(70,250,50,40);
        num1.setBounds(125,250,50,40);
        num0.setBounds(15,300,105,40);
        decimal.setBounds(125,300,50,40);
        per.setBounds(180,200,50,40);
        f.add(per);
        f.add(add);
        f.add(mul);
        f.add(div);
        f.add(sub);
        f.add(find);
        f.add(zero);
        f.add(num1);
        f.add(num2);
        f.add(num3);
        f.add(num4);
        f.add(num5);
        f.add(num6);
        f.add(num7);
        f.add(num8);
        f.add(num9);
        f.add(num0);
        f.add(decimal);
        f.setLayout(null);
        f.setSize(250,350);
        f.setVisible(true);
    }
    public static void main(String[] args)
    {
        new Demo("Calculator");
    }

}

Write a helper method, e.g.

static Button createButton(Frame f, String label, int x0, int y0, int width, int height) {
    Button b = new Button(label);
    b.setBounds(x0, y0, width, height);
    f.add(b);
    return b;
}

Then your code would simplify to lines like:

createButton(f, "+", 70, 100, 50, 40);

which is a reduction of roughly 2/3.

Of course this does not address the problem that you are trying to do pixel-exact layouts. You should rather be dropping elements on a grid which can be resized freely. (However, it has been a long time since I've used AWT so I can't give an example).


Parsing syllables from a string This method takes a string and parses the syllables. I've broken much of the logic into helper methods. Without getting into the helper methods, it's pretty easy to tell what this is doing. But there are a lot of conditionals. I tried handling the conditions that handle adding to the syllables variable and those that subtract as two separate methods, but syllables kept changing value out from under me.

def count_syllables
  exceptions = YAML::load_file(File.join(__dir__, 'exceptions.yml'))['exceptions']
  return exceptions[word.to_s] if exceptions.keys.include?(word)
  syllables = count_vowels
  syllables += count_ys_in_vowel_role if contains_non_initial_y?
  syllables += 1 if contains_le_vowel_sound?
  syllables += 1 if begins_with_re_vowel?
  syllables += 1 if ends_in_sm?
  syllables -= 1 if ends_in_silent_e?
  syllables -= count_diphthongs if contains_diphthongs?
  syllables <= 1 ? 1 : syllables
end

Some notes:

YAML::load_file. Loading a file each time a method is called is dubious. I'd load it in the initialize of the class so it's only done once.
return exceptions[word.to_s] if exceptions.keys.include?(word) Inline conditionals are ok as guards (in a fact here it's kind of a guard), but as a general rule indented conditionals are more declarative (granted, at the cost of an indentation level and some lines).
+=, -=. Imperative programming. As always, I'd advise against in-place updates, try to avoid statements in favor of expressions (functional programming).

I'd write:

def count_syllables
  if @exceptions.has_key?(word)
    @exceptions[word]
  else
    counts = [
      count_vowels,
      (count_ys_in_vowel_role if contains_non_initial_y?)
      (+1 if contains_le_vowel_sound?),
      (+1 if begins_with_re_vowel?)
      (+1 if ends_in_sm?),
      (-1 if ends_in_silent_e?),
      (-count_diphthongs if contains_diphthongs?),
    ]
    [counts.compact.reduce(0, :+), 1].max
  end
end


PHP Bilingual Error System Ideas I am building a php based mobile website that must be in both Spanish and English. This is my first bilingual site so I've been having to re-think a lot of coding practices I currently use to accommodate multiple languages.

I'm using a custom MVC pattern and currently I'm trying to use the same controller and model for both Spanish and English version of the site and just change the view for each language.

Since I'm using same model for both Spanish and English I have created an error system
in the model that supports both languages see sample below.

The error list will be different depending on the model but I have 1 model with almost 30 errors and 60 translations. Its a big Form with a lot of input field validations.

Do you think it would be better to keep it as 1 large nested array or split the array into something like $english_errorids and $spanish_errorids

Open to any ideas you guys may have, it currently works as is I'm just trying to make sure I'm doing this the right way.

 /**
 * Created by PhpStorm.
 * User: wmcgee
 * Date: 11/19/14
 * Time: 12:05 PM
 */

 class SampleModel
 {
     #region Error System
     /**
      * List of all recorded errors
      * @var array
      */
     public $errors;

     /**
      * Can be set to either ENG or SPAN
      * @var string
      */
     public $lang = "ENG";

     /**
      * List of errors with translations
      * @var array
      */
     public $errorids = array(
         10 => array('ENG'=>"Vehicle Condition Missing", 'SPAN'=>"Condicion de vehiculo falta"),
         11 => array('ENG'=>"Signature Missing",         'SPAN'=>"Falta su firma "),
     );

     /**
      * Records a translated error based on what lang is set and
      * what error id was passed into recorded errors list.
      *
      * @param $id int
      * @param bool $override if true id is treated as an
      *                       error message and is recorded
      *                       in error list.
      */
     public function recordError($id, $override = false)
     {
         //- Allow manual error messages not in translation list to be added
         if( $override ){
             $this->errors[] = $id;
             return;
         }

         $this->errors[] = $this->errorids[$id][$this->lang];
     }

    /**
     * Returns errors formatted in HTML
     * @return HTML
     */
    public function getErrors()
    {
        if( sizeof($this->errors) == 0){ return ''; }

        $msg = '
Report Errors
';

        foreach($this->errors as $error)
        {
            $msg .= "&bull; " . $error . "
";
        }

        $msg .= "
";

        return $msg;
    }
     #endregion
 }

I have had this problem several times and have tried different solutions. This is my current solution.

I use an associative array as a key-value list of message strings. Then I set the errors to a specific key name and fetch the corresponding message in a appropriately named file like english.php etc. This file can be all types of formats, but I will stick with PHP.

This has two main advantages:

Human readable key names
A central place all message string are stored, which in turn makes reuse of messages easier.

An example would be:

/*
* File: english.php
* This must return an associative array. This array can be multidimentional to better
* group different messages.
*/
$lang = [];
$lang['field_required'] = 'The field is required.';
$lang['success'] = 'The post was successfully created.';

// A grouped entry.
$lang['registration']['email_unavailable'] = 'The provided email is already in use.';

/*
 * A message string that requires some input that cannot be determined beforehand can
 * be solved by using the sprintf() or vsprintf() functions with the latter using an
 * array as an argument.
 */
$lang['shopping']['cart']['items']['amount_of_items'] = 'There are %d item(s) in your shopping cart.';

return $lang;

/*
 * File: bootstrapper.php (example)
 *
 * Some centrally available file. The $languages variable should be provided to
 * classes using dependency injection or made available otherwise.
 */
$current_language = 'english'; // Detected in a class or some other code.

$file = "path/to/language/{$current_language}.php"; // This file must return an array.

/*
 * Include the currently supported language file.
 * You can also make a list of supported languages before trying to load the file.
 */
if(!is_file($file) || !is_readable($file)) {
    // Do something here...
}

$languages = include $file;

/*
 * (OPTIONAL)
 * Here you can check if the language file returned the expected format.
 * Example: if(!is_array($languages)) { // do something }
 */

/*
 * Some model or controller (if you're validating input before sending it to the
 * model).
 * Here the language key is the same for all languages and only the value is
 * different.
 */
 $field_id = 'username';
 $field = filter_input(INPUT_POST, $field_id, FILTER_SANITIZE_STRING); // Just as good practice

 if(!check_required_field_function($field)) {
     $errors[$field_id] = $languages['field_required'];
 }

 /*
  * File: some view.php
  * Since this file properly contains some HTML I have used an alternative PHP syntax
  */
 <?php if(isset($errors) && !empty($errors)): ?>

The following errors occurred.

     <?php foreach($errors as $error): ?>

<?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?>

     <? endforeach; ?>

 <?php endif; ?>

The output escaping isn't stictly related to this question, but I added it as good practice.

This approach can properly be refactored a lot. Please let me know if you have any questions or something you would point out.

This is a very simple outline of the strategy I use. Hope it helps.


Feedback on generator functions and class composition in Python 3 I have written a Python script whose purpose is to read logs from CloudWatch and then post them to ElasticSearch. It is not quite finished but I've progressed far enough that I could benefit from feedback from Python experts, specifically:

Is the use of Python Generators correct and idiomatic
Is the use of Class Composition correct and idiomatic
Anything else style-wise inappropriate for Python 3.

#!/usr/bin/env python3

import json
import time
import uuid
import os
import sys

import boto3
from elasticsearch import Elasticsearch, helpers

client = boto3.client("logs")

def usage() -> None:
    print("Usage: GROUP_NAME=cloudwatch_group ES_HOST=es_host {}".format(
        os.path.basename(__file__)))
    sys.exit(1)

if "GROUP_NAME" not in os.environ:
    usage()
if "ES_HOST" not in os.environ:
    usage()

class CWLogs:
    group_name = os.environ["GROUP_NAME"]

    def events(self) -> None:
        for event in self.__generate_events():
            yield event

    def __generate_streams(self) -> None:
        kwargs = {
            "logGroupName": self.group_name,
        }

        while True:
            stream_batch = client.describe_log_streams(**kwargs)
            yield from stream_batch["logStreams"]
            try:
                kwargs["nextToken"] = stream_batch["nextToken"]
            except KeyError:
                break

    def __generate_events(self) -> None:
        stream_names = \
      [stream["logStreamName"] for stream in self.__generate_streams()]

        for stream_name in stream_names:
            kwargs = {
                "logGroupName":  self.group_name,
                "logStreamName": stream_name,
            }

            while True:
                logs_batch = client.get_log_events(**kwargs)
                yield from logs_batch["events"]
                try:
                    kwargs["nextToken"] = logs_batch["nextToken"]
                except KeyError:
                    break

class ESWriter:
    es_host = os.environ["ES_HOST"]
    elastic = Elasticsearch()

    def post(self, events: object) -> None:
        try:
            response = helpers.bulk(
                self.elastic, self.__transformer(events))
            print("\nRESPONSE:", response)
        except Exception as e:
            print("\nERROR:", e)

    @staticmethod
    def __index_name(timestamp: str) -> str:
        return "eventbridge-auth0-{}".format(
            time.strftime("%Y.%m", time.localtime(timestamp)))

    @staticmethod
    def __normalize(message: str) -> str:
        return message # TODO.

    def __transformer(self, events: object) -> None:
        for event in events:
            yield self.__transform(event)

    def __transform(self, event: dict) -> None:
        timestamp = event["timestamp"]
        index_name = self.__index_name(timestamp)
        message = self.__normalize(event["message"])

        return "\n".join([
            json.dumps({
                "index": {
                    "_id": str(uuid.uuid4()), # TODO. Check
                    "_index": index_name,
                    "_type":  "_doc"}}),
            json.dumps({
                "source": {
                    "@source": "auto-populate script",
                    "@timestamp": timestamp,
                    "@message": message}})])

if __name__ == '__main__':
    ESWriter().post(CWLogs().events())

Code Organization
Your code organization seems non-existent.  You have:

imports
code
function definition
code
class definitions
main-guarded code

Code should be organized in a more consistent structure, like:

imports
class definitions
function definitions
main-guarded code

The point of using a main-guard is to prevent code from running if the file is imported into another file.  Here, you have two separate code blocks which are unconditionally executed.  This limits code reuse.  For example, imagine someone could use CWLogs for their own task, but doesn't need ESWriter.  They try from your_file import CWLogs, and find their program exits after displaying a cryptic error message about a how to execute a program they are not actually running, due to a missing environment variable they don't actually use.
sys.exit()
Don't call this.  It terminates the Python interpreter.
Any debugging you may have hoped to do when the program finishes will be impossible, because the entire Python environment imploded.  It is impossible to safely import your file using try: import your_file except ImportError: because Python execution terminates during the import, meaning the program trying to import it unconditionally terminated.  If you try to use unittest to test your program, or Sphinx to generate documentation for your program, or any number of other common things, you can't, because your file has unconditionally terminated the Python interpreter.
Don't call it.
Instead:
if __name__ == '__main__':
    if {'GROUP_NAME', 'ES_HOST'} <= os.environ.keys():
        main()
    else:
        usage()

No need for usage() to call sys.exit().  After usage() is called, and returns normally, execution reaches the end of the file, which if this is the main program file, will naturally end the program.  Of course, if this is not the main program file, the main guard would have not run either method, the execution would reach the end of the file completing the importation of the file as a module in another program.
Stop Writing Classes
See "Stop Writing Classes" for a PyCon talk by Jack Diederich.
A class with no instance data members probably shouldn't be a class.  Neither ESWriter nor CWLogs have any instance data members.
A class with no constructor and only one public method to call shouldn't be a class.  Neither ESWriter nor CWLogs have a constructor.  Both have a single public method, called immediately after constructing a class instance, so the instance is not even saved.
These should not be classes.
Private name mangling
Private name mangling is used to prevent private member name collisions when a class is derived from another class, typically when the base class and the derive class are under control of different entities.  For instance, if you derive your own class from a tkinter.Frame, and you create a _validate method in your class, you could cause the base class to stop functioning properly if it had its own _validate method that was just abruptly changed on it.  So, the base class would use __validate, the leading double underscore would trigger name "mangling", and replace the name with _Frame__validate, so collisions are less likely.
There appears to be no reason for your usage of a double underscore prefix in your method names; a single underscore would be more idiomatic.
Type Hints
Your type hints are wrong.
For instance, the following is clearly returning a str, not None:
    def __transform(self, event: dict) -> None:
        ...
        return "\n".join( ... )

Since __transformer is yielding the results of __transform, it is not returning None either, but should be declared as:
from typing import Generator

...

    def __transformer(self, events: object) -> Generator[str, None, None]:
        ...

Or simply:
from typing import Iterator

...

    def __transformer(self, events: object) -> Iterator[str]:
        ...

And events: object is virtually meaningless, since everything in Python is an object.  Either use a proper type for it, or don't bother with a type hint at all.
Generator Expressions
As yedpodtrziko noted,
def __generate_events(self) -> None:
    stream_names = [stream["logStreamName"] for stream in self.__generate_streams()]

    for stream_name in stream_names:
        ...

builds up a temporary list, only to immediately iterate through it.  They made a fairly large change in the code to avoid the temporary list.  There is a much smaller change that can be made:
def __generate_events(self) -> None:
    stream_names = (stream["logStreamName"] for stream in self.__generate_streams())

    for stream_name in stream_names:
        ...

Because it may be hard to see the change, I'll amplify it: the [...] got changed to (...).  This means instead of stream_names being realized as an in-memory list, it becomes a generator expression, which will produce the values one at a time when asked.
It doesn't make much of a difference here, but if stream_names was being passed to a function, instead of being used locally, the change proposed by yedpodtrziko would require reworking code much further away to accept the stream_obj and extracting the stream names inside that function.


Recursive Insertion in Hash Table (Linear Probing) I was practicing implementing a hash function. I tried to use linear probing to insert in hash table. The insertion is working alright but I am not satisfied with the recursion. It doesn't feel like "good recursion". The Linear_Probing function instead of being recursive itself uses two other functions (excluding hash function) for recursive insertion: Index_Finder() and its auxiliary function.

Is there any way I can do the recursion better in this code for inserting into a hash table?

int Hash(int number); //<Hash function returns index by adding the first and last digit of a number;
bool Linear_Probing(int array[], bool flags [], int MAX_SIZE, int number, int &collisions); //<This function if possible inserts the number in the Hash Table
int Index_Finder(int number, bool flags[], int MAX_SIZE, int &collisions); //<This function finds the index where the number should be inserted. It returns -1 if no empty slot is found.
int Index_Finder(bool flags[], int MAX_SIZE, int index, int limit, int &collisions); //<This is an auxilary function

int main()
{
    const int MAX_SIZE = 11;
    int collisions = 0;
    int array[MAX_SIZE];
    bool flags[MAX_SIZE];

    for (int i = 0; i < MAX_SIZE; i++)
    {
        array[i] = 0;
        flags[i] = false;

    }

    //<Inserting numbers in hash table using linear probing
    Linear_Probing(array, flags, MAX_SIZE, 67, collisions);
    Linear_Probing(array, flags, MAX_SIZE, 19, collisions);
    Linear_Probing(array, flags, MAX_SIZE, 3, collisions);
    Linear_Probing(array, flags, MAX_SIZE, 808, collisions);
    Linear_Probing(array, flags, MAX_SIZE, 337, collisions);
    Linear_Probing(array, flags, MAX_SIZE, 1, collisions);
    Linear_Probing(array, flags, MAX_SIZE, 86, collisions);
    Linear_Probing(array, flags, MAX_SIZE, 38, collisions);

    return 0;
}

bool Linear_Probing(int array[], bool flags[], int MAX_SIZE, int number, int &collisions)
{
    int dummy_collisions = 0;
    int index = Index_Finder(number, flags, MAX_SIZE, dummy_collisions);

    if (index == -1)
        return false;

    else
    {
        collisions += dummy_collisions;

        array[index] = number;
        flags[index] = true;
        return true;
    }
}

int Index_Finder(int number, bool flags[], int MAX_SIZE, int &collisions)
{
    int index = Hash(number);

    if (index < MAX_SIZE && !flags[index])
        return index;

    if (index >= MAX_SIZE)
    {
        index = 0;

        if (!flags[index])
            return index;

        else
            collisions++;
    }

    else
    {
        collisions++;
    }

    int limit = index;

    return Index_Finder(flags, MAX_SIZE, ++index, limit, collisions);

}

int Index_Finder(bool flags[], int MAX_SIZE, int index, int limit, int &collisions)
{
    if (limit == index)
        return -1;

    if (index == MAX_SIZE)
        index = 0;

    if (!flags[index])
        return index;

    else
    {
        collisions++;
        return Index_Finder(flags, MAX_SIZE, ++index, limit, collisions);
    }
}

int Hash(int number)
{
    int first_digit = 0, last_digit = 0;
    bool first_time = true;

    while (number > 0)
    {
        if (first_time)
        {
            first_digit = number % 10;
            number -= (number % 10);
            number /= 10;
            first_time = false;
        }

        else
        {
            last_digit = number % 10;
            number -= (number % 10);
            number /= 10;
        }
    }

    return (first_digit + last_digit);
}

When commenting to describe a function's purpose, it's more common to have them on top of the signature of the function definition.  Having them next to the prototypes like that makes those lines harder to read and increases the code'd horizontal length.
Your curly brace usage with single-line statements is inconsistent.  It's also better to use them for all statements like these and can prevent some bugs and ease maintenance.
Instead of initializing the arrays with a loop, you can use std::fill_n():

std::fill_n(array, MAX_SIZE, 0);
std::fill_n(flags, MAX_SIZE, false);

While it may not matter in smaller programs, it's still more concise and can be safer.
You're passing C-arrays to functions, which shouldn't be done in C++ as this will cause them to decay to pointers.  Instead, pass in an object of a container class such as std::vector (dynamic) or std::array (static).  Choose whichever best gets the job done for you.


Taking student scores from a file, calculating averages, and printing This program takes scores for each student from a .txt file and calculates their averages, as well as the average for each assignment and the class overall. This program works properly, just curious if I can make it look more professional.

Scores.txt

5
6
95.2 89.1 98.0 78.9 100 67
100 99.6 100 100 90.1 82.2
100 85.5 85.1 74 81 79.4
98.6 71.5 68.9 62.4 56.9 0
100 100 100 88.3 91.6 81.3

StudentGradeBookScores.java

import java.util.*;
import java.io.*;
import java.text.*;
public class StudentGradebookScores {
  public static void main(String[]args) throws IOException {

    File inputFile = new File("scores.txt");
    Scanner data = new Scanner(inputFile);
    DecimalFormat averages = new DecimalFormat("#.#");
    int students = data.nextInt();
    int assignments = data.nextInt();
    double gradebook[][] = new double [students + 1][assignments + 1];

    //putting the scores into the array
    for (int i=0; i<students; i++) { //rows
      for (int j=0; j<assignments; j++) { //coloums
        gradebook[i][j] = data.nextDouble();
      }
    }

    //calculating the average assignment score for each student (coloums)
    for (int i=0; i<students; i++) {
      double studentTotal = 0;
      for (int j=0; j<assignments; j++) {
        studentTotal = studentTotal + gradebook[i][j];
      }
      gradebook[i][assignments] = studentTotal/assignments;
    }

    //calculating the average score of each assigment for all students (rows)
    for (int j=0; j<assignments; j++) {
      double assignmentTotal = 0;
      for (int i=0; i<students; i++) {
        assignmentTotal = assignmentTotal + gradebook[i][j];
      }
      gradebook[students][j] = assignmentTotal/students;
    }

    //printing the gradebook
    System.out.print("\t\t\t\tAssignment #:\n\t\t");
    for (int j=0; j<assignments; j++) {
      System.out.print((j+1) + "\t");
    }

    System.out.println("Avg");
    for (int i=0; i<students; i++) {
      System.out.print("Student #" + (i+1) + ":\t");
      for (int j=0; j<assignments; j++) {
        System.out.print(gradebook[i][j] + "\t");
      }
      System.out.println(averages.format(gradebook[i][assignments]));
    }
    System.out.print("Average\t\t");
    for (int j=0; j<assignments; j++) {
      System.out.print(averages.format(gradebook[students][j]) + "\t");
    }
    System.out.println();

    double overallAvg = 0;
    for (int i=0; i<students; i++) {
      overallAvg = overallAvg + gradebook[i][assignments];
    }

    System.out.println("\nOverall Average: " + averages.format(overallAvg/students));
  }
}

Declaring that main() throws IOException is probably the right thing to do for a simple program like this.  A lot of beginners try to catch an exception that they don't have any idea how to handle properly.

That's a lot of code to be stuffed into a single main() function.  Ideally, you should develop classes such that main() contains just a minimal amount of code, like this:

public static void main(String[] args) throws IOException {
    try (Scanner input = args.length > 0 ? new Scanner(new File(args[0])) :
                                           new Scanner(System.in)) {
        GradeBook book = new GradeBook(input);
        System.out.println(book);
        System.out.printf("Overall Average: %s\n",
                          FMT.format(book.average()));
    }
}

Hard-coding an input filename makes it hard to reuse your code.  I've modified it to read from either a filename specified on the command line or from System.in.

You should be able to avoid having to explicitly specify the dimensions of the data in the file.

Using Java 8 streams removes a lot of tedious looping from the implementation.  Here is the rest of my suggested implementation:

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.IntStream;

public class GradeBook {
    private List<double[]> students;
    private static final DecimalFormat FMT = new DecimalFormat("#.#");

    public GradeBook(Scanner input) {
        this.students = new ArrayList<double[]>();
        while (input.hasNextLine()) {
            double[] student = Arrays.stream(input.nextLine().trim().split("\\s+"))
                  .mapToDouble(Double::parseDouble)
                  .toArray();
            students.add(student);
        }
    }

    public double getScore(int student, int assignment) {
        return this.students.get(student)[assignment];
    }

    public double averageForStudent(int student) {
        return Arrays.stream(this.students.get(student))
                     .average()
                     .getAsDouble();
    }

    public double averageForAssignment(int assignment) {
        return this.students.stream()
                   .mapToDouble((assignments) -> assignments[assignment])
                   .average()
                   .getAsDouble();
    }

    public double average() {
        return IntStream.range(0, this.students.size())
                        .mapToDouble((s) -> this.averageForStudent(s))
                        .average()
                        .getAsDouble();
    }

    public String toString() {
        StringBuilder out = new StringBuilder();
        int numAssignments = this.students.stream()
                                 .mapToInt((assignments) -> assignments.length)
                                 .max()
                                 .getAsInt();

        // Header
        out.append("\t\t\t\tAssignment #:\n\t\t");
        for (int a = 0; a < numAssignments; a++) {
           out.append(a + 1).append('\t');
        }
        out.append("Avg\n");

        // Body
        for (int s = 0; s < this.students.size(); s++) {
            out.append("Student #").append(s + 1).append(":\t");
            for (int a = 0; a < numAssignments; a++) {
                out.append(FMT.format(this.getScore(s, a))).append('\t');
            }
            out.append(FMT.format(this.averageForStudent(s))).append('\n');
        }

        // Footer
        out.append("Average\t\t");
        for (int a = 0; a < numAssignments; a++) {
            out.append(FMT.format(this.averageForAssignment(a))).append('\t');
        }
        out.append('\n');

        return out.toString();
    }

    public static void main(String[] args) throws IOException {
        try (Scanner input = args.length > 0 ? new Scanner(new File(args[0])) :
                                               new Scanner(System.in)) {
            GradeBook book = new GradeBook(input);
            System.out.println(book);
            System.out.printf("Overall Average: %s\n",
                              FMT.format(book.average()));
        }
    }
}


Find the range of index of consecutive integers from a sorted array I would like to know how can   improve  my solution.

import java.util.*;
public class prog{

    public   Map<Integer, Integer>  findList(int[] array1)
    {
         Map<Integer, Integer> list= new HashMap<Integer, Integer>();

         int start_index= 0;
         int end_index = 0;
         int length = array1.length;

         for(int i = 1; i < length ; ++i)
         {
             if(array1[i-1] + 1 != array1[i])
             {

                 end_index = i - 1;
                 list.put(start_index, end_index);
                 start_index = i;
             }
         }
         if( array1[length -2]+1 == array1[length -1])
         {
             end_index = length - 1;
             list.put(start_index, end_index);
         }
          return list;
    }

    public static void main(String[] arr)
    {
        int [] array1 = { 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 20, 22, 23, 24, 27,34 };
        prog prg = new prog();
        Map<Integer, Integer> list1= new HashMap<Integer, Integer>();
        list1 = prg.findList(array1);

        for( Map.Entry<Integer,Integer> entry: list1.entrySet())
        {
            System.out.println( entry.getKey()+"--"+ entry.getValue());
        }
    }
}

Correctness:

Your code doesn't seem to actually produce the correct answer.

When I ran this code, I got:

0--5
6--6
7--10
11--11
12--14
15--15

However... the list has 17 elements, so 16--16 is missing.

The reason for this is that once you are done with the for loop, you do handle the case when the last two elements are part of a consecutive range, but in your test case, they aren't.

The way to fix this is very easy: remove the if. It should look like this:

for(int i = 1; i < length ; ++i) {
    // same as yours
}
end_index = length - 1;
list.put(start_index, end_index);

return list;

Style:

Aside from the things that Mayur already mentioned,

Comment your code. It took me many more minutes than it should have to figure out what it does.
Along the same vein, name things according to what they do. For example, I would rename findList (A completely pointless name... might as well have been foobar) to buildConsecutiveRangeMap. I would also change array1 to numbers, or at least drop the unnecessary "1". Lastly, prog is just a completely meaningless name for a class...rethink this.
Make " "'s matter. Why do you have extra spaces between public and Map? > and findList? Right before the return? At the same time, you could use more to make length -2 into length - 2, array[index]+1 into array[index] + 1 and so on.
Don't prematurely optimize. That's the only reason I could see for using another variable to store array1.length instead of using that everywhere. Little secret: It's just a field lookup that takes O(1) time and a modern day JIT will notice that that value is constant and optimize your loop for you.
Import just the things you need. It's a waste to include everything under the sun.

Other comments

Test, test, test. Testing would have led you to find the bug and helps developers figure out what you are trying to accomplish based on the expected output.
To clean things up, I suggest checking if the range is something like 15--15 and instead just print 15.
Don't waste your time allocating things when you don't need to. You allocate some memory for list1 in main and then in the findList method, you allocate some more. The garbage collector will of course clean this up...but it also makes your code uglier. Just replace your
code in main with:

Map<Integer, Integer> rangeMap = findList(numbers);

Another feature you might want is to print the numbers in order. The fact that the results happened to be in order is coincidence. A Map guarantees nothing about order and it is up to you to sort the data as you like. Testing different numbers and larger data sets will make this clear.


Checking directory for processing This checks whether it's valid to make a processing. Processing can occur if:

there are files and spreadsheets (spreadsheet is the spec attribute)
there are any files or spreadsheets (it never occurs if there is at least one of the two)

AllFiles is empty only if one has sent a zip, but it wasn't unzipped and has been deleted. If unzipped and deleted, allFilesIsEmpty is false because one usually receives files in addition to the formats allowed that the program doesn't delete.

It should be at least one .swf, .gif or .jpg processing to occur. If not, it's not an allowed file format.

I described the best in the code but I have cyclomatic complexity. Any idea on how I can reduce?

private boolean directoryIsEmpty(OldValidacao validacao) {
        Map<String, String> allFiles = validacaoService.getFilenameMap(validacao.getArquivoPath());
        if (allFiles.isEmpty() && validacao.getSpec() == null) {
            return true;
        } else if (validacao.getSpec() != null) {
            return false;
        } else if (!allFiles.isEmpty()) {
            String files = allFiles.toString();
            if (files.contains("swf") || files.contains("jpg") || files.contains("gif")) {
                return false;
            }
        }
        return true;
    }

It should be at least one .swf, .gif or .jpg processing to occur. If not, it's not an allowed file format.

The way try to check this is not so good:

    String files = allFiles.toString();
    if (files.contains("swf") || files.contains("jpg") || files.contains("gif")) {
        return false;
    }

You should not rely on the .toString() implementation to verify values.
You should use the values. I suggest to rewrite like this or similar:

for (String filename : allFiles.values()) {
    if (filename.endsWith(".swf") || filename.endsWith(".jpg") || filename.endsWith("gif")) {
        return false;
    }
}

This loop iterates over the values, and I replaced the .contains check with .endsWith, which seems to be more accurately matching what you really want to check. Another alternative to write the condition:

if (filename.matches(".*(\\.swf|\\.jpg)$")) {
    return false;
}

  I described the best in the code but I have cyclomatic complexity. Any idea on how I can reduce?

It seems you want to reduce cyclomatic complexity of the method.
The main contributors to the high cyclomatic complexity in your example:

many return statements
many if conditions
many && and || operators

One way to reduce cyclomatic complexity is to extract some parts of the method to another method, for example:

if (allFiles.isEmpty() && validacao.getSpec() == null) {
    return true;
} else if (validacao.getSpec() != null) {
    return false;
} else if (!allFiles.isEmpty()) {
    if (containsMediaFiles(allFiles)) {
        return false;
    }
}
return true;

I just invented the helper method containsMediaFiles,
and eliminated a for loop and some || conditions.

But in this particular example, there's an even easier way.
Realize that you don't really need to check if allFiles is not empty.
You can just loop over it, and if it's empty,
there will be nothing to loop over, so the empty case will be automatically handled, like this:

private boolean directoryIsEmpty(OldValidacao validacao) {
    Map<String, String> allFiles = validacaoService.getFilenameMap(validacao.getArquivoPath());

    if (allFiles.isEmpty() && validacao.getSpec() == null) {
        return true;
    }

    if (validacao.getSpec() != null) {
        return false;
    }

    for (String filename : allFiles.values()) {
        if (filename.matches(".*\\.(swf|jpg|gif)$")) {
            return false;
        }
    }

    return true;
}

@ismael-miguel made a good point in comments that probably you want to match extensions like "JPG", and even "JPg". An easy way to do that is to convert filename to lowercase before the .matches call above. And you might want to add more patterns, for example jpeg, or use the pattern jpe?g to take care of both "jpeg" and "jpg" at the same time.


Stripping leading tab of each line from a file I've got this Python code:

import os, re

def clnFile(file):
    inputFile = open(file, 'r')
    filename = file + '.tmp'
    outputFile = open(filename, 'w')
    code = inputFile.read()
    pattern = re.compile('\n\t')
    code = pattern.sub('\n', code)
    outputFile.write(code)
    inputFile.close()
    outputFile.close()
    os.remove(file)
    os.rename(filename, file)

It supposed to change content of the file.
My algorithm is:

open original file
open original temporary file
read original file content to a string
change the string
write string to original temporary file
close original file
close temporary file
remove old original file
rename temporary file

I am sure there should be a way to simplify this code. Because now it's rather bulky.
Could anyone help me to adjust it?

You can use a different approach here:

Open file in r+ mode, it allows us to read as well as write the file along with truncation.
Read the content first and store it in a variable.
Seek back to 0th position using file.seek(0).
Truncate the file using file.truncate(), i.e it will truncate it to 0 bytes.
Now write the new content to the file object.

Code:

def clean_file(filename):
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0)
        f.truncate()
        f.write(content.replace('\n\t', '\n'))

Few other points:

Prefer variable names with underscores in Python.
Always open files using the with statement in Python.
You can change the variable name file to filename to make it clearer to the user, otherwise it's hard to tell whether the file object expects a file name or file object.
Instead of using regex simply use the str.replace method.
To modify a file line by line in-place you can look into fileinput module.


Idiomatic iterator for a linear function A while back, I asked a question about implementing an idiomatic iterator in C++. I've recently revisited the code, and I'm bothered by the duplication in the begin and end iterators. The code goes over a collection/iterator over a domain, and lazily produces the range using the iterator. After trimming down some code from the accepted answer, here's what I have:

class LinearFunction
{
public:
    LinearFunction(double m, double b) : m_(m), b_(b) { }

    double operator()(double x) const { return m_ * x + b_; }
private:
    double m_, b_;

};

template <typename IterType>
class LinearFunctionIterator
{
public:
    LinearFunctionIterator(IterType iter, LinearFunction const &linearFunction)
        : xIter_(iter), linearFunction_(linearFunction) { }

    LinearFunctionIterator &operator++() {
        ++xIter_;
        return *this;
    }

    double operator*() const {
        return linearFunction_(*xIter_);
    }

    bool operator!=(LinearFunctionIterator const &other) const {
        return xIter_ != other.xIter_;
    }

private:
    IterType xIter_;
    LinearFunction linearFunction_; // <--- (1)
};

template <typename IterType>
class LinearFunctionIteratorProxy
{
public:
    LinearFunctionIteratorProxy(IterType xBegin, IterType xEnd,
                                LinearFunction const &linearFunction)
        : xBegin_(xBegin), xEnd_(xEnd), linearFunction_(linearFunction) { }

    LinearFunctionIterator<IterType> begin() const {
        return { xBegin_, linearFunction_ };
    }

    LinearFunctionIterator<IterType> end() const {
        return { xEnd_, linearFunction_ };
    }

private:
    IterType xBegin_, xEnd_;
    LinearFunction linearFunction_;
};

template<typename Container>
auto makeLinearFunction(Container const &domain,
                        LinearFunction const &linearFunction)
-> LinearFunctionIteratorProxy<decltype(std::begin(domain))>
{
    return { std::begin(domain), std::end(domain), linearFunction };
}

Usage:

#include "LinearFunction.h"
#include <iostream>
#include <vector>

int main()
{
    std::vector<double> domain { 1.0, 5.0, 2.0, 8.0 };
    LinearFunction linearFunction(10.0, 5.0);

    std::cout << "Range:\n";
    for(auto rangeValue : makeLinearFunction(domain, linearFunction))
    {
        std::cout << rangeValue << ", ";
    }
}

What I'm looking for from the review:

Notice in the example usage, that there are three copies of the LinearFunction instance: one in the proxy, one in the begin iterator, and one in the end. Is there a better way to achieve the same behavior without this duplication?
General advice to improve this code would be appreciated.

I suppose that if you don't really have a need to end member names with underscores, then you can avoid them.  Having similar names as constructor parameters won't even matter as long as you're using an initializer list.
Probably a bit nit-picky, but you may not need the precision of a double here.  If so, then you can just use floats.
With begin() and end(), you can also provide const versions (cbegin() and cend()).

Also, be careful with these names since they're also used in the STL.  You may also use slightly different names if you prefer.
If you really need operator!=, then you should also provide operator==.

In addition, it's usually preferred to define operator!= in terms of ==:

return !(xIter_ == other.xIter_);


Project Euler Problem 10 - Sum of primes < 2mil /*The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.
*/
#include <iostream>
#include <vector>

using namespace std;

int main(){
//We will be storing the primes as bool in a vector.
    vector<bool>primes(2000000,true);

// This is the Sieve of Eratosthenes. It is not perfect, but It solve's the problem.

    primes[1] = false;
    for(int a = 2; a*a < primes.size(); ++a){
        if(primes[a]==true){
            for(int b = 0; a*a+b*a < primes.size(); ++b){
                    primes[a*a+b*a] = false;
            }
        }
    }
//This simply add's all the prime numbers
    long long total = 0;
    for(int c = 1; c < primes.size(); c++){
        if(primes[c] == true)
            total +=c;
    }
    std::cout << total;

return 0;
}

This works well. I'm trying to improve my C++ and was wondering if there is a way to improve on it. I'm just learning, and would welcome any advice.

I have several things to add onto @rolfl's great advice:

Since you have a container of bools, which doesn't store the actual primes, consider renaming primes to is_prime or something similar.  This sounds more conditional and makes more sense with the type of values being stored.
I might still assign the 2000000 to a constant to make this more understandable for users without the full documentation (someone might otherwise think that there should be 2M primes, looking at the vector's name).  It would also help in case you'll need this number elsewhere.

You could have something like this (feel free to use a better name):

const int maxNumbers = 2000000;

std::vector<bool> primes(maxNumbers, true);

You can leave out the true from your if statements:

This

if(primes[a]==true)

is the same as

if(primes[a])

If you were to do something with false, you would use !:

if(!primes[a])

You're hard-coding a*a+b*a in some places, and it's not quite clear what this computation corresponds to (especially with your single-character variable names).

You could assign it to a local variable and use it where it's needed.  To keep it within a close scope (it's only needed within a small space), initialize it within the loop.
Some of your comments seem noisy/useless:

// We will be storing the primes as bool in a vector.

The "we" sounds like you're demonstrating this code for a tutorial or such, and this doesn't appear to be the intent.  Just a simple "this does..." or "this is..." will do.

Other than that, the entire comment is not helpful.  It's clear that it's an std::vector of bools that stores primes.  There's no need to state the obvious; the code speaks for itself.

// This is the Sieve of Eratosthenes. It is not perfect, but It solve's the problem.

The second sentence is just noisy and adds nothing of value; just remove it.  The first sentence, however, is okay because it's not entirely obvious that this is the Sieve.


Handling HTTP status messages and multiple returns I am new to Python and have written a function which calls an API and does some processing. Please review the code and explain what is the right and pythonic way.

def fetch_storedetails(api_link, zone_id, latitude, longitude):
    """

    :param api_link:
    :param zone_id:
    :param latitude:
    :param longitude:
    :return:
    """
    import requests
    store_details = requests.get(
        api_link + '/' + str(zone_id) + '/' + str(0) + '/' + str(latitude) + '/' + str(longitude),
        headers={'language': 'en'})
    print(store_details, store_details)
    print(store_details.json)
    s_details = store_details.json()
    if store_details.status_code == 400:
        return "'Sorry , we do not deliver to your selected address at this moment as it’s out of delivery reach."
    elif store_details.status_code == 404:
        return "Stores are not available in your location"
    elif store_details.status_code == 500:
        return "Internal server error"
    else:

        print(s_details)
        store_name = []
        store_address = []
        banner_image = []
        store_rating = []
        store_id = []

        for i in s_details['data']:
            store_name.append(i['businessName'])
            store_address.append(i['storeAddr'])
            banner_image.append(i['bannerLogos']['bannerimage'])
            store_rating.append(i['businessRating'])
            store_id.append(i['businessId'])

    return store_name, store_address, banner_image, store_rating, store_id

If you're going to drop in a comment block for function documentation, fill it out. Otherwise, delete it.
Generally you shouldn't import on the inside of a function. import at the top of a file.
Your constructed URL shouldn't use a series of +. You should be using the % formatting operator or str.format(). This will also avoid calling str(0).
None of your elses are necessary. You return before each of them, so you can simply continue writing the rest of the function afterward.
If I were you, I would simply return s_details['data']. Decomposing the payload into a series of lists isn't really useful, and if it is indeed useful for your application, it should be done in a separate function.
Returning an error string to indicate an error is a bad idea. You should raise an exception instead.


Creating a configuration Class in php I am creating a system for a client that loads information from an XML file and then parses the information where needed. For this, I have got this class:

<?php
class Config
{
    private static $init;
    private static $link;

    private static $db_hostname;
    private static $db_username;
    private static $db_password;
    private static $db_database;

    public static $ABSPATH;
    public static $GWPATH;
    public static $CONFIGPATH;
    public static $CONNECTIONPATH;

    public static $configfile;
    public static $connectionfile;

    private static $cfg;

    const CONFIGFILEPATH = "E:/projects/php/_site/_site/_include/Config/web.config.xml";

    /** Private to implement singleton pattern */
    private function __construct() {  }

    /** @return Config */
    public static function Init()
    {
        return static::$init = (
            null === static::$init ? new self() : static::$init
        );
    }

    public function RequireFiles()
    {
        require_once static::$connectionfile;
        require_once static::$GWPATH . 'libraries/functions/user.loggedin.php';
    }

    public function LoadConfig()
    {
        static::$cfg = simplexml_load_file(self::CONFIGFILEPATH);

        $path = static::$cfg->paths;
        $database = static::$cfg->database;

        static::$ABSPATH = (string) $path->abs;
        static::$GWPATH = (string) $path->gwpath;
        static::$CONFIGPATH = (string) $path->configpath;
        static::$configfile = (string) $path->configfile;
        static::$CONNECTIONPATH = (string) $path->connectionpath;
        static::$connectionfile = (string) $path->connectionfile;

        static::$db_hostname = (string) $database->hostname;
        static::$db_username = (string) $database->username;
        static::$db_password = (string) $database->password;
        static::$db_database = (string) $database->name;
    }

    public function GetLink()
    {
        if (empty(static::$link) || null === static::$link)
            $this->SetLink();
        return static::$link;
    }

    public function SetLink()
    {
        static::$link =
            new Database($this->GetDBHostname(), $this->GetDBUsername(), $this->GetDBPassword(), $this->GetDBDatabase())
                or die("Failed to connect to the server. Error: " . static::$link->connect_error);
    }

            private function GetDBHostname()
    {
        return static::$db_hostname;
    }

    private function GetDBUsername()
    {
        return static::$db_username;
    }

    private function GetDBPassword()
    {
        return static::$db_password;
    }

    private function GetDBDatabase()
    {
        return static::$db_database;
    }

    public function GetConfigXML($do = false)
    {
        if ($do == true)
            return static::$cfg;
        return null;
    }
}

This is working for me, but I wanted to know if there is a better way to do this?

Info:
This is used in this way:

$config = Config::Init();
$config->LoadConfig();
$config->RequireFiles();
$link = $config->GetLink();

There is no need to make anything static here. I would pass the config file name in the constructor, and make everything an instance variable.
Any other object that needs configuration needs this config object, rather than referencing it via the singleton pattern
Storing the database configuration, like hostname, username and password makes sense in a config class. Actually connecting to the database does not.
Instead of using the die(...) function, throw an exception. Really, this would be made obsolete by not connecting to the database in a config class, but whenever you decide to do this, throwing an exception is more appropriate. You communicate that an insurmountable problem has occurred that you cannot fix, but you give other code in the system the option of fixing it.
The method names are in PascalCase -- idiomatic for C#, but not for PHP. The PHP Coding Style Guide from PHP-FIG is a good reference. Use camelCase instead, so LoadConfig becomes loadConfig.
The RequireFiles method isn't really configuration and doesn't belong in a config class. A class or function that has a more global scope in the application should be loading those, or take advantage of autoloading.


Dynamic array of integers: another attempt This is follow up to this one. In the previous some minor errors slipped, so I couldn't update the code. Also took some advice.
So final version is below.

header:

#define DEFAULT_CAPACITY 1000

// Define a vector type
typedef struct
{
  int nrOfElements; // This just denotes current number of elements.
  int capacity;     // This denotes the capacity of the array.
  int *data;        // Actual pointer to array elements.
} CVectorInt;

typedef enum {VECTOR_SUCCESS, VECTOR_OUTOFBOUNDS, VECTOR_MEMORYERROR, VECTOR_LIMITEXCEEDED} vector_status;

vector_status CVectorInit(CVectorInt *vector);
vector_status CVectorAppend(CVectorInt *vector, int value);
vector_status CVectorGet(CVectorInt *vector, int index, int * value);
vector_status CVectorSet(CVectorInt *vector, int index, int value);
void CVectorFree(CVectorInt *vector);

source:

#include "CVectorInt.h"
#include <stdio.h>
#include <stdlib.h>

///
// Initialize vector.
//  Set capacity to default value. Current number of elements to 0.
//  Allocate memory dynamically for the default number of elements.
//
//
// Return
//  If there is some problem, error code is returned.
//
vector_status CVectorInit(CVectorInt *vector)
{
    int i = 0;

    vector->capacity = DEFAULT_CAPACITY;
    vector->nrOfElements = 0;

    // Allocate array
    vector->data = malloc(sizeof(int) * vector->capacity);
    if(vector->data == NULL)
        return VECTOR_MEMORYERROR;

    // Initialization the array to default values.
    for(i = 0; i < DEFAULT_CAPACITY; i++)
        vector->data[i] = 0;

    return VECTOR_SUCCESS;
}

vector_status CVectorAppend(CVectorInt *vector, int value)
{
    int * ptr = NULL;
    int i = 0;

    if(vector->capacity == 32000)
        return VECTOR_LIMITEXCEEDED;

    // Do we have room to append elements?
    if(vector->capacity <= vector->nrOfElements)
    {
        // No, increase capacity
        vector->capacity *= 2;

        // Resize array
        ptr = realloc(vector->data, vector->capacity * sizeof(int));
        if(ptr == NULL)
        {
            // We had an error
            return VECTOR_MEMORYERROR;
        }
        else
        {
            vector->data = ptr;

            // Initialize only new elements to 0.
            for(i = vector->nrOfElements; i < vector->capacity; i++)
                vector->data[i] = 0;
        }
    }

    // Now, after possible resize, add the element.
    vector->data[vector->nrOfElements++] = value;

    return VECTOR_SUCCESS;

}

vector_status CVectorGet(CVectorInt *vector, int index, int * value)
{
    // Is the index within bounds?
    if(index < vector->nrOfElements && index >= 0)
    {
        *value = vector->data[index];
        return VECTOR_SUCCESS;
    }else
    {
        return VECTOR_OUTOFBOUNDS;
    }
}

vector_status CVectorSet(CVectorInt *vector, int index, int value)
{
    // We can't set outside capacity
    if(index >= vector->capacity || index < 0)
        return VECTOR_OUTOFBOUNDS;

    // zero fill the vector up to the desired index
    while(vector->nrOfElements <= index)
        CVectorAppend(vector, 0);

    vector->data[index]=value;
}

void CVectorFree(CVectorInt *vector)
{
  // Free underlying array
  free(vector->data);
}

Your entire CVectorInit function can essentially be trimmed down to this:

vector_status CVectorInit(CVectorInt *vector)
{
    vector->capacity = DEFAULT_CAPACITY;

    // Allocate array
    vector->data = calloc(vector->capacity, sizeof(int));
    if(vector->data == NULL)
        return VECTOR_MEMORYERROR;

    return VECTOR_SUCCESS;
}

Fundamentally though, is there a reason to zero out the allocated array? You make sure that you never access an index that's out of bounds in your functions so there should be no need to zero out the allocated array. Especially on resizing the vector, this will just be a performance hit that you'll take with little benefit (especially when the vector gets to be quite large).

Moreover, I would replace the ints holding the size and capacity of the vector with size_t or something similar. These values are never going to hold negative numbers so there's no need to have them as signed ints.

Also, there seems to be this magic constant 32000. Why is it 32k and what's the reasoning? Create a named variable for this constant. So in your .c file:

static const size_t MAXIMUM_CAPACITY = 32000;

Also, why is that value so low? A standard signed int can hold a maximum value of around 2 billion so 32k seems pretty low. Maybe putting a comment above that named variable to justify your reason could be helpful.

As a design consideration, you might want to think whether or not you want to have DEFAULT_CAPACITY declared as a macro in your header file. As it is, someone could go to your header and set DEFAULT_CAPACITY to a negative value or some other erroneous number. Assuming that you might be compiling this as some sort of library, it might be better to declare DEFAULT_CAPACITY as a private variable to your implementation file to avoid such things:

In your .c file:
static const size_t DEFAULT_CAPACITY = 1000;

This also comes with the added benefit of type safety and avoiding the use of the preprocessor.


Display relevant contents if radio button is clicked using knockout.js I have four radio buttons and I want to display relevant contents for each of them if they are clicked. I am using knockout.js for data binding.

Is there a better way to write the if statement block?

      <input type="radio" data-bind="checked: print_size_radio" name="print-size" value="Standard" />Standard (Letter)

    No. of Copies
      <input type="text" data-bind="value:print_size_standard_q, valueUpdate:'keyup'" />

      <input type="radio" data-bind="checked: print_size_radio" name="print-size" value="13 x 19" />13" x 19"

    No. of Copies
      <input type="text" data-bind="value:print_size_13_19_q, valueUpdate:'keyup'" />

      <input type="radio" data-bind="checked: print_size_radio" name="print-size" value="Contact Sheet">Contact Sheet

    No. of Images/Page
      <input type="text" data-bind="value:print_size_contact_q, valueUpdate:'keyup'" />

      <input type="radio" data-bind="checked: print_size_radio" name="print-size" value="Custom Size" />Custom Size

        Width
          <input type="text" data-bind="value:print_size_custom_w, valueUpdate:'keyup'" />

        Height
          <input type="text" data-bind="value:print_size_custom_h, valueUpdate:'keyup'" />

        Pixels/Inches
          <select data-bind="options: print_size_custom_units, value: print_size_custom_sel"></select>

        No. of Copies
          <input type="text" data-bind="value:print_size_custom_q, valueUpdate:'keyup'" />

self.print_size_radio.subscribe(function(p) {
  if (p == 'Standard') {
    self.print_size_standard(true);
    self.print_size_13_19(false);
    self.print_size_contact(false);
    self.print_size_custom(false);
  } else if (p == '13 x 19') {
    self.print_size_standard(false);
    self.print_size_13_19(true);
    self.print_size_contact(false);
    self.print_size_custom(false);
  } else if (p == 'Contact Sheet') {
    self.print_size_standard(false);
    self.print_size_13_19(false);
    self.print_size_contact(true);
    self.print_size_custom(false);
  } else if (p == 'Custom Size') {
    self.print_size_standard(false);
    self.print_size_13_19(false);
    self.print_size_contact(false);
    self.print_size_custom(true);
  } else {
    self.print_size_standard(false);
    self.print_size_13_19(false);
    self.print_size_contact(false);
    self.print_size_custom(false);
  }
});

Not sure how much better it is, but some would say it could look nicer to intialize everything to false, then only change when true.  Like so:

self.print_size_radio.subscribe(function(p) {

   self.print_size_standard(false);
   self.print_size_13_19(false);
   self.print_size_contact(false);
   self.print_size_custom(false);

   if (p == 'Standard') {
      self.print_size_standard(true);
   }
   else if (p == '13 x 19') {
      self.print_size_13_19(true);
   }
   else if (p == 'Contact Sheet') {
      self.print_size_contact(true);
   }
   else if (p == 'Custom Size') {
      self.print_size_custom(true);
   }
});


updateBuildChart method with a lot of dependencies I've some refactoring issue with one method.
This method has a lot of dependencies

 function updateBuildChart(Filter, PagerFactory, ChartBuilder, LimitsManager) {
     Filter.clearFilters();

     this.currentReports = $scope.$parent.reports;

     $scope.pager = PagerFactory.Create({
         items: this.currentReports
     });

     this.originalReports = angular.copy(this.currentReports);
     LimitsManager.calcFteLimits();

     if (this.currentReports.length > 0) {
         $scope.showGraph = true;
         ChartBuilder.buildChart(this.currentReports);
     } else {
         $scope.showGraph = false;
     }

     Filter.setReports(self.currentReports);
 };

Now I want to split this big method to a small parts. Do you have some ideas how to change it?

The function is named updateBuildChart,
but building a chart seems a very tiny part of all its responsibilities.
If we kept only what its name implies and removed everything else:

function updateBuildChart(ChartBuilder) {
    var currentReports = $scope.$parent.reports;
    if (currentReports.length > 0) {
        ChartBuilder.buildChart(currentReports);
    }
}

However,
without seeing all your code,
it's hard to advise.
Mainly,
it's not clear if the statements in the function have side effects or not.
So I'm just going to go over line by line and ask you some questions that might help you clean up this thing.

The function starts with using Filter and ends with using Filter,
and it doesn't use it anywhere in between:

Filter.clearFilters();

// ...

Filter.setReports(self.currentReports);

Does this ordering matter?
Will your program still work if you move the Filter.setReports call right after Filter.clearFilters?
If not, then these calls will be good to group together.

It will be even better if you move them to a dedicated function whose responsibility is to clear filters and set the reports,
perhaps something like resetFilters(Filter).

And move the call to this new function outside of updateBuildChart,
where it really doesn't belong.

What is this for?

this.currentReports = $scope.$parent.reports;

Is it just to be a shortcut for $scope.$parent.reports in the rest of the function, or will this have a side effect outside this function?
If it's the first case, then it would be better to use var currentReports = instead.

PagerFactory is only referenced in one place:

$scope.pager = PagerFactory.Create({
    items: this.currentReports
});

Similar to the treatment of Filter earlier,
it would be better to move this into a dedicated function,
say updatePager, and call it outside of this function.

What is this for?

this.originalReports = angular.copy(this.currentReports);

Since this.originalReports is not referenced again within the function,
it would seem that this produces a side effect outside the function.
Or else, it's pointless and should be deleted.

The only references to LimitsManager:

LimitsManager.calcFteLimits();

What is it doing there in the middle of the function?
Does it need to be in the middle?
Can it be at the start or at the end?
Or does it have a side effect that makes a difference for the code that appears before or after it?

If the code dealing with ChartBuilder is moved out to its own method,
then this part can be simplified:

if (this.currentReports.length > 0) {
    $scope.showGraph = true;
    ChartBuilder.buildChart(this.currentReports);
} else {
    $scope.showGraph = false;
}

To this:

$scope.showGraph = this.currentReports.length > 0;

If I make the optimistic and possibly completely false assumption that the statements in the function produce no side effects,
I would replace it with this code:

function updateCharts(ChartBuilder) {
    var currentReports = $scope.$parent.reports;
    if (currentReports.length > 0) {
        ChartBuilder.buildChart(currentReports);
        $scope.showGraph = true;
    } else {
        $scope.showGraph = false;
    }
}

function updateFilters(Filter) {
    Filter.clearFilters();
    Filter.setReports($scope.$parent.reports);
}

function updatePager(PagerFactory) {
    $scope.pager = PagerFactory.Create({
        items: this.currentReports
    });
}

function updateLimits(LimitManager) {
    LimitsManager.calcFteLimits();
}

Once again,
this decomposition is only useful if these functions really don't have side effects, which only you can tell.
If they have side effects, then the order in which you call them might matter.
In that case, you should at least document it.
A better solution would be to reorganize the code to convert the side effect to direct effect, visible in the code.