ArrayBlockingQueue in which queue head is removed if the queue is full while adding an element I am trying to write a simple queue like ArrayBlockingQueue in which the head of the queue will be removed if the queue is full while adding an element. The class should just have the below public methods

To get the size of the Queue
To get an element from the head of the queue
To add an element at the tail of the queue

Can someone review the below code and let me know if there is a better way of doing this?

public class CircularArrayNonBlockingQueue<E> {
    private ArrayBlockingQueue<E> blockingQueue;

    public CircularArrayNonBlockingQueue(int size) {
        blockingQueue = new ArrayBlockingQueue<>(size);
    }

    public synchronized int size() {
        return blockingQueue.size();
    }

    public synchronized void add(E element) {
        if(blockingQueue.remainingCapacity() <= 0) {
            blockingQueue.poll();
        }
        blockingQueue.add(element);
    }

    public synchronized E poll() {
        return blockingQueue.poll();
    }
}

This has been discussed in stackoverflow

  Having a thread-safe backend collection does not necessarily make a
  correct program. When only your add method is synchronized, the
  take() method may run concurrently to it, so it is possible that
  after your if(blockingQueue.remainingCapacity() <= 0) test within
  add, a concurrently running take() removes an element, so the
  poll() within add may remove an element unnecessarily. There is a
  perceivable difference to the situation where add() would complete
  before the take(), as the consuming thread would receive a different
  item. It other words, the effect would be as if add would sometimes
  not remove the oldest item, but the second oldest one.

  On the other hand, if you use synchronized for all of your methods
  consistently, there is no need to have a thread-safe backend
  collection:

import java.util.ArrayDeque;

public class CircularNonBlockingQueue<E> {
    private final ArrayDeque<E> blockingQueue;
    private final int maxSize;

    public CircularNonBlockingQueue(int size) {
        if(size<1) throw new IllegalArgumentException("size == "+size);
        blockingQueue = new ArrayDeque<>(size);
        maxSize = size;
    }

    public synchronized int size() {
        return blockingQueue.size();
    }

    public synchronized void add(E element) {
        if(blockingQueue.size() == maxSize) {
            blockingQueue.poll();
        }
        blockingQueue.add(element);
        notify();
    }

    public synchronized E take() throws InterruptedException {
        while(blockingQueue.isEmpty()) wait();
        return blockingQueue.remove();
    }
}

  However, if you can live with weaker guarantees regarding the oldest
  element, you can use a BlockingQueue and don’t need any
  synchronized:

public class CircularNonBlockingQueue<E> {
    private final ArrayBlockingQueue<E> blockingQueue;

    public CircularNonBlockingQueue(int size) {
        blockingQueue = new ArrayBlockingQueue<>(size);
    }

    public int size() {
        return blockingQueue.size();
    }

    public void add(E element) {
        while(!blockingQueue.offer(element)) {
            blockingQueue.poll();
        }
    }

    public E take() throws InterruptedException {
        return blockingQueue.take();
    }
}

  It must be noted that neither of these solutions provides “fairness”.
  So if the number of producer and consumer threads is large compared to
  the queue’s capacity, there is the risk that producers repeatedly
  remove items without reactivating threads blocked in take(). So you
  should always ensure to have a sufficiently large capacity.


Simple JS/jQuery notification system I'm new to front-end development and now I'm learning JavaScript with jQuery.
I couldn't understand JavaScript's classes and objects and jQuery plugins, but after reading some articles and examples I wrote simple notifications system.

