Processing a sequence of additions and deletions I am working on a program which manages a list, and must be able to insert new items, and delete ranges of items. I want the user to be able to specify the insertions and deletions in terms of the current state of the list, and not have to worry about how later operations will need an offset index in order to work on the correct items.
eg:

  delete: 4-5
  insert: 2,6

will insert an element before index 2, and another element before what was originally element 6, and delete the items originally at 4 and 5.

I want to convert these instructions into a list of deletions followed by insertions, which can be performed consecutively, ie the operations above would become:

  delete 4, delete 4, insert 2, insert 4

as the deletion at 4 shifts the following operations left, so the next deletion also acts at 4. The insertion of 2 shifts the insertion of 6 right, but the previous 2 subtractions shift it left.

I'm looking for a (hopefully readable) formula for converting the indices of these insertions and deletions into the form they will be in in the delete and insert lists.

So far, I have a rather unreadable python function, which would be difficult to maintain, but which seems to output the correct values:

ii = jj = kk = 0 # list indices
plus = minus = 0 # plus / minus offset
while ii < len(dellist) or jj < len(addlist):
    if jj < len(addlist): # in the list
        if addlist[jj] == kk: # at the specified index
            addlist[jj] -= minus # deletions happen first, so shift it back
            addlist[jj] += plus # then additions happen, so shift it forward
            jj += 1 # next addition
            plus += 1 # one more item inserted before the others
    if ii < len(dellist): # in the list
        if dellist[ii] == kk: # at the specified index
            dellist[ii] -= minus # previous deletions, so shift back
            ii += 1 # next deletion
            minus += 1 # one more item removed from before the others
    kk += 1 # next list element

I'm mainly concerned with having readable code, that I can easily modify later; and, ideally, something more modular, although I'm not sure how that would be achieved in this case.

So I made your code a function and then ran it on the example you gave.
I got to the following code:

def shift_indexes(dellist, addlist):
    ii = jj = kk = 0
    plus = minus = 0
    while ii < len(dellist) or jj < len(addlist):
        if jj < len(addlist):
            if addlist[jj] == kk:
                addlist[jj] -= minus
                addlist[jj] += plus
                jj += 1
                plus += 1
        if ii < len(dellist):
            if dellist[ii] == kk:
                dellist[ii] -= minus
                ii += 1
                minus += 1
        kk += 1
    return dellist, addlist

dellist = [4, 5]
addlist = [2, 6]
print('del: {}\nadd: {}'.format(*shift_indexes(dellist, addlist)))

It works fine with the input you gave, but it doesn't when I change addlist to 6, 2 not 2, 6.
And so I'll 'white box' test your code:

if addlist[0] == 0: # 6 == 0 : False
kk += 1             # kk = 1
if addlist[0] == 1: # 6 == 1 : False
kk += 1             # kk = 2
if addlist[0] == 2: # 6 == 2 : False
kk += 1             # kk = 3
if addlist[0] == 3: # 6 == 3 : False
kk += 1             # kk = 4
if addlist[0] == 4: # 6 == 4 : False
kk += 1             # kk = 5
if addlist[0] == 5: # 6 == 5 : False
kk += 1             # kk = 6
if addlist[0] == 6: # 6 == 6 : True
jj += 1             # jj = 1
kk += 1             # kk = 7
if addlist[1] == 7: # 2 == 7 : False
kk += 1             # kk = 8
if addlist[1] == 8: # 2 == 8 : False
...                 # loop for ever

The error is clear!

Ok, so lets change this.
We know that the deletes and the adds are in an order,
and that order is important!
We should be able to guess that inserts and removals should be able to happen anywhere.
We need the algorithm to work with numbers in any order.

And so honestly I'd recommend a new algorithm.

To make all the code easier I'd highly recommend that you change the input,
this input should be a list in the order you want to add and remove.
The items in this list should be (operation, index).

To save you figuring out how to change your current input to this form. You want to:

Make two lists. One of operations, one of indexes.
zip lists together.
Change list to list of list, from list of tuples (Python2) or iterator of tuples (Python3).

And so:

list_ = [list(i) for i in
         zip(['del'] * len(dellist) + ['add'] * len(addlist), dellist + addlist)]

Not too nice to read, but it makes the algorithm much nicer!
Your plus minus method doesn't work, and so I'm not going to talk about modifying it.

And so the simplest method from this is to transform the list_ whilst iterating through it.
When iterating we will want to pass it through enumerate this is to get the index in list_,
we also want the operator and the index that we want to shift relative to.
This results in:

for i, (operation, curr_index) in enumerate(list_):

From this we want to skip any operations that we don't know.
If you later decide to remove the horrible zip list comprehension stuff.
This is a simple if ...: continue:

if operation not in ('add', 'del'):
    continue

And now the main part of the algorithm.
You want to change the indexes after that item by +1 if the operator is add otherwise -1.

change = 1 if operation == 'add' else -1

You then want to add the change to all the items following the current item if the index is greater than the current one.
And so:

i += 1
for j, (_, index) in enumerate(list_[i:], i):
    if index >= curr_index:
        list_[j][1] += change

If we merge this all together, you should get:

def shift_indexes(dellist, addlist):
    # Transform input to better format
    list_ = [list(i) for i in
             zip(['del'] * len(dellist) + ['add'] * len(addlist), dellist + addlist)]
    for i, (operation, curr_index) in enumerate(list_, 1):
        if operation not in ('add', 'del'):
            continue
        change = 1 if operation == 'add' else -1
        for j, (_, index) in enumerate(list_[i:], i):
            if index >= curr_index:
                list_[j][1] += change
    return list_

If you have more than just add and del then you may want to use a dictionary.
The current 'dictionary' we have is:

d = {
    'add': 1,
    'del': -1
}

To use this dictionary you'd change the if and how to get change.
Using dict.get to get the change or None if it's not a valid item then we can use:

change = d.get(operator, None)
if change is None:
    continue

Either way this is much simpler to what you were doing.


Outputting results from a conditional row count across multiple tables Follow up question for: Conditional row count across 4 tables

After getting some excellent help from 200_success, i managed to output the SUM() total of my query using the following code:

get_results returns standard mysqli_assoc_array:

$row = $this->get_results($query);
$sum = $row[0];
 foreach($sum as $sum) {
    echo $sum;
}

Is this the best way to handle the result, are there any drawbacks / performance hits to doing it this way, how would you handle this querys result?

Query

$query = "SELECT SUM(inactive_count) AS inactive_count
FROM (
    SELECT COUNT(article_active) AS inactive_count
        FROM wcx_articles WHERE article_active = 0
    UNION ALL
    SELECT COUNT(video_active)
        FROM wcx_videos WHERE video_active = 0
    UNION ALL
    SELECT COUNT(app_active)
        FROM wcx_apps WHERE app_active = 0
    UNION ALL
    SELECT COUNT(link_active)
        FROM wcx_links WHERE link_active = 0
) AS wcx_objects";

MySQL

Your query looks fine, I'm not sure it could be further optimized of itself. What I would suggest though is to plug it into a stored procedure, and there are a few good reasons to do this.

Cleaner PHP script by only having your behavioral code in your script while just calling the procedure from there.
Easier to modify, e.g., if you found yourself using this SQL script in multiple PHP scripts and you had to make a change to it, you would have to change it everywhere, as opposed to just changing the stored procedure once.
Better SQL optimization. The way you have it now, every time you run the PHP script it sends an ad-hoc request to the SQL engine and it has to figure out the optimization each time. By storing the SQL script in the RDBMS the engine will optimize it ahead of time, so it will respond quicker each time.

Create procedure

You can run this just once:

DELIMITER |
CREATE PROCEDURE wcx_objects() AS
BEGIN

SELECT SUM(inactive_count) AS inactive_count
FROM (
    SELECT COUNT(article_active) AS inactive_count
        FROM wcx_articles WHERE article_active = 0
    UNION ALL
    SELECT COUNT(video_active)
        FROM wcx_videos WHERE video_active = 0
    UNION ALL
    SELECT COUNT(app_active)
        FROM wcx_apps WHERE app_active = 0
    UNION ALL
    SELECT COUNT(link_active)
        FROM wcx_links WHERE link_active = 0
) AS wcx_objects;

END|
DELIMITER ;

Call Procedure in PHP

Then from PHP all you need to do to get your result set is write this:

$query = "CALL wcx_objects();"


Good Vs. Evil - Battle For Middle Earth - CodeWars This is the code that I'm submitting for the "Good vs Evil" Kata on CodeWars:

https://www.codewars.com/kata/good-vs-evil/train/javascript

function goodVsEvil(good, evil) {
  good = good.split(' ');
  evil = evil.split(' ');

  //hobbits, men, elves, etc
  let goodWorth = [1, 2, 3, 3, 4, 10];
  //orcs, men, wargs, etc
  let evilWorth = [1, 2, 2, 2, 3, 5, 10];

  let goodArmyPoints = [];
  //multiply goodWorth by type:
  for (let i = 0; i < goodWorth.length; i++) {
    goodArmyPoints.push(good[i] * goodWorth[i]);
  }

  goodArmyPoints = goodArmyPoints.reduce(function (sum, value) {
    return sum + value;
  });

  let evilArmyPoints = [];
  for (let j = 0; j < evilWorth.length; j++) {
    evilArmyPoints.push(evil[j] * evilWorth[j]);
  }

  evilArmyPoints = evilArmyPoints.reduce(function (sum, value) {
    return sum + value;
  });

  if (evilArmyPoints < goodArmyPoints) {
    return "Battle Result: Good triumphs over Evil";
  } else if (evilArmyPoints > goodArmyPoints) {
    return "Battle Result: Evil eradicates all trace of Good";
  } else {
    return "Battle Result: No victor on this battle field";
  }

}

But I'm not sure what:

goodArmyPoints = goodArmyPoints.reduce(function (sum, value) {
    return sum + value;
  });

is doing exactly.

I see that reduce "executes a reducer function (which I've provided?) on each member of the array, resulting in a single output value".

But can someone please walk me through what .reduce(function (sum, value) is doing, exactly? Where is this function coming from? What are sum and value?

I'm still learning JavaScript and this is new to me. Thanks.

I see at least two things about your code that could be improved.

  let goodArmyPoints = [];
  //multiply goodWorth by type:
  for (let i = 0; i < goodWorth.length; i++) {
    goodArmyPoints.push(good[i] * goodWorth[i]);
  }

  goodArmyPoints = goodArmyPoints.reduce(function (sum, value) {
    return sum + value;
  });

Here you allocate a whole array to store the results of multiplications, and then reduce over it. This extra array is wasteful. It would be much clearer and cleaner (and faster) to write simply

  let goodArmyPoints = 0;
  for (let i = 0; i < goodWorth.length; ++i) {
    goodArmyPoints += good[i] * goodWorth[i];
  }

Another confusing thing about your original code is that in the line

  goodArmyPoints = goodArmyPoints.reduce(...);

you are assigning over goodArmyPoints. And not just assigning over its value, but actually changing its type — from "array of numbers" to "just a single number."

Since a variable's name usually reflects what's stored in it, and what's stored in it is usually a function of its type, it follows that variables of different types rarely end up with the same name. For example, if I had two variables, one that stored an array of point-values and one that stored a single point-value, I would probably name them goodScores and goodScore, or goodPartialScores and goodTotal, or something like that. But I definitely would not give them the same exact name!

By giving each variable a unique name, and never changing the type of an existing variable, we increase the understandability of the code. Because now, when the reader asks, "What is the type of variable goodArmyPoints?", we can actually give an answer! In your original code, if the reader asks "What is the type of variable goodArmyPoints?", all we can do is hedge: "Well, at this point in the code it's an array, but when we use it two lines later, it's a number..." That's a more complicated and confusing answer, which is just another way of saying that your original code is more complicated and confusing than the simplified code above.


Create numerical-key array from existing string-key array, with a given string-key as first item I have an array of available languages for my website, with a short ISO country code as the key for each language. I need to create a new array that contains the same info, but with numerical keys and where the first item in the new array is the current language.

I have this, which works fine:

$allLanguages = [
    'en' => ['locale' => 'en_US', 'code' => 'en', 'displayName' => 'English'],
    'sv' => ['locale' => 'sv_SE', 'code' => 'sv', 'displayName' => 'Swedish'],
    'de' => ['locale' => 'de_DE', 'code' => 'de', 'displayName' => 'German']
];

$currentLanguage = 'sv';

// Create new numerical-ordered array with current language info as first element
$langugeList = [];
foreach( $allLanguages as $key => $value ){
    if( $key == $currentLanguage )
        array_unshift($langugeList, $value);
    else
        array_push($langugeList, $value);
};

Result:

    array (
        0 =>
            array (
                'locale' => 'sv_SE',
                'code' => 'sv',
                'displayName' => 'Swedish',
            ),
        1 =>
            array (
                'locale' => 'en_US',
                'code' => 'en',
                'displayName' => 'English',
            ),
        2 =>
            array (
                'locale' => 'de_DE',
                'code' => 'de',
                'displayName' => 'German',
            ),
    )

Is there another, more elegant way of doing this?

I first had the idea to copy the array values and then sort them using usort() (keeping the original order except for the current language), but that doesn't seem like an improvement to neither performance nor "elegancy".

I just realized that one option would be

$langugeList = [ $allLanguages[$currentLanguage] ];
foreach( $allLanguages as $key => $value ){
    if( $key != $currentLanguage )
        $langugeList[] = $value;
};

PHP has a function built in for this: array_values()

<?php

$allLanguages = [
    'en' => ['locale' => 'en_US', 'code' => 'en', 'displayName' => 'English'],
    'sv' => ['locale' => 'sv_SE', 'code' => 'sv', 'displayName' => 'Swedish'],
    'de' => ['locale' => 'de_DE', 'code' => 'de', 'displayName' => 'German']
];

var_dump(array_values($allLanguages));

Outputs:

array(3) {
  [0]=>
  array(3) {
    ["locale"]=>
    string(5) "en_US"
    ["code"]=>
    string(2) "en"
    ["displayName"]=>
    string(7) "English"
  }
  [1]=>
  array(3) {
    ["locale"]=>
    string(5) "sv_SE"
    ["code"]=>
    string(2) "sv"
    ["displayName"]=>
    string(7) "Swedish"
  }
  [2]=>
  array(3) {
    ["locale"]=>
    string(5) "de_DE"
    ["code"]=>
    string(2) "de"
    ["displayName"]=>
    string(6) "German"
  }
}

Live Example

If you combine that function with this answer, you can move the desired array element to the top of the array before removing the keys:

<?php

$allLanguages = [
    'en' => ['locale' => 'en_US', 'code' => 'en', 'displayName' => 'English'],
    'sv' => ['locale' => 'sv_SE', 'code' => 'sv', 'displayName' => 'Swedish'],
    'de' => ['locale' => 'de_DE', 'code' => 'de', 'displayName' => 'German']
];

$currentLanguage = 'sv';

// Move the desired language to the front of the array
$allLanguages = [$currentLanguage => $allLanguages[$currentLanguage]] + $allLanguages;

// Get a new array with just the values
$allLanguages = array_values($allLanguages);

var_dump($allLanguages);

Live Example

As a one liner:

<?php

$allLanguages = array_values([$currentLanguage => $allLanguages[$currentLanguage]] + $allLanguages);

Live Example

As a helper function:

<?php

function processLanguages($current, $languages) {
    return array_values([$current => $languages[$current]] + $languages);
}

$allLanguages = [
    'en' => ['locale' => 'en_US', 'code' => 'en', 'displayName' => 'English'],
    'sv' => ['locale' => 'sv_SE', 'code' => 'sv', 'displayName' => 'Swedish'],
    'de' => ['locale' => 'de_DE', 'code' => 'de', 'displayName' => 'German']
];

var_dump(processLanguages('sv', $allLanguages));

Live Example


Random assignment function with caveat Assign equal number chores to each person (assertion made elsewhere to ensure chores % number of people == 0) with the stipulation that each chore must not be one which the person was assigned the previous time.

My simpleton solution (there has to be a cleverer way):

import random

chores = ["hoovering", "dusting", "wash dishes", "tidy garden",
          "clean windows", "empty dishwasher", "dust", "cook"]

people_data = {"David": {"email": "example@gmail.com",
                         "chores" : []},
               "Mark": {"email": "example@gmail.com",
                         "chores": []},
               "Anaya": {"email": "example@gmail.com",
                         "chores": []},
               "Cooper": {"email": "example@gmail.com",
                          "chores": []}
               }

prev_assignment_data = None

def assign_chores(chore_list, prev_assignment_data, people_data):
    """Returns a dict with assign chores to each person

    Arguments:
    chore_list            --  a list of the chores to be assigned
    prev_assignment_data  --  if there has been prev chore assignments this
                              will be a dict containing said assignments.
                              Otherwise, it will have no value ('None')
    people_data           --  a dict of the names and the email address
                              associated with those names. Assigned chores
                              will be appended to this dict and dict
                              returned.
    """

    # if no previous data available, assign each a random chore
    if not prev_assignment_data:
        while chore_list:
            for name in people_data.keys():
                chore = random.choice(chore_list)
                chore_list.remove(chore)
                people_data[name]["chores"].append(chore)

    # if prev data available, assign each chores not the same as previous
    else:
        new_chores = False
        while not new_chores:
            chore_list_copy = chore_list
            for name in people_data.keys():
                # get all chores still available and which are not those
                # the person was assigned the previous time
                avail_chores = [chore for chore in chore_list_copy if chore not
                                in prev_assignment_data[name]["chores"]]

                if avail_chores:
                    chore = random.choice(avail_chores)
                    people_data[name]["chores"].append(chore)
                    chore_list_copy.remove(chore)

                # if only chores remaining are those the person did previously,
                # restart entire assignment process
                else:
                    break
            # all chores assigned and are different to those person did prev
            if not chore_list_copy:
                new_chores = True

    return people_data

assigned_chores = assign_chores(chores, prev_assignment_data,
                                people_data)
print(assigned_chores)

Well, you have your code in a function, but it is still top down. It makes it harder to read, and much harder to improve.

If you instead break the code down into separate functions you'll have an easier time improving code. You'll also not repeat your self.

Make use of annotations!

def assign_chores(chore: list, prev_assignment: dict or None, persons: dict):
    ...

that way you don't have to litter your variable names with clues to what types they might be.

I think your trying to create a deep copy and not a shallow copy:

chore_list_copy = chore_list

to make a deep copy;

chore_list_copy = chore_list[:]

that way you'll actually get a copy.

for name in people_data.keys():

is the same as

for name in people_data:

Instead of working with the objects in people_data i suggest you work with data structures. It becomes easier to manipulate that way.

The data you care about can be represented with:

chores_dist = [[] for _ in range(len(persons))]

and if previous is summited:

prev_chores = [person["chores"] for person in prev_assigment.values()]

Work with data structures instead.

Protect your code by:

def main():
    ...

if __name__ == '__main__':
    main()

that way your code don't get executed if you import your code into another file.

Instead of choosing a random chore, you could just shuffle them all beforehand, that way the randomness task is done.

chores = chores[:]
shuffle(chores)

Another way to call your function then to send in a None

def assign_chores(chore_list, prev_assignment_data, people_data):
    ...

prev_assignment_data = None
    assigned_chores = assign_chores(chore_list, prev_assignment_data,
                                    people_data)

is to define it in your function

def assign_chore(chores: list, persons: dict, prev_assignment: dict=None):
    ...

now you can call it like

people_data = assign_chore(chores, people_data)
people_data = assign_chore(chores, people_data, some_previous_data)

When I broke down your code I did it like this:

from random import shuffle

def assign(chores: list, persons: dict):
    for key, person in enumerate(persons):
        persons[person]["chores"] = chores[key]
    return persons

def get_shuffled_chores(chores: list, persons: dict):
    chores = chores[:]
    shuffle(chores)
    chores_dist = [[] for _ in range(len(persons))]
    for key, i in enumerate(range(len(chores))):
        chores_dist[key % len(persons)] += [chores.pop()]
    return chores_dist

def assign_without_regard(chores: list, persons: dict):
    return assign(get_shuffled_chores(chores, persons), persons)

def is_repetitive(news: list, olds: list):
    for new, old in zip(news, olds):
        if any(chore in old for chore in new):
            return False
    return True

def assign_with_regard(chores: list, prev_assigment: dict, persons: dict):
    prev_chores = [person["chores"] for person in prev_assigment.values()]
    new_chores = get_shuffled_chores(chores, persons)
    return assign(new_chores, persons) \
        if not is_repetitive(new_chores, prev_chores) \
        else assign_chore(chores, prev_assigment, persons)

def assign_chore(chores: list, persons: dict, prev_assignment: dict=None):
    if prev_assignment is None:
        return assign_without_regard(chores, persons)
    return assign_with_regard(chores, prev_assignment, persons)

def main():
    chores = ["hoovering", "dusting", "wash dishes", "tidy garden",
              "clean windows", "empty dishwasher", "dust", "cook"]

    people_data = {"David": {"email": "example@gmail.com",
                             "chores": []},
                   "Mark": {"email": "example@gmail.com",
                            "chores": []},
                   "Anaya": {"email": "example@gmail.com",
                             "chores": []},
                   "Cooper": {"email": "example@gmail.com",
                              "chores": []}
                   }

    people_data = assign_chore(chores, people_data)
    print(people_data)
    print(assign_chore(chores, people_data, people_data))

if __name__ == '__main__':
    main()


Printing polynomials I am taking a class on ruby and our assignment is to take user input and print out a polynomial. Wondering if I can get any feedback to how to improve my code.

class PolynomialElements
  attr_accessor :element, :size

  def printElement
    if size.to_i == 0
      num = "#{@element}"
    elsif size.to_i == 1
      if element.to_i.abs == 1
        num = "x"
      else
        num = "#{@element}x"
      end
    else
      if element.to_i.abs > 1
        num = "#{@element}x^#{@size}"
      elsif element.to_i.abs == 1
        num = "x^#{@size}"
      end
    end
  end
end

askAgain = true
polyArray = Array.new

while askAgain
  puts "How many numbers do you want to enter? "
  numString = gets
  num = numString.to_i
  while num > 0
    puts "Enter a value for the Polynomial "
    value = gets
    polyArray.push(value.chomp)
    num -= 1
  end
  outputArray = Array.new
  sizeOfArray = polyArray.length
  polyArray.each do |x|
    var = PolynomialElements.new
    sizeOfArray -= 1
    var.size = sizeOfArray
    if x.to_i != 0
      var.element = x
      if var.element.to_i > 0
        outputArray.push("+")
        outputArray.push(var.printElement)
      elsif var.element.to_i < 0
        outputArray.push(var.printElement)
      end
    end
  end

  if outputArray[0] == "+"
    outputArray.delete_at(0);
  end

  outputArray.each do |x|
    print x
  end
  puts

  puts "Enter y to enter new number or anything else to quit"
  cont = gets
  if cont.chomp != "y"
    askAgain = false
  else
    polyArray.clear
  end
end

Ruby agreement is to use snake_case to name methods and variables, and not javaCase. While you could say it's a matter of taste, it's so common in Ruby world you would do better to just stick with it. Ruby programmers also tend to push for initializing arrays like this:

polyArray = []

Your PolynomialElements class is not how you use OOP. It has accessor, but what you pass to them aren't parts of its state - those are arguments for printElement. More proper abstraction would be to make it hold an array of coeficients, and iterate over it to form a string.

class Polynomial
  attr_accessors :coeficients # I think this is a proper name for elements (?)

  def initialize coeficients_array = [0] # default value, just in case
    coeficients = coeficients_array
  end

  def to_s
    coefficients.each_with_object("").with_index do |(coef, str), idx|
      # ...
    end
  end
end

Than, you could use it like:

polynomial = Polynomial.new poly_array
puts polynomial.to_s

Notice that you don't need to operate on array of characters - Ruby string allows you to work in the same way, just use append instead of push, and then you just print/puts it instead of printing each character separately.

Generally speaking, you barely ever need to keep track of index of iteration manually with Ruby. This:

num = numString.to_i
while num > 0
  puts "Enter a value for the Polynomial "
  value = gets
  polyArray.push(value.chomp)
  num -= 1
end

could be much better written as

num_string.to_i.times do
  # ...
end

Ruby way to do (potentially) infinite loop would be:

loop do
  polyArray = []
  # ...
  cont = gets
  break if cont.chomp != "y"
end

This seems more readable, as we directly talk to our loop itself by breaking it, instead of using variable as a "middleman".
Also notice how initializing array inside a loop eliminates need for clearing it.


Checking String with is_numeric in C I am a newbie in stack exchange code review. I just wrote a C function where the function checks if the given string is numeric or not. What do you think about my way of doing this? And could this be done in other ways?
#include <stdio.h>
#include <stdbool.h>

bool is_numeric(const char* str)
{
    while (isspace(*str))
       str++;

    if (*str == '-' || *str == '+')
       str++;

    while (*str)
    {
        if (!isdigit(*str) && !isspace(*str))
            return false;
        str++;
    }

    return true;
}

int main(int argc, char** argv)
{
  printf("%s\n", is_numeric("123436")  ? "true" : "false"); // should be true
  printf("%s\n", is_numeric("123.436") ? "true" : "false"); // should be false
  printf("%s\n", is_numeric("    567") ? "true" : "false"); // should be true
  printf("%s\n", is_numeric("235   ")  ? "true" : "false"); // should be true
  printf("%s\n", is_numeric("794,347") ? "true" : "false"); // should be false
  printf("%s\n", is_numeric("hello")   ? "true" : "false"); // should be false
  printf("%s\n", is_numeric("-3423")   ? "true" : "false"); // should be true
}

Thanks in advance!

regarding:
if (!isdigit(*str) && !isspace(*str))

the isdigit() handles 0...9, so catches if any of the passed in char array is not numeric.
The && !isspace(*str))  has nothing to do with numeric values


Very basic Context Free Grammar in Java I wrote this program for an assignment, thus I had some requirements as far as the format of the cfg.txt file and some basic other classes that we had to use. Other than that, I am curious if there is a way to drastically simplify this code. Although the program runs fine and produces the desired output, is there a better way to go about writing this? (What initially spurred my concern was the iterateData method. I did not like the code repetition and thought it may be convenient to "reuse" some of it. However, in doing so, I then introduced numerous class variables to prevent from having to pass in 7 instance variables to the method. I can't say that I'm all too thrilled about this...) Regardless, advice and suggestions appreciated.

Thank you.

import java.util.Scanner;
import java.io.*;
import java.util.Random;

public class ContextFreeGrammar {

    private static String nt, useExp = "";
    private static int totalWeight = 0, randomNum;
    private static ArrayUnsortedList<Production> data = new ArrayUnsortedList<Production>();
    private static Production pObj;

    public static void main(String[] args) throws IOException {

        String result = "<S>";
        File myFile = new File("cfg.txt");
        Scanner fileScan = new Scanner(myFile);

        // Read and process each line of the file
        while (fileScan.hasNext()) {
            Production p = new Production(fileScan.nextLine());
            data.add(p);
        }

        // If the result string still contains non-terminals
        while (result.contains("<")) {

            // Get the non-terminal
            nt = result.substring(result.indexOf('<')+1, result.indexOf('>'));

            // Cannot condense because we have an ambiguous
            // totalWeight. Hence, we need to iterate twice:
            // 1. To generate appropriate random number from totalWeight
            // 2. To determine when the totalWeight exceeds that random number.

            iterateData(false);

            Random rand = new Random(); // Generate a random number object
            randomNum = rand.nextInt(totalWeight - 1) + 1; // Generate actual random number

            // Resets
            totalWeight = 0;
            data.reset();

            iterateData(true);

            // Replace the non-terminal with the expression to use
            result = result.replaceFirst("<" + nt + ">", useExp);
            totalWeight = 0; // Reset totalWeight;
        }

        System.out.println(result);
    }

    public static void iterateData(boolean GETEXP) {
        // Iterate through list again
        for (int i = 0; i < data.size(); i++) {

            // Get the current value
            pObj = data.getNext();

            // Keep track of weight
            if (nt.equalsIgnoreCase(pObj.getNonTerminal())) {
                totalWeight += pObj.getWeight();

                if (GETEXP) {
                    if (totalWeight > randomNum) {
                        useExp = pObj.getExpression(); // This is expression to use
                        break;
                    }
                }
            }
        }
    }
}

My cfg.txt file is as such:

80 <S> = My homework is late because <reason>.
20 <S> = I want to <action> instead of writing this program.
40 <reason> = <who> ate it
40 <reason> = I set it on fire because I was cold
20 <reason> = I didn't feel like doing it
30 <who> = Deep Shah
70 <who> = my pet <animal>
10 <animal> = dog
20 <animal> = narwhal
50 <animal> = python
20 <animal> = velociraptor
30 <action> = go on a vacation
30 <action> = indulge in a giant feast
40 <action> = frolic in the snow

It is said that "a method should do one thing, and it should do that one thing well". Your iterateData method is being used to do two separate things, depending on the parameter you send it.
If your ArrayUnsortedList is this class (which really could use a code review itself) then I don't really understand why you are using it. The way I see it is that you could use a regular ArrayList.
What you are referring to as "class variables" are static variables. It would be better to use them as instance variables. Currently you can't have two ContextFreeGrammar objects at once, each with it's own state. Remove the static keyword and *create an instance of ContextFreeGrammar to properly use it as an instance (which is a lot better practice, although you might not have learned about such things yet. If you haven't learned about it yet, you should ask your teacher about it)
Only create a new Random object once. Random objects are meant to be re-used. When they are initialized, they get a random seed set depending on the system clock time. Repeatedly creating a Random object gives a loss in randomness.
Instead of your current iterateData method, consider using one method such as int calculateTotalWeight(List<Production> list, String nonTerminal) and one String determineExpression(List<Production> list, String nonTerminal, int weightRandom). Determining such an important behavior of your method by sending it a true/false value makes your code harder to understand. You don't need to pass seven variables to the method when it only uses two or three.


Create an associative array with values as an array from an another associative array I have a query that returns an array or associative arrays of ids and years. It looks like this:

[{"id":8,"year":1950},{"id":9,"year":1950},{"id":8,"year":1951},{"id":9,"year":1951},{"id":8,"year":1952}]

There is a fixed number of ids, but they each have many years associated. I wrote the following script to turn the results of the query into a more simple associative array with the ids as keys and an array of years as the value.

$rows = array("8" => array(),"9" => array());

foreach(array_keys($rows) as $key){
    foreach($results as $result){
        if ($key == $result['id']){
            array_push($rows[$key], $result['year']);
        }
    }
}

returns:

{"8":[1950,1951,1952],"9":[1950,1951]}

I would like to change this so that the initial $rows array is not hard-coded (ie get the keys from the initial query). I would also like to avoid the nested foreach/foreach/if nastiness as well if possible.

By iterating through array_keys($rows), you are not using the $results associative array effectively.  You should be able to just write this:

foreach ($results as $result) {
    $rows[$result['id']][] = $result['year'];
}

Also, there is no need to call array_push() if you are appending just one item.  You can just assign $rows[] = with no index to indicate that you want to append one element.


TimeSpan don't support years so how do I deal with it? Is there could be smarter solution? explain:

from start day till now I've got 7.7 mb size, how long it will be to make it 10 gb size

open System

let dd = (DateTime.Now - DateTime.Parse("12/09/2012")).Days
let oneday = 7.7 / Convert.ToDouble(dd)

let in10gb = Convert.ToInt32( Math.Round (10.0 * 1024.0 / oneday) )
let years = Convert.ToInt32( Math.Round (float in10gb / 365.0) )
let mutable months = Convert.ToInt32( Math.Round (float (in10gb - years * 365) / 30.0) )
let days =
    let d = in10gb - years * 365 - months * 30
    if d > 0 then d else month = month - 1; (30 - d)

printf "%d years %d months %d days" years months days
Console.ReadKey() |> ignore

Also / 30.0 for months is dirty hack here... I'm not sure how to avoid it in easy way.

I would propose an alternative method of calculating your time, using seconds and DateTimes:

open System

let startDate = DateTime.Parse ("2012-09-12")
let now = DateTime.Now;
let currentRuntime = (now - startDate).TotalSeconds
let timePerGig = currentRuntime / 7.7;
let tenDate = startDate + TimeSpan.FromSeconds (10.0 * timePerGig);

With that done, you can do whatever you like to represent the final date relative to the current date.

An overly simplistic example is as follows:

printf "%d years %d months %d days" (finalDate.Year - now.Year) (finalDate.Month - now.Month) (finalDate.Day - now.Day)

Of course, you would have to account for roll-over for days and months in any final piece of code, but it illustrates how you could pull the date parts back out.


Function to get the next character of a giving position of strings of a dataframe I want to get the next character giving a position of a another character of a string in a dataframe. If we have browsed every character of a string I should go to the next line.

And to do so I have written the function bellow.

def get_char(df, y, z):
    if z < len(df[0][y])-1:
        return df[0][y][z+1]
    elif z == len(df[0][y])-1:
        if y < len(df[0])-1:
            return df[0][y+1][0]

so for the dataframe :

ar = np.array(["aba", "bcb", "zab"])
df = pd.DataFrame(ar)

if I

print get_char(df, 1, 2)

gives me z

and

print get_char(df, 2, 2)

should return nothing , in my function it returns None

I am pretty sure that I can do it with a much easier way.

My dataframe will have only one column.

Maybe this helps?  It will save you some if statements by just joining strings (although it will only read one position to the next dataframe element at the right in case you're in the last character of the y item).

So take care in case you have empty strings and you want your search to keep jumping over to the next item (in that case you can just delete y+2 in the code and leave [y:,0].

import numpy as np
import pandas as pd

ar = np.array(["aba", "bcb", "zab"])
df = pd.DataFrame(ar)

def get_char(df, y, z):
    a = ''.join(df.iloc[y:y+2,0])
    try:
        return a[z+1]
    except:
        return None

print(get_char(df, 1, 2))
# z
print(get_char(df, 2, 2))
# None


unique_ptr basic implementation for single objects This is an implementation to simulate the basic functionality of unique_ptr.
This doesn't provide features like custom deleter and make_unique().

I would really appreciate any feedback to improve the below code, any other api's that I should be providing etc.

my_unique_ptr.h

#ifndef MY_UNIQUE_PTR_H_
#define MY_UNIQUE_PTR_H_

#include <utility>

namespace kapil {
  template <typename T>
  class unique_ptr final {
    private:
      T* ptr_;
      unique_ptr(const unique_ptr&) = delete;               // Make unique_ptr non copy constructible
      unique_ptr& operator = (const unique_ptr&) = delete;  // Make unique_ptr non copy assignable

    public:
      explicit unique_ptr (T* ptr = nullptr) noexcept
        : ptr_{ptr} { }

      unique_ptr(unique_ptr<T>&& rval) noexcept               // Move constructor
        : ptr_{rval.ptr_} {
        rval.ptr_ = nullptr;
      }

      unique_ptr& operator = (unique_ptr&& rhs) noexcept {   // Move assignment
        delete ptr_;
        ptr_ = rhs.ptr_;
        rhs.ptr_ = nullptr;
        return *this;
      }

      ~unique_ptr() noexcept {
        delete ptr_;
      }

      T* release() noexcept {
        T* old_ptr = ptr_;
        ptr_ = nullptr;
        return old_ptr;
      }

      void reset(T* ptr = nullptr) noexcept {
        delete ptr_;
        ptr_ = ptr;
      }

      void swap(unique_ptr& rhs) noexcept {
        std::swap(ptr_, rhs.ptr_);
      }

      T* get() const noexcept {
        return ptr_;
      }

      explicit operator bool() const noexcept {
        return (ptr_ != nullptr);
      }

      T& operator * () const {
        return *ptr_;
      }

      T* operator -> () const noexcept {
        return ptr_;
      }

      friend bool operator == (const unique_ptr& lhs, const unique_ptr& rhs) {
        return lhs.get() == rhs.get();
      }

      friend bool operator != (const unique_ptr& lhs, const unique_ptr& rhs) {
        return !(lhs == rhs);
      }
  };

  template <typename T>
  void swap(unique_ptr<T>& lhs, unique_ptr<T>& rhs) {
    lhs.swap(rhs);
  }
} //kapil

#endif

Don't mark your class final without a good reason. It inhibits user-freedom.
The default-access for members of a class is already private.
Explicitly deleting copy-constructor and copy-assignment-operator is superfluous, as you define move-constructor and move-assignment, which already suppresses them. Still, some assert being explicit adds clarity.
I wonder why you didn't declare construction from T* to be constexpr...
Try to consistently use the injected class-name (unique_ptr), instead of sporadically naming the template-arguments (unique_ptr<T>).
You are missing implicit upcasting in the move-ctor and move-assignment-operator.

template <class U, class = std::enable_if_t<
    std::has_virtual_destructor<T>() && std::is_convertible<U*, T*>()>>
unique_ptr(unique_ptr<U>&& other) noexcept
: ptr_(other.release())
{}

template <class U>
auto operator=(std::unique_ptr<U>&& other) noexcept
-> decltype((*this = unique_ptr(other))) {
    return *this = unique_ptr(other);
}

Take a look at std::exchange(object, value) from <utility>. It allows you to simplify some of your code.
If you use move-and-swap, you could isolate freeing of the referee to the dtor. Having it at only one place ensures you always do it the same, and is a good first step for retrofitting custom deleters. Not to mention that it in many cases simplifies the implementation.
(ptr != nullptr) can be simplified to ptr. In contexts where you have to force the type, !!ptr.
Why are op==() and op!=() inline-friend-functions, but swap() isn't? That's inconsistent. It's especially puzzling as they are all written to use the public interface only.
There is exactly one place where you don't have a single empty line between two functions, but two. Yes, that's nothing big.


Structure JavaScript code I am new to JavaScript development, so I'm seeking help in guidelines on how I can better organize my code in a better way. This is what I have for a small app I am working on:

var app = app || {};

app.p = function(){ ... };
app.q = function(){ ... };
app.r = function(){ ... };

app.init = function(){ ... };
app.onload = function(){
    if (window.applicationCache) {
        window.applicationCache.addEventListener('updateready', function() {
            // do stuff
        });
    }
};

window.addEventListener('load', app.onload);
window.addEventListener('online',app.p);

Zepto(function($){
    app.init();
    app.p();

    $('#aaaa').change(function(){
        app.q();
        app.r();
    });

});

Is it good enough that I am splitting my functions and then adding them to a single global object? Any better way?
I am using some native window.addEventListener() calls. Is it ok to keep native code, even when you have a library loaded on the page, just for the performance gain? Or does it depend on the size of codebase?  Is it ok for small enough and probably moving in a large one?
How the whole execution begins, like Zepto kickstarts init() function on document ready event and then I take it from there, is this how I should be doing it or is there a better way?

Any other suggestions welcome!

Namespacing

  1) Is it good enough that I am splitting my functions and then adding them to a single global object? Any better way?

Yes, it's a good and popular approach. It's simple and it works.

You might consider using closures to create app.p, app.q and app.r. I think this is referred to as using IIFEs (immediately invoked function expressions) [details]. Right now, app.p, app.q and app.r have no persistent private scope. The only private scope they will have is whatever happens within the function, itself. If they needed to keep track of something, they will need to use a variable in the global scope because it is the only scope outside of the function. Using an 'IIFE' would allow there to be some persistent and private state for each function:

app.p = (function() {
    var someCounter = 0;
    return function(){
        someCounter++;
        // do stuff
    }
})();

Now, app.p can access the someCounter variable but nothing else can. Some people don't care for this, but I'm a fan.

For larger projects, the var app = app || {}; might become unwieldy. Something I've been working with a bit that allows a little more flexibility is at the bottom of this page:

http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/

function namespace(namespaceString) {
    var parts = namespaceString.split('.'),
        parent = window,
        currentPart = '';

    for(var i = 0, length = parts.length; i < length; i++) {
        currentPart = parts[i];
        parent[currentPart] = parent[currentPart] || {};
        parent = parent[currentPart];
    }

    return parent;
}

Using this approach, to define something in a namespace (modified from the same page):

// using an immediately invoked function expression (IIFE)
// keeps things private to the function and prevents spillage
// of variables into this outer scope
(function() {
    // retrieve what exists or make a new definition
    var examples = namespace('io.examples');

    // add something to it (another IIFE)
    examples.log = (function() {
        // can have private variables
        var numMsgs = 0,
            // for this, the api is an invokable function: api(), but
            // we will also add more functions to it: api.subFunction()
            // these will all have access to the numMsgs private variable
            api = function() {
                numMsgs++;
                console.log.apply(console, arguments);
            };
        api.getMsgCount = function() {
            return numMsgs;
        }
        // returning api sets io.examples.log to the api function
        return api;
    })();
})();

And, to use something from a namespace:

// retrieve what exists (we already made something,
// so it will not create an empty place-holder)
var log = namespace('io.examples.log');

// the api was a function, so we can call it
// or access the sub-function we attached to it
log('hello');
var numSoFar = log.getMsgCount();

A related topic is AMDs (asynchronous module definitions) and dependency-injection (which is rather a sub-set of what AMDs set out to do, I think). Some options are requireJS, yepnope, and angularjs (which entails committing the project to the angularjs framework). I'm sure there are a lot of others, I just don't know them.

native addEventListener

  2) I am using some native window.addEventListener() calls...

Historically, when I avoid using a library it's because I don't want to either load it. That being said, the performance difference is impressive. Most things I write are driven from UI events, which are generally rare (how often are you clicking?), and the performance difference between the two doesn't matter. I would say it doesn't even matter if the code base is large. Seems like the main thing would be whether you are handling events that occur super-frequently or not.

It's also worth noting that creating a dependency on a library can hinder the reusability of whatever you're writing.

init process

  3) How the whole execution begins, like Zepto kickstarts init() function

If you're using native event listeners, then you don't have a choice, it can't go in the Zepto init. If you're using the Zepto init process, I would just put it in the Zepto(...) if a) nothing else needs a reference to it and b) you don't need it before then, anyway.


Form for OTP entry with six single-character text fields I am working on an app in which I have to pass 6 digits OTP through 6 textFields in which you to provide only one character and after that it automatically goes to another textField. I created 6 textFields outlets and used this code.

override func viewDidLoad() {
    super.viewDidLoad()

txtOTP1.delegate = self
txtOTP2.delegate = self
txtOTP3.delegate = self
txtOTP4.delegate = self
txtOTP5.delegate = self
txtOTP6.delegate = self

}

And I used this logic to create the functionality

 func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool {
    // Range.length == 1 means,clicking backspace
    if (range.length == 0){
        if textField == txtOTP1 {
            txtOTP2?.becomeFirstResponder()
        }
        if textField == txtOTP2 {
            txtOTP3?.becomeFirstResponder()
        }
        if textField == txtOTP3 {
            txtOTP4?.becomeFirstResponder()
        }
        if textField == txtOTP4 {
            txtOTP5?.becomeFirstResponder()
        }
        if textField == txtOTP5 {
            txtOTP6?.becomeFirstResponder()
        }
        if textField == txtOTP6 {
            txtOTP6?.resignFirstResponder()
        }
        textField.text? = string
        return false
    }else if (range.length == 1) {
        if textField == txtOTP6 {
            txtOTP5?.becomeFirstResponder()
        }
        if textField == txtOTP5 {
            txtOTP4?.becomeFirstResponder()
        }
        if textField == txtOTP4 {
            txtOTP3?.becomeFirstResponder()
        }
        if textField == txtOTP3 {
            txtOTP2?.becomeFirstResponder()
        }
        if textField == txtOTP2 {
            txtOTP1?.becomeFirstResponder()
        }
        if textField == txtOTP1 {
            txtOTP1?.resignFirstResponder()
        }
        textField.text? = ""
        return false
    }
    return true
}

But it is very long and messy. Is there anyway I can make it simple?

Your solution to this particular problem is fine in its own way. However when it comes to scaling, it will become quite messy. Since I don't see any scope of improvement/tweaking in your approach, I suggest an alternative solution.

As pointed out in the comments, you can get what you want with Outlet Collections, since they are basically an array of UIKit objects, thus making it easy to manipulate them for our specific case.

Step 1

First off, connect your textfields to an Outlet Collection, and delegates in Interface Builder itself (as shown in the image below), which gets rid of the redundant

@IBOutlet var txtOTP1: UITextField!

and

txtOTP1.delegate = self

statements.

@IBOutlet var textFieldsOutletCollection: [UITextField]!

Step 2

We are going to use a dictionary with the textfield as the key and its corresponding index in the outlet collection as the value:

var textFieldsIndexes:[UITextField:Int] = [:]

override func viewDidLoad() {
    for index in 0 ..< textFieldsOutletCollection.count {
        textFieldsIndexes[textFieldsOutletCollection[index]] = index
    }
    super.viewDidLoad()
}

Step 3

The basic idea is, we can get the index of the textfield in our collection by supplying (to the dictionary) the textfield object we get in shouldChangeCharactersIn method, and then make the next or previous textfield the first responder:

enum Direction { case left, right }

func setNextResponder(_ index:Int?, direction:Direction) {

    guard let index = index else { return }

    if direction == .left {
        index == 0 ?
            (_ = textFieldsOutletCollection.first?.resignFirstResponder()) :
            (_ = textFieldsOutletCollection[(index - 1)].becomeFirstResponder())
    } else {
        index == textFieldsOutletCollection.count - 1 ?
            (_ = textFieldsOutletCollection.last?.resignFirstResponder()) :
            (_ = textFieldsOutletCollection[(index + 1)].becomeFirstResponder())
    }

}

Step 4

Now the shouldChangeCharactersIn method becomes more simple and clean:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if range.length == 0 {
        setNextResponder(textFieldsIndexes[textField], direction: .right)
        textField.text = string
        return true
    } else if range.length == 1 {
        setNextResponder(textFieldsIndexes[textField], direction: .left)
        textField.text = ""
        return false
    }
    return false
}

Final Code

With all the above code combined, your view controller should look like this:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textFieldsOutletCollection: [UITextField]!

    var textFieldsIndexes:[UITextField:Int] = [:]

    override func viewDidLoad() {
        super.viewDidLoad()
        for index in 0 ..< textFieldsOutletCollection.count {
            textFieldsIndexes[textFieldsOutletCollection[index]] = index
        }
    }

    enum Direction { case left, right }

    func setNextResponder(_ index:Int?, direction:Direction) {

        guard let index = index else { return }

        if direction == .left {
            index == 0 ?
                (_ = textFieldsOutletCollection.first?.resignFirstResponder()) :
                (_ = textFieldsOutletCollection[(index - 1)].becomeFirstResponder())
        } else {
            index == textFieldsOutletCollection.count - 1 ?
                (_ = textFieldsOutletCollection.last?.resignFirstResponder()) :
                (_ = textFieldsOutletCollection[(index + 1)].becomeFirstResponder())
        }

    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        if range.length == 0 {
            textField.text = string
            setNextResponder(textFieldsIndexes[textField], direction: .right)
            return true
        } else if range.length == 1 {
            textField.text = ""
            setNextResponder(textFieldsIndexes[textField], direction: .left)
            return false
        }

        return false

    }

}

This method should theoretically work for infinite number of UITextFields with same amount of code as opposed to your approach, in which the amount of code is dependent on the number of textfields used, which is not handsome/pretty.


Check if one shape is in another shape I have a code to check if one shape (circle or square) envelops another. I have used this code. It gives true if the this object envelops the passed shape. Can anyone suggest me an improvement or better alternate method?

public boolean envelops(Shape s) {
boolean flag = true;
double distance = 0.0;
if(s instanceof Square){ //check if the shape is a Square
 Point bottomLeft= new Point(((Square)s).getTopLeft().getX(),((Square)s).getTopLeft().getY()-((Square)s).getSideLength()); //calculating the cordinates of the square
 Point bottomRight= new Point(((Square)s).getTopLeft().getX()+((Square)s).getSideLength(),((Square)s).getTopLeft().getY()-((Square)s).getSideLength());
 Point topRight= new Point(((Square)s).getTopLeft().getX()+  ((Square)s).getSideLength(),((Square)s).getTopLeft().getY());

 ArrayList<Point> points = new ArrayList<Point>(); //storing points in a ArrayList of points
 points.add(((Square)s).getTopLeft());
 points.add(bottomLeft);
 points.add(topRight);
 points.add(bottomRight);
    for(int i=0; i<points.size(); i++)
       {
          distance= this.center.distance(points.get(i));  //finding ditance of each cordinate from the center of the circle
          if(distance-this.radius>Shape.TOLERANCE) flag= false;      //if the distance is greater than the radius then flag becomes false, ie., the cordinate is outside the circle

       }
 }

if(s instanceof Circle){
 distance=this.center.distance(((Circle)s).getCenter());  //finding distance between the centers of the 2 circles
 distance= distance +((Circle)s).getRadius();
 if(distance- this.getRadius()> Shape.TOLERANCE || distance==this.getRadius()){ //The method will return false if both circles have 0 radius
    flag=false;                                           //make flag false if the distance is more than the radius of the object Circle
 }
}

return flag;
}

Your indentation is quite messy. Indentation is usually 4 spaces in Java, so use 4 spaces.
Including some other minor readability improvements (such as each line is a maximum of 80 characters), your code will look like:
public boolean envelops(Shape s) {
    boolean flag = true;
    double distance = 0.0;
    if (s instanceof Square) { // check if the shape is a Square
        // calculating the coordinates of the square
        Point bottomLeft = new Point(((Square) s).getTopLeft().getX(),
                ((Square) s).getTopLeft().getY() - ((Square) s).getSideLength());
        Point bottomRight = new Point(((Square) s).getTopLeft().getX() +
                ((Square) s).getSideLength(),
                ((Square) s).getTopLeft().getY() - ((Square) s).getSideLength());
        Point topRight = new Point(((Square) s).getTopLeft().getX() +
                ((Square) s).getSideLength(), ((Square) s).getTopLeft().getY());

        // storing points in a ArrayList of points
        ArrayList<Point> points = new ArrayList<Point>();
        points.add(((Square) s).getTopLeft());
        points.add(bottomLeft);
        points.add(topRight);
        points.add(bottomRight);
        for (int i = 0; i < points.size(); i++) {
            //finding ditance of each cordinate from the center of the circle
            distance = this.center.distance(points.get(i));
            // if the distance is greater than the radius then flag becomes false,
            // ie., the cordinate is outside the circle
            if (distance - this.radius > Shape.TOLERANCE) flag = false;
        }
    }

    if (s instanceof Circle) {
        // finding distance between the centers of the 2 circles
        distance = this.center.distance(((Circle) s).getCenter());
        distance = distance + ((Circle) s).getRadius();
        // The method will return false if both circles have 0 radius
        if (distance - this.getRadius() > Shape.TOLERANCE
                 || distance == this.getRadius()) {
            // make flag false if the distance is more than
            // the radius of the object Circle
            flag = false;
        }
    }

    return flag;
}

Some other points:
You don't need to cast to Square or Circle every time. Instead, create a new Square or Circle:
Square square = (Square) s;

and:
Circle circle = (Circle) s;

You don't need to keep a flag that you will eventually return with. Just return directly.
You don't need an ArrayList: just use an array.
Final Code
public boolean envelops(Shape s) {
    double distance = 0.0;
    if (s instanceof Square) { // check if the shape is a Square
        Square square = (Square) s;
        // calculating the coordinates of the square
        Point bottomLeft = new Point(square).getTopLeft().getX(),
                square.getTopLeft().getY() - square.getSideLength());
        Point bottomRight = new Point(square.getTopLeft().getX() +
                square.getSideLength(),
                square.getTopLeft().getY() - square.getSideLength());
        Point topRight = new Point(square.getTopLeft().getX() +
                square.getSideLength(), square.getTopLeft().getY());

        // storing points in a ArrayList of points
        Point[] points = { square.getTopLeft(), bottomLeft, topRight, bottomRight };
        for (int i = 0; i < points.length; i++) {
            //finding distance of each coordinate from the center of the circle
            distance = this.center.distance(points[i]);
            // if the distance is greater than the radius then flag becomes false,
            // ie., the cordinate is outside the circle
            if (distance - this.radius > Shape.TOLERANCE) return false;
        }
    }

    if (s instanceof Circle) {
        Circle circle = (Circle) s;
        // finding distance between the centers of the 2 circles
        distance = this.center.distance(circle.getCenter());
        distance = distance + circle.getRadius();
        // The method will return false if both circles have 0 radius
        if (distance - this.getRadius() > Shape.TOLERANCE
                 || distance == this.getRadius()) {
            // make flag false if the distance is more than
            // the radius of the object Circle
            return false;
        }
    }

    return true;
}


Battleships game in Python The idea is, you enter an amount of ships, for example 10. It will then place 10 ships on a 10x10 grid (0-9). You may enter a coordinate, and it will tell you if it is a hit or a miss. A simplified version of the well-known board game.

C indicates 'Computer'. These are not shown on the grid, but are stored in the 2D array.
H indicates 'Hit'. Self explanatory.
M indicates 'Miss'. Also self explanatory.
Null / whitespace indicates that nothing has been set at that coordinate.

I created this program with the intent of making it as efficient and readable as possible. It's difficult to explain the inner workings of my mind, so I apologize for no comments.

best ran outside of IDE (in console)

code:

import random, os

ships = int(input("Enter ship count: "))
gridSize = 10
game = [[' ' for x in range(gridSize)] for y in range(gridSize)]

def getGrid(x,y):
    return game[x][y]

def setGrid(x,y,char):
    game[x][y] = char

for i in range(ships):
    x = random.randint(0,gridSize-1)
    y = random.randint(0,gridSize-1)
    setGrid(x,y,'C')

xLabel = " " * 3
for i in range(gridSize):
    xLabel += str(i) + " "

result = "Make a move!"
hits = 0

while hits != ships:
    os.system("cls")
    print(" " + result + " [Ships: " + str(ships) + ", Size: " + str(gridSize) + ", Hits: " + str(hits) + "]\n")
    print(xLabel)
    for x in range(gridSize):
        print(" " + str(x) + " ",end="")
        for y in range(gridSize):
            print(" " * 2 if getGrid(x,y) == 'C' else getGrid(x,y) + " ",end="")
        print("")

    xGuess = int(input("\n X: "))
    yGuess = int(input(" Y: "))

    if getGrid(xGuess,yGuess) == 'C':
        result = "Hit! (" + str(xGuess) + ":" + str(yGuess) + ")"
        setGrid(xGuess,yGuess,'H')
        hits += 1
    else:
        result = "Miss! (" + str(xGuess) + ":" + str(yGuess) + ")"
        setGrid(xGuess,yGuess,'M')

print("\nCongratulations, you won the game!")
os.system("pause >nul")

Your program is pretty good, imports at the top, some functions and comprehensions.
But they can all be improved.

To adhere to PEP8 you should only import one module per import.
You need some more functions, the ones your are using I would not use and would infuriate me.
This is more an unwritten notion, but _ is known as the throw away variable.
Since you throw away the range's items you could do:

[' ' for _ in range(gridSize)]

I'd change the way you display the rows, currently you display two characters per print,
this is quite hard to read, and not very efficient.
Instead I'd recommend a list comprehension!

You display a space if getGrid(x,y) is "C", otherwise getGrid(x,y), for each character in that row.
So:

row = [" " if getGrid(x, y) == "C" else getGrid(x, y) for y in range(gridSize)]

To then display this row you should use ' '.join(row). This puts a single space in-between each position on the board.

The other major change I'd make is the use of str.format.
Take the following line:

print(" " + result + " [Ships: " + str(ships) + ", Size: " + str(gridSize) + ", Hits: " + str(hits) + "]\n")

That's hard to read with all the string concatenations and conversion, which str.format tidies up.
The equivalent would be:

print(" {} [Ships: {}, Size: {}, Hits: {}]\n".format(result, ships, gridSize, hits))

You can now tell the format of the string, and can reasonably guess what will go there.
All in little to no time.

For a few additional changes I'd recommend you change range with enumerate to get the x positions and the row, where you display the grid.
And I'd completely remove the range when using the row comprehension.
To show this:

for x, row in enumerate(game):
    print(' {} {}'.format(x, ' '.join([" " if y == "C" else y for y in row])))

I would also change the boards variable name to board so that people can instantly understand what you mean when you reference it.

In Python you should use snake_case not pascalCase for functions and variables, so gridSize should be grid_size.

And finally, you should use a try-except block when you are converting user input to a number as CAD97 put in their answer.
This is as your program will crash if I enter "a".

To improve the xLabel creation you can think of it like we did the row, however you display the item you get from the range. This means that the list comprehension that you'd do is:

row = [str(i) for i in range(gridSize)]
xLabel = " " * 3 + " ".join(row)


Explicitely passing a parameter by reference in C++03 In C#, passing a parameter by reference can't be ignored:

// C#
void foo(ref int p_value) ; // passing an int by reference

void bar()
{
   int i = 0 ;
   foo(ref i) ;
}

In C++ (and as far as I am concerned, it is a good thing), the passing by reference is only marked in the function prototype, so the code above becomes:

// C++
void foo(int & p_value) ; // passing an int by reference

void bar()
{
   int i = 0 ;
   foo(i) ;     // at call site, there is no "ref" marker.
}

The thing is, for a few special functions, to ease code reviewing, we would want to use a C#-like solution to read at call site if a variable is expected to be modified or not.

I devised a solution wrapping the value with a struct, something like:

template<typename T>
struct Ref
{
   T & m_value ;
   explicit Ref(T & p_value) : m_value(p_value) {}

   operator T & () { return this->m_value ; }
   operator const T & () const { return this->m_value ; }
} ;

template <typename T>   // wrapping T with Ref
Ref<T> byRef(T & p_value)
{
   return Ref<T>(p_value) ;
}

template <typename T>   // idempotent-enabling overload (no need for Ref<Ref<T>>)
Ref<T> & byRef(Ref<T> & p_value)
{
   return p_value ;
}

I expect this trivial code to be inlined away in optimized code.

This enables me to write the code:

void foo(Ref<int> p_int)
{
   p_int *= 10 ;
}

void bar()
{
   int i = 0 ;
   foo(byRef(i)) ;
}

Which is exactly what I want:

no use of foo(& i) C-style notation, with pointers, needing to handle NULL, etc.
in the cases we care, we can see in the code what is passed by non-const reference

Did I miss some unexpected problem/hidden cost that will come back to bite me in a few weeks/months/years?

Could this code be written better?

Will the code be confusing when seen through some un*x debuggers?

P.S.: Of course, Ref and byRef will be properly namespaced. I'm still not sure about making Ref::m_value public or private.

I can't see anything I would do majorly different.

I would make the member T & m_value private.
I would change the name of the method byRef() to just ref()

Note you still have a difference in identifiers.
The class is Ref while the function is ref()

The only problem I see is that at inside the function, the object is not automatically usable in its native type you need to cast it back before you can use it:

struct X { void print();};

void print(Ref<X> x)
{
    x.print();  // This fails to compile

    // To use the x object I need to cast it back to an X
    static_cast<X&>(x).print();

    // If we are going to use it multiple times then we could set up
    // a local reference to the object as this will generate an implicit cast
    X&  x1 = x;
    x1.print();
}

Thus getting at methods in the object becomes slightly on the messy side.


Simple Card Game in Python After finishing up finals, I wasn't really working on coding for a while. I decided to write a card game to get back into the programming scene.  I'm just wondering if there's anything that I missed or could be improved upon.

import random

suit_choices = ("Diamonds", "Hearts", "Clubs", "Spades")
suit_picked = random.choice(suit_choices)

number_picked = random.randint(2,9)

while True:
    print suit_choices
    user_card = raw_input('\nEnter a suit to pick from. Your choices are listed above. ').title()

    if user_card == suit_picked:
        print '\nYou guessed the suit type correct!'
        user_number = input('\nNow pick a number card (2-9) ')
        if user_number == number_picked:
            print '\n You guessed the card number correct!'
            break
        else:
            print '\nShucks. Try again.'
            continue
    else:
        print '\nOH NO'
        continue

continue

Both your continue statements fall back to the end of the loop anyway, so they are redundant.

    user_number = input('\nNow pick a number card (2-9) ')

In the other place you correctly used raw_input. The difference is that input executes the given string as an expression, which is seldom what you want (and usually unsafe).

Nothing else really. The \ns at the start of all your strings are a bit ugly, and some people prefer using empty print statements to indicate extra empty lines.


changing root password with an ansible playbook It is with great difficulty that I resolved to solve my problem, so I allow myself to submit here the solution.

I wanted a playbook that could replace on all hosts the root password with a string containing the last 3 digits of the IP address of the remote host.

Example:
suppose the password is my_password and my LAN is 172.1.1.0/24. I wanted to set my_password@111 on the host with IP 172.1.1.111, my_password@112 on IP 172.1.1.112, and so on.

Here is the solution i propose:

- hosts: test

  vars:
    shared_string: my_very_secure_password

  tasks:

   - debug:
       msg: "Remote IP host is {{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"

   - name: Extract last digits of remote host ip
     set_fact:
        last_digits: "{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] | regex_search(regexp) }}"
     vars:
        regexp: '\d{1,3}$'

   - debug:
        msg: "Last digits are {{ last_digits }}"

   - name: Compose and encrypt the password as shared_string@last_digits
     command: openssl passwd -crypt "{{ shared_string }}@{{ last_digits }}"
     register: crypted_password

   - debug:
       msg: "clear password is {{ shared_string }}@{{ last_digits }}"
   - debug:
       msg: "crypted password is {{ crypted_password.stdout }}"

   - name: Change root password
     user: name=root update_password=always password={{ crypted_password.stdout }}

what do you think, how to improve it?

For starter, I’d remove debug messages: they do nothing except leaking sensitive information. If you want a deeper sense of what is going on when running your playbook, you can always invoke Ansible with the verbose (-v) option.

Second, I would not use vars to store a password. Instead, I would ask it to the user using a vars_prompt. In fact, using a prompt to update a user password seems so common a need that Ansible itself provide this very possibility; but here you want to automatically append something else, so I’d reuse part of your approach.

The playbook I’d use would be:

- hosts: test

  vars_prompt:
    - name: shared_string
    - prompt: "Common base for your passwords? "
    - private: yes

  tasks:
   - name: Extract last digits of remote host ip
     set_fact:
        last_digits: "{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] | regex_search(regexp) }}"
     vars:
        regexp: '\d{1,3}$'

   - name: Compose and encrypt the password as shared_string@last_digits
     command: openssl passwd -crypt "{{ shared_string }}@{{ last_digits }}"
     register: crypted_password

   - name: Change root password
     user: name=root update_password=always password={{ crypted_password.stdout }}


Representing the opening and closing time for a business I have an OpenClose class which just represents the hours of operation of a business by the opening and closing time. It takes the opening and closing times as arguments to its constructor, and each is a datetime object.

The data is coming from an external source in a string, formatted like "HH:MM (AM|PM)-HH:MM (AM|PM)"

I have the following function to turn this into an OpenClose object:

def __get_times(self, hours):
    return OpenClose(*map(lambda x: datetime.strptime(x, "%I:%M %p"), hours.split("-")))

What do you think of this? Is it too much for one line? Too confusing? Should I split it up into multiple lines?

It sort of bugged me when doing it with multiple lines, but I can certainly see how this would be more readable, despite my hatred of explicitly doing the datetime calculation twice:

format = "%I:%M %p"
open_time, close_time = hours.split("-")
open_time = datetime.strptime(format)
close_time = datetime.strptime(format)
return OpenClose(open_time, close_time)

An alternative would be to use a combination of these approaches:

format = "%I:%M %p"
hours = hours.split("-")
open_time, close_time = map(lambda x: datetime.strptime(x, format), hours)
return OpenClose(open_time, close_time)

Which of these is best?

Yes, too much for one line, yes, too confusing. Making a map an lambda for two values like that is silly, unless you are trying to win an obfuscation contest.

So, the middle version is best.


Lexer for expression evaluator I started learning my first functional programming language (Haskell) yesterday and I have been working on a lexer for an expression evaluator. The lexer is now basically feature complete, but I'm not sure what I can do to improve the code.

import Data.Char
import Data.List

data TokenType = Identifier |
                 RealNumberLiteral |
                 PlusSign |
                 MinusSign |
                 Asterisk |
                 ForwardSlash |
                 Caret |
                 LeftParenthesis |
                 RightParenthesis
    deriving (Show)

data Token = Token TokenType String
    deriving (Show)

read_token :: String -> Token
read_token [] = error "Unexpectedly reached the end of the source code while reading a token."
read_token source_code@(next_character:_)
    | isSpace next_character = read_token (dropWhile isSpace source_code)
    | isAlpha next_character = Token Identifier (takeWhile isAlpha source_code)
    | isDigit next_character = let token_lexeme = (takeWhile (\x -> isDigit x || x == '.') source_code)
                               in let period_count = length (filter (=='.') token_lexeme)
                                  in Token RealNumberLiteral (if period_count <= 1
                                                                  then token_lexeme
                                                                  else error "There can only be one period in a real number literal.")
    | next_character == '+' = Token PlusSign "+"
    | next_character == '-' = Token MinusSign "-"
    | next_character == '*' = Token Asterisk "*"
    | next_character == '/' = Token ForwardSlash "/"
    | next_character == '^' = Token Caret "^"
    | next_character == '(' = Token LeftParenthesis "("
    | next_character == ')' = Token RightParenthesis ")"
    | otherwise = error ("Encountered an unexpected character (" ++ [next_character] ++ ") while reading a token.")

append_read_tokens :: [Token] -> String -> [Token]
append_read_tokens tokens source_code
    | null source_code = tokens
    | isSpace (head source_code) = append_read_tokens tokens (dropWhile isSpace source_code)
    | otherwise = let next_token@(Token next_token_type next_token_lexeme) = read_token source_code
                  in append_read_tokens (tokens ++ [next_token]) (drop (length next_token_lexeme) source_code)

tokenize :: String -> [Token]
tokenize [] = []
tokenize source_code = append_read_tokens [] source_code

No need of TokenType: data Token = Identifier String | RealNumberLiteral String | PlusSign ...
No need of nested let statements, see http://learnyouahaskell.com/syntax-in-functions#let-it-be
camelCase naming is preferred everywhere.
generally it is more efficient to aggregate lists using cons (: operator), and reverse at the end, if needed. It is about tokens ++ [next_token] fragment.
read_token could return a tuple of token and the rest string, no need to drop (length next_token_lexeme) source_code after that.

Note, I didn't inspect code logic at all.


Generic sum method for a Collection While answering this question, I wanted to use a generic sum of Collection function.  Java doesn't have a native method, so I wrote one.  There are a couple things I don't like about it though, so I wrote a more specific method for my answer.

public static <T extends Number, U extends Collection<T>> BigInteger sum(U numbers) {
    BigInteger sum = BigInteger.ZERO;

    for ( T number : numbers ) {
        sum = sum.add(new BigInteger(number.toString()));
    }

    return sum;
}

The first problem of course is that this wouldn't work for all Number types.  In particular, Float, Double, and BigDecimal are not guaranteed to fit in an integer type.  That's easy enough to fix:

public static <T extends Number, U extends Collection<T>> BigDecimal sum(U numbers) {
    BigDecimal sum = BigDecimal.ZERO;

    for ( T number : numbers ) {
        sum = sum.add(new BigDecimal(number.toString()));
    }

    return sum;
}

Now the problem is that it switches from an integer type to a decimal type.  So we have to convert it back if we really preferred an integer type.

I'm also not happy with converting to and from a String to convert it to a BigDecimal.  They're all numeric types.  Why add this intermediate step?  Unfortunately, String is the only interoperable type.  All the Number types have a toString method, and BigDecimal has a constructor from a String.

Overall, this may be more hacky than useful.  Does anyone have an alternative version that works better?  Or should I stick with writing a custom method each time the issue arises?  Or am I being too hard on this version?

Choosing between Long/Integer and Float/Decimal

I'd let the user choose.
Not because that's the best way, but because I don't see any other way.

Number itself is not reflective on the presence of decimal digits.
It would need an interface Integer and interface Decimal or something like that in order to deal with this in a single signature.
However, the API is not designed this way.

So, if both is needed, I'd have a sumInt and a sumFloat method, or maybe sumInteger and sumDecimal. (I prefer Float over Decimal because Decimal is simply wrong because it means 1/10ths and that's just the wrong name. BigDecimal is the wrong name.)

Simpler usage of Generics

The type parameter U is redundant. You could directly go for this signature:

public static <T extends Number> BigDecimal sum(Collection<T> numbers)

And given that inside you actually don't need T, Number is sufficient, you could go for this signature:

public static BigDecimal sum(Collection<? extends Number> numbers)

Going via String is a bit "far away" from numbers, and unnecessary. You could use Number.longValue() in case of BigInteger and Number.doubleValue() in case of BigDecimal.

Then the code would look like this:

public static BigInteger sumInt(final Collection<? extends Number> numbers) {
    BigInteger sum = BigInteger.ZERO;
    for (final Number number : numbers)
        sum = sum.add(new BigInteger(number.longValue());
    return sum;
}

public static BigDecimal sumFloat(final Collection<? extends Number> numbers) {
    BigDecimal sum = BigDecimal.ZERO;
    for (final Number number : numbers)
        sum = sum.add(new BigDecimal(number.doubleValue());
    return sum;
}

How it looks like with Java 8 Streams

With Java 8 Streams, the code could look like this:

public static BigDecimal sumFloat(final Collection<? extends Number>  numbers) {
    return numbers
            .parallelStream()
            .mapToDouble(Number::doubleValue)
            .mapToObj(BigDecimal::new)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
}

LSP Violation

However, all these implementations violate the LSP - Liskov Substitution Principle. They will not work correctly for all potential Number types. If the Collection numbers contains BigDecimal or BigInteger objects which exceed the range expressible in double or long, the functions would fail to produce the correct result.

Given the signature, which suggests that any Number would do, and given the fact that class BigInteger extends Number and class BigDecimal extends Number, and given the fact that the signature uses BigInteger resp. BigDecimal as a return value, that would be a pretty unexpected behavior.

The following helper function can fix that problem for the known classes BigDecimal and BigInteger:

public static BigInteger toBigInteger(final Number number) {
    return
        Number instanceof BigInteger ? (BigInteger) number :
        Number instanceof BigDecimal ? ((BigDecimal) number).toBigInteger() :
        new BigInteger(number.longValue());
}

However, if someone creates another subclass of Number which exceeds the range of long, there still would be a problem. This problem could only be solved by fixing the API: class Number should have toBigInteger() and toBigDecimal() methods, which in Number, could be implemented with corresponding defaults. Because the root cause for the LSP violation is not in your code, not in my code, but in the API - in the way how class Number actually is defined.

Using the helper function, the code could look like this:

public class Numbers {

    public static BigInteger sumInt(final Collection<? extends Number> numbers) {
        BigInteger sum = BigInteger.ZERO;
        for (final Number number : numbers)
            sum = sum.add(toBigInteger(number);
        return sum;
    }

    public static BigDecimal sumFloat(final Collection<? extends Number>  numbers) {
        return numbers
                .parallelStream()
                .map(Numbers::toBigDecimal)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    public static BigInteger toBigInteger(final Number number) {
        return
            Number instanceof BigInteger ? (BigInteger) number :
            Number instanceof BigDecimal ? ((BigDecimal) number).toBigInteger() :
            new BigInteger(number.longValue());
    }
    // ...
}


Check a string for 2 values I have a string, for example: dashboard/12398911/overzicht and I want to check that string for 2 values. For dashboard and overzicht. If the first check is false, then the second check doesn't need to happen.

This is my current code:

private pageTypes = ['dashboard', 'klantenkaart', 'complexkaart', 'objectkaart', 'collegakaart'];
private subTypes = ['overzicht', 'tijdlijn', 'contracten', 'financieel', 'mededelingen'];

private isOnPageWithFilter(currentUrl: string): boolean {
    for (const pageType of this.pageTypes) {
        if (currentUrl.includes(pageType)) {
            for (const subType of this.subTypes) {
                if (currentUrl.includes(subType)) {
                    return true;
                }
            }
        }
    }
    return false;
}

I was wondering if there's a way of doing this where I don't need a nested for loop.

Plunkr: https://plnkr.co/edit/FXhbCr9aaXcL61g3q7Fe?p=preview

You can simplify it by using Array.prototype.some method and lazy evaluation of && operator

const pageTypes = ['dashboard', 'klantenkaart', 'complexkaart', 'objectkaart', 'collegakaart'];
const subTypes = ['overzicht', 'tijdlijn', 'contracten', 'financieel', 'mededelingen'];

function isOnPageWithFilter(currentUrl) {
    return pageTypes.some(x => currentUrl.includes(x)) && subTypes.some(x => currentUrl.includes(x));
}

console.log(isOnPageWithFilter('foobar.com?dashboard')); // false
console.log(isOnPageWithFilter('foobar.com?dashboard&overzicht')); // true

```


A Summation Function For Boost.MultiArray in C++ This is a follow-up question for
A Summation Function For Arbitrary Nested Vector Implementation In C++ and A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++. I am trying to implement a recursive_sum function for the Boost Multidimensional Array Library. The purpose of this recursive_sum function is to sum up each element in a input boost::multi_array data.  The recursive structure here is similar to the previous implementation for std::vector and the other type nested iterable. Furthermore, I found that there are several types including boost::multi_array, boost::detail::multi_array::sub_array and boost::detail::multi_array::const_sub_array in Boost.MultiArray library. I am trying to handle these types with multiple overload function as below.
template<class T> requires is_summable<T>
auto recursive_sum(const T& input)
{
    return input;
}

//  Deal with the boost::multi_array case
template<class T, std::size_t Dims> requires is_summable<T>
auto recursive_sum(const boost::detail::multi_array::const_sub_array<T, Dims>& input)
{
    T sum_output{};
    for (typename boost::multi_array<T, Dims>::index i = 0; i < input.shape()[0]; i++)
    {
        sum_output += recursive_sum(input[i]);
    }
    return sum_output;
}

//  Deal with the boost::multi_array case
template<class T, std::size_t Dims> requires is_summable<T>
auto recursive_sum(const boost::detail::multi_array::sub_array<T, Dims>& input)
{
    T sum_output{};
    for (typename boost::multi_array<T, Dims>::index i = 0; i < input.shape()[0]; i++)
    {
        sum_output += recursive_sum(input[i]);
    }
    return sum_output;
}

//  Deal with the boost::multi_array case
template<class T, std::size_t Dims> requires is_summable<T>
auto recursive_sum(boost::multi_array<T, Dims>& input)
{
    T sum_output{};
    for (typename boost::multi_array<T, Dims>::index i = 0; i < input.shape()[0]; i++)
    {
        sum_output += recursive_sum(input[i]);
    }
    return sum_output;
}

The used is_summable concept:
template<typename T>
concept is_summable = requires(T x) { x + x; };

The test for this recursive_sum function:
int main()
{
    // Create a 3D array that is 3 x 4 x 2
    typedef boost::multi_array<double, 3> array_type;
    typedef array_type::index index;
    array_type A(boost::extents[3][4][2]);

    // Assign values to the elements
    int values = 0;
    for (index i = 0; i != 3; ++i)
        for (index j = 0; j != 4; ++j)
            for (index k = 0; k != 2; ++k)
                A[i][j][k] = values++;

    auto recursive_sum_output = recursive_sum(A);
    std::cout << "recursive_sum_output: " << recursive_sum_output;

    return 0;
}

All suggestions are welcome.

Which question it is a follow-up to?
A Summation Function For Arbitrary Nested Vector Implementation In C++ and
A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++

What changes has been made in the code since last question?
The previous question is focused on the common containers in C++ STL, such as std::vector. The main idea in this question is trying to implement another type summation function which can deal with boost::multi_array.

Why a new review is being asked for?
I found that there are three types of array structure in Boost.MultiArray library which are boost::multi_array, boost::detail::multi_array::sub_array and boost::detail::multi_array::const_sub_array. In order to handle these different type classes, there are three overload functions recursive_sum for dealing with each type separately. I am not sure is there any better way to simplify these overload functions. Moreover, if there is any possible improvement for this code, please let me know.

Implement a recursive std::reduce()
You shouldn't need to special-case boost::multi_array and related types, as those types already act like STL containers (they provide begin() and end() for example). The main problem however is how to deduce the return type of recursive_sum(). Your functions seem to work because they deduce T from a boost::multi_array<T, Dims>, but do they really? Your recursive_sum() recurses over the dimensions of a multi_array, but it doesn't actually handle nested multi_arrays, like for example:
boost::multi_array<boost::multi_array<double, 2>, 3> array;

The reason is that in the above case, calling recursive_sum(array) will deduce T to be a boost::multi_array<double, 2> instead of a double.
To solve this issue, I would do what std::reduce() does, and sidestep the issue by requiring an initial value for the sum. The type of this initial value will also be the return type. For example:
template<class T, class ValueType, class Function = std::plus<ValueType>>
auto recursive_reduce(const T& input, ValueType init, const Function& f)
{
    return f(init, input);
}

template<class Container, class ValueType, class Function = std::plus<ValueType>>
requires is_iterable<Container>
auto recursive_reduce(const Container& input, ValueType init, const Function& f = std::plus<ValueType>())
{
    for (const auto &element: input) {
        auto result = recursive_reduce(element, ValueType{}, f);
        init = f(init, result);
    }

    return init;
}

Then you can call it like so:
boost::multi_array<...> array(...);
std::cout << recursive_reduce(array, 0.0) << "\n";

You could perhaps write some template to find the inner-most value type, so that you can use that as a default for the template parameter ValueType in recursive_reduce(), and then you can use {} as the default value for init, and be able to write:
std::cout << recursive_reduce(array) << "\n";


PHP filesystem on a shared file system I have a project which we need to migrate from an on-prem solution to the AWS cloud. Currently, the software is running on a single instance. It's working fine but the business want the software to be Highly Available (HA). As part of the HA, the program will be installed on a shared file system (AWS EFS) and mount the filesystem on the multiple EC2 instances so that the same configuration accessed by all the instances.
The challenge for me is
PHP_ETC_BASE=/etc/php/7.0
PHP_INI=${PHP_ETC_BASE}/apache2/php.ini

I can install PHP on all the AWS EC2 instances (PHP_ETC_BASE) but the PHP_INI need to be on a shared file system so that the configuration can be accessed by other instances. What I read is that I cant move /etc/php/7.0 to a shared filesystem then PHP wont work
  installDepsPhp70 () {
  debug "Installing PHP 7.0 dependencies"
  PHP_ETC_BASE=/etc/php/7.0
  PHP_INI=${PHP_ETC_BASE}/apache2/php.ini
  checkAptLock
  sudo apt install -qy \
  libapache2-mod-php \
  php php-cli \
  php-dev \
  php-json php-xml php-mysql php-opcache php-readline php-mbstring php-zip \
  php-redis php-gnupg \
  php-gd

  for key in upload_max_filesize post_max_size max_execution_time max_input_time memory_limit
  do
      sudo sed -i "s/^\($key\).*/\1 = $(eval echo \${$key})/" $PHP_INI
  done
  sudo sed -i "s/^\(session.sid_length\).*/\1 = $(eval echo \${session0sid_length})/" $PHP_INI
  sudo sed -i "s/^\(session.use_strict_mode\).*/\1 = $(eval echo \${session0use_strict_mode})/" $PHP_INI
}

Similar issue for the /var/lib/mysql
prepareDB () {
  if sudo test ! -e "/var/lib/mysql/mysql/"; then
    #Make sure initial tables are created in MySQL
    debug "Install mysql tables"
    sudo mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
    sudo service mysql start
  fi

  if sudo test ! -e "/var/lib/mysql/misp/"; then
    debug "Start mysql"
    sudo service mysql start

Consider your system in three parts:

Core OS (all files on ec2)
Your App (I would keep the core app files on ec2 - reasons below - but your way would work)
Data (I would have only "data" on EFS)

Answer Part 1: php.ini lives with the OS.
Reasons:

Major: If you want to upgrade to a newer PHP without downtime, you create new EC2s with new OS one at at time and swap them in to your ELB: this can't use the shared php.ini as you propose.
Medium: Changes to php.ini won't bite instantly you may need to start http/fcgi to get traction - you still need to visit each server to restart.

Answer Part 2: The actual application files also live on ec2, and only data on EFS.
Reasons:

Major: Similar to above, you can update one at a time by swapping servers with new code in.
Medium: Security; it's safer to create the application instances and "lock in" the files, than rely on files on EFS that may have been connected to another EC2 by mistake.
Medium: Testing: you can attach your EC2s to a different data store / different ELB for testing before connecting to live.
Medium: If your EFS fails (it happens!) your application can still respond and say "Sorry - please come back later".
Medium: You want to have the EC2 in different AZs so much faster
Minor: Slightly faster if they all share the same AZ.
Downside: Updating the application is a bigger pain, but you can script this too.

How:
The great news is that you already have this scripted. Split your deploy into slightly smaller stages:
a) Create your BaseAMI (includes the OS, PHP as you have scripted above). This only changes when you do a major OS update.
b) Using your BaseAMI, you can then create a GoldenAMI which has your application on top. (Run minor OS updates at this point to maintain security if your Base AMI is older). This Golden AMI will be near identical for all EC2s
c) Using Auto-Scale Groups (ASG), use GoldenAMI as your base, and tweak if needed using userdata properties of the ASG.
When you release new code, you launch stage (b) and create new GoldenAMI and use that for the ASG. Kill the old servers and the new ones magically appear = no downtime.
If you really need to update php.ini (which will be rare), then start again at stage (a) to build the BaseAMI, then Golden AMI and swap servers in one at at time.
To "cheat" (shortcut) when updating, deploy your application code to S3, have each EC2 check S3 (or notified via SNS when updates happen) and it can pull down the code and self update. But ensure your security is rock-solid tight if you do this (as you would if putting the application code on EFS).

Regarding MySql,

you can't share like that at all as files need to be exclusively opened;
having data live on a single disk is not "HA";
having data live on EFS is slow.

Use the RDS solutions provided by AWS and you can add redundancy to your heart's content (multiple AZs, failovers, backups). It may cost a bit more, but HA will.