Count number of ways to paint a fence with N posts using K colors A friend sent me this question, and I'd love somebody to review this and give his opinion.

  Write an algorithm that counts the number of ways you can paint a
  fence with N posts using K colors such that no more than 2 adjacent
  fence posts are painted with the same color"

Is this algorithm accurate? Could it be implemented in a better way?  Is there anything really un-pythonic that I did there?  I hope I haven't made any embarrassing mistakes.

def find_combinations(n, colours):

combos_list = []

    for i in range(1, n+1):

        #Check if the combos_list is empty (happens when post number == 1)
        if not combos_list:
            #Add all variations for when there's only one post
            for c in colours:
                combos_list.append([c])
        else:
            new_combo_list = []
            for combo in combos_list:
                for c in colours:
                    #Check if last 2 posts are from the same colour, meaning we can't add another one
                    if not combo[len(combo) - 2:] == [c, c]:
                        combo_to_add = combo[:]
                        combo_to_add.append(c)
                        new_combo_list.append(combo_to_add)
            combos_list = new_combo_list[:]

    return combos_list, len(combos_list)

colours = ["black", "white"]
n = 4

print find_combinations(n, colours)

Example of input:

  colours = ["a", "b"]
  n = 3

Output:

  a, a, b
  a, b, a
  a, b, b
  b, a, a
  b, a, b
  b, b, a

Number of combos - 6

1. Code review

The question says, "Write an algorithm that counts the number of ways" but the program does not only do this: it also builds a list of the combinations. This means that the program is limited to values of \$N\$ and \$K\$ that are small enough that the list of combinations fits in the storage space of the computer. Whereas a program that did not have to produce this list could work for much larger values of \$N\$ and \$K\$, as we'll see in §3 below.
It's good practice to write a docstring for each function, describing what the function does, the arguments that it takes, and what it returns.
If a function returns a list, it does not also need to return the length of the list. If the caller needs that information, it can call len just as easily. So the function could just return combos_list.
In the line:

combos_list = new_combo_list[:]

it's unnecessary (and wasteful) to take a copy of new_combo_list. The new list can just be assigned to the old name, like this:

combos_list = new_combo_list

When a loop index (here i) is not used, it's conventional to name it _.
The code that's guarded by the line:

if not combos_list:

only runs once (on the first iteration of the loop), so it would be simpler to move it out of the loop, have one fewer iteration of the loop, and so avoid the if ... else .... Like this:

combos_list = []
for c in colours:
    combos_list.append([c])
for _ in range(1, n):
    new_combo_list = []
    # etc.

Instead of:

combos_list = []
for c in colours:
    combos_list.append([c])

use a list comprehension and write:

combos_list = [[c] for c in colours]

These lines:

combo_to_add = combo[:]
combo_to_add.append(c)
new_combo_list.append(combo_to_add)

could be simplified to:

new_combo_list.append(combo + [c])

This condition:

if not combo[len(combo) - 2:] == [c, c]:

could be simplified to:

if combo[-2:] != [c, c]:

(since Python allows you index a list backwards from the end using negative numbers).

2. Revised code

def find_combinations(n, colours):
    """Return a list of combinations of n items from the sequence colours,
    with the constraint that no colour appears three times in a row.

    >>> [''.join(combo) for combo in find_combinations(3, 'ab')]
    ['aab', 'aba', 'abb', 'baa', 'bab', 'bba']

    """
    combos = [[c] for c in colours]

    for _ in range(1, n):
        new_combos = []
        for combo in combos:
            for c in colours:
                # Check that last two colours aren't both c.
                if combo[-2:] != [c, c]:
                    new_combos.append(combo + [c])
        combos = new_combos

    return combos

Note the example code in the docstring. This can be run as a test case using the doctest module.

3. Let me count the ways

The question asked for "an algorithm that counts the number of ways", so here's how I'd go about that.

I'll start with some notation. Assume that \$k\$ is fixed. Then:

\$T(n)\$ is the total number of ways to paint \$n\$ fenceposts with \$k\$ colours, subject to the constraint that no three adjacent posts are the same colour.
\$D(n)\$ is the number of ways to paint \$n\$ fenceposts with \$k\$ colours such that the last two fenceposts are different colours (or \$n < 2\$).
\$S(n)\$ is the number of ways to paint \$n\$ fenceposts with \$k\$ colours such that the last two fenceposts are the same colour.

And then the following recurrence relations are clear:

\$D(n) = (k−1)(D(n−1) + S(n−1))\$ for \$n ≥ 2\$
\$S(n) = D(n−1)\$ for \$n ≥ 2\$
\$T(n) = D(n) + S(n)\$

We can use (2) to eliminate \$S\$ (being careful about the bound on \$n\$ as we do so), getting the recurrences:

\$D(n) = (k−1)(D(n−1) + D(n−2))\$ for \$n ≥ 3\$
\$T(n) = D(n) + D(n−1)\$ for \$n ≥ 2\$

And then substitute (5) into (4), getting:

\$D(n) = (k−1)(T(n−1))\$ for \$n ≥ 3\$

and so:

\$T(n) = (k−1)(T(n−1) + T(n−2))\$ for \$n ≥ 3\$

Since the recurrence depends only on the last two values of the sequence, it's easy to program:

def triple_free_combinations(n, k):
    """Return the number of ways to choose n items (with k choices for
    each item), subject to the constraint that no colour appears three
    times in a row.

    """
    if n == 0:
        return 1
    a, b = k, k * k
    for _ in range(n - 1):
        a, b = b, (k - 1) * (a + b)
    return a

(You should recognize this as a very simple example of the tabular method, aka "dynamic programming".)

The effort that went into find_combinations is not wasted, because now we can use that function as source of test cases:

>>> from itertools import product
>>> all(triple_free_combinations(n, k)
...     == len(find_combinations(n, list(range(k))))
...     for n, k in product(range(1, 8), repeat=2))
True

Another useful source of test cases is the On-Line Encyclopedia of Integer Sequences. For example, when \$k=2\$ we have sequence A128588:

>>> [triple_free_combinations(i, 2) for i in range(16)]
[1, 2, 4, 6, 10, 16, 26, 42, 68, 110, 178, 288, 466, 754, 1220, 1974]

and similarly when \$k=3,4,5,\ldots\$ we have A121907, A123620, A123871, ....

Finally, note that triple_free_combinations is capable of computing values that are far beyond the reach of the original function:

>>> triple_free_combinations(40, 40)
472189463994618801762969606024644975976973566598588071193029590400

(Revised version)
It is unnecessary to write a search algorithm if you find an equation for the answer. If there is no restriction on adjacent posts of same color then

                  N
Number of ways = K

If no adjacent posts of same color are allowed then

                              (N - 1)
Number of ways = K * ( K - 1 )

The question actually allows maximum 2 adjacent posts of same color, which needs a different equation.

You can even avoid computation by storing this table of results (revised).

Colors K --->  2     3     4     5
Posts N
      1        2     3     4     5
      2        4     9    16    25
      3        6    24    60   120
      4       10    66   228   580
      5       16   180   864  2800
      6       34   492  3276 13520


Printing all even and odd numbers with threads The original question is on careercup.

  Write a multi threaded C code with one thread printing all even numbers and the other all odd numbers. The output should always be in sequence
  ie. 0,1,2,3,4....etc

Now I want to use  C# for it.

class Program
{
    static Object obj = new Object();
    static Thread t1;
    static Thread t2;
    static LinkedList<int> a = new LinkedList<int>();
    static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            a.AddLast(i);
        }

        t1 = new Thread(PrintOdd);
        t2 = new Thread(PrintEven);
        t1.Name = "Odd";
        t2.Name = "Even";
        t1.Start();
        t2.Start();
        t1.Join();
        t2.Join();

        Console.WriteLine("Done!");
        Console.Read();
    }

    private static void PrintOdd()
    {
        while (true)
        {
            if (a.Count == 0)
                break;
            lock (obj)
            {
                int x = a.First();
                if (x % 2 != 0)
                {
                    Console.WriteLine(Thread.CurrentThread.Name + " " + x);
                    a.RemoveFirst();
                }
            }
        }
    }

    private static void PrintEven()
    {
        while (true)
        {
            lock (obj)
            {
                if (a.Count == 0)
                    break;
                int x = a.First();
                if (x % 2 == 0)
                {
                    Console.WriteLine(Thread.CurrentThread.Name + " " + x);
                    a.RemoveFirst();
                }
            }
        }
    }
}

Any improvements?

This looks very good to me, but I am not very advanced at C# myself.  I can give you some tips, though.

First, you should not use ambiguous names like t1 and t2.  You should use more descriptive names like EvenThread and OddThread instead.

Second, you can shorten this:

while (true)
{
  if (a.Count == 0)
    break;

Into this:

while (Numbers.Count > 0)  // For PrintOdd()

And this:

while (Numbers.Count > 1)  // For PrintEven()

Also, you could look into other forms of mutual exclusion techniques, such as semaphores and mutexes, instead of just using an Object.

This is an implementation with a SemaphoreSlim (only code shown is changed):

using System.Threading;

class Program
{
    static SemaphoreSlim ThreadLock = new SemaphoreSlim(1,1);
    static Thread Odd;
    static Thread Even;
    static LinkedList<int> Numbers = new LinkedList<int>();
    static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            Numbers.AddLast(i);
        }

        Odd = new Thread(PrintOdd);
        Even = new Thread(PrintEven);
        Odd.Name = "Odd";
        Even.Name = "Even";
        Odd.Start();
        Even.Start();
        Odd.Join();
        Even.Join();

        Console.WriteLine("Done!");
        Console.Read();
    }

    private static void PrintOdd()
    {
        while (Numbers.Count > 0)
        {
            ThreadLock.Wait();

            int x = Numbers.First();
            if (x % 2 != 0)
            {
                Console.WriteLine(Thread.CurrentThread.Name + " " + x);
                Numbers.RemoveFirst();
            }

            ThreadLock.Release();
        }
    }

    private static void PrintEven()
    {
        while (Numbers.Count > 1)
        {
            ThreadLock.Wait();

            int x = Numbers.First();
            if (x % 2 == 0)
            {
                Console.WriteLine(Thread.CurrentThread.Name + " " + x);
                Numbers.RemoveFirst();
            }

            ThreadLock.Release();
        }
    }
}

Instead of checking the modulo via if (x % 2 == 0) and  if (x % 2 != 0) you could simply use Console.WriteLine(Thread.CurrentThread.Name + " " + (2*x)); and Console.WriteLine(Thread.CurrentThread.Name + " " + (2*x+1)); to display even an odd numbers respectively. As a mathematician this seems more reasonable to me.


Return nil after loop and also in unless block in Ruby I have a working code as below. Is there any better way to return nil after the each loop and unless else in the below example?
def find_member(member_name)
  unless members.empty?
    members.each do |member|
      if member.name == member_name
        return member
      end
    end
    nil
  else
    nil
  end
end

I should pass nil in each case because there are different conditions in other methods where this method is called. That is the reason why I have written the code as above.

Ruby has a detect method, so your entire method can be replaced with
members.detect { |member| member.name == member_name }

As an aside, each works fine for empty arrays, hence the empty? check you have is completely unnecessary even if you keep the explicit loop.

It's a method on Enumerable. It is also aliased to find which may be a more descriptive verb depending on the context. Using the built-in functions will always be faster because they are implemented in c


Populate two arrays with two different SQL queries I am using Joomla and connecting to an MSSQL database to store the resulting set(s) in arrays. I am utilizing this syntax, but there must be a more efficient way of coding this.

<?php
    $option = array();
    $option['driver'] = 'mssql';
    $option['host'] = '555.555.55.5';
    $option['user'] = 'username';
    $option['password'] = 'password';
    $option['database'] = 'database';
    $option['prefix'] = '';
    $db = JDatabaseDriver::getInstance($option);
    $sql = $db->getQuery(true);
    $sql = "Select ranchstyle from information";
    $db->setQuery($sql);
    $rows = $db->loadRowList();
    $output = array();
    foreach ($rows as $row) {
        array_push($output, $row);
    }
    $data = json_encode($output[0]);

    $query2 = $db->getQuery(true);
    $query2 = "Select maestro from musicinfo";
    $db->setQuery($query2);
    $rows1 = $db->loadRowList();
    $output1 = array();
    foreach ($rows1 as $r) {
        array_push($output1, $r);
    }

    $data1 = json_encode($output1[0]);
?>

There are two possible answers to this question, a generalized one and a specific one.

To help with such questions in general, there is one programming concept which is often underestimated by PHP users. It is called user-defined functions

In a nutshell, you can write a code once and then use it any number of times.

function getArrayFromSql($db, $sql)
{
    $db->setQuery($sql);
    $rows = $db->loadRowList();
    $output = array();
    foreach ($rows as $row) {
        array_push($output, $row);
    }
    return $data;
}

Here you created a function which you can use any number of times:

$sql = "Select ranchstyle from information";
$output = getArrayFromSql($db, $sql);
$data = json_encode($output[0]);

$sql = "Select maestro from musicinfo";
$output = getArrayFromSql($db, $sql);
$data1 = json_encode($output[0]);

Whereas for the specific answer we need to review your code more closely. It does unnecessary job all the time.

First, you are making a useless call to $db->getQuery(true);, as with the very next step the $sql variable gets overwritten.

Second, you actually have an array already, as $db->loadRowList(); gives you a first class array. But for some reason you are duplicating it into $data. So your code actually should be

$sql = "Select ranchstyle from information";
$db->setQuery($sql);
$rows = $db->loadRowList();
$data = json_encode($rows[0]);

$sql = "Select maestro from musicinfo";
$db->setQuery($sql);
$rows = $db->loadRowList();
$data1 = json_encode($rows[0]);

Third, given you are encoding only the first item of the array, you seems don't need an array at all, so select and fetch one line only.

$sql = "Select ranchstyle from information limit 1";
$db->setQuery($sql);
$row = $db->loadRow();
$data = json_encode($row);

$sql = "Select maestro from musicinfo limit 1";
$db->setQuery($sql);
$row = $db->loadRow();
$data1 = json_encode($row);


Comparing dates (without the time part) in Java In my current project, I have to deal a lot with dates, especially checking if the date entered by user is today, or max one year from today etc. As I find the datetime API of Java7 (which I regrettably still have to use) pretty confusing, in order to keep my code clean and readable, I wrote the following method:

public static int compareDates(Date date1, Date date2) {
    SimpleDateFormat math = new SimpleDateFormat("yyyyMMdd"); // I'm working with servlets, so keeping it thread-safe
    Long date1asLong = new Long(math.format(date1));
    Long date2asLong = new Long(math.format(date2));
    return date1asLong.compareTo(date2asLong);
}

// usage, e.g. to find if the date entered by user is greater than today
if (MyDateUtils.compareDates(dateFromUser, new Date()) > 0) {
    // do the work
} else {
    // scream
}

Anyway, I am not sure whether this approach has any serious drawbacks, so I am throwing it here for review. Looking forward to your comments.

It's an interesting, simple approach.

But you don't need new Long objects. Better use primitive types instead.

In fact, as @njzk2 pointed out in a comment,
you don't need long at all, as dates in yyyyMMdd format are alphabetically sorted, you can use simple String comparison.

It's good you mention in comments that you create a SimpleDateFormat instance inside the method for thread safety.
Another common solution in such situations is to use a ThreadLocal.
You can wrap a SimpleDateFormat instance in a ThreadLocal so that all threads will have their own copy, eliminating thread safety issues.

Last but not least, "math" is a poor name for a date formatter object.

Putting my suggestions together:

private static final ThreadLocal<DateFormat> dateFormatThreadLocal = new ThreadLocal<DateFormat>() {
    @Override
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyyMMdd");
    }
};

public static int compareDates(Date date1, Date date2) {
    DateFormat dateFormat = dateFormatThreadLocal.get();
    return dateFormat.format(date1).compareTo(dateFormat.format(date2));
}

This isn't as transparent as the calendar version, but you can easily do this by dividing the time value to get a number of days. E.g.
long one-day = 24*60*60*1000
int compare = Long.compare(d1.getTime()/oneDay,d2.getTime()/oneDay)


Chinese mapping number routing I want to design Chinese mapping number routing. How can I improve this code in the method mapRouting?

I want to use reflect auto get method name by providing a value without if else, but I have no idea how to do it.

public class FwMappingChi {

    public static Map<String, String> mapRouting(String mapName){
        if(mapName == "ACTION") {
            return ACTION;
        }
        else if(mapName == "ENVIRONMENT") {
            return ENVIRONMENT;
        }
        else if(mapName == "RULE_TYPE") {
            return RULE_TYPE;
        }
        return null;
    }

    @SuppressWarnings("serial")
    private static final Map<String, String> ACTION = new HashMap<String, String>(){
        {
            put("0", "新增");
            put("1", "刪除");
        }
    };

    @SuppressWarnings("serial")
    private static final Map<String, String> ENVIRONMENT = new HashMap<String, String>(){
        {
            put("0", "正式環境");
            put("1", "長期UAT");
            put("2", "測試需求");
        }
    };

    @SuppressWarnings("serial")
    private static final Map<String, String> RULE_TYPE = new HashMap<String, String>(){
        {
            put("0", "系統間連接");
            put("1", "系統間連接");
            put("2", "人員維護用");
            put("3", "提供服務用");
            put("4", "User對外連接");
        }
    };
}

example:

List<Map<String, Object>> exportDatas = fwApplyListDetailMapper.getExportQuery(idsArr);
List<List<String>> pdfValues = new ArrayList<>();
for (int i = 0; i < exportDatas.size(); i++) {
    List<String> record = new ArrayList<>();
    Map<String, Object> map = exportDatas.get(i);
    for (String index : headerIndex) {
        Object value = map.get(index);

        if(FwMappingChi.mapRouting(index) != null) {
            record.add(FwMappingChi.mapRouting(index).get(String.valueOf(value)));
        }

    }
    pdfValues.add(record);
    record = null;
}

You could simply put your maps in a map, as the mapRouting function is nothing but a simple lookup.

Prepare somewhere

private static final Map<String, Map<String, String>> MASTER = new HashMap<>() {
   {
       put("ACTION", ACTION);
       put("ENVIRONMENT", ENVIRONMENT);
       put("RULE_TYPE", RULE_TYPE);
   }
};

And simply access that map:

public static Map<String, String> mapRouting(String mapName) {
    return MASTER.get(mapName);
}

BTW: in times of Java 10 you should really use Map.of instead of anonymous map subclasses.

Example of using reflection.

public static Map<String, String> mapRouting(Class<?> declaringClass, String mapName)
        throws IllegalAccessException {

    if (declaringClass == null || mapName == null) {
        return null;
    }
    Field[] declaredFields = declaringClass.getDeclaredFields();
    for (Field field : declaredFields) {
        field.setAccessible(true);
        if (mapName.equals(field.getName())) {
            return (Map<String, String>) field.get(mapName);
        }
    }
    return null;
}

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
    Map<String, String> map = mapRouting(FwMappingChi.class, "ACTION");
    System.out.println(map);
}

I suggest you look at this link


Is it okay to 'abuse' re-assignment? Because I don't like using \ to break long lines (to comply with PEP8), I tend to do something like this:

message = "There are {} seconds in {} hours."
message = message.format(nhours*3600, nhours)
print(message)

It also makes code cleaner. Is this an okay way of doing things?

It's more than okay, it is nicely readable, has no problems and involves no abuse whatsoever. I sometimes do the same.

Nothing necessarily wrong with doing that - I use that for situations that the message would be used more than once. However, for one-shot, multiline messages I'd do:

message =  "There are %d seconds " % nhours*3600
message += "in %d hours." % nhours
print message

Honestly, the only difference is stylistic. I prefer this method because it places the variables directly within the string, which I feel is more readable.


Python function to find the next smaller number with same set of digits Problem: Write a function that takes a positive integer and returns the next smaller positive integer containing the same digits.

My solution:

def next_smaller(n):
    import itertools
    x = list(str(n)) #list of digits
    #permutates and joins digits
    x = [int(''.join(i)) for i in list(itertools.permutations(x))]
    x.sort() #sorts numerically
    #picks number previous to original in list
    r = [x[i-1] for i in range(0,len(x)) if x[i] == n][0]
    if r > n: return -1 #returns -1 if no solution
    else: return r #returns solution

My code works, however it is terribly inefficient with very large numbers. Any way to make this code more efficient and cut down the execution time?

The solution to a good algorithm is a clear logic. Your code uses the "hammers" that are present, spring to mind, and do a tiny bit more than needed. So start to find a logic first.

To get the next smaller number the most strict algorithm would be:

Example: 1253479

Start from the last digit to the first as long as the digits are decreasing or equal. 12[5]+increasing 3479, 5 > 3.
From the increasing tail pick the element just smaller (4), and reverse the tail. 12(4)+decreasing 97[5]3.

Result: 1249753

The math is relatively simple, and the algorithm linear to the length.

  As you see the code can do with the "hammers", functions, you use.

Explanation (on request)

Say you have a number 1253479 = prefix 12, digit 5, and increasing suffix 3479. (5 > 3 hence a smaller permutation on digit+suffix is possible)

An increasing (non-decreasing) suffix 3479 is the first minimum permutation; other permutations like 4379 are greater.

A decreasing (non-increasing) suffix 9753 is the last maximum permutation; other permutations like 9735 are smaller.

Hence a permution++ resp. permutation-- works like:

1 2 5 3 4 7 9
     \ / / /
= =
     / \ \ \
1 2 4 9 7 5 3

Roughly reminiscent of increasing/decreasing an integer on paper with a suffix 00...0.

A proof would be more for a math forum.

As this answer has its probably deserved downvotes (it insists on a redesign), I leave it at that.

Following the input from Joop Eggen, I believe the below algorithm works and it is much faster than the original solution in the question. Making a list of all permutations will have an enormously large number of entries for large numbers (like 125658452143250) and will probably stall your computer.

import itertools

def next_smaller(number):
    new_number = number
    digit = [int(i) for i in str(number)]
    digits = len(digit)-1
    index_1 = digits-1

    while index_1 >= 0:
        index_2 = digits
        while index_2 > index_1:
            if digit[index_2] < digit[index_1]:
                digit[index_2], digit[index_1] = digit[index_1], digit[index_2]
                _first = digit[0:index_1+1]
                _second = digit[index_1+1:]
                _second.sort(reverse=True)
                digit = _first + _second
                new_number  = int(''.join(str(i) for i in digit))
                print(f'the next smaller number is: {new_number}')
                return new_number

            else:
                index_2 -= 1

        index_1 -= 1

    return new_number

def main():
    number = int(input('give me a number please: '))
    solution=[number]

    counter = 0

    while counter>-1:
        new_number = next_smaller(number)
        if new_number < number:
            number = new_number
            solution.append(number)
            counter += 1

        else:
            print(f'smallest number is found ...\n'
                  f'number of smaller numbers is {counter}')
            break

    print(f'solution is \n {solution}')

if __name__ == "__main__":
    main()

Thanks to Ruud van der Ham below is a more Pytonic version of the function:

def next_smaller(number):
    new_number = number
    digit = list(str(number))  # there is no need to convert to numbers. Characters are ok.
    digits = len(digit)-1

    for index_1 in range(digits-1, -1, -1):  # this is prefered over while
        for index_2 in range(digits, index_1-1, -1):  # this is prefered over while
            if digit[index_2] < digit[index_1]:
                digit[index_2], digit[index_1] = digit[index_1], digit[index_2]
                _first = digit[0:index_1+1]
                _second = digit[-1:index_1:-1]  # by just backward slicing, there's no need for sort
                digit = _first + _second
                new_number = int(''.join(digit))
                return new_number
    return new_number


New features for Processing game/desk accessory I have written a simple desk accessory in Proccessing called Trip, you can see it below. It is working, but it is very simple, and needs more features.

import processing.pdf.*;

PImage tardis;
int flash = 0;

void setup() {
  size(256, 256);
  frame.setResizable(true);
  tardis = loadImage("TARDIS1.jpg");
  beginRecord(PDF, "trip.pdf");
  background(random(100), random(100), random(100));
  randomSeed(299792458);
}
void draw() {
  stroke(random(100), random(100), random(100));
  line(random(width), random(height), mouseX, mouseY);
  if (flash == 1) {
    background(random(100), random(100), random(100));
  }
}
void keyPressed() {
  if (key == 's') {
    endRecord();
    exit();
  }
  else if (key == 'q') {
    exit();
  }
  else if (key == 'b') {
    background(random(100), random(100), random(100));
  }
  else if (key == 't') {
    image(tardis ,0 ,0, width, height);
  }
  else if (key == 'f') {
    if (flash == 0) {
      flash = 1;
    }
    else if (flash == 1) {
      flash = 0;
    }
  }
}

I would appreciate any new ideas for features, particularly Easter egg-style secret features.

How about something where if you change the background to a particular color, something cool happens?

Like if it turns full black,(0,0,0), it causes an image to pop up on screen.


Python program to find the topic with the most meeting time dedicated to it I must create a program for information regarding schedules and topics of meetings at work.
The data relating to the meetings are stored in an "M" matrix with 5 columns, in which the generic row [g, m, in, fin, arg] denotes the fact that a meeting has been scheduled for day "g" of month "m", from hours "in" to "fin" hours, on the topic "arg".
Write a function "common_argument(M)" that returns the topic to which more time is dedicated.
I wrote the function and correctly returns the element but is it ok or is it too long?

def common_argument(M):
    element = M[0][4]
    for i in range(len(M)):
        if M[i][4] != element:
            if period(M, element) < period(M, M[i][4]):
                element = M[i][4]
    return element

 def period(M,c):
        s = 0
        for i in range(len(M)):
            if c in M[i]:
                if M[i][2] != M[i][3]:
                     if M[i][2] > M[i][3]:
                         s += M[i][2] - M[i][3]
                     if M[i][3] > M[i][2]:
                         s += M[i][3] - M[i][2]
         return s

common_argument([[10, 1, 15, 17, 'Vendite'],
    [10, 1, 17, 18, 'Progetti'],
    [16, 2, 10, 12, 'Vendite'],
    [16, 2, 13, 15, 'Progetti'],
    [5,3,10, 13, 'Progetti']])

This can be radically simplified (and made much more legible) in a variety of ways.

First off, the you use 5 lines of code to compute the duration of a meeting, including checking in advance if that duration will be 0 (if M[i][2] != M[i][3]). You don't care if the duration is 0 (s += 0 leaves s unchanged), and the rest of that logic just ensures that you get a positive difference even if the order of those values is backwards. Technically, the definition of a "meeting" that you give doesn't allow those values to be backwards, so it should be safe to simply subtract the start from the end time; however, even if you want to ensure you end up with a positive value, you can just use abs (absolute value):

def period(M,c):
    s = 0
    for i in range(len(M)):
        if c in M[i]:
            s += abs(M[i][3] - M[i][2])
    return s

Next, don't iterate over the indices of a list when you can just iterate over the list. Why do you care about i? You don't, you only want the value M[i], which is much more cheaply and clearly obtained by simply looping on M:

def period(M,c):
    s = 0
    for meeting in M:
        if c in meeting:
            s += abs(meeting[3] - meeting[2])
    return s

Also, you check if c in m, but that's not really what you mean: you actually want to know if the topic c is the topic that meeting m is about. While we're at it, let's also unpack exactly what a meeting is expected to be, rather than use arbitrary integer indices into a list:

def period(M,c):
    s = 0
    for _, _, start, fin, topic in M:
        if c == topic:
            s += abs(fin - start)
    return s

That's become much more clear now that we've given every value a name (rather than just a number) and been explicit about what we're doing.

Alright, let's tackle the main function now. You iterate over every meeting, and compare it to every other meeting, but this isn't strictly necessary. It also risks doing repeated work (e.g., if you have one REALLY long meeting about 'A' and a thousand tiny ones about 'B', you'll compute the total meeting durations for 'B' a thousand times, and actually do the same with 'A'). Let's first figure out all unique topics, and that way we'll be sure to not re-do any work:

def common_argument(M):
    all_topics = {topic for _, _, _, _, topic in M}
    element = all_topics.pop()
    for other_topic in all_topics:
        if period(M, element) < period(M, other_topic):
            element = other_topic
    return element

Well, that still doesn't prevent us from not duplicating work... let's make sure that we only compute the period of each topic once:

def common_argument(M):
    topic_duration = {topic: period(M, topic) for _, _, _, _, topic in M}
    element, element_duration = ...  # What to put here?
    for other_topic, other_duration in topic_duration.items():
        if element_duration < other_duration:
            element = other_topic
    return element

Alright, we're now only compute each duration once. But the rest of that function is just asking "What is the max topic, sorted by duration?" And, in Python, there's a much easier way to ask that:

def common_argument(M):
    topic_duration = {topic: period(M, topic) for _, _, _, _, topic in M}
    return max(topic_duration, key=topic_duration.get)

The function topic_duration.get takes a topic and returns its duration, and iterating over topic_duration yields each unique topic once, so this will give us exactly what we want.

The one thing we could still improve is that we're iterating over M once for each topic, yielding a runtime of O(N*T) where N = len(M) and T is the number of unique topics. There's no reason for that, we could easily loop over the array just once. That would look more like the following:

from collections import defaultdict

def common_argument(M):
    topic_duration = defaultdict(int)
    for _, _, start, fin, topic in M:
        topic_duration[topic] += abs(fin - start)

    return max(topic_duration, key=topic_duration.get)

And voila, we've collapsed all of the same logic into effectively 4 lines of code, and reduced computational complexity significantly.

You can keep the nesting small by using continue if the condition is not the right one.

def common_argument(M):
    element = M[0][4]
    for i in range(len(M)):
        if M[i][4] == element:
            continue
        if period(M, element) < period(M, M[i][4]):
            element = M[i][4]
    return element

 def period(M,c):
    s = 0
    for i in range(len(M)):
        if c not in M[i]:
            continue;

        if M[i][2] == M[i][3]:
            continue;

        if M[i][2] > M[i][3]:
            s += M[i][2] - M[i][3]
        if M[i][3] > M[i][2]:
            s += M[i][3] - M[i][2]
    return s

See the Zen of Python: Flat is better than nested.


Construct A String Using StringBuilder from a List using elements index I am a java beginner and want to build a string from elements in a list using its elements index, the code runs fine yet i want to learn if there are other ways to improve upon it.Below is my sample code and I'm welcomed to suggestions.

String buildObject(List<Integer> obj){
    StringBuilder name = new StringBuilder();
   for(int i = 0; i < obj.size(); i ++){
       int m = obj.size() - 1;//will be nine
       if(i == 0 && i < 2){
           name.append(obj.get(0))
                   .append(" & ")
                   .append(obj.get(1));
       }else if (i >= 2 && i != m) {
           name.append(", ");//between second and before last value
            name.append(obj.get(i));
       }else if(i == m){//last value
           name.append(" and ")
                   .append(obj.get(m));
       }

   }
  return name.toString();
   }

As far as your code is concerned, it would be more efficient to apply the strings from the first 2 and the last elements outside the loop.  This will eliminate 3 elements from the loop:

String buildObject(List<Integer> obj){
   StringBuilder name = new StringBuilder();
   name.append(obj.get(0))
       .append(" & ")
       .append(obj.get(1));
   int limit = obj.size() - 1;
   for(int i = 2; i < limit; i++){
       name.append(", ");
           .append(obj.get(i));
   }
   name.append(" and ")
       .append(obj.get(limit));
   return name.toString();
}

you can use Streams and MessageFormat and skip the StringBuilder...

List<T> list;

//not mentioned in your question, so...
assert list != null && list.size() > 1

if (list.size() > 2){
    int limit = list.size()-1;
    return new MessageFormat("{0} and {1}" , list.stream().limit(limit).collect(Collectors.joining(" & "), list.get(limit)).toString();
}else{
    return new MessageFormat("{0} & {1}",list.get(0), list.get(1)).toString();
}


File-encryption utility application I made a simple file-encryption utility application for a little school project.
I'm really interested in cryptography, and tried my best while making it.
Can you see it, and give me feedback?

The input is always a FileInputStream (wrapped by a BufferedInputStream), and the output is a ByteBufferOutputStream, which will be written to the output file.

 public class Cryptography {

    private final Cipher c;
    private final MessageDigest md5;
    private final String AES_CBC_PKCS5 = "AES/CBC/PKCS5Padding";
    private final String MD5 = "MD5";
    private final int BLOCK_SIZE = 16;
    private final byte[] bytesIV = new byte[BLOCK_SIZE];

    public Cryptography() throws NoSuchAlgorithmException, NoSuchPaddingException {
        c = Cipher.getInstance(AES_CBC_PKCS5);
        md5 = MessageDigest.getInstance(MD5);
    }

    public void initIV() {
        new SecureRandom().nextBytes(bytesIV);
    }

    public void encryptStream(InputStream in, OutputStream out, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException {
        out.write(bytesIV);
        out.flush();
        c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(bytesIV));
        out = new CipherOutputStream(out, c);
        byte[] buf = new byte[1024];
        int numRead = 0;
        while ((numRead = in.read(buf)) >= 0) {
            out.write(buf, 0, numRead);
        }
        out.close();
    }

    public void decryptStream(InputStream in, OutputStream out, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException {
        in.read(bytesIV);
        c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(bytesIV));
        in = new CipherInputStream(in, c);
        byte[] buf = new byte[1024];
        int numRead = 0;
        while ((numRead = in.read(buf)) >= 0) {
            out.write(buf, 0, numRead);
        }
        out.close();

    }

    public byte[] hash(byte[] key) {
        return md5.digest(key);
    }

    public byte[] getIV() {
        byte[] temp = new byte[BLOCK_SIZE];
        System.arraycopy(bytesIV, 0, temp, 0, BLOCK_SIZE);
        return temp;
    }
}

Exposing the IV only leaves room for errors. Simply generate it at the start of encryption.
There is no point in having a completely unrelated hash method on this class.
There is not integrity protection, so an attacker who can modify the ciphertext you decrypt will likely be able to pull off a padding-oracle attack. Unfortunately it's not trivial to combine streaming decryption with integrity protection, since you must ensure that you don't release any plaintext you haven't authenticated.
Once you eliminate the IV storage, as recommended above, you have no state to preserve across calls, which means you don't need any instance fields anymore. They only make your class thread-unsafe without any benefit.
Closing out seems pretty weird, I wouldn't expect that behaviour. On the other hand you don't close in.
If you decide to dispose resources, use try...finally (or try-with-resources) to do so reliably.
I'd make the class immutable and threadsafe, storing only the key (and algorithm if it's not hardcoded) in it.

Some general comments:

String initialisaion, avoid things like String AES_CBC_PKCS5 = "AES/CBC/PKCS5Padding"; - wrap the "..." in new String( "..." ); Same comment for MD5.
Variable naming, use lower case as a preference, camelCase with variable names that are multiple words (like you have with method names). Avoid underscores separating words in variable names.
If you're initialising some things in the Constructor, you may as well initialise them in the variable declaration (variables are generated immediately prior to Constructor calls).
Your private fields get no benefit from the final keyword, and indeed, you shouldn't have a final IV. Block size probably should be passed into the Constructor (and sanitized). But then, you could also pass the cipher spec at runtime too.
There's no point generating a new SecureRandom every time you want to initIV() - move SecureRandom to a private field.
You're propogating an awful lot of exceptions further up the stack. Avoid this. Handle the exceptions in an acceptable way, re-throw exceptions (even custom ones) where necessary.
encryptStream() doesn't only encrypt. It writes to another stream. Do you need to work with streams here? I'd suggest working with an array of bytes is more appropriate (and allows you to change keys between blocks of bytes at arbitary lengths). Same comment for decryptStream()
If you really need to read from stream, encrypt and immediately write to another stream, rename the methods to be descriptive. Also, since you always close out, maybe you should close in too? Or maybe you should let the caller decide (by allowing them to specify a boolean argument; or by not doing anything and providing JavaDoc comment stating why you're not closing resources).
hash() is a poorly named method. Consider something like getKeySum()
getIV() is a poorly named method, and in it's current implementation is only appropriate if you've encrypted the stream and haven't called initIV() again.
decryptStream() assumes that the IV is the same as the one generated in initIV() - this gives rise to a fairly trivial bug if I give you a stream that was encrypted with a previously generated IV.


External variable in callback for chunk() I am trying to implement search in Laravel. I want to search on models. Since there can be many records in the database, I am trying the chunk function.

public function searchLeads($param)
    {
        $results = array();

        // get all leads
        Lead::chunk(100, function($leads) use ($results, $param) {
            // search in name
            $results = array_merge($results, $this->repository->searchInName($leads, $param));

            // search in email
            $results = array_merge($results, $this->repository->searchInEmail($leads, $param));

           // and so on ...
    }

    // eliminate duplicates
    $collection = collect($results);
    $collection = $collection->unique();

    $results = $collection->all();

    dd($results);
    // return $results;
}

Note: The searchIn... functions return array of results and are working as expected.

When I try the above code, I get an empty array. So I changed the following line (added a reference & to $results).

Lead::chunk(100, function($leads) use (&$results, $param) {

Now I get the expected output.

Am I doing this the correct way? Have I stumbled upon the right solution, or am I missing something that might introduce bugs in the code?

You managed to bypass the query builder, which could have implemented this as a trivial, single query on the backing database, and instead managed to emulate that query in an very inefficient manner yourself.

// get all leads
Lead::chunk(100, function($leads) use ($results, $param) {
    // search in name
    $results = array_merge($results, $this->repository->searchInName($leads, $param));

    // search in email
    $results = array_merge($results, $this->repository->searchInEmail($leads, $param));

    // and so on ...
}

This effectively causes 2 additional queries to the database for each 100 results in the Lead model. This might still work reasonably in your test environment where you have at most a few dozen leads registered, but will crawl to a halt in production as the number of leads increases with time.

Even worse, it requires you to stream all existing Lead instances through PHP, even if they are not even part of the final result set.

The chunk call should replace the get call - it is designed to work on the pre-get() query builder object.

means you need to change Lead::chunk to
$leads = Lead::orderBy('created','desc');
$leads->chunk(100, function($leads) use ($results, $param) {
            // search in name
            $results = array_merge($results, $this->repository->searchInName($leads, $param));

            // search in email
            $results = array_merge($results, $this->repository->searchInEmail($leads, $param));

           // and so on ...
    }

and for more
do not need of method $collection->all()

$collection = collect($results);
$collection = $collection->unique();
$return  = $collection->all();
dd($return);


Python static / instance method or function? background:
I have a model called FileInfo, which represents a sftp file / windows dfs file.

class FileInfo(object):
    def __init__(self, server_info, folder_path, file_name):
        self.server_info = server_info
        self.folder_path = folder_path
        self.file_name = file_name

    def get_file_full_path(self):
        return os.path.join(self.folder_path, self.file_name)

FileInfo has a ServerInfo to hold the server connection info: e.g. sftp connection details.

class ServerInfo(object):
    pass

class WindowsServerInfo(ServerInfo):
    pass

class SFTPServerInfo(ServerInfo):
    pass

this is how I print out the full path:

if __name__ == '__main__':
    sftp_server_info = SFTPServerInfo()
    win_server_info = WindowsServerInfo()

    print FileInfo(win_server_info, r'\\dfs\domain\tmp', 'test.txt').get_file_full_path()
    print FileInfo(sftp_server_info, r'/tmp', 'test.txt').get_file_full_path()

the application is running in Windows and Linux, so the output of the above code will be different -- depends on the hosting OS result on Linux:

\\dfs\domain\tmp/test.txt
/tmp/test.txt

result on Windows:

\\\\dfs\\domain\\tmp\\test.txt
/tmp\\test.txt

I want to have a consistent output, such as:

\\dfs\domain\tmp\test.txt
/tmp/test.txt

so I start to refactor the code:

v1. if...else...

class FileInfo(object):
    def get_file_full_path(self):
        if isinstance(self.server_info, SFTPServerInfo):
             return r'%s/%s' % (self.folder_path, self.file_name)
        elif isinstance(self.server_info, WindowsServerInfo):
            return r'%s\%s' % (self.folder_path, self.file_name)
        else
            raise exception

it works, but if...else means it'll be a big method if I want to support more server types. so I'm going to create a dict to handle it.

v2. a dict contains ServerInfo type and function mapping

class FileInfo(object):
    def get_file_full_path(self):
       return get_full_path_functions[type(self.server_info)](self.folder_path, self.file_name)

def get_full_path_windows(folder_path, file_name):
    return r'%s\%s' % (folder_path, file_name)

def get_full_path_sftp(folder_path, file_name):
    return r'%s/%s' % (folder_path, file_name)

get_full_path_functions = {
    WindowsServerInfo: get_full_path_windows,
    SFTPServerInfo: get_full_path_sftp
}

it works fine, but I think it may be a good idea to move these methods into ServerInfo

v3. instance method

class FileInfo(object):
    def get_file_full_path(self):
        return self.server_info.get_full_path(self.folder_path, self.file_name)

class WindowsServerInfo(ServerInfo):
    def get_full_path(self, folder_path, file_name):
        return r'%s\%s' % (folder_path, file_name)

class SFTPServerInfo(ServerInfo):
    def get_full_path(self, folder_path, file_name):
        return r'%s/%s' % (folder_path, file_name)

however, get_full_path methods are not using self, and this method should not belongs to any instance of ServerInfo

v4. static method

class FileInfo(object):
    def get_file_full_path(self):
        return type(self.server_info).get_full_path(self.folder_path, self.file_name)

class WindowsServerInfo(ServerInfo):
    @staticmethod
    def get_full_path(folder_path, file_name):
        return r'%s\%s' % (folder_path, file_name)

class SFTPServerInfo(ServerInfo):
    @staticmethod
    def get_full_path(folder_path, file_name):
        return r'%s/%s' % (folder_path, file_name)

All these 4 versions are working as expected, please help to review them and let me know:

from the OOP perspective, which one is the best? is there a better way to desing it?
from Python perspective, which one is the most
pythonic way?

Since you have classes that represent the configuration of various server types, you should keep the path structure in them and uses it from them. pathlib provide an abstraction over windows and unix file paths that you can store in these classes and reuse it from FileInfo.

import pathlib

class FileInfo(object):
    def __init__(self, server_info, folder_path, file_name):
        self.server_info = server_info
        self.folder_path = folder_path
        self.file_name = file_name

    def get_file_full_path(self):
        return self.server_info.paths(self.folder_path, self.file_name)

class ServerInfo(object):
    pass

class WindowsServerInfo(ServerInfo):
    paths = pathlib.PureWindowsPath

class SFTPServerInfo(ServerInfo):
    paths = pathlib.PurePosixPath

However, if the only purpose of the FileInfo class is to retrieve a path from its arguments, then you’re better of putting this function directly into ServerInfo:

class ServerInfo(object):
    def get_file_full_path(self, folder_path, file_name):
        return self.paths(folder_path, file_name)

class WindowsServerInfo(ServerInfo):
    paths = pathlib.PureWindowsPath

class SFTPServerInfo(ServerInfo):
    paths = pathlib.PurePosixPath

And you could improve it by allowing multiple path segments:

class ServerInfo(object):
    def get_file_full_path(self, *path_segments):
        return self.paths(*path_segments)

class WindowsServerInfo(ServerInfo):
    paths = pathlib.PureWindowsPath

class SFTPServerInfo(ServerInfo):
    paths = pathlib.PurePosixPath

But it seems that you're only using Python 2, so pathlib may not be available. You can still use your '%s/%s' or '%s\\%s' style approach, but you will loose some path simplifications provided by pathlib:

class ServerInfo(object):
    def get_file_full_path(self, *path_segments):
        return self.path_delimiter.join(*path_segments)

class WindowsServerInfo(ServerInfo):
    path_delimiter = '\\'

class SFTPServerInfo(ServerInfo):
    path_delimiter = '/'

Oh, and talking about '%s/%s' or '%s\\%s', str.format is the prefered way over % formating syntax.

IMHO, OS dependence is in behavior, not in the class state. So modeling the differences in the class hierarchy may not be desirable. Maybe your code can detect the OS environment early and dispatch to different functions that represent the behaviors.

def get_full_path(os_env):
  return {
      'Windows': lambda : ...,
      'Sftp': lambda : ...
    }.get(os_env)()


String finder function This function finds a certain string within a string. I feel like my function is too messy.

I'm new to C memory functions. Are there any shortcuts I can take to make this function shorter? Is this implementation effective?

bool strfound(char * find, char * name) {
    int j = 0;
    int size = strlen(name) + 1;
    char * buffer;
    buffer = (char*)malloc(size + 1);
    for (int i = 0; i < size; i++) {
        std::cout << buffer << std::endl;
        if (i == 0 && name[i] != ' ') {
            j++;
            buffer[j - 1] = name[0];
        }
        if (i != 0 && name[i] != ' ') {
            buffer[j] = name[i];
            j++;
        }

        if (name[i] == ' ' || i == size - 1) {
            buffer[j] = '\0';
            if (strcmp(buffer, find) == 0) {
                std::cout << "String is found: " << buffer << std::endl;
                buffer[j] = '\0';
                std::cout << name << std::endl;
                free(buffer);
                return true;
            }
            strcpy(buffer, ""); // or null from 0
            buffer = (char*)malloc(size + 1);
            j = 0;
        }
    }
    return false;
}

Output: https://gyazo.com/2fc0fe88958dfeb2f8cf20eff1f2d113

The answer to your primary question is yes, methods already exist in libraries that can do this. Reference this StackOverflow post.

Your method can then be simplified to what's shown below:

#include <string>

bool strfound(const std::string &in, const std::string &substr) {
    return in.find(substr) != std::string::npos;
}

Quick function I wrote up that might help, tested it twice so it should work:

//Returns 0 for succes and 1 for failiure
int strfound(const char *string, const char *name) {
    int stringSize = strlen(string);
    int nameSize = strlen(name);

    if (nameSize > stringSize || nameSize <= 0) {
       return 1;
    }

    int foundChars = 0; //Number of the chars found in the scanned string

    for (int i = 0; i < stringSize; i++) {
        if (string[i] == name[foundChars]) { //Looks for match in string and name at indexes i and foundChars
           foundChars++;
           if (foundChars == nameSize) {
              return 0; //Succes
           }
        }
        else {
            foundChars = 0; //Reset the foundChars counter
        }
    }

    return 1; //Scanned whole string failiure
}

If you want the function to only find the words as their own words and not inside of another word, you can just check for a space one step back, before foundChars gets set to 1 (also check if it's the start of the string i.e. i == 0). For the end of the name (foundChars == nameSize) check for a space or end of string one step forward in string. Leave a comment on the answer if you want a more in depth/better explanation.

I think this method could work a lot better because you don't need to allocate any memory manually, and it's much more readable.

Hope this helps.


How could I make this PHP $_POST more secure? -Or is it secure already? On most my $_post data inputted on my site I use the following php:

$example = $_POST['textfield'];
$example = strip_tags($example);
$example = mysql_real_escape_string($example);

And then I would interact with the MySQL database...

Is this 'secure' / 'safe'?

Any major exploits to the above code?

-How could I make it secure?

Thanks alot.

I recommend getting yourself a simple, simple function that uses PDO and parameterizing of queries by default behind the scenes.

Here are sample use cases for query functions that use PDO in the background that I use all the time:

$iterable_resultset = query('select * from users where email = :email and username ~* :username or user_id = :user_id', array(':email'=>$email, ':username'=>$username, ':user_id'=>(int)$user_id));
// Results a resultset that is able to be foreached over.

$multidimensional_array = query_array('select * from users where email = :email and username ~* :username or user_id = :user_id', array(':email'=>$email, ':username'=>$username, ':user_id'=>(int)$user_id));
// Results in a multidimensional array with each subarray corresponding to a database row, or null.

$row_of_data = query_row('select * from users limit 1');
//Results in a single dimensional array or null.

$item = query_item("select max(score) from players where username ~* :username", array(':username'=>$username));
// Returns a single piece of information, or null.

There's a lot of advantage from a refactoring viewpoint to having simple function-based parameterizing of sql queries.  PDO is often verbose, and sometimes when you're securing bad code you need simple, terse functions to fit in the place of old mysql_query() calls and the like.

In your specific case, I think that you are making the mistake of escaping before it's time, which can often introduce weird bugs.

$untrusted_input = @$_REQUEST['password'];

is all that you should do when getting the input.  Don't strip tags, don't do anything until it comes time to -use- that untrusted input in sql or in html:

In the sql, parameterize it while using the sql, filter/modify the data based on the circumstances.
When outputting to html, escape it then, e.g. via .htmlentities($example). or using a templating engine.

Here's an example of your code turning a non-existent get/post variable (that would normally result in null) into an empty string, for just the first of many subtle things that happen when you escape too early: http://ideone.com/r7bSr

In general, when you're first getting used to the security issues that php can throw your way, I really recommend using a template engine (e.g. smarty) to help you keep your business logic and your display templates separate.  A lot of people will argue about whether you need a templating engine with php because php is a templateable system already.  Engine or not doesn't matter, but a template-based approach to separate your manipulation logic from your display logic is very necessary, which most programmers would probably agree on.  And personally, I found it easier to learn how that separation benefits php when I was first starting out by just learning how a templating engine does things, before I could understand how to apply those principles to native php without a templating engine.

TL;DR; - Set up a templating engine, it'll get you using best practices faster.

Apart from what has already been mentioned, a crucial part you're missing is a magic_quotes check and taking according action, this means reversing all its effects. (unless you do that at the beginning after your script starts).

If enabled, magic_quotes will escape all quotes with a backslash, and each backslash with a backslash.

Read more about magic_quotes here.


Check if there's exactly one match in a vector The challenge is to iterate over the vector only once and return the value within the range of the zero. However, if there are no matches or more than 1 match, deliver an error. The vector is unsorted and has no guarantee on it's size or the range of data.
More technically, the number of data accesses into the vector can't exceed N + 1 (access to iterators doesn't count)

I did this with a simple loop with 2 nested checks, and was wondering if there was a stdlib based or a better algorithmic solution that I'm not able to find.

Maybe ranges can help, but I'm limited to c++17 here, though the only c++17 feature I'm using is std::optional for error handling.

#include <optional>
#include <vector>

std::optional<int> get_unambiguous(const std::vector<int> &data,
                                    const int range,
                                    const int zero = 0)
{
    std::optional<int> found;
    for (const auto& item: data)
    {
        if (std::abs(item - zero) < range) {
            if (found) {
                return {};
            }
            found = item;
        }
    }
    return found;
}

The standard library find functions return the .end() iterator for the container if they fail to find anything. We could follow the same convention, instead of using std::optional.

Rather than nesting the checks, we could split it into two separate loops, and use  std::find_if from the <algorithm> header, something like this:

auto const is_in_range = [&] (int item) { return std::abs(item - zero) < range; };

auto const first = std::find_if(data.begin(), data.end(), is_in_range);

if (first == data.end())
    return data.end(); // found nothing

auto const second = std::find_if(std::next(first), data.end(), is_in_range);

if (second != data.end())
    return data.end(); // found a second entry

return first;

If you're just checking for two values in a range, use a lambda and search linearly through the vector. To speed things up, you can break once you find a second value in that range. Here's how I did it:

struct Match
{
    bool has_match;
    int value;
};

Match has_one_match(const std::vector<int>& data, int lower, int upper)
{
    if (upper < lower)
    {
        return { false, 0 };
    }

    unsigned times_found = 0;
    const auto is_in_range = [&lower, &upper](int input)
    {
        return input >= lower && input <= upper;
    };

    Match ret_match{ false, 0 };
    for (const auto& num : data)
    {
        if (is_in_range(num))
        {
            if (++times_found == 2)
            { // 2 values found, condition violated; break
                break;
            }

            ret_match.value = num;
        }
    }

    if (times_found == 1)
    {
        ret_match.has_match = true;
    }

    return ret_match;
}

From there, to avoid using std::optional, just check if Match::has_match is true before preforming anything with the value.


Seq[Either[A, B]] => Either[A, Seq[B]] Function I wrote a function of type Seq[Either[String,Int]] => Either[String, Seq[Int]]

scala> xs
res11: List[Either[String,Int]] = List(Right(1), Right(55))

scala> acc
res12: Either[String,Seq[Int]] = Right(List())

scala> xs.foldLeft(acc){ (acc, elem) => {
     |     acc.right.flatMap(list => elem.right.map(_ +: list) )
     | }}
res10: Either[String,Seq[Int]] = Right(List(55, 1))

Please review my foldLeft solution. Perhaps there's a higher order function that can more elegantly do this work?

A few points:

Your implementation reverses the order of elements if it succeeds (i.e. if they're all rights). I'm assuming this isn't intentional?
You're taking a list but returning a Seq. This may be what you want, but I find it a little confusing.
The inner curly brackets are unnecessary (and I personally find them kind of noisy).
I'd strongly suggest not shadowing the external acc with the accumulator function argument.

So I'd probably write it like this:

val xs: List[Either[String, Int]] = List(Right(1), Right(55))

xs.foldRight(Right(Nil): Either[String, List[Int]]) { (elem, acc) =>
  acc.right.flatMap(list => elem.right.map(_ :: list))
}

Or:

xs.foldRight(Right(Nil): Either[String, List[Int]]) { (elem, acc) =>
  for {
    t <- acc.right
    h <- elem.right
  } yield h :: t
}

But that's only if I couldn't use cats or Scalaz, both of which provide this operation as sequenceU:

scala> import cats._, cats.syntax.traverse._, cats.std.all._
import cats._
import cats.syntax.traverse._
import cats.std.all._

scala> val xs: List[Either[String, Int]] = List(Right(1), Right(55))
xs: List[Either[String,Int]] = List(Right(1), Right(55))

scala> xs.sequenceU
res0: scala.util.Either[String,List[Int]] = Right(List(1, 55))

Which is much nicer.

Probably not the most glamorous solution (feel free to efficientiate) to the problem, but you could always...

    def transmogrify[A, B](someSeq: Seq[Either[A, B]]): Either[A, Seq[B]] = {
      if (someSeq.exists(_.isLeft)) Left(someSeq.collect( { case Left(anA: A) => anA }).head)
      else Right(someSeq.collect { case Right(aB: B) => aB })
    }


Find the repeated elements in a list You are given an array of n+2 elements. All elements of the array are in range 1 to n. All elements occur once except two numbers, which occur twice. Your task is to find the two repeating numbers.

My solution is:

t=int(input()) #number of test cases
for _ in range(t):
    n=int(input()) # no. of array elements
    l=[int(x) for x in input().split()]  #array elements
    for i in range(1,n-1):
        if l.count(i)==2:  # using count function to count the elements
            print(i,end=' ')
    print()

How can I improve it?  Currently, it shows time limit exceeded on hackerrank.

Minor

Consider using the unittest module instead of using input to test
Use a if __name__ == "__main__" guard
Make it a function
Don't print but return variables

Timing improvements

  l.count(i) == 2

It will search the entire list from the start.

Let's take a sample input (worst case) of [2, 3, 4, 5, 6, 7, 8, 1, 1, 2, 2], it will search the entire list 10 times!

This can be done in \$ O(n) \$ (worst case), because we know

  All elements of the array are in range 1 to n

You can create a list temp with length n filling it with None or 0
For every number in the array, check if the value in temp[i] is empty (0 or None)

If it is empty put the value on that position
If the number is the same as the value of the temp list, we have seen it before

Revised Code

def find_repeating(lst):
    counts = [None] * len(lst)
    for i in lst:
        if counts[i] is None:
            counts[i] = i
        elif i == counts[i]:
            yield i

Note

This has the disadvantage of continuing to loop after the numbers are found, to avoid this you could add the elements to another array and return when the length of the array is 2.

It will not make the most "beautiful" code, but it will be faster than @Peilonrayz's answer for anything but worst case, since that requires to loop through the entire array.

def find_repeating(lst, count=2):
    ret = []
    counts = [None] * len(lst)
    for i in lst:
        if counts[i] is None:
            counts[i] = i
        elif i == counts[i]:
            ret += [i]
            if len(ret) == count:
                return ret

Timing all solutions

Your approach: Count iterates throuh the whole array for every element. That mean n^2 times.
Better solution: Do not compare numbers that were already compared. You should compare a number only with numbers infront of it.

#list with your numbers
num_list = [...]

for i in range(len(num_list)):
    for j in range(i+1, len(num_list)):
        if num_list[i] == num_list[j]:
            print(num_list[i])


Interface for server requests and responses I have an MVC framework I've written. I'm trying to abstract out ASP.NET specific bits as well as make it more testable. Previously, I relied on HttpContext.Current in many places, which proves to be very unfriendly to unit testing. So, I started designing my own minimalistic interface for everything I'd need from there. However, it seems to keep on growing.

/// <summary>
/// This is a very simplified context for server requests and responses
/// It should not cover "everything", but should instead have only what BarelyMVC needs to function
/// As a result, it will usually only have the most commonly used things in it
/// All "get" methods should normally return null if a given name/key doesn't exist
/// </summary>
public interface IServerContext
{
    /// <summary>
    /// Gets a cookie from the current request
    /// </summary>
    HttpCookie GetCookie(string name);
    /// <summary>
    /// Sets a cookie to send with the current response
    /// </summary>
    void SetCookie(HttpCookie cookie);
    /// <summary>
    /// Kills the current request. Kills it with fire! This function should never return(for security purposes)
    /// </summary>
    void KillIt();
    /// <summary>
    /// Gets the user agent sent by the current request
    /// </summary>
    string UserAgent{get;}
    /// <summary>
    /// Maps a relative URL path to an absolute path on the host (is this needed?)
    /// </summary>
    string MapPath(string path);
    /// <summary>
    /// Gets the client's IP address
    /// </summary>
    string UserIP{get;}
    /// <summary>
    /// Gets an HTTP header by name from the current request
    /// </summary>
    string GetHeader(string name);
    /// <summary>
    /// Sets an HTTP header to be sent back in the response to the current request
    /// </summary>
    void SetHeader(string name, string value);
    /// <summary>
    /// Performs a server-side transfer to another URL to service the current request (is this needed?)
    /// Should perform a KillIt() afterwards and never return
    /// </summary>
    void Transfer(string url);
    /// <summary>
    /// Send a 302 redirect back to the client for the given URL and use KillIt() to end the request
    /// </summary>
    void Redirect(string url);
    /// <summary>
    /// Gets a generic item from a key/value store associated with the current request only
    /// </summary>
    object GetItem(string name);
    /// <summary>
    /// Sets a generic item to a key/value store associated with the current request only
    /// </summary>
    object SetItem(string name, object value);
    /// <summary>
    /// Gets or sets the HTTP status code
    /// </summary>
    string HttpStatus{get;set;}
    /// <summary>
    /// Gets a TextWriter which can be used to send content back as the response
    /// </summary>
    TextWriter Writer{get;}
    /// <summary>
    /// Gets a parameter dictionary corresponding to the FORM values passed in by a POST request
    /// </summary>
    ParameterDictionary Form{get;}
    /// <summary>
    /// Gets the URL of the current request
    /// </summary>
    Uri RequestUrl{get;}
}

Is this interface already too big? I know I could abstract out the Request and Response parts, but I tend to think it make it a bit harder to use, especially because of my limits on "get" and "set" being stuck to request and response respectively.

What do you think? Refactoring into Request/Response interfaces, or is it OK how it is?

You have to keep in mind that the earlier version of the .NET framework suffered in applying the interface segregation principle. In this case, the HTTP context includes methods associated with the request (ex. URL), the response (ex. HTTP status) and server utility functions (ex. map path).

With that in mind, the interface looks OK and familiar in terms of usage in comparison to the original HttpContext (System.Web) and HttpContextBase (System.Web.Mvc) and should be fine.

One aspect in regards to MVC that is hard to manage is the multiple data sources (query parameters, URL parameters, HTTP post Form values, routing parameters, session and the per request key/value store (HttpContext.Current.Items)) - perhaps it would be worthwhile to create an intermediary to manage these.

As a framework author, you have the responsibility to do a lot of the heavy lifting for your users.  Put yourself in their shoes.  Ask what you'd like?  Think about scenarios in which someone might need a request without a response or vis versa.  Also note any properties/operations of HttpContext that are about the server (MapPath) and not related to requests or responses at all.


Simple countdown programs to print "3, 2, 1, Action!" using while loop My program is a simple while loop making a countdown starting from 3 and shouts "Action!" upon reaching zero and then breaks. I would like to know which of the following ways is better in means of clarity and functionality. I am aware that there are other ways to achieve the same thing. I would like to hear your thoughts and suggestions.

countDown = 3
while (countDown >= 0):
    print(countDown)
    countDown = countDown - 1
    if countDown == 0:
        print("Action!")
        break

or

countDown = 3
while (countDown >= 0):
    if countDown != 0:
        print(countDown)
        countDown = countDown - 1
    else:
        print("Action!")
        break

Why does it has to be a while?

Maybe it is preference but for loops look cleaner.

Reversing can be done by using reversed function which reverses a iteration

countdown = 3
for count in reversed(range(1, countdown+1)):
    print(count)
print('action!')

Or you could use the step parameter in range(start, end, step) and rewrite the for loop to

for count in range(countdown, 0, -1):

count_down = 5

while count_down > 0:

print(count_down - 1)

count_down -= 1

if count_down == 0:

print ("Action!")


Transform an object into another object structure I've got such an input object, which I should modify in order to use it with some charts library.

const input = {
  foo: {
    bar: 'biz',
  },
  statistic: {
    "2019-11": {
      A: 11,
      B: 11,
      C: 11,
      D: 11,
      E: 11,
    },
    "2019-12": {
      A: 12,
      B: 12,
      C: 12,
      D: 12,
      E: 12,
    },
    ....
  }
};

My library expects an input like this:

[
  { subject: 'A', '2019-11': 11, '2019-12': 12 },
  { subject: 'B', '2019-11': 11, '2019-12': 12 },
  { subject: 'C', '2019-11': 11, '2019-12': 12 },
  { subject: 'D', '2019-11': 11, '2019-12': 12 },
  { subject: 'E', '2019-11': 11, '2019-12': 12 }
]

And this is my current solution:

const transform = arg => {
  const keys = ['A', 'B', 'C', 'D', 'E'];
  return _.map(keys, key => {
    const data = _.reduce(arg.statistic, (result, value, k) => {
      result[k] = value[key];
      return result;
    }, {});
    return {
      subject: key,
      ...data
    }
  });
}

Any improvements would be very welcome!

So you have five data series here right (A through E)?  What happens when you have 4 or 6 data series?  Do you really want to rewrite your code?

Also, unless you have some reason to do so, lodash seems kind of unnecessary for these sort of simple data transforms these days.  I am guessing using ES6 Array.map, Array.reduce and similar would do the same exact thing while also yielding a more fluent, readable style,

Using reduce to build a map object sounds wrong. By definition, the word reduce means "to make smaller", but you are using it here "to make bigger". A first step might be:

const data = {};
_.foreach(arg.statistic, (key, value) => data[key] = value);

I don't know whether lodash actually has foreach, it's just to illustrate the idea.

There's probably an even more elegant way to create this map out of the data.


Earliest time frog can jump to the other side of a river in C# I'm new to C#, I programmed a little in Java in the past. I had the two previous exercises reviewed here (permCheck, cyclicRotation, with a 100% score, just like this one), and I'm applying what the accepted answers contributed to me.
Even though the site expects names like public int solution(int X, int[] A), I refactored the code after it was accepted, and applied those contributions I mentioned.
Is this how professional code should look like in terms of quality, or are there still things to improve in solutions of easy exercises like this written by me?

Task description

A small frog wants to get to the other side of a river. The frog is
initially located on one bank of the river (position 0) and wants to
get to the opposite bank (position X+1). Leaves fall from a tree onto
the surface of the river.
You are given an array A consisting of N integers representing the
falling leaves. A[K] represents the position where one leaf falls at
time K, measured in seconds.
The goal is to find the earliest time when the frog can jump to the
other side of the river. The frog can cross only when leaves appear at
every position across the river from 1 to X (that is, we want to find
the earliest moment when all the positions from 1 to X are covered by
leaves). You may assume that the speed of the current in the river is
negligibly small, i.e. the leaves do not change their positions once
they fall in the river.
For example, you are given integer X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
In second 6, a leaf falls into position 5. This is
the earliest time when leaves appear in every position across the
river.
Write a function:
class Solution { public int solution(int X, int[] A); }
that, given a non-empty array A consisting of N integers and integer
X, returns the earliest time when the frog can jump to the other side
of the river.
If the frog is never able to jump to the other side of the river, the
function should return −1.
For example, given X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
the function should return 6, as explained above.
Write an efficient algorithm for the following assumptions:
N and X are integers within the range [1..100,000]; each element of
array A is an integer within the range [1..X].

/// <summary>
/// Check if a given array contains the integers 1..N
/// </summary>
/// <returns>
/// -1 if <paramref name="fallenLeaves"/> does not contain all integers
///     1..N, where N = <paramref name="requiredAmountOfLeaves"/>
/// a possitive int i, if the required amount of ints were present at
///     <paramref name="fallenLeaves"/>
/// </returns>

const int FROG_CANT_JUMP_TO_THE_OTHER_SIDE = -1;

public static int GetSecondsRequired
    (int requiredAmountOfLeaves, int[] fallenLeaves)
{
    bool[] leavesAsSteps = new bool[requiredAmountOfLeaves + 1];
    int espectedSum = 0, correctSum = 0;
    for (int i = 1; i <= fallenLeaves.Length; i++)
    {
        if (i <= requiredAmountOfLeaves)
        //get summatory of 1..N
            correctSum += i;
        if (fallenLeaves[i - 1] <= requiredAmountOfLeaves &&
            !leavesAsSteps[fallenLeaves[i - 1]])
        {
        //accumulate where the expected leaf fell and set its location to true
            espectedSum += fallenLeaves[i - 1];
            leavesAsSteps[fallenLeaves[i - 1]] = true;
        }
        if (espectedSum == correctSum && i >= requiredAmountOfLeaves)
        //if all the espected leaves fell, then return the array's
        //index where the last expected leaf was found
            return i - 1;
    }
    return FROG_CANT_JUMP_TO_THE_OTHER_SIDE;
}

Readability

The code needs more spacing. Considering the comments, the indentation and the ifs, it's hard to read without some good old empty lines.

Use brackets when using conditions, especially if you have comments above your single line, it gets really confusing. Also, the readability is increased and, the biggest factor, you'll avoid weird bugs.

If you really don't want to use brackets, at least indent your comments so it's clear the line under it is still into the if.

Considering that we have your explanation of the problem, we can understand pretty clearly what your variable names mean. But still... it could be improved or at least well documented. fallenLeaves doesn't represent fallen leaves, it represent when leaves are falling at which position. expectedSum and correctSum don't mean much, to a point I'm wondering if they are well initialized.

Result for now :

public static int GetSecondsRequired(int requiredAmountOfLeaves, int[] fallenLeaves)
{
    bool[] leavesAsSteps = new bool[requiredAmountOfLeaves + 1];
    int espectedSum = 0, correctSum = 0;

    for (int i = 1; i <= fallenLeaves.Length; i++)
    {
        if (i <= requiredAmountOfLeaves)
        {
            //get summatory of 1..N
            correctSum += i;
        }

        if (fallenLeaves[i - 1] <= requiredAmountOfLeaves &&
            !leavesAsSteps[fallenLeaves[i - 1]])
        {
            //accumulate where the expected leaf fell and set its location to true
            espectedSum += fallenLeaves[i - 1];
            leavesAsSteps[fallenLeaves[i - 1]] = true;
        }

        if (espectedSum == correctSum && i >= requiredAmountOfLeaves)
        {
            //if all the espected leaves fell, then return the array's
            //index where the last expected leaf was found
            return i - 1;
        }
    }

    return FROG_CANT_JUMP_TO_THE_OTHER_SIDE;
}

Algorithm

You use i - 1 everywhere but one place, it would be smarter to reverse this. Use i everywhere and i + 1 at one place.
You use the accessor fallenLeaves[i] often, you should consider storing it in a variable. It will make the code more readable. So : int currentFallenLeaf = fallenLeaves[i];
The usage of expectedSum and correctSum is too complicated for the problem at hand. You don't need to check the sum, only that the number of true elements in leavesAsSteps (minus one because of the zero index) equals requiredAmountOfLeaves.
You could check right at the beginning of the loop if you already marked the "leaf step" as true and that the leaf is valid, so that you don't do useless work.

public static int GetSecondsRequired(int requiredAmountOfLeaves, int[] fallenLeaves)
{
    // You should comment why there's a + 1 here.
    bool[] leavesAsSteps = new bool[requiredAmountOfLeaves + 1];
    int numberOfFallenLeaves = 0;

    for (int i = 0; i < fallenLeaves.Length; i++)
    {
        int currentFallenLeaf = fallenLeaves[i];

        // Have we already checked this number?
        // Is the leaf number out of range?
        // If so, let's just stop right there for this leaf.
        if (currentFallenLeaf > requiredAmountOfLeaves
            || leavesAsSteps[currentFallenLeaf])
        {
            continue;
        }

        numberOfFallenLeaves++;
        leavesAsSteps[currentFallenLeaf] = true;

        // Have we marked all our leaves? We're done.
        if (numberOfFallenLeaves == requiredAmountOfLeaves)
        {
            return i;
        }
    }

    return FROG_CANT_JUMP_TO_THE_OTHER_SIDE;
}

Another way of using Set uniqueness feature is described below:
using System;
using System.Collections.Generic;
class Solution {
public int solution(int X, int[] A) {
    var uniques = new HashSet<int>();
    for (int i = 0; i < A.Length; i++)
    {
        if (!uniques.Contains(A[i]))
        {
            uniques.Add(A[i]);
        }
        if (uniques.Count == X)
        {
            return i;
        }
    }
    return -1;
}

}


Is it possible to DRY these 2 methods of a tailrec Node Tree? I have a Tree structure composed by Node class.

I have to @tailrec method that are visiting up to the root.

Those 2 methods are completely similar, but 1 of those is manipulated a "stats" variable to check the visit and return the root, the other just return the root node.

Here the code sample:

class Node(parent: Option[Node], var visited: Int)
@tailrec
def asc(): Node = {
  parent match {
    case None => this
    case Some(x) => x.asc()
  }
}

@tailrec
def ascVisited(deltaInc: Inc): Node = {
  visited += deltaInc

  parent match {
    case None => this
    case Some(x) => x.ascVisited(deltaInc)
  }
}

Is there any way to reuse the logic of the parent checking and then call recursively the method? I thought with a higher-order function should be possible, but I am not sure is possible with different input argument in the functions.

Any suggestion?

Is it possible somehow to DRY out these 2 bits :

parent match {
  case None => this
  case Some(x) => x.asc()
 }
// and
parent match {
  case None => this
  case Some(x) => x.ascVisited(deltaInc)
}

I defined a Higher-Order function:

@tailrec
def foldAsc(op: Node => Node): Node = {
  op(this)       // <= still this statemnt when x=>x is useless..
  parent match {
    case None => this
    case Some(x) => x.foldAsc(op)
  }
}

def asc(): Node = foldAsc(x => x)

def ascVisited(deltaInc: Inc): Node = foldAsc { x =>
  visited += deltaInc
  x
}

It is not still optimal but DRYed out a little.


Parsing console application arguments In our console app, the parsing of application arguments is done like so:

using System.Linq;

namespace Generator
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            var param1 = args.SingleOrDefault(arg => arg.StartsWith("p1:"));
            if (!string.IsNullOrEmpty(param1))
            {
                param1  = param1.Replace("p1:", "");
            }
            //...
        }
    }
}

It's supposed to be called like this:

`Generator.exe p1:somevalue`

Is there a better/simpler way to parse arguments?

I'd recommend taking advantage of the excellent Mono.Options module.  It's a single .cs file you can drop in to your solution and get full-featured parsing of GNU getopt-style command lines.  (Things like -x -y -z, which is equivalent to -xyz, or -k value, or --long-opt, and so forth.)

Please check solution from link. IT uses linq. It short and reuseble in my opinion. Provides extension method so you just do somethink like:

args.Process(
           () => Console.WriteLine("Usage is switch1=value1,value2 switch2=value3"),
           new CommandLine.Switch("switch1",
               val => Console.WriteLine("switch 1 with value {0}",
                   string.Join(" ", val))),
           new CommandLine.Switch("switch2",
               val => Console.WriteLine("switch 2 with value {0}",
                   string.Join(" ", val)), "s1"));
   }

for details please visit my blog


Various simple JavaScript solutions Please critique my solutions to these simple exercises. I have no programming experience, so the more anal you are, the more I'll learn. I'm teaching myself, this is not for school:

  Write a function translate() that will translate a text into
  "rövarspråket". That is, double every consonant and place an
  occurrence of "o" in between. For example, translate("this is fun")
  should return the string "tothohisos isos fofunon".

var translate = function(x) {
  var string = x.toLowerCase();
  var vowels = ["a", "e", "i", "o", "u", " "];
  var y = "";
  for (i = 0; i < string.length; i++) {
     var current = string.charAt(i);
    if (vowels.indexOf(current) != -1)
    y = (y + (current));
   else
    y = (y + (current + "o" + current));
  }
  return y;
}

  Define a function sum() and a function multiply() that sums and
  multiplies (respectively) all the numbers in an array of numbers. For
  example, sum([1,2,3,4]) should return 10, and multiply([1,2,3,4])
  should return 24.

var sum = function(array) {
  var length = array.length;
  var total = 0;
  for (i = 0; i < length; i++) {
    total += array[i];
  }
  return total;
};

var multiply = function(array) {
  var length = array.length;
  var total = 1;
  for (i = 0; i < length;  i++) {
    total *= array[i];
  }
  return total;
};

  Define a function reverse() that computes the reversal of a string.
  For example, reverse("jag testar") should return the string "ratset
  gaj".

var reverse = function(string) {
  var length = string.length;
  var reversed = [];
  var joined = ("");
  for (i = length; i > 0; i--){
    reversed.push(string.charAt(i-1));
  };
  for (i = 0; i < (length) ; i++){
    joined += (reversed[i]);
  }
  return joined;
}

  Write a function findLongestWord() that takes an array of words and
  returns the length of the longest one.

var findLongestWord = function(array) {
  var elements = array.length;
  var count = 0;
  for (i = 0; i < elements; i++) {
    if (array[i].length > count)
      count = array[i].length;
  }
  return count;
}

  Write a function filterLongWords() that takes an array of words and
  an integer i and returns the array of words that are longer than
  i.

var filterLongWords = function(array, int){
  var length = array.length;
  var longestWords = [];
  for (i = 0; i < length; i++) {
    if (array[i].length > int) {
      longestWords[longestWords.length] = array[i];
    }
  }
  return longestWords;
}

  Write a function charFreq() that takes a string and builds a
  frequency listing of the characters contained in it. Represent the
  frequency listing as a JavaScript object. Try it with something like
  charFreq("abbabcbdbabdbdbabababcbcbab").

var charFreq = function(string){
  var list = {};
  var length = string.length;
  for (var i = 0; i < length; i++) {
  if (string.charAt(i) in list)
    list[string.charAt(i)] += +1;
  else
    list[string.charAt(i)] = 1;
  }
  return list;
}

EDIT: I forgot to mention that rather than use global methods, I tried to as much as possible code for the result I wanted, like reverse, and join, etc.

Here one way to sum a list of integers using ECMAScript 5's functional support

// Sum all values in a list by reducing the list to a single value
array.reduce(function(prev, curr) {
  return prev + curr;
});

Not faster than your approach due to the repeated function calls, but definitely shorter.

Your approach can be further simplified:

// Move everything into the parenthesis of for-loop!
var sum = function(array) {
  for (
    var i = 0, len = array.length, total = 0;
    i < len;
    total += array[i++]
  );
  return total;
};

Not recommended because it's not very readable. I just think it's interesting :)

I'll give you an alternative approach to the "Find length of longest string" problem:

// Sort it by length descending and then get the first
var longestStrLen = array.sort(function(a, b) {
    a.length - b.length;
})[0].length;

Hope these open your eyes to some of the possibilities!

Now, here's an actual review:

var charFreq = function(string){
  var list = {}; // Not a list (implies order). Should name it a dictionary or map
  var length = string.length; // no need to have this be separate line
  for (var i = 0; i < length; i++) {
  if (string.charAt(i) in list)
    // What's with the +1??
    list[string.charAt(i)] += +1;
  else
    // No need to call string.charAt multiple times!
    list[string.charAt(i)] = 1;
  }
  return list;
}

Revised version:

var charFreq = function(string){
  var dict = {};
  for (var i = 0, len = string.length; i < len; i++) {
    var currChar = string.charAt(i);
    if (currChar in dict) {
      dict[currChar] += 1;
    } else {
      dict[currChar] = 1;
    }
  }
  return dict;
}

Hope that helps!

Try using '' instead of "" wherever possible.  In most languages the content of the double quotes gets interpreted, so the single quote version is faster and does not leak variables.

I'm not sure if it is better, but you can define functions like this too:

function findLongestWord(array) {

instead of

var findLongestWord = function(array) {


Unique compile time (constexpr) type ID without RTTI I am making a library where I need to generate a unique ID for a type where the ID must be known at compile time. I first relied on the address of a template function, but it proved itself unreliable both with MSVC and Clang on windows.

Then I came up with the address of a static data member inside a template class.

I want to support most use cases as possible here's what comes to my mind:

Eager optimizations that would merge the definition of static variables or inline functions
DLL and shared libraries
Link time optimizations

My tests were successful, but it wasn't an exotic setup with multiple level dlopen or stuff like that. I'm not an expert with the kind of use case I want to support so it's hard to tell if I can ensure my claims are okay.

My design work by declaring a static data member of type T* inside a template class, then taking its address as the value of the ID.

namespace detail {

/**
 * Template class that hold the declaration of the id.
 *
 * We use the pointer of this id as type id.
 */
template<typename T>
struct type_id_ptr {
    // Having a static data member will ensure (I hope) that it has only one address for the whole program.
    // Furthermore, the static data member having different types will ensure (I hope) it won't get optimized.
    static const T* const id;
};

/**
 * Definition of the id.
 */
template<typename T>
const T* const type_id_ptr<T>::id = nullptr;

} // namespace detail

/**
 * The type of a type id.
 */
using type_id_t = const void*;

/**
 * The function that returns the type id.
 *
 * It uses the pointer to the static data member of a class template to achieve this.
 * Altough the value is not predictible, it's stable (I hope).
 */
template <typename T>
constexpr auto type_id() noexcept -> type_id_t {
    return &detail::type_id_ptr<T>::id;
}

It there any caveats to be aware with this design?

Here's some usage of this and motivation for this code:

constexpr auto id_of_int_type = type_id_t{type_id<int>()};
constexpr auto id_of_float_type = type_id_t{type_id<float>()};

static_assert(id_of_int_type != id_of_float_type);

This can be compiled with -fno-rtti.

Also, it can fully be used at compile time. Here's the equivalent with RTTI:

constexpr auto test = typeid(int); // won't compile

This code won't compile since typeid cannot be used at compile time. Also, disabling RTTI also disables static RTTI.

The code is useful because it can be used in data structure or to be couple with compile time type erasure.

std::map<type_id_t, void*> anything;

// sorry for raw new
anything[type_id<std::string>()] = new std::string{"hello"};

// compile time example
static auto static_int = int{};
static auto static_double = double{};

// type_id as the keys in a compile time map
constexpr auto anything_compiletime = frozen::unordered_map<type_id_t, void*, 2>{
    {type_id<int>(), &static_int},
    {type_id<double>(), &static_double}
};

I'm convinced that your design will work correctly. Uniqueness of static variables is guaranteed, and they won't be optimized away if you define and odr-use them (taking the address of a variable is odr-using it). Running it through stack-overflow would be a good idea though, because it will probably catch the eye of one of those 200K+ reputation guru who answer all the tricky language questions.

What I can't understand is what you're trying to achieve with this. The only useful property of this compile-time id is its uniqueness, so it doesn't achieve anything more than the type itself: what is the difference between if (type_id<A>() == type_id<B>()) and if (std::is_same_v<A, B>)? I would argue that it achieves a lot less, because types have other useful traits (for a partial but ready-made list, just take a look at the type_traits header in the standard library).

Besides, your id generator isn't truly generic: type_id<int&>() won't compile because a pointer can't point to a reference (thus static const int&* const id is illegal). Of course there's always the possibility to remove the reference, but it means that you'll use type_traits to make your type_id work -so it underlines that you should use well-established, standard type traits instead of this new compile-time type_id.

I'd suggest, if it is possible, that you post here a larger part of your code,
 containing use cases, and let our collective brain work on the solution of the broader problem.

Edit: I understand now better what you want to do. I really like the simplicity of use, and I find the hack very clever. Actually, if it was uglier, limitations like no-references-allowed wouldn't matter much, because everyone would see it as work-around. But since it seems so fluent, it could quickly become pervasive in the code; then limitations matter, all the more when they result in obscure error messages.

Anyway, I believe I would have come up with a less ambitious design, which would also be easier to maintain and understand (this concrete implementation relies on C++17 but it wouldn't be to difficult to implement in previous standards):

#include <iostream>
#include <vector>

template <typename... Types>
struct Type_register{};

template <typename Queried_type>
constexpr int type_id(Type_register<>) { static_assert(false, "You shan't query a type you didn't register first"); return -1; }

template <typename Queried_type, typename Type, typename... Types>
constexpr int type_id(Type_register<Type, Types...>) {
    if constexpr (std::is_same_v<Type, Queried_type>) return 0;
    else return 1 + type_id<Queried_type>(Type_register<Types...>());
}

int main() {
   Type_register<int, float, char, std::vector<int>, int&> registered_types;
   constexpr auto test1 = type_id<int&>(registered_types);
   constexpr auto test2 = type_id<int*>(registered_types);
}

I really liked your design, but for a reason that I'm not sure to understand it actually yields the same value for any type (your static_assert breaks).
Perhaps it's due to my compiler, Visual Studio 2019, breaking the technique because of its identical COMDAT folding linker optimization, like in this answer from another similar question.
Basically the compiler falsely assumes that it can throw away template information and do the same logic for any type, so the same value will be returned each time.
But for instance, this approach works on my machine. I like yours better though! :-(