(function ($) {
    var notification = function (title, msg, duration) {
        var self = this;

        this.hide = function () {
            self.element.fadeOut(1000, function () {
                self.element.remove();
            })
        }

        this.element = $('

' + title + '

' + msg + '
(double click to hide)

');
        this.element.dblclick(self.hide);

        if (duration !== undefined) {
            setTimeout(function () {
                self.hide();
            }, duration * 1000);
        }

        $('#notifications_bar').prepend(this.element.hide().fadeIn(1000));
    };
    $.extend({
        notify:function (title, msg, duration) {
            return new notification(title, msg, duration);
        }
    });

Example:

$(function() {
    $.notify('Title', 'Message'); // sticky note
    $.notify('Title', 'Message', 2); // 2-seconds notification
});

The most terrible were closures and this keyword. I couldn't understand how to use them, so I want to know if there in my code above 'bad-practice' parts.

First of, for someone learning jQuery and JavaScript, you've done a great job of avoiding the pitfalls of most new developers to JavaScript;

You're not passing strings to setTimeout, which a lot of people do.
You've got a good grasp on closures (no matter how long they took you to learn :)).
You're using strict equals (===) rather than equals.

... so, if you want me to be really, really picky;

I don't see much point in adding your code to the jQuery namespace. It would work just as well to be added to your own namespace. A lot of people fall into the habit of defining everything on $, and are scared of declaring your own namespace; don;t be:

var ME = {};

ME.notify = function (title, msg, duration) {
    return new notification(title, msg, duration);
};

It's a code convention to use a capital letter for constructors (e.g. functions you need to call new on); change function notification to function Notification.
You could make use of prototypical inheritance. As it stands, you're defining and adding a hide function on every instance of a notification you create. Obviously this has a negligible memory impact. Instead, use prototypical inheritance, and declare the function once;

function Notification (blah, blah, blah) {
   // blah blah blah
}

Notification.prototype.hide = function () {
    var self = this;

    this.element.fadeOut(1000, function () {
        self.element.remove();
    });
}

... you'd then have to change your double click handler to use the anonymous function approach I recommended in my answer, as this will no longer be the correct this.
You've got a potential XSS exploit. For example, given the message:

This will be injected, and evaluated in your page. You can fix this by setting the h3 and p using text() explicitly;

this.element = $('

(double click to hide)

');

this.element.find('h3').text(title);
this.element.find('span.text').text(message);

... but again, I want to re-iterate that I'm being very, very picky. What you've got is well written, functioning JavaScript.


Legibility of code with ternary operators in Python My lead developer has commented that the code I write is hard to understand and that I "overcomplicate things". I'm willing to accept this and improve but I'm not sure if this is genuinely the case or if his personal preferences are seeping into his judgement.

A red flag for me was the following situation: We're receiving database entries in the form of an array of dictionaries called columns. We then make HTML templating decisions based on their contents. Note that "special" types such as files or map coordinates are really text fields with an additional type_[name] array field for validation.

columns = someDBData
for column in columns:
    column_type = column['data_type']
    isValid = Someclass.perform_some_validation(column_type) # returns a boolean
    isCalendar = Someclass.is_calendar(column_type) # returns true if it's a time, datetime or datetime-local data type
    isString = Someclass.is_string(column_type) # ditto but with text, mediumtext or varchar

    isHidden = True if column['hidden'] != 0 else False
    isReadOnly = True if (configuracion_open == "" and column['open_insert'] == 0) or (configuracion_open == "Editando_registro" and column['open_edit'] == 0) else False
    isFile = True if column_type == "text" and column['type_file'] is True else False
    isGeo = True if column_type == "text" and column['type_geo'] is True else False
    isGeneric = True if isCalendar or isString and not isFile else False

   # repeat for other validations and then do templating stuff

When reviewing my work, he claimed that using "long ternary operators such as these" would be confusing for other people maintaining the code in the future. It seems as if he'd prefer to use a more verbose if/elif/else structure for readability, even though giving the program unnecessary verticality will also result in a readability problem in the future, at least in my opinion. In summary, should I reserve ternary operators for short and simple validations?

I think there is nothing wrong with using boolean-valued expressions to compute boolean results, instead of if/elif/else statements. However, it is still important to write these expressions clearly. Most of your expressions can be simplified, and none of your expressions actually require using the ternary operator.

If you write a ternary operator where the true-branch has the value True and the false-branch has the value False, then the ternary operator is superfluous.

If the condition is a boolean already, such as True if column['hidden'] != 0 else False, then you can simply write column['hidden'] != 0 as this will already be either True or False as required.

If the condition is not necessarily a boolean, e.g. True if my_list else False (not from your example) where my_list is a list and the condition tests if it is non-empty, then you can simply write bool(my_list) to calculate the boolean result you want.

When you have a condition like isCalendar or isString and not isFile which has both and and or, I recommend always using brackets to clarify the order of operations. Not everyone knows that and takes precedence over or, and even if they do know this, they may not know that you knew, and might trust the code less. Write isCalendar or (isString and not isFile) to make clear what this code does; or if you wanted it to be (isCalendar or isString) and not isFile, write that.

The expression for isReadOnly is very long, so I suggest splitting this over multiple lines. If an expression is inside (parentheses), then you can space it across multiple lines however you wish.

By the way, column['type_file'] is True is redundant, assuming column['type_file'] is always a boolean. If it's True, then True is True results in True, while False is True results in False; either way, the result is the same as the original value of column['type_file']. Imagine writing x + 0 where x is a number; it won't change the result, so you might as well just write x.


Use functional-programming to convert a tree of parent:children objects to array Having some trouble with a code I'm trying to refactor, where I need to go over a 'tree' of items, filter some invalid items, and create a new array of filtered items which takes properties from both parent and child objects.

To demo the problem I made a quick snippet -

const items = [
  {
    name: 'Shirley Hardin',
    isValid: true,
    children: [
      {
        name: 'Mildred Mata',
        isValid: true,
      },
      {
        name: 'Christopher Herring',
        isValid: false,
      },
    ],
  },

  {
    name: 'Tad M. Colbert',
    isValid: false,
    children: [
      {
        name: 'James J. Spencer',
        isValid: true,
      },
    ],
  }
];

function toParentChildModel(parent, child) {
  return {
    parentName: parent.name,
    childName: child.name,
  };
}

function getValidChildParent(list) {
  const validParentChild = [];
  for (let i=0; i<list.length; i++) {
    const parent = list[i];
    if (parent.isValid) {
      for (let j=0; j<parent.children.length; j++) {
        const child = parent.children[j];
        if (child.isValid) {
          validParentChild.push(toParentChildModel(parent, child));
        }
      }
    }
  }
  return validParentChild;
}

function print(list) {
  console.log(list);
}

print(getValidChildParent(items));

The code can also be found at here

How would you refactor this code, specifically the 'getValidChildParent' function, in a functional way?

getValidParentAndChild can be rewritten as follows:

function getValidParentAndChild(list){
    return list.filter((obj) => obj.isValid)
               .map((obj) => obj.children.filter((kid) => kid.isValid)
                                         .map((kid) => toParentChildModel(obj, kid))
               .reduce((arr1, arr2) => arr1.concat(arr2));
}

The filter takes the element of the list and keeps it if the condition passed in is met. (In this case, both uses keep all the valid elements.)

map applies a function over each element of the list and returns the list of what the function returned for each element. Here it converts the list to a list of the parent-child pairs.

reduce is also called fold. These apply a two-argument over a list such that if your list was [a, b, c, d], with the function f, the reduce would return f( f( f(a, b), c), d). Here it is used to make a 2D list a 1D array.

This problem becomes more interesting if children could have children. In that case I would do the following:

function getPairsForNode(node){
    if(node.children)
       return node.children.map((child) => getPairsForNode(child))
                           .concat(node.children.map((child) => toParentChildModel(node, child))
                           .reduce((arr1, arr2) => arr1.concat(arr2));
    else return [];
}

function getValidParentAndChild(list){
    return list.filter((node) => node.isValid)
               .map(getPairsForNode)
               .reduce((arr1, arr2) => arr1.concat(arr2));
}


jQuery Font Switcher I have some code here that changes the font size depending on what link you clicked and it works perfectly, I now want to add another feature but need some help. I want to add current font size which changes as you press bigger or smaller.

jQuery:

$(document).ready(function() {

    function change_size(element, size) {

        var current = parseInt(element.css('font-size'));

        if (size == 'smaller') {
            var new_size = current - 4;
        } else if (size == 'bigger') {
            var new_size = current + 4;
        }

        element.css('font-size', new_size + 'px');
    }

    $('#smaller').click(function() {
        change_size($('p'), 'smaller');
    });

    $('#bigger').click(function() {
        change_size($('p'), 'bigger');
    });
});

HTML:

Font size: Smaller | Bigger Current Font Size:

This is some text

This is some more text

I felt that this code would be good as a jQuery plugin, so I went ahead and altered your code until I was satisfied. I left in some comments that are applicable to your code, but I would encourage someone else (and may do it myself still, I don't know yet) to give an actual review.

(function ($, console) {
    'use strict';

    var defaultOptions = {
        //markup is what will be used to create the font sizer widget; you can do this a million better ways, but I felt this was easy to understand.
        //I'd consider enhancing it to take a jQuery object or a function that returns a string or a jQuery object, but all of that would make this more complex.
        //At the very least, this way makes for progressive enhancement as opposed to breakage when JS is disabled.
        markup: 'Font size: Smaller | Bigger Current Font Size:',
        markupClickFilter: 'a', //if you change the markup of this widget to something where you use elements other than A tags for buttons, you may wish to change this
        affects: null, //required: this is a jQuery object representing the elements that this widget affects
        size: null, //override for initial size of affected elements
        increment: 4
    };
    $.fn.fontSizer = function (options) {
        //initialize / preconditions
        var opts = $.extend({}, defaultOptions, options),
            $currentSize, //$ for element in markup if it exists
            sizeChange = function () {}; //noop to avoid null check when using this, meh...
        if (!opts.affects || !opts.affects.length) {
            //should always UI test in a modern browser that provides console
            console.error('failed to initialize fontSizer: must provide affects property');
            return this; //jQuery plugins are expected to follow this convention
        }

        //widget setup
        this.html(opts.markup); //again, this setup functionality could be done better in many ways
        $currentSize = this.find('[data-id=current_size]'); //for example to not use magic strings like this
        if ($currentSize.length) {
            sizeChange = function () { //this could also be a trigger
                $currentSize.html(opts.affects.css('font-size'));
            };
        }

        //set initial size and update $currentSize
        if (opts.size !== null) {
            opts.affects.css({
                'font-size': opts.size
            });
        }
        sizeChange();

        return this.on('click', opts.markupClickFilter, function (e) {
            var size = parseFloat(opts.affects.css('font-size')), //parseFloat is more correct than parseInt
                make = $(this).data('make'),
                fixed = parseFloat(make); //minor enhancement: allow fixed sizing

            if (make === 'smaller') { //preference: always use ===
                size -= opts.increment; //a new variable was unnecessary, if you feel you must, you should at least declare it at the top of the function
            } else if (make === 'bigger') {
                size += opts.increment;
            } else if (fixed !== 0) {
                size = make; //using make instead of fixed here allows things like make === '1.5em'
            }

            //update size (and set $currentSize)
            opts.affects.css({
                'font-size': size
            });
            sizeChange();

            //this prevents the annoying hashchange and extra history step that isn't doing anything useful
            e.preventDefault();
        });
    };
}(jQuery, console || {error: function () {}}));

Usage:

(function ($) {
    'use strict';
    $(function () {
        $('#sizer').fontSizer({
            affects: $('p.basic')
        });
        $('#sizer2').fontSizer({
            affects: $('p.custom'),
            markup: 'Font size: Small | Large | XL Current Font Size:'
        });
    });
}(jQuery));

Html for usage example:

Enable Javascript for a font resizer

some text

some text

some text

Enable Javascript for a font resizer

some text

some text

some text

JsFiddle


Macro code that removes excess rows I'm a business student who just started to learn VBA. I am trying to write a macro for a project but only have minimal experience actually stepping into the code.

The macro I have written is to delete all row entries which do not meet my criteria if they contain certain words, including removing those with future month's dates in them, and I'd like for this to update based on the current month.  I have found that normally the code runs very quickly, but when I add the last part, which removes those with future dates, the code becomes extremely slow.

Is there a way to speed it up or rewrite it so that it is faster?

Sub Remove_excess_entries()
    Dim lRow As Long
    Dim iCntr As Long
    lRow = 10000
    For iCntr = lRow To 1 Step -1
        If Cells(iCntr, 12).Value = "Mule" Or Cells(iCntr, 11).Value = "*R1*" Or Cells(iCntr, 11).Value = "*R2*" Or Cells(iCntr, 7).Value = "*Mule*" Or Cells(iCntr, 6).Value = "*Unassigned*" Or Cells(iCntr, 12).Value = "PS" Or Cells(iCntr, 7).Value = "Marketing" Or Cells(iCntr, 12).Value = "V1" Or DatePart("m", Cells(iCntr, 16).Value) > DatePart("m", Date) Then
            Rows(iCntr).Delete
        End If
    Next
End Sub

Here's that conditional, reformatted with line continuations for readability:

If Cells(iCntr, 12).Value = "Mule" _
    Or Cells(iCntr, 11).Value = "*R1*" _
    Or Cells(iCntr, 11).Value = "*R2*" _
    Or Cells(iCntr, 7).Value = "*Mule*" _
    Or Cells(iCntr, 6).Value = "*Unassigned*" _
    Or Cells(iCntr, 12).Value = "PS" _
    Or Cells(iCntr, 7).Value = "Marketing" _
    Or Cells(iCntr, 12).Value = "V1" _
    Or DatePart("m", Cells(iCntr, 16).Value) > DatePart("m", Date) _
Then
    Rows(iCntr).Delete
End If

There are a number of problems here:

Cells (and Rows) are implicit references to the active sheet; this means you're accessing the active worksheet without explicitly saying so - so if the macro takes a long while to run and the user decides to activate another sheet while it's running, your macro will fail to do what it was written for.
You're accessing the active sheet multiple times per row, and doing many checks that you may not need to be doing - if Cells(iCntr,11).Value is "*R1*", then every single next check is happening even though you already know you want to delete that row.

So how do you make it so that you only validate what needs to be validated, and that you don't access the worksheet more than you need to?

First make sure you specify Option Explicit at the top of the module. Option Explicit forces you to always declare all variables you're using, and that alone can prevent many bugs, since without it VBA will happily compile a typo.

Then make it one single read:

Dim target As Worksheet
Set target = Application.ActiveSheet

Dim rowValues()
Dim i As Long
For i = 10000 To 1 Step -1
    rowValues = target.Range(target.Cells(i, 1), target.Cells(i, 20)).Cells
    If IsUpForDeletion(rowValues) Then target.Rows(i).Delete
Next

Now, in one single worksheet operation, we've got an array that contains the values of columns 1-20 for row i; we call a function that returns a Boolean value when the row is "up for deletion", and so we remove that row when that function returns True.

The question is, what would this function do? Remember, we want it to only check what it needs to, and return as soon as it knows it should be returning True.

There's a little hack involving Select Case True that can help here:

Private Function IsUpForDeletion(ByRef rowValues()) As Boolean

    Dim result As Boolean
    result = True

    Select Case True
        Case rowValues(1, 5) = "*Unassigned*"
        Case rowValues(1, 6) = "*Mule*"
        Case rowValues(1, 6) = "Marketing"
        Case rowValues(1, 10) = "*R1*"
        Case rowValues(1, 10) = "*R2*"
        Case rowValues(1, 11) = "PS"
        Case rowValues(1, 11) = "V1"
        Case IsFutureMonth(rowValues(1, 15))
        Case Else
            result = False
    End Select

    IsUpForDeletion = result

End Function

Private Function IsFutureMonth(ByVal value As String) As Boolean

    If Not IsDate(value) Then
        IsFutureMonth = False
        Exit Function
    End If

    IsFutureMonth = DatePart("m", CDate(value)) > Month(Date)

End Function

VBA will evaluate each Case until it finds a condition that evaluates to True, and then immediately jump out and return. Because we're working with an in-memory 2D array here, and not accessing any cells, this is going to run much faster.

Notice the column indices are off by one - that's because VBA arrays are zero-based by default. If you want to refer to column 11 with an 11, then you could use Option Base 1 at the top of the module, and do this:

Private Function IsUpForDeletion(ByRef rowValues()) As Boolean

    Dim result As Boolean
    result = True

    Select Case True
        Case rowValues(1, 6) = "*Unassigned*"
        Case rowValues(1, 7) = "*Mule*"
        Case rowValues(1, 7) = "Marketing"
        Case rowValues(1, 11) = "*R1*"
        Case rowValues(1, 11) = "*R2*"
        Case rowValues(1, 12) = "PS"
        Case rowValues(1, 12) = "V1"
        Case IsFutureMonth(rowValues(1, 16))
        Case Else
            result = False
    End Select

    IsUpForDeletion = result

End Function

For even faster code, make one single read, and iterate an array instead of iterating a worksheet and making 10000 worksheet reads - this code should run orders of magnitude faster than your original code:

Option Base 1

Sub DoSomething()

    Dim target As Worksheet
    Set target = Application.ActiveSheet

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Dim rowValues()
    Dim i As Long
    rowValues = target.Range(target.Cells(1, 1), target.Cells(10000, 20)).Cells
    For i = 10000 To 1 Step -1
        If IsUpForDeletion(rowValues, i) Then target.Rows(i).Delete
    Next

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

End Sub

Private Function IsUpForDeletion(ByRef rowValues(), ByVal i As Long) As Boolean

    Dim result As Boolean
    result = True

    Select Case True
        Case rowValues(i, 6) = "*Unassigned*"
        Case rowValues(i, 7) = "*Mule*"
        Case rowValues(i, 7) = "Marketing"
        Case rowValues(i, 11) = "*R1*"
        Case rowValues(i, 11) = "*R2*"
        Case rowValues(i, 12) = "PS"
        Case rowValues(i, 12) = "V1"
        Case IsFutureMonth(rowValues(i, 16))
        Case Else
            result = False
    End Select

    IsUpForDeletion = result

End Function

Private Function IsFutureMonth(ByVal value As String) As Boolean

    If Not IsDate(value) Then
        IsFutureMonth = False
        Exit Function
    End If

    IsFutureMonth = DatePart("m", CDate(value)) > Month(Date)

End Function


Is there any problem in checking PHP PDO connection this manner? Is there any problem in checking PHP PDO connection this manner?

Is this way reliable?

function pdo_mysql()
{
$mysql_string  = "xxxxxxxxxxx";
$mysql_user = "xxxxxxxxxxx";
$mysql_pass = "xxxxxxxxxxx";

try
{
    $pdo_mysql = new PDO( $mysql_string, $mysql_user, $mysql_pass );
    $pdo_mysql->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $pdo_mysql->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
    return true;
}
catch( PDOException $ex )
{
    log_action( "pdo_mysql", $ex->getCode() . ": " . $ex->getMessage() );
    return false;
}
return false;

}

and then checking the return like this:

if( $pdo_mysql = pdo_mysql() )

I'm not quite sure I see the purpose of this function.

It essentially checks if a PDO connection is possible.  It does not actually return a connection.  In addition to that, it has hard coded credentials, thus killing all flexibility.  Also, there's no evident reason why you made it MySQL specific.  None of your options used are MySQL specific.

Since a boolean is returned, if( $pdo_mysql = pdo_mysql() ) is redundant too:

if (pdo_mysql()) is sufficient (unless you plan on using the true/false $pdo_mysql outside of the if/else block).

You should pass the credentials into the function instead of hard coding them.  Once you've done that though, you've kind of removed any need for the function.

Personally, I don't see a purpose for this function.  Just make the connection without this function.  If you want to keep it in some kind of centralized place, just keep in it a simple bootstrap file, or even a simple bootstrapping class.

I've been vague on basically everything in this post, so if you want more detail, let me know :).

Also, I might have missed the point of your function.  Is your end goal to connect to a MySQL server, or to check if you could connect to a MySQL server?


Block storage rewrites Summary

  In a block storage system, new data is written in blocks. We are going to represent the flash memory as one sequential array. We have a list of block writes coming in the form of arrays of size 2: writes[i] = [first_block_written, last_block_written].

  Each block has a rewrite limit. If rewrites on a block reach a certain specified threshold we should run a special diagnostic.

  Given blockCount (an integer representing the total number of blocks), writes (the list of block-write arrays of size 2), and threshold, your task is to return the list of disjoint block segments, each consisting of blocks that have reached the rewrite threshold. The list of block segments should be sorted in increasing order by their left ends.

Examples

  For blockCount = 10, writes = [[0, 4], [3, 5], [2, 6]], and threshold = 2, the output should be blockStorageRewrites(blockCount, writes, threshold) = [[2, 5]].

  After the first write, the blocks 0, 1, 2, 3 and 4 were written in once;
  After the second write, the blocks 0, 1, 2 and 5 were written in once, and the blocks 3 and 4 reached the rewrite threshold;
  After the final write, the blocks 2 and 5 reached the rewrite threshold as well, so the blocks that should be diagnosed are 2, 3, 4 and 5.
  Blocks 2, 3, 4 and 5 form one consequent segment [2, 5].

  For blockCount = 10, writes = [[0, 4], [3, 5], [2, 6]], and threshold = 3, the output should be
  blockStorageRewrites(blockCount, writes, threshold) = [[3, 4]]

  For blockCount = 10, writes = [[3, 4], [0, 1], [6, 6]], and threshold = 1, the output should be
  blockStorageRewrites(blockCount, writes, threshold) = [[0, 1], [3, 4], [6, 6]]

Constraints

1 ≤ blockCount ≤ 10**5
0 ≤ writes.length ≤ 10**5
writes[i].length = 2
0 ≤ writes[i][0] ≤ writes[i][1] < blockCount

First try

from itertools import groupby

def group_blocks(num_writes, threshold):
    i = 0
    for key, group in groupby(num_writes, lambda x : x >= threshold):
        # This is faster compared to len(list(g))
        length = sum(1 for _ in group)
        if key:
            yield [i, i + length - 1]
        i += length

def blockStorageRewrites(blockCount, writes, threshold):
    num_writes = [0] * blockCount
    for lower, upper in writes:
        for i in range(lower, upper + 1):
            num_writes[i] += 1
    return list(group_blocks(num_writes, threshold))

Here I just do exactly what is asked, I create an array of blockCount size, loop over the writes and lastly group the consecutive ranges with itertoos.groupby

After trying to optimize

I'm not quite sure what the complexity was, but I tried to lessen the load, yet I still didn't pass the TLE constraints

def get_bad_blocks(blockCount, writes, threshold):
    cons = False
    u = l = -1
    for i in range(blockCount):
        count = 0
        for lower, upper in writes:
            if lower <= i <= upper:
                count += 1
            if count >= threshold:
                if not cons:
                    cons = True
                    l = i
                    u = -1
                break
        else:
            u = i - 1
            cons = False

        if u != -1 and l != -1:
            yield [l, u]
            l = -1
    if cons:
        yield [l, i]

def blockStorageRewrites(blockCount, writes, threshold):
    return list(get_bad_blocks(blockCount, writes, threshold))

Questions

You can review any and all, but preferably I'm looking for answers that:

Tell me if my first example is readable
I'm less concerned about readability in my second try, and more interested in speed
Please ignore the PEP8 naming violations as this is an issue with the programming challenge site

First off when you're optimizing code you need to know what to optimize. At first I thought the problem code was not the groupby, but instead the creation of num_writes. And so I changed your code to be able to find the performance of it.

import cProfile
import random

from itertools import groupby

def group_blocks(num_writes, threshold):
    i = 0
    for key, group in groupby(num_writes, lambda x : x >= threshold):
        # This is faster compared to len(list(g))
        length = sum(1 for _ in group)
        if key:
            yield [i, i + length - 1]
        i += length

def build_writes(block_count, writes):
    num_writes = [0] * block_count
    for lower, upper in writes:
        for i in range(lower, upper + 1):
            num_writes[i] += 1
    return num_writes

def blockStorageRewrites(blockCount, writes, threshold):
    num_writes = build_writes(blockCount, writes)
    return list(group_blocks(num_writes, threshold))

block_count = 10**5
writes = []
for _ in range(10**4):
    a = random.randrange(0, block_count)
    b = random.randrange(a, block_count)
    writes.append([a, b])

cProfile.run('blockStorageRewrites(block_count, writes, 10**4)')

Resulting in the following profile:

         200008 function calls in 25.377 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.002    0.002   25.377   25.377 <string>:1(<module>)
   100001    0.019    0.000    0.025    0.000 lus.py:10(<genexpr>)
        1   25.342   25.342   25.342   25.342 lus.py:16(build_writes)
        1    0.000    0.000   25.375   25.375 lus.py:24(blockStorageRewrites)
        1    0.000    0.000    0.033    0.033 lus.py:6(group_blocks)
   100000    0.007    0.000    0.007    0.000 lus.py:8(<lambda>)
        1    0.000    0.000   25.377   25.377 {built-in method builtins.exec}
        1    0.007    0.007    0.033    0.033 {built-in method builtins.sum}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Changing the code as per Georgy's comment to:

def build_writes(block_count, writes):
    num_writes = dict(enumerate([0] * block_count))
    for lower, upper in writes:
        num_writes[lower] += 1
        num_writes[upper] -= 1
    return list(accumulate(num_writes))

Gets the following profile, which is orders of magnitude faster:

         200011 function calls in 0.066 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.002    0.002    0.066    0.066 <string>:1(<module>)
   100002    0.021    0.000    0.028    0.000 lus.py:10(<genexpr>)
        1    0.025    0.025    0.025    0.025 lus.py:16(build_writes)
        1    0.003    0.003    0.064    0.064 lus.py:24(blockStorageRewrites)
        2    0.000    0.000    0.036    0.018 lus.py:6(group_blocks)
   100000    0.008    0.000    0.008    0.000 lus.py:8(<lambda>)
        1    0.000    0.000    0.066    0.066 {built-in method builtins.exec}
        2    0.008    0.004    0.036    0.018 {built-in method builtins.sum}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


Binary tree from given Inorder and Preorder traversal This builds a BinaryTree from given Inorder and Preorder lists.

class TreeNode(object):
  """Node of a Binary tree."""
  def __init__(self, key, left=None, right=None):
      self.key = key
      self.left = left
      self.right = right

  def __str__(self):
    return "{0}".format(self.key)

  def __repr__(self):
    return "<TreeNode>"

def insert_left(parent, node):
  parent.left = node
  return parent

def insert_right(parent, node):
  parent.right = node
  return parent

def level_order(node):
  """Given Binary Tree gives list nodes in each level."""
  if node is None:
    return
  current_level = [node]
  res = []
  while current_level:
    res.append(current_level)
    next_level = []
    for node in current_level:
      if node.left:
        next_level.append(node.left)
      if node.right:
        next_level.append(node.right)
    current_level = next_level
  return res

def build_tree(inorder, preorder):
  """Builds a Binary Tree from given inorder and preorder traversal.
  Steps:
    1. Take the first element from the preorder list.
    2. Get the index of the element from inorder list.
    3. Set the element as root.
    4. Take all elements left to root from inorder list.
    5. Take all elements right to root from inorder list.
    6. Calculate preorder list for left and right subtree respectively.
    7. Repeat from step 1 for each subtree.
  """
  def recurse(node, inorder, preorder):
    if len(preorder) == 1:
      return TreeNode(preorder)
    key  = preorder[0]
    root_index    = inorder.find(key)
    inorder_left  = inorder[:root_index]
    inorder_right = inorder[root_index+1:]
    preorder_left = preorder[1:len(inorder_left)+1]
    preorder_right = preorder[root_index+1:]
    node = TreeNode(key)
    if len(inorder_left):
      insert_left(node, recurse(None, inorder_left, preorder_left))
    if len(inorder_right):
      insert_right(node, recurse(None, inorder_right, preorder_right))
    return node
  return recurse(None, inorder, preorder)

import unittest

class TestBinaryTree(unittest.TestCase):
  def setUp(self):
    self.root = build_tree('DBEAFC', 'ABDECF')

  def test_build_tree(self):
    expected = [['A'], ['B', 'C'], ['D', 'E', 'F']]
    actual = []
    for level in level_order(self.root):
      actual.append([node.key for node in level ])
    self.assertEqual(actual, expected)

if __name__ == '__main__':
  unittest.main()

Output

A
B C
D E F

Although the code passes given test case I have to shamefully admit that it took me nearly the whole day to figure out the recursive build_tree method. I had a hard time to debug my recursive code by pen and paper as I was unable to track the progress of each recursive call (hope I could use version control and show the code progress). Anyway, as a last resort I started putting random code here and there finally putting None in this call insert_left(node, recurse(None, inorder_left, preorder_left)) worked.

So, I am here with some fundamental questions:

How can I structure the code to reduce the cognitive overload (I was literally stuck juggling with all those variables)?
How can I debug these kinds of recursive calls?

Recursive Code Should Be Recursive

Making build_tree recursive makes perfect sense. After all, pretty much everything you're going to do with trees is recursive, and this algorithm definitely lends itself well to recursion. However, your function isn't recursive. It calls a recursive function, and recurse takes a node - which obfusticates the algorithm. It would be much easier to understand if you just made it recursive - this goes a long way "to reduce the cognitive overload."

Let's start with the base case - if we have no ordering, we have no tree:

def build_tree(inorder, preorder):
    if not inorder:
        return None
    else:
        ### ??

Now, your enumerated steps for recursion seem to overcomplicate the algorithm. We want to go top-down! Given your example, when we start with:

in:  DBEAFC
pre: ABDECF

What's the root? A. The first element of pre-traversal is the root. Now we just need to find the left and right subtrees. To find that, we need to break up our in orderings into the root, left, and right sections:

in:  DBE|A|FC

So we have 3 nodes less than A and two nodes greater than A. We use the same sizes for the preorder:

pre: A|BDE|CF

And then recurse on those two parts. That is:

def build_tree(inorder, preorder):
    if not inorder:
        return None
    else:
        idx = inorder.index(preorder[0])
        return TreeNode(preorder[0],
                left=build_tree(inorder[:idx], preorder[1:idx+1]),
                right=build_tree(inorder[idx+1:], preorder[idx+1:])
                )

As a truly recursive solution, divided neatly into base and recursive cases, I find it much easier to follow the logic.

Debugging

Rather than write a level-by-level comparison, you should simply write an __eq__ method on TreeNode (or, alternatively, a much more correct __str__ or __repr__), and then use that to compare:

self.assertEqual(
    build_tree('DBEAFC', 'ABDECF'),
    TreeNode('A',
        TreeNode('B', TreeNode('D'), TreeNode('E')),
        TreeNode('C', TreeNode('F'))))

This is a more direct comparison. As is, you're comparing the levels, but there's not one unique tree that has three levels 'A', 'BC', and 'DEF'. For instance, what if your code erroneously returned one of these:

     A        |        A
   /   \      |     /    \
  B     C     |    B      C
 / \     \    |     \    / \
D   E     F   |      D  E   F

You'd think you succeeded. Always compare directly against what you want to get.


"Guess the number" game Any tips on how to improve my code and make it cleaner to read for other programmers? Formatting, spacing, etc.

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <cstdlib>
#include <windows.h>

using namespace std;

int main()
{
    int userInput;
    int number;
    int min = 1;
    int max = 10;
    float playerTimesToPlay = 0;
    int playAgain;
    float tries = 3;

    do
    {
        system("CLS");
        cout << "Welcome to my number guessing game!" << endl;
        cout << "====================================================" << endl;
        cout << "The computer is generating a number between 1 and 10." << endl;
        cout << "====================================================" << endl;
        srand(time(0));
        number = rand()% (max - min + 1)+min;
        playerTimesToPlay = 0;
        tries = 3;

        do
        {

            cout << "Please take a guess: ";
            if (!(cin >> userInput))
            {
            cout << endl;
            cout << "Please enter numbers only." << endl;
            cin.clear();
            cin.ignore(10000,'\n');
            }

            while(userInput > 10 || userInput < 0)
            {
                cout << "Pick a number BETWEEN 1 TO 10." << endl;
                cout << endl;
                userInput = NULL;
                playerTimesToPlay=0;
            }

            tries--;
            cout << endl;
            cout << "You picked: " << userInput << endl;
            cout << "======================" << endl;
            playerTimesToPlay++;

            if(userInput != number && tries > 0 && userInput <= 10)
            {
                cout << "Sorry! Invalid choice. Please try again. You have " << tries << " guess(es) remaining." << endl;
                cout << endl;
            }

            else if(userInput != number && tries == 0)
            {
                cout << "Sorry! Invalid choice." << endl;
                cout << "You have " << tries << " guesses remaining. You lose." << endl;
                cout << endl;
                cout << "Play again? " << endl;
                cout << "1. Yes" << endl;
                cout << "2. No" << endl;
                cout << ": " ;
                cin >> playAgain;
            }

            if(userInput == number)
            {
                cout << "Congratulations! You guessed the correct number!" << endl;
                cout << "Thanks for playing!" << endl;
                Sleep(2500);
            }

        }
        while (playerTimesToPlay < 3 && userInput != number);
    }
    while (playAgain == 1);

    system("Pause(0)");
    return 0;
}

Headers

You can remove stdlib.h as it is redundant to use both stdlib.h and cstdlib. The cstdlib is the c++ variant.
The same goes for the time.h header. Use ctime instead.
The Sleep() functions are virtually useless, I removed them and also the <windows.h> header along with it. Don't confuse your users with pauses such as those, not to mention the portability issues. Keep it simple and let the program run at its own pace on their machines.

Namespace

Don't make a habit of utilizing using namespace std;. You will run into trouble later on down the road if you choose to build something that another developer will make use of. It is heavily frowned upon as it will potentially cause namespace collisions, especially if included in a header file for say, a library.

Instead just explicitly call the functions with the scope operator:

std::cout << "Don't muddy your scope!";

Variables

You have quite a few extra variables that can be removed, and also ones that could be more productive as a different data type.

The minimum and maximum variables should be declared as constants as they're not configurable anywhere in your code. Also, they could probably be a little more descriptive instead of just 'min' and 'max'.

const int LOWER_NUMBER_BOUND = 1;
const int UPPER_NUMBER_BOUND = 10;

number is also pretty vague and should be renamed to infer its purpose.

int numberToGuess;

It appears you have two variables keeping track of the same data. You decrement tries when the player guesses incorrectly but at the same time you increment playerTimesToPlay. I would advise removing one of these and sticking to one variable that tracks the guess attempts remaining. It would also be a good idea to include a constant variable that holds the max attempts so you can reset the tracking variable after a game ends.

const int GUESS_ATTEMPTS = 3;
int guessAttemptsRemaining;

userInput can also be named more clearly. Something to solidify the function of the variable.

int userGuess;

Random

You're currently reseeding the random algorithm every time you play the game. This is unnecessary and it can be moved out of your loop.
Consider using the newer <random> instead, however the rand() function is simpler and more easily understood for a beginner. Also your distribution isn't critical so I wouldn't worry about this for the moment.

Logic

Inside of the inner do loop, the while statement can be altered to reflect when there are guesses remaining instead of using the incremented variable that was removed. It's also redundant to check if the user's guess is correct so that can also be removed.

do{...} while (guessAttemptsRemaining > 0);

You can shrink the input validation and remove some of the output by simply asking them to enter a number between the bounds.

while (userGuess < 1 || userGuess > 10)
{
    std::cout << "Please pick a number between 1 and 10: ";
    if (!(std::cin >> userGuess))
    {
        std::cin.clear();
        std::cin.ignore(10000, '\n');
    }
}

There is a logic error when checking the bounds of the user's input. Instead of checking if the number is less than 0 it should be if it is less than 1 as 0 is invalid input.

while (userGuess < 1 || userGuess > 10)

You check for the same conditions multiple times. Instead of repeating yourself you can restructure your logic to only check for a condition once. There is quite a bit of this going on so instead of pointing out every specific example I'll just go ahead and refactor it to show you what I mean.

Output

Instead of std::endl consider using \n instead. It is faster than a function call and also doesn't have the additional overhead of buffer manipulation that is included with std::endl.

Refactored Code

#include <iostream>
#include <ctime>
#include <cstdlib>

const int LOWER_NUMBER_BOUND = 1;
const int UPPER_NUMBER_BOUND = 10;
const int GUESS_ATTEMPTS = 3;

int main(int argc, _TCHAR* argv[])
{
    int userGuess;
    int numberToGuess;
    int guessAttemptsRemaining;
    int playAgain = 0;

    srand(time(0));

    do
    {
        system("CLS");
        std::cout << "Welcome to my number guessing game!\n";
        std::cout << "====================================================\n";
        std::cout << "The computer is generating a number between 1 and 10.\n";
        std::cout << "====================================================\n";

        numberToGuess = rand() % (UPPER_NUMBER_BOUND - LOWER_NUMBER_BOUND + 1) + LOWER_NUMBER_BOUND;
        guessAttemptsRemaining = GUESS_ATTEMPTS;

        do
        {

            userGuess = 0;

            while (userGuess < 1 || userGuess > 10)
            {
                std::cout << "Please pick a number between 1 and 10: ";
                if (!(std::cin >> userGuess))
                {
                    std::cin.clear();
                    std::cin.ignore(10000, '\n');
                }
            }

            --guessAttemptsRemaining;
            std::cout << "You picked: " << userGuess << ".\n";

            if (userGuess != numberToGuess)
            {
                std::cout << "Sorry! You've guessed incorrectly!\n";

                if (guessAttemptsRemaining > 0)
                {
                    std::cout << "Please try again. You have " << guessAttemptsRemaining << " guess(es) remaining.\n";
                }
                else
                {
                    std::cout << "You have no guess remaining. Play Again?\n";
                    std::cout << "1. Yes\n";
                    std::cout << "2. No\n";
                    std::cin >> playAgain;
                }

            }
            else
            {
                std::cout << "Congratulations! You guessed the correct number!\n";
                std::cout << "Thanks for playing!\n";
                break; //Add some way to continue here?
            }

        } while (guessAttemptsRemaining > 0);

    } while (playAgain == 1);

    return 0;
}

Additional

I didn't cover everything so I may add more in the future. I also didn't go into extreme detail about the topics I went over so take my additions/alterations/etc. with a grain of salt and do your own research!


Integration test for database access This integration test involves database access and hence opening and closing a database connection. Does it look correct? I am concerned about ensuring the the database connection is closed should the test fail.

"use strict";

describe("MyCtorFunction", function () {

  describe("myMethod", function () {
    var _db = null,
        _testContext = null;

    beforeEach(function () {
      _testContext = {};
      new DbHelper().openConnection(function (err, dbConnection) {
        if (err) {
          throw err;
        }

        _db = dbConnection;
      });

      waitsFor(function () {
        return _db;
      }, "establishing a connection to the database.", 5000);
    });

    afterEach(function () {
      waitsFor(function () {
        return _testContext.assertions.callCount === 1;
      }, "waiting for the assertions to be called.", 5000);

      runs(function () {
        if (_db) {
          _db.close();
          _db = null;
        }
      });
    });

    it("should do something", function () {
      runs(function () {
        //arrange
        _testContext.assertions = assertions;
        spyOn(_testContext, "assertions").andCallThrough();

        //act (_testContext.assertions invoked as callback)
        new MyCtorFunction(_db).myMethod(_testContext.assertions);

        //assert
        function assertions(err, config) {
          expect(config).toNotBe(null);
          //etc.
        }
      });
    });
  });
});

From a once over and reading some Jasmine docs:

I am not a big fan of _db and _testContext, I see no reason for the underscores.
It is not guaranteed that _db will be set in new MyCtorFunction(_db).myMethod(_testContext.assertions);, so you should check for that prior to calling.
You did not tell us what database (API) you are using, so we cannot tell whether you close the connection properly.
I wish you had provided us the code in assertions, it would have helped with the review
JsHint could find nothing wrong
I would advise you to make sure an assertion fails and put a log statement in your db closing code, this way you can be assured that the db connection will be closed. Though from reading the docs you should be fine.
This:

waitsFor(function () {
  return _testContext.assertions.callCount === 1;
}, "waiting for the assertions to be called.", 5000);

Seems a bit paranoid, afterEach is guaranteed to run after your assertions if I read your code well. If I am right then you can clean up your code tremendously since you will not need _testContext any more.
I hope MyCtorFunction and myMethod are not the true names in your code, those are horrible names ;)

All in all I dont really like your code, I blame Jasmine for that. I dont like their approach to naming functions nor their approach to asynchronous processing.

Update:

I realized on the subway that in my mind, the waiting for the db and the waiting for the test to finish ought to be part of the test, not part of the setup/teardown. This approach will definitely simplify since you wont need runs anymore in afterEach, plus you will not need testContext any more.

I cannot test this, but you should get the picture.

"use strict";

describe("MyCtorFunction", function () {

  describe("myMethod", function () {
    var db;

    beforeEach(function () {

      new DbHelper().openConnection(function (err, dbConnection) {
        if (err) {
          throw err;
        }
        db = dbConnection;
      });
    });

    afterEach(function () {
      if (db) {
        db.close();
        db = null;
      }
    });

    it("should do something", function () {
      //Wait for the green light
      waitsFor(function () {
        return db;
      }, "establishing a connection to the database.", 5000);
      //Start acting!
      runs(function () {
        //arrange
        spyOn(_testContext, "assertions").andCallThrough();
        //act (assertions invoked as callback)
        new MyCtorFunction(_db).myMethod( assertions );

        //assert
        function assertions(err, config) {
          expect(config).toNotBe(null);
          //etc.
        }
      });
      //Wait for the action to be done
      waitsFor(function () {
        return assertions.callCount === 1;
      }, "waiting for the assertions to be called.", 5000);
      //Done
    });
  });
});

Finally, from a library perspective, check out https://github.com/derickbailey/jasmine.async


The average amount of time required to travel between two points in a torus-like space I have recently started to work with C++ and I do consider myself quite basic in C++ coding.
I have made the following two functions and I was wondering whether someone could give me some hints on how to improve and speed up this code.
Please, note that the second function is then used in R through Rcpp R package.
#include <Rcpp.h>
using namespace Rcpp;
using namespace std;

double sumAll(double i, double j, int a, int b, double coeff) {

  double pi = 2 * acos(0.0);

  double total = 0;
  int half_a =  a / 2;
  int half_b =  b / 2;

  for (int k = 0; k <= half_a; ++k) {

    for (int l = 0; l <= half_b; ++l) {

      double fkl;
      if (k == 0 && l == 0) {
        fkl = 0;
      } else {
        fkl = pow((1 - (coeff * (1 - cos(2.0 * pi * k / a)))), 2.0) *
              pow((1 - (coeff * (1 - cos(2.0 * pi * l / b)))), 2.0);
      }

      double a1 = 1 - (cos(2.0 * pi * i * k / a) * cos(2.0 * pi * j * l / b));

      double deltaa;
      if (k == 0) {
        deltaa = 1;
      } else {
        deltaa = 0.5;
      }

      double deltab;
      if (l == 0) {
        deltab = 1;
      } else {
        deltab = 0.5;
      }

      if (k == 0 && l == 0) {

        total = total + 0;

      } else {

        double res = (fkl * a1) / (deltaa * deltab * (1 - fkl));

        total = total + res;
      }
    }
  }
  return total;
}

// [[Rcpp::export]]
NumericVector series_Sum(NumericVector xvec, NumericVector yvec, int a, int b,
                         double coeff) {

  int size = xvec.length();
  NumericVector series_res(size);

  for (double i = 0; i < size; i++) {
    series_res[i] = sumAll(xvec[i], yvec[i], a, b, coeff);
  }

  return series_res;
}

Consider that in sumAll :

i and j: are integers, which can get values between 0 and a/2 or 0 and b/2, respectively.
coeff: can be a value between 0 and 1.0.
a and b: can be any integer values higher than 5 (arbitrary choice).

In series_Sum :

xvec and yvec: are vectors of i and j values.

In other words, series_Sum use sumAll over several possible combinations of i and j.

Don't write using namespace std;.
The constants including pi are provided in a standard header already.  If you did need to define a constant,  use constexpr.
double deltaa;
if (k == 0) {
        deltaa = 1;
      } else {
        deltaa = 0.5;
      }

That is much clear to write as:
const double deltaa = k==0 ? 1 : 0.5;

which also allows you to initialize the value in the declaration and make it const.
The block for deltaa and deltab are the same except for the parameter.  You should make a small inline function for that.
total = total + 0;

Why?
total = total + res;

Better to write total += res;

Generally:
Use const where you can.  Initialize variables in the statement where you declare them.
In addition to using const, which may allow the optimizer to better figure such things out on its own, consider hoisting subexpressions out of the loop.  For example pi * k does not change inside the nested loop so compute it once in the outer loop only.
Express your comments as preconditions (e.g. assert or Expect statements).

for (double i = 0; i < size; i++) {
    series_res[i] = sumSij(half_a, half_b, xvec[i], yvec[i], a, b, coeff);
  }

Why is i of type double?  It's an index into the NumericArrays.
I see a call to sumSij but no call to sumAll.  The code is not complete, and doesn't agree with your comment (unless the former calls the latter, but I don't know how).


Count occurrences of an element in a list I've been learning Haskell from LYAH for quite some time, and as a first practice for Chapter 7: Modules, I decided to make a simple numTimesFound function: it returns the number of times an element is found in a list.

Here's my working code:

numTimesFound :: Ord a => a -> [a] -> Integer
numTimesFound _ [] = 0
numTimesFound x list
  | x `notElem` list = 0
  | otherwise =
      let
        appearencesTable = map (\full@(first:_) -> (first, length full + 1)) . group . sort $ list
        appearencesOfX = snd $ head $ filter (\(elem, _) -> elem == x) appearencesTable
      in
        toInteger appearencesOfX

Personally, I think I take the cake for using Haskell features, but I also think that the intent of this code is hard to understand. One of my major gripes with it is that it's hard to tell what the appearencesTable actually is from the code - it's a list of tuples that gives you the number of times each element was found. For example, for the list [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5] the appearencesTable is [(1, 3), (2, 2), (3, 4), (4, 2), (5, 1)]. If you know that it's pretty easy to get what the rest of the code is trying to do, but it still does require quite a bit of study for such a trivial function.

I would greatly appreciate any help in improving the readability of this code.

Since your type a is required to be an Ord you can access Eq functions. This makes counting occurrences a bit simpler, because you can just filter and count the matching elements:

numTimesFound :: Ord a => a -> [a] -> Integer
numTimesFound _ [] = 0
numTimesFound x list = sum $ map (\a -> 1) $ filter (== x) list

Of course we don't need to stop there. We can use function composition and length to  write the last line as:

numTimesFound x xs = (length . filter (== x)) xs

In addition to that 200_success raises an interesting point in the comments:

  Actually, there is no reason to require Ord a, when Eq a will do


Simple jQuery validation script works but it uses a ton of if/else statements I've a jQuery validation script to check all form fields for a valid value and prevent form submission and display an error message if any fields fail. It was requested that the validation script not check fields one by one, but that it check and highlight ALL fields that failed validation. It works perfectly. But I am more a front-end person, than a real developer and even though it works I feel like it's twice as long as it needs to be.

I've tried to combine logic where I could but it still feels like I have a ton of if/else statements and it just doesn't seem very...well...elegant.

A little more background: The script is used by three different forms which each have a different number of fields (form 1 has only email, form 2 has email and country, form 3 has email, country, and gender). The script checks for a form ID before bothering to validate any fields that aren't there.

$("#footer_newsletter").submit(function(){
var hasValue = true;
var validEmail = true;
// validate email
if($.trim($("#newsletter_email").val()) == ""){
  $("#newsletter_email").addClass("error");
  hasValue = false;
}else{
  $("#newsletter_email").removeClass("error");
}if(!$("#newsletter_email").val().match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.([A-Z]{2,4})$/i)){
  $("#newsletter_email").addClass("error");
  validEmail = false;
}else{
  $("#newsletter_email").removeClass("error");
}
if(parseInt($("#newsletter_form_id").val()) > 0){
// validate country
  if($("#newsletter_country").prop("selectedIndex") == 0){
      $("#newsletter_country").addClass("error");
      hasValue = false;
  }else{
    $("#newsletter_country").removeClass("error");
  }
}
if(parseInt($("#newsletter_form_id").val()) > 1){
  // validate gender
  if($(".email_signup_form_wrapper :radio:checked").val() == undefined){
      $("#newsletter_gender").addClass("error");
      hasValue = false;
  }else{
    $("#newsletter_gender").removeClass("error");
  }
}
if(!validEmail && !hasValue){
  $("#error_required_field").show();
  return false;
}else if(!validEmail && hasValue){
  $("#error_valid_email").show();
  $("#error_required_field").hide();
  return false;
}else if(validEmail && !hasValue){
  $("#error_required_field").show();
  $("#error_valid_email").hide();
  return false;
}else if(validEmail && hasValue){
  $("#error_valid_email").hide();
  $("#error_required_field").hide();
  $("#newsletter_submit").hide();
  $("#newsletter_sending").show();
  $.ajax({ type: "get", url: $("#footer_newsletter").attr("action"), data: $("#footer_newsletter").serialize(), dataType: "script" });
  return false;
}

My basic thinking behind the script is this:

In all fields I have to check for a value, and in the email field I have to check for a VALID value so I create two variables at the top of the script to record whether a field has a value, and whether or not that value is valid if it's the email field.
Look at each field and test it's value. If it fails add a class of "error", otherwise remove the class "error".
Then, if any of the following are true: The form has empty fields and does not have a valid email address, or the form has all fields filled out but does not have a valid email address, or the form has a valid email address but not all fields are filled out then display the appropriate error message.
Otherwise, everything looks good so submit the form.

Here is a fiddle where you can see it in action. For simplicity I've removed the submission bit and the command to show the loading graphic.

http://jsfiddle.net/judah/Ppewz/21/

I would recommend that you use the JQuery validation plugin (http://docs.jquery.com/Plugins/Validation) then your validation declaration would be as follows (fields which do not exist are ignored):

$("#footer_newsletter").validate(
    rules: {
            email: {
                    required: true,
                    email: true
                   },
            country: "required",
            gender: "required"
    },
    messages: {
             email: {
                     required: "Please enter an email",
                     email: "Please enter a valid email address"
                    },
             country: "Please select a country",
             gender: "Please select your gender"
    }
);


Validating multiple EditText fields I am using the following method to validate if user has given any input or left an EditText empty. I am concerned about the return statement in particular, because my IDE keeps complaining about it.

Environment: Android Studio 1.0

public void clientsideauth() {

        if (TextUtils.isEmpty(edt_name.getText().toString().trim())) {
            onShake(edt_name, "Please enter a valid name");
            return;
        } else {
            name = edt_name.getText().toString().trim();
        }
        if (isValidEmail(edt_email.getText().toString().trim())) {
            email = edt_email.getText().toString().trim();
        } else {
            onShake(edt_email, "Please enter a valid email ID");
            return;
        }

        if (((edt_password.getText().length() < 6) || (TextUtils.isEmpty(edt_password.getText().toString().trim())))) {
            onShake(edt_password, "Password must be at least six characters long");
            return;
        } else {
            pwd = edt_password.getText().toString().trim();
        }

        if (TextUtils.isEmpty(edt_password1.getText().toString().trim())) {
            onShake(edt_password1, "Not valid");
            return;
        } else {
            pwd1 = edt_password1.getText().toString().trim();
        }

        if (pwd.equals(pwd1)) {
            startbackgroundtask("formBased");
        } else {
            onShake(edt_password, "Passwords do not match");
            onShake(edt_password1, "Passwords do not match");
            return;
        }
    }

The return type of the method is void, because I don't want any return from this, I only want to stop execution if validation fails. However my IDE complains about the last return statement in the last if-else construct. I am wondering if I should in fact change the return type from void to boolean and maintain an array value for each form field. Later on I can check if all the array values are true or not.

The above function gets called on the Submit button and is further processed to the server.

The warning is trying to tell you that the return is pointless,
because it's the last statement anyway.
Here's a better way to rewrite that,
which will make the warning naturally go away:

if (!pwd.equals(pwd1)) {
    onShake(edt_password, "Passwords do not match");
    onShake(edt_password1, "Passwords do not match");
    return;
}

startbackgroundtask("formBased");

I simply inverted the condition, and removed the else branch.
If you think about it, all the else branches are unnecessary when the if branch returns. You can apply this to all the conditions in the posted code.

Many of your conditions handle the invalid case in the if and the normal case in the else, but not all.
It would be better to consistently handle the invalid case first everywhere,
and use early returns so you can get rid of the else. Like this:

    if (TextUtils.isEmpty(edt_name.getText().toString().trim())) {
        onShake(edt_name, "Please enter a valid name");
        return;
    }
    name = edt_name.getText().toString().trim();

    if (!isValidEmail(edt_email.getText().toString().trim())) {
        onShake(edt_email, "Please enter a valid email ID");
        return;
    }
    email = edt_email.getText().toString().trim();

    if (((edt_password.getText().length() < 6) || (TextUtils.isEmpty(edt_password.getText().toString().trim())))) {
        onShake(edt_password, "Password must be at least six characters long");
        return;
    }
    pwd = edt_password.getText().toString().trim();

    if (TextUtils.isEmpty(edt_password1.getText().toString().trim())) {
        onShake(edt_password1, "Not valid");
        return;
    }
    pwd1 = edt_password1.getText().toString().trim();

    if (!pwd.equals(pwd1)) {
        onShake(edt_password, "Passwords do not match");
        onShake(edt_password1, "Passwords do not match");
        return;
    }

    startbackgroundtask("formBased");

Notice that the code contains many duplicated logic, for example here,
the code to extract and clean edt_name is written twice:

    if (TextUtils.isEmpty(edt_name.getText().toString().trim())) {
        onShake(edt_name, "Please enter a valid name");
        return;
    }
    name = edt_name.getText().toString().trim();

It would be better to rewrite without duplication, like this:

    String cleanedName = edt_name.getText().toString().trim();
    if (cleanedName.isEmpty()) {
        onShake(edt_name, "Please enter a valid name");
        return;
    }
    name = cleanedName;

I also removed TextUtils.isEmpty, which was either a bug or pointless:

It's a bug if edt_name can be null, or if edt_name.getText() might return null: in both of these cases you will get a NullPointerException
If there won't be nulls, then you don't need TextUtils, you can use isEmpty method of String

There are several elements of poor coding style:

Variable names and method names should be camelCase, not like "edt_name" or "clientsideauth"
pwd and pwd1 are also poorly named, since pwd is the first password and pwd1 is the second. pwd1 and pwd2, or even pwd and pwdConfirmation would have been even better.

The clientsideauth method is doing too much:

Validate input
If successful, start background task
It mutates variables defined outside the method

Instead of mutating variables defined outside,
it would be better to validate,
collect the cleaned values in local variables,
and then pass these variables to the authentication task.

Since you do .getText().toString().trim() so often,
a helper method to do this for you would be a good idea,
to reduce your typing and the noise for readers.


Username-Password Matching Program I started university this semester. Can you review my code and share your thoughts with me
# 5-November-2020

username = input("Please enter your username: ")
password = input("Please enter your password: ")

username_password = {
    'Mert': "mertt"
}

if username in username_password:
    if username == "Mert" and password == username_password[username]:
        print("Welcome Sir")
    else:
        print("You're not authorized!")
else:
    confirmation = input("Do you want to register? (Y/N): ")
    if confirmation == "Y":
        username = input("Enter your username: ")
        password = input("Enter your password: ")
        password_2 = input("Confirm your password: ")
        if password == password_2:
            username_password[username] = password
        else:
            print("Your password is incorrect!")
    else:
        print("Good bye")
print(username_password)

If you have any improvement suggestion please tell me.

Validate input
You should be certain that your program wouldn't fail for any kind of bad input, something the user shouldn't have entered that might cause the program to behave incorrectly
Is this possible for your program? Yes, take this line
username = input("Please enter your username: ")

If the user enters Ctrl+Z here, it causes an error and the program stops.

EOFError

We can catch these exceptions using try and except in Python
try:
    username = input("Please enter your username: ")
except (Exception, KeyboardInterrupt):
    print("Please enter a valid username!")

The same applies to the input for password
One step further, I would also like to check the length of the details, i.e if the username or password is too short. Show a custom message if that is true

On an exception
Due to the changes we made previously, we can easily print an error message if we catch an exception rather than the termination of the program. But what happens after?
You have two options, either to stop the program there because you cannot process bad input or, you can ask for input again.
If you choose the second option, that will take a few more lines of code but is surely better because the user gets another chance rather than running the whole program again
For that, we need to wrap it in a while loop that will iterate till it gets valid input
def username_input():
    while True:
        try:
            username = input("Please enter your username: ")
        except Exception:
            print("Please a enter valid username! \n\n")
            continue
        return username

def password_input():
    while True:
        try:
            password = input("Please enter your password: ")
        except Exception:
            print("Please enter a valid password! \n\n")
            continue
        return password

Here we are repeating ourselves, the functions are identical. With a little hack, we can clean up the code
def ask_input(field):
    while True:
        try:
            word = input(f"Please enter your {field}: ")
        except (Exception, KeyboardInterrupt):
            print(f"Please enter a valid {field}! \n\n")
            continue
        if not word: continue # if field is empty
        return word

def take_input():
    username = ask_input("username")
    password = ask_input("password")
    return username, password

Split work into functions
In my last point, you must've noticed I moved something into a function
We can really clean up our code if we follow the SRP rule or the Single-responsibility principle

The single-responsibility principle (SRP) is a computer-programming
principle that states that every module, class, or function in a
computer program should have responsibility over a single part of that
program's functionality,

If assig the task of taking input in this program, to let's say take_input()
We can re-use the same function if we would ever want to perform the same task again, without copy-pasting the same segment of code
username, password = take_input()
process_login( username, password ):

take_input() will take care of the input related tasks, and when it has proper valid it returns a username and password
process_login() decides whether the login will be authorized or not, based on the records

Check with key username
if username in username_password:
    if username == "Mert" and password == username_password[username]:
        print("Welcome Sir")
    else:
        print("You're not authorized!")

This works right now, but only due to the fact that the size of records is 1, any extra records added and your algorithm will fail, if the size was 50 you cannot write 50 if statements, you need to check with the username entered
def process_login(username, password, records):
    try:
        if records[username] == password:
            print("Authorized")
            return True
    except KeyError:
        print("Not authroized")
        return False

Here, if the username isn't present in records, a KeyError is raised, which I will catch and print Not authorized

Re-written
def ask_input(field):
    while True:
        try:
            word = input(f"Please enter your {field}: ")
        except (Exception, KeyboardInterrupt):
            print(f"Please enter a valid {field}! \n\n")
            continue
        if not word: continue

        return word

def take_input():
    username = ask_input("username")
    password = ask_input("password")
    return username,password

def process_login(username, password, records):
    try:
        if records[username] == password:
            print("Authorized")

    except KeyError:
        print("Not authroized")

I have left out the last part, which is the "registration". Which I will explain next
records = {
    "__Testu" : "__Testp",
    "__Testu2" : "__Testp2"
}

username, password = take_input()
process_login(username, password, records)

Write records into a file
As it is currently, you have pre-added a record to your dictionary, any record added after this is pointless since the next time you run the program, the dictionary will be initialized again with the same one record you added.
You need some way to save the users records so that the next time he opens your program, his previous details are saved
The best way to do this is the user the csv module in Python, - csv.DictReader which will automate all reading/writing of the file for you. But is something you would have to write on your own.
Cheers
>>> Please enter your username: (empty input)
>>> Please enter your username: __Testu
>>> Please enter your password: (empty input)
>>> Please enter your password: __Testp

>>> Authorized


Initiating an action based on product type I am starting my studies with Ruby and OO and I have received a test to do about OO. I am looking for new ways to improve the scenario following object-oriented concepts. Is there a better way to develop this design applying polymorphism?

Here is my problem:

If the product is physical, I have to generate a shipping label.
If it's a book, I have to mention that this product doesn't have taxes.
If the product is a membership, I have to activate the signature and notify the buyer via email.
If the product is digital, I have to send an email for the buyer and give a $10 discount for this product.

class Product
  attr_reader :name, :description, :type, :amount
  include Shipping
  include Discount

    def initialize(name, description, type, amount)
        @name = name
        @description = description
        @type = type
        @amount = amount
    end
end

class Physical < Product
    def initialize(name, description, type, amount)
        super(name, description, type, amount)
    end

    def shipping
        case @type
            when :book
                create_shipping_label
                notify_buyer_product_without_taxes
            else
                create_shipping_label
            end
    end

    def discount
        discount_for_physical_product = 0.0
      return discount_for_physical_product
    end
end

class Membership < Product
    attr_reader :membership_status

    def initialize(name, description, type, amount)
        super(name, description, type, amount)
    end

  def activate_membership()
    @membership_status = true;
  end

  def shipping
    notify_buyer_via_email
    activate_membership
  end

  def discount
    discount_for_membership_product = 0
    return discount_for_membership_product
  end
end

class Digital < Product

    def initialize(name, description, type, amount)
        super(name, description, type, amount)
    end

  def shipping
    notify_buyer_via_email
  end

  def discount
    discount_for_digital_product = 10.00
    return discount_for_digital_product
  end
end

module Discount

    def prepare_discount(order)
        total_discount = 0
        order.get_items.each do |item|
             total_discount += item.product.discount
        end
        return total_discount
    end

    def discount
        discount_default = 0.0
        return discount_default
    end
end

You have a conditional based on the type of object. You can apply the Replace Conditional with Polymorphism refactoring pattern.

In this case, you might have a base class Product, with subclasses DigitalProduct and PhysicalProduct which each implement discount(). I don't think it's sensible to have a MembershipProduct class - membership should be related to the buyer. From an OO perspective, it should feel wrong when you have methods like discount_for_X() - the method should be part of the respective class so that you can make use of polymorphism.


Python raw_input and conditions I have a very simple code that allows me to keep track of what the user inserts in a raw_input.

The kind of controls I check are if the user inserts "f" the program is finished or if the user inserts nothing, the program keeps on running remembering all the inputs the user has inserted.

It works but I think it's very ugly and rudimental.

I would love to get suggestions from experts so I can learn how to handle correctly simple tasks.

Here's the little code:

#!/usr/bin/python
import os
good_receipts = []
done = False
inserted_text = ''
while not done:
    # This function is os dependent and will work only if you use linux
    os.system('clear')
    inserted_text = raw_input("Insert receipt number (if you finished insert 'f'): ").upper()
    if inserted_text and inserted_text != 'F':
        good_receipts.append(inserted_text)
    while not inserted_text == 'F':
        # This function is os dependent and will work only if you use linux
        os.system('clear')
        if good_receipts:
            print "Here's your receipts:"
            print good_receipts
        if not good_receipts:
            print "You didn't enter a single receipt..."
        inserted_text = raw_input("Insert receipt number (if you finished insert 'f'): ").upper()
        if inserted_text and inserted_text != 'F':
            good_receipts.append(inserted_text)
    done = True
# This function is os dependent and will work only if you use linux
os.system('clear')
print "You did a great job, here's your receipts:"
print good_receipts

Here is what I came up with:

#!/usr/bin python
from os import system as sys

def GetReceipt():
    prompt = "Insert receipt number (if you finished insert 'f'): "
    inserted_text = ''
    while True:
        sys('clear')
        inserted_text = raw_input(prompt).upper()
        if inserted_text == 'F': break
        yield inserted_text

def final(receipt):
    sys('clear')
    print ["You did a great job, here's your receipts:\n"+' '.join(receipt),
        "You did not enter a single receipt..."][len(receipt) == 0]

if __name__ == '__main__':
    valid_receipts = [ f for f in GetReceipt() ]
    final(valid_receipts)


Printing the values on each level of a Binary Tree The below code is for printing level-by-level in a binary tree:

//level order printing
public static void levelOrderPrint(Node root){
    Queue<Node> que = new LinkedList<Node>();
    Node mark = new Node(0);
    if(root != null){
        que.add(root);
        que.add(mark);
    }
    while(!que.isEmpty()){
        Node temp = que.poll();
        if(temp != mark)
        System.out.print(temp.key);
        if(temp == mark){
            if(que.peek() == mark || que.isEmpty()){
                return;
            }
            que.add(mark);
            System.out.println();
        }
        if(temp.left != null){
            que.add(temp.left);
        }
        if(temp.right != null){
            que.add(temp.right);
        }
    }
}

I would like to know if there are any bugs or possible optimizations.

This is good code.

General

While it does what it says it will do, here is one beef I have with it, but it's a small one:

    Node temp = que.poll();
    if(temp != mark)
    System.out.print(temp.key);

No braces, no indenting, code meaning is confused.....

That should be:

    Node temp = que.poll();
    if(temp != mark) {
        System.out.print(temp.key);
    }

There is a fair amount of debate about using '1-liner' if statements. The following are reasons why I despise them:

the meaning of the code becomes white-space defined (like your indenting problem above). There are whole languages ( cough Pythong cough ) which are defined by whitespace. Java is defined by braces {}. Use them.
If you use a version-control-system like CVS, SVN, Git, etc. then small changes to code blocks can become visually big in a change-log. Adding one line to the code means updating 3 lines.
it can lead to bugs where people do not put braces in to lines where there should be two statements.
etc.
etc.

I don't like 1-liners Sam-I-Am

OK. But, as code goes, yours is good. How can it be better?

Improvements

You can make mark a private static final instance:

private static final Node MARK = new Node(0);

The following statement has redundancy:

        if(que.peek() == mark || que.isEmpty()){
            return;
        }

it could be:

        if(que.isEmpty()){
            return;
        }

It is not possible for the queue to have two consecutive marks, so the peek can never be a mark.
Now, back to that indentation on the println() method call... here's your code:

    if(temp != mark)
    System.out.print(temp.key);
    if(temp == mark){
        if(que.peek() == mark || que.isEmpty()){
            return;
        }
        que.add(mark);
        System.out.println();
    }

if you had correct braces, etc. you would see that you would be better off with an if/else condition, and that will save an if check:

    if(temp != mark) {
        System.out.print(temp.key);
    } else {
        if(que.peek() == mark || que.isEmpty()){
            return;
        }
        que.add(mark);
        System.out.println();
    }

System.out.println(...) and all the print*(...) variants are slow (they are synchronized). Your code would be faster if you used a system like:

StringBuilder sb = new StringBuilder();
....

    if (temp != mark) {
        sb.append(temp.key);
    } else {
        ....
        sb.append("\n");
    }

....
System.out.print(sb);

Conclusion

Otherwise, this is good code.


Testing an implementation of ports-and-adaptors for tkinter I'm trying to test my implementation of ports-and-adaptors for tkinter.

Assume I have a tkinter Entry declared like so:

entry = tk.Entry(container)
entry.value = tk.StringVar()
entry.configure(textvariable=entry.value)

In module ports.py I have a simple function to set the value:

def set_widget_value(widget, value):
    widget.value.set(value)

In module adaptors.py I have a class that provides domain specific method to set the value:

from myapp.gui.ports import set_widget_value

class EntryAdaptor(object):
    """Wraps a Tkinter Entry widget."""

    def __init__(self, entry):
        self._entry = entry

    def set_value(self, value):
        set_widget_value(self._entry, value)

To test my adaptor layer I have come up with two options.

Option A

import unittest
import unittest.mock as mock

from myapp.gui.adaptors import EntryAdaptor

class EntryAdaptorTests(unittest.TestCase):

    def test_should_set_value_of_entry(self):
        entry = mock.Mock()
        adaptor = EntryAdaptor(entry)

        text = 'some user-typed text'
        adaptor.set_value(text)
        entry.value.set.\
            assert_called_once_with(text)

Option B

import unittest
import unittest.mock as mock

class EntryAdaptorTests(unittest.TestCase):

    def test_should_set_value_of_entry(self):
        entry = mock.Mock()
        with mock.patch('myapp.gui.ports.set_widget_value') as set_widget_value:
            from myapp.gui.adaptors import EntryAdaptor
            adaptor = EntryAdaptor(entry)

            text = 'some user-typed text'
            adaptor.set_value(text)

            set_widget_value.assert_called_once_with(entry, text)

In Option A, I'm looking at the mocked tkinter.Entry object and checking if it was called as expected; this has the disadvantage of mocking the external tkinter API.

In Option B, I mock my set_widget_value() function and check if it was called as expected; this has the disadvantage of performing the import of EntryAdaptor within the test_should_set_value_of_entry() method because of the dependency of adaptors.py to ports.py.

Which is the best way to perform the test: A, B or something completely different?

I prefer Option A over Option B. While you do then end up resting both the port and the adapter in one go, the port and adapter together constitute the unit you are trying to test: the piece of code that allows you to manipulate the widget in question.

Option B, in my opinion, is perhaps a tad too granular.


Simple Matrix Rotation I needed to rotate a non-square matrix in my program to transpose some spreadsheet data and decided to make a function to rotate 90, 180, or 270 degrees.

It doesn't rotate the matrix in place, but instead generates a copy and returns that. I want to go for processing efficiency, let me know what I can do better:

//Rotates the provided matrix by provided degrees counterclockwise
function RotateMatrix(matrix, degrees){
  if(degrees == 90){
    //For 90 degrees swap the height/width and swap the location of each element
    var output = GenerateMatrix(matrix[0].length, matrix.length, 0); //Swapping the width and height for non square matrices
    for(var i = 0; i < matrix[0].length; i++){
      for(var j = 0; j < matrix.length; j++){
        output[i][j] = matrix[j][i];
      }
    }
  } else if(degrees == 180) {
    //For 180 degrees, rebuild array backwards
    var output = GenerateMatrix(matrix.length, matrix[0].length, 0);
    for(var i = matrix.length - 1; i >= 0; i--){
      for(var j = matrix[0].length - 1; j >=0; j--){
        output[matrix.length - 1 - i][matrix[0].length - 1 - j] = matrix[i][j];
      }
    }
  } else if(degrees == 270) {
    //For 270 degrees, not sure how to make short description
    var output = GenerateMatrix(matrix[0].length, matrix.length, 0); //Swapping the width and height for non square matrices
    for(var i = 0; i < matrix[0].length; i++){
      for(var j = matrix.length - 1; j >=0; j--){
        output[i][matrix.length - 1 - j] = matrix[j][i];
      }
    }
  }
  return output;
}

//Generates a matrix with the requested length and width and value
function GenerateMatrix(length, width, value){
  var output = [];
  for(var i = 0; i < length; i++){
    width > 0 ? output.push([]) : output.push(value); //If matrix has 0 width
    for(var j = 0; j < width; j++){
      output[i].push(value)
    }
  }
  return output;
}

Unnecessary matrix generation

In JavaScript, Arrays don't have a fixed size. For example, you could do this:

var arr = [];
arr[324] = 91;

with no problem.

Your GenerateMatrix function is really over-doing it. All you need to do is create the arrays for the rows/columns then change their values.

And, you can do that with a neat trick:

Array.apply(null, Array(rowCount)).map(function(){return []});


Calling a method outside class statically, passing other method's output as parameter I have this class:

class adminTemplate {

    public static function load()
    {
        return new self();
    }

    public function sidebarGuide()
    {
        return 'content'; // Very long html markup
    }

    public function wrapSidebars($content)
    {
        ob_start();
        echo "
";
        echo $content;
        echo "
";
        $output = ob_get_contents();
        ob_end_clean();
        return $output;
    }

    // Other methods here

}

Somewhere in my script, I have to call wrapSidebars using sidebarGuide's output as parameter:

echo adminTemplate::load()->wrapSidebars(adminTemplate::load()->sidebarGuide());

It works, but I'm pretty confident there is a more appropriate way.

Is there a proper way of passing methods'output as other method's parameter in a class loaded "statically"?
Besides that, is there a more elegant code structure to accomplish the same "task"?

You are calling load() every time you call either sidebarGuide or wrapSidebars. Are you doing anything other than returning an instance of the class? If not, then just instantiate the class and making load() a construct would be more ideal. Doing so, your class would look like:

class adminTemplate {
    public function __construct(){}

    public function sidebarGuide(){
        return "content"; # Very long html markup
    }

    public function wrapSidebars($content){
        ob_start();
        echo "
";
        echo $content;
        echo "
";
        $output = ob_get_contents();
        ob_end_clean();
        return $output;
    }
}

You would then use it as follows:

$adminTemplate = new adminTemplate();
$adminTemplate->sidebarGuide();
$adminTemplate->wrapSidebars($adminTemplate->sidebarGuide());

If you wanted, you could even store the return value of sidebarGuide() in a property of the class so that you could call wrapSidebars() without injecting sidebarGuide(), as follows:

class adminTemplate {
    private $sidebarGuideReturnValue

    public function __construct(){}

    public function sidebarGuide(){
        $this->sidebarGuideReturnValue = "content"; # Very long html markup

        return $this->sidebarGuideReturnValue;
    }

    public function wrapSidebars($content = ""){
        # Make $content an optional parameter. If its not set, grab the property
        $content = ($content ? $content : $this->sidebarGuideReturnValue);

        ob_start();
        echo "
";
        echo $content;
        echo "
";
        $output = ob_get_contents();
        ob_end_clean();
        return $output;
    }
}

If you know that would only be calling sidebarGuide() exclusively as a param to wrapSidebars(), you could even relegate sidebarGuide()'s to a private called on instantiation in the construct, or move its body to the construct itself.

One question that bothers me though is, is there any specific reason you want to use static load()? Or just because it looks nice?


Simple card game to learn OOP My goal was to get my hands dirty in OOP by designing and using classes and getting started with inheritance and other OOP concepts.

I have written a very small code to play a card Game called "War". The rules are simple. Each person playing the game is given 1 card. The person with the highest card wins. I am not worrying too much about Ties right now. My code does work but I wanted feedback on my OOP usage.

import itertools
import random
class Cards:
    def __init__(self):
        self.suits = ['Spades','Hearts','Diamonds','Clubs']
        self.values = range(1,14)
        self.ActualCards = [] #Empty List to Append
        for Card in itertools.product(self.suits,self.values):
            self.ActualCards.append(Card) #Cartesian Product to Create Deck
    def GetRandomCard(self):
        RandomNumber = random.randint(0,51)
        CardToBeReturned = self.ActualCards[RandomNumber] #Generates Random Card
    return(CardToBeReturned)

class Player:
    def __init__(self,ID,Card):
        self.PlayerID = ID
        self.CardForPlayer = Card

class Game:
    def __init__(self,NameOfGame):
        self.name = NameOfGame

class SimpleWar(Game):
    def __init__(self,NumberOfPlayers):
        self.NumberOfPlayers = NumberOfPlayers
        self.PlayerList = []
    def StartGame(self):
        DeckOfCards = Cards()
        for playerID in range(0,self.NumberOfPlayers):
            CardForPlayer = DeckOfCards.GetRandomCard() #Deal Card to Player
            NewPlayer = Player(playerID,CardForPlayer) #Save Player ID and Card
            self.PlayerList.append(NewPlayer)
        self.DecideWinner()
    def DecideWinner(self):
        WinningID = self.PlayerList[0] #Choose Player 0 as Potential Winner
        for playerID in self.PlayerList:
            if(playerID.CardForPlayer[1]>WinningID.CardForPlayer[1]):
                WinningID = playerID #Find the Player with Highest Card
        print "Winner is Player "+str(WinningID.PlayerID)
        print "Her Card was "+ str(WinningID.CardForPlayer[1]) + " of " + str(WinningID.CardForPlayer[0])

if __name__=="__main__":
    NewGame = SimpleWar(2)
    NewGame.StartGame()

Syntax Error

In Cards.GetRandomCard(), the return statement is incorrectly indented.  (Also, I would recommend writing the return without parentheses.)

Style Conventions

Use lower_case_names for variables and methods.

For readability, please add one space after each comma, and one newline between functions definitions.

Modeling

Your Game class isn't useful.  You never set or use NameOfGame.  I recommend getting rid of the Game class altogether.

In a real-life card game, you would deal a card from the deck to each player, without replacement.  In your code, you deal with replacement (i.e., there is a chance of dealing the same card to both players).  A more realistic simulation would do a random.shuffle() on the array.  When dealing, you would pop() a card from the list to remove it from the deck.  51 is a "magic" number; you should use len(self.ActualCards) - 1.

Cards is really a Deck.  Rather than just a tuple of strings, you should have a Card class representing a single card.  The Card class should have a __str__() method that returns a string such as "Ace of diamonds".  If you also define comparison operators, then you can determine the winner using max(self.PlayerList, key=lambda player: player.CardForPlayer).

Expressiveness

In Python, you can usually avoid creating an empty list and appending to it:

self.ActualCards = [] #Empty List to Append
for Card in itertools.product(self.suits,self.values):
    self.ActualCards.append(Card) #Cartesian Product to Create Deck

Instead, you should be able to build it all at once:

self.actual_cards = list(itertools.product(self.suits, self.values))


Haskell function to error-diffuse a floating value to a list of integers I needed to write a function which would 'error diffuse' floating values to integers:

errorDiffuse :: Double -> Int -> Double -> [Int]

errorDiffuse _ 0   _   = []

errorDiffuse v num err = tv : errorDiffuse v (num - 1) (err + v - fromIntegral tv)
  where tv = truncate (v + err)

So that, for example:

errorDiffuse 1.4 10 0 => [1,1,2,1,1,2,1,2,1,1]

(i.e., the function produces a list of num integers, each of which is the ceiling or floor of v, starting with a given error value (zero in this case)).

Is there a better way to write this sort of for loop? What's the higher-order function I ought to be thinking in terms of?

First I'd get rid of the dependency on num, since that's just a counter,
and you can use take num on an infinite list of errorDiffuses:

errorDiffuses :: Double -> Double -> [Int]
errorDiffuses v err = tv : errorDiffuses v (err + v - fromIntegral tv)
 where
  tv = truncate (v + err)

So we have:

errorDiffuse' :: Double -> Int -> Double -> [Int]
errorDiffuse' v num err = take num $ errorDiffuses v err

Then I'd think about generating the list of errorDiffuses differently.
Since we're trying to generate a list, that makes me think of unfolds,
which you can find in Data.List:

unfoldr :: (b -> Maybe (a, b)) -> b -> [a]

The unfold takes a function that, given a seed, produces the next
value in the outputted list, along with a new seed. The function
starts with an intitial seed, and keeps using those seeds, adding to the
list until the function returns Nothing.

The function we're looking for is the following:

nextErrorDiffuse :: Double -> Double -> Maybe (Int, Double)
nextErrorDiffuse v err = Just (tv, err + v - fromIntegral tv)
 where
  tv = truncate (v + err)

Our list is infinite, so we always return a Just value. The value that is output at each stage is tv, and the next "seed" is given by err + v - fromIntegral tv.

Putting things together we have:

errorDiffuse'' :: Double -> Int -> Double -> [Int]
errorDiffuse'' v num err = take num $ unfoldr (nextErrorDiffuse v) err