Winform that exports a datagrid to Excel

Yes, I'd say the if..else is enough, but it's a little wordy. Button.Checked is already a Boolean value, so comparing it to true is superfluous. There's also a lot of shortening of code you can do with the judicious use of using directives. Also, I had to do some fancy dancing to make sure Excel itself is truly shut down when it needs to be. Give this a look-see and let me know what you think:

namespace WindowsFormsApplication1
{
    using System;
    using System.IO;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;

    using Microsoft.Office.Interop.Excel;

    using Application = Microsoft.Office.Interop.Excel.Application;

    public partial class Form1 : Form
    {
        private Application xlExcel;

        private Workbook xlWorkBook;

        public Form1()
        {
            this.InitializeComponent();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                this.QuitExcel();
                this.xlExcel = new Application { Visible = false };
                this.xlWorkBook = this.xlExcel.Workbooks.Add(Missing.Value);

                // Copy contents of grid into clipboard, open new instance of excel, a new workbook and sheet,
                // paste clipboard contents into new sheet.
                this.CopyGrid();

                var xlWorkSheet = (Worksheet)this.xlWorkBook.Worksheets.Item[1];

                try
                {
                    var cr = (Range)xlWorkSheet.Cells[1, 1];

                    try
                    {
                        cr.Select();
                        xlWorkSheet.PasteSpecial(cr, NoHTMLFormatting: true);
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(cr);
                    }

                    this.xlWorkBook.SaveAs(Path.Combine(Path.GetTempPath(), "ItemUpdate.xls"), XlFileFormat.xlExcel5);
                }
                finally
                {
                    Marshal.ReleaseComObject(xlWorkSheet);
                }

                MessageBox.Show("File Save Successful", "Information", MessageBoxButtons.OK);

                // If box is checked, show the exported file. Otherwise quit Excel.
                if (this.checkBox1.Checked)
                {
                    this.xlExcel.Visible = true;
                }
                else
                {
                    this.QuitExcel();
                }
            }
            catch (SystemException ex)
            {
                MessageBox.Show(ex.ToString());
            }

            // Set the Selection Mode back to Cell Select to avoid conflict with sorting mode.
            this.dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.QuitExcel();
        }

        private void QuitExcel()
        {
            if (this.xlWorkBook != null)
            {
                try
                {
                    this.xlWorkBook.Close();
                    Marshal.ReleaseComObject(this.xlWorkBook);
                }
                catch (COMException)
                {
                }

                this.xlWorkBook = null;
            }

            if (this.xlExcel != null)
            {
                try
                {
                    this.xlExcel.Quit();
                    Marshal.ReleaseComObject(this.xlExcel);
                }
                catch (COMException)
                {
                }

                this.xlExcel = null;
            }
        }

        private void CopyGrid()
        {
            // I'm making this up...
            this.dataGridView1.SelectAll();

            var data = this.dataGridView1.GetClipboardContent();

            if (data != null)
            {
                Clipboard.SetDataObject(data, true);
            }
        }
    }
}


Both std::istream and std::ostream are actually not defined in <iostream>, despite the fact that they look similar.  They're respectively defined in <istream> and <ostream>.

You should instead include these in the implementation file and include <iosfwd> (the iostream declaration forwarding library) in the header.
These data members should be private:

glm::vec3 position;
glm::vec3 normal;
glm::vec2 texCoord;

Otherwise, they will be accessible outside of the class.  If they are not meant to be this way, then you should use a struct instead, which are public by default.
If you don't need a default constructor, then leave it out.  The compiler will provide one for you.
Regarding operator==:

Conditional operators overloads, such as operator==, should be const as they should not modify any data members:

bool operator==(const Vertex& other) const;

Its definition could also be split into multiple lines, which is easier to read than one long line:

bool Vertex::operator==(const Vertex& other) {
    return position == other.position
        && normal == other.normal
        && texCoord == other.texCoord;
}


Run Length Encoding (RLE) and Move To Front (MTF) in C++

Looks quite nice, but let's get down to ripping it apart.

First your runlength-encoding:

Try to use the same type for size-variables / indices throughout:
std::basic_string<...> uses std::size_t.
That way you would also heal the one sign-mismatch.
Your comment about the encoded form // encode (aaaaeecd -> 4a2e1c1d) is wrong.
You probably meant: // encode (aaaaeecd -> \x04a\x02e\x01c\x01d)
You are wasting \x00 and thus the chance to encode runs of length 256.
(Yes, the comment // run_count is between 0 and 255 (unsigned char) is wrong.)
You are missing the header <algorithm>.

Next your Move-To-Front:

I suggest you move from std::list to std::array.
A list is a far too heavy data-structure, jumping every-which-way in memory kills your performance quite easily.
The std::deque is a bit better, but using a std::array would probably still handily beat it due to simplicity.


increase speed & lower memory consumption of text normalization function

You can save a little bit of time by not re-running str.maketrans for each token, since it's always going to produce the same result:

import nltk
from statistics import mean
import string
import time
from typing import List

def normalize_text3(text: str) -> List[str]:
    output: List[str] = []
    punctuation_filter = str.maketrans('', '', string.punctuation)
    for token in nltk.word_tokenize(text):
        token = token.translate(punctuation_filter)
        if not token:
            continue
        output.append(token.lower())
    return output

tested with:

for func in [normalize_text, normalize_text2, normalize_text3]:
    times = []
    for _ in range(1000):
        start = time.time()
        tokens = normalize_text(t)
        end = time.time()
        times.append(end - start)
    print(f"{func.__name__.rjust(15)}: {mean(times)}")

gets me:

dog runs
 normalize_text: 0.003226396322250366
normalize_text2: 0.0032752704620361327
normalize_text3: 0.0030987038612365725

If you want to lower memory consumption, you might consider having this function return a generator rather than a list...


Although you think that the second one is closer to your desired syntax, it is actually somewhat confusing. If LetSet was a function with only one parameter, this would cause a Let coercion on the RHS, if an object is supplied. E.g. if the RHS is a range, the usual behaviour of a Let assignment is that the values in the range are assigned instead of the object. Only because LetSet is parameterized, the object itself is assigned.

So, following the principle of least surprise, I would suggest to use the first version.


Is there a better way to optimize these conditionals?

You're throwing System.Exception - that's bad, you'll want to throw a meaningful exception. See this answer for more details.

The main problem with this code, is that you're using exceptions to control the execution flow of your program, which is very expensive - I assume you're going to be catching these exceptions somewhere down the call stack.

If a is Nothing, then accessing it will throw an NullReferenceException. Same for b, c, d and e (say, you also have f in there?).

Let it blow up with whatever exception you get - and catch it. Use exceptions for exceptional cases, and avoid throwing them altogether if you can.

"Exceptions are expensive"

"Throwing and catching exceptions is expensive", you'll read [almost] everywhere. There's truth in that, Jon Skeet has a great article here that correlates performance to the depth of the call stack. The reason for this, is because the thread stops at the throw instruction, and then the exception's StackTrace gets populated - the call stack gets unwinded and the thread walks it until it reaches a catch block. The deeper the stack, the longer it takes.

But the problem isn't about performance - it's about efficiency. Exceptions are not a way to control your execution flow. Regardless of whether or not you care about wasting cycles and populating a stack trace, regardless of how long that takes for the runtime to complete, the point and the matter is, there are ways to make the intent much clearer to whoever is maintaining this code, than by throwing an exception.

The goal is to validate a bunch of objects, and return a message that informs which object is in an invalid state.

By throwing an exception, the first invalid object exits the function and you can't know if other ones were invalid.

By nesting the conditions and returning a String, the last invalid object gets its status reported... if you're lucky - I mean, when anotherObject isn't null, nothing else gets checked and you can't report that theString was NullOrEmpty.

How about returning a flag enum that contains all validation errors? (not sure of VB syntax here, my background is C#):

[Flags]
Public Enum MyValidationError
    None = 0
    FirstObjectIsInvalid = 1
    MyEnumerationIsInvalid = 2
    TheStringIsInvalid = 4
    SomeCollectionIsInvalid = 8
    AnotherObjectIsInvalid = 16
End Enum

Then the function can return a MyValidationError value:

Public Function MyProjectFunction(...) As MyValidationError

    Dim result As MyValidationError
    If IsNothing(firstObject) Then result += MyValidationError.FirstObjectIsInvalid
    If IsNothing(anotherObject) Then result += MyValidationError.AnotherObjectIsInvalid
    If MyEnumeration = 0 Then result += MyValidationError.MyEnumerationIsInvalid 'an enum type shouldn't ever be 'Nothing'...
    If String.IsNullOrEmpty(theString) Then result += MyValidationError.TheStringIsInvalid
    If IsNothing(SomeCollection) OrElse SomeCollection.Count = 0 Then result += MyValidationError.SomeCollectionIsInvalid

    Return result

End Function

Notice all parameters are validated every time now, and the result will contain everything that went wrong. Then another method can use bitwise AND operations on the result and determine the message(s) to log/display, all without throwing an exception, and without nesting anything.


Flexible generic event system that binds to objects

It looks good to me. The Event_Receivable thing looks like a vanilla observer pattern, which involves inheritance. I don't really have comments on the architecture, but I recommend a look at this Game Programming Patterns chapter if you haven't already.

Code review

A few considerations on the design:

The first thing that jumps to the eye here is the heavy use of raw pointers. The event queue, for instance, has a vector of Event_Receiver pointers which it does not own. It would be a disaster if one of those objects were to be deleted while the pointer is still in the queue's vector. Event_Receiver also keeps a raw pointer to its owner. I think you should take a step back and rethink this. It can save you a lot of headache on pointer debugging in the future, not to mention the potential for memory leaks, which can be a serious problem in a game. If you can use C++11, then consider the standard smart pointers. It seems that a combination of shared_ptrs and weak_ptrs would be suitable here.
You already know this, but when you do decide how to handle copy/assignment, take a look at the Rule of Three. The safest course of action until then would be to make the types that hold naked pointers, or arrays of pointers, non-copyable, by deleting the copy constructor and assignment operator. That might actually suit your needs and it is very easy to do.
You are using strings to define the event type and name/id; not sure if this is a good approach. The only reason I would chose to represent those as strings would be if I had the need to create event types dynamically during runtime. The two main issues with using strings are 1) performance: it is much faster comparing an integer/enum-constant than it is comparing a string; 2) when declaring/referencing an event in the code, if you mistype a string, you will only find out about the error after a little runtime debugging. That problem goes away with compile-time constants. Your choice should really be based on how flexible you need the system to be, then choose your trade-off.

Miscellaneous:

Your get* methods are missing const at the end, which would make it impossible to call one of them on a const object. Since they don't mutate member data, make them const correct. E.g.:

boost::any get_info() const { return info; }
                      ^^^^^

Still talking about the getters, I'm not sure how costly it is to copy, for instance, a boost::any, but if the caller will mostly just be inspecting the value, then consider returning complex objects by const reference. E.g.:

const boost::any & get_info() const { return info; }
^^^^^            ^            ^^^^^

Looking in the repository link, I see that you have some very long-winded for loops in Event_Queue, such as this one from Event_Queue::poll_input():

for(std::vector<Event_Receiver*>::iterator it = receiver_list.begin(); it != receiver_list.end(); ++it)

Such huge line can be made a lot simpler by using a range-based for loop (C++11), or at least the use of auto for the iterators.
Event_Sender seems to be missing a constructor, which would leave its member pointer uninitialized until it is set somewhere else. This is very dangerous and can be a source of bugs. Always initialize your variables to a known value. Don't leave room for chance.
Looking at the implementation of Event_Receiver, the destructor is empty, so you can just remove it and let the compiler supply a default.
You have a mixed style of public/private class sections. Some have private at the start, others have it at the end. I'd suggest that you make it uniform through all classes. My personal preference is to place the public section of a class first in the header file. The rationale is that people using and reading my code will care much more about the public methods and data, so that's what they want to see first when reading the header file. Private/protected sections of a class are of interest to the programmer maintaining the code, so it makes sense that they don't need that much visibility.
Use the constructor initializer list to init member data. Using the assignment operator might result in redundant initialization if the compiler is not able to optimize the code (calls the default constructor of a type + operator =).

Event(std::string name_str, std::string type_str)
    : name(std::move(name_str))
    , type(std::move(type_str))
{ }

That's also a perfect place for a move, to avoid copying things over and over. Without move the best would have been taking name_str and type_str by const reference.


Java PrintWriter not printing data to file

With any Java Writer or Stream... YOU MUST PROPERLY FLUSH AND CLOSE it.

The documentation is not fantastically clear... but:

when you exit the method, you must ensure that the file is flushed and closed. you are exiting your program before the data is written to disk.

Always use the following pattern when doing IO (if you are using Java7) :

try (PrintWriter output = new PrintWriter(path)) {
    output.printf("%1$s %2$.2f", title, price);
    output.flush();
}

This is a 'try-with-resource' block.


Calculating the push or pull force of a molecule at a vertex

First of all you probably should type your numpy arrays but be warned, whether you use the np.ndarray notation, or the memory view notation, only limited operations occur at the speed of c, that is indexing, 'shape', and a very few others. With a memory view you can only use these fast operations, with a ndarray type you can access all the python operations too but they still occur at the speed of python, not c.

In this case, your code doesn't actually use any array functions that would benefit from the arrays being properly typed so you'd gain nothing in the mere act of typing the arrays. The overhead of calling a python function is significant so you might benefit from not using the numpy array functions, if the numpy arrays are short and if the functionality is straightforward to reproduce as cython code using array indexing (fast) and if the function is called many times. The profiler should tell you this stuff.

I can see some low-hanging fruit in the above code, take this line, mentioned to be a major offender:

Fe_pull  = np.max([Fe_pull_minus1, Fe_pull_plus1, Fe_pull])

What happens here, is np.max is a call to a python function of a python module, the list will be constructed as a python list and the floats will be converted to python floats because a python list can't hold c floats. Then that code will all run at the speed of python. np.max will then unpack all that stuff and the result of np.max will be a python float which is converted to a c float. This will be slow!. In fact it may even be slower than python, because it involves creating extra temporary python objects.

What you would do is rewrite that to eliminate the python function call (and thus all the intermediate python objects). As it happens, if you use the python built-in 'max' on typed variables, cython is smart enough to eliminate the python call entirely:

Fe_pull = max(Fe_pull_minus1, Fe_pull_plus1, Fe_pull)

That will automatically become optimal inline c code for calculating the max of the 3 variables (Cython actually unrolls it as if/else statements)

The next low-hanging fruit, and another stated offender is this:

Fe_plus, Fe_plus_ = self.calculate_edge_force( ...

In some cases Cython optimizes away tuple-unpacking, but it doesn't in the case of function calls. So what is going to happen is cython will create an intermediate tuple (a python object), pack stuff into the tuple (Again, converting to python objects, as tuples can't hold c types), then unpack the tuple and convert the python objects to their c types. Again this should be turned into something that translates readily to c. Unfortunately in this case there is no faster better cleaner syntax, you would probably be best served by making a 'pair' struct and manually packing and unpacking it, something like:

#At the top level
cdef struct float_pair:
    float a
    float b

# In the class method definition
cdef floar_pair calculate_edge_force(...
    ...
    cdef float_pair result
    result.a = ...
    result.b = ...
    return result

# In your function
    cdef float_pair result = self.calculate_edge_force( ...
    Fe_plus = result.a
    Fe_plus_ = result.b

Using a struct is by no means the only option here, but it's going to be faster than using a small array. You could also use the C++ 'pair' template which would be just as fast as a struct but it involves bringing in C++. For that matter you could also pass in the floats by pointers. None of these are clearly superior in either speed or elegance, but all will compile down to clean c code.

I imagine if you root out those big ghoulies of python calls you'll get a significant speed improvement. After that it's a matter of using cython -a on the .pyx file. The generated html file shows 'unoptimized' lines in yellow/orange, you can click on a line to see the generated c code. From there you can figure out how to eliminate the python calls - if it is worth it.


function Project(project) {
  this.name = project.name;
  this.order = project.order;
  this.title = project.title;
  this.date = project.date;
  this.tags = project.tags;
  this.logo = project.logo;
  this.html = project.html;
  this.agency = project.agency;
  this.slides = Object.values(project.slides).map(slide => slide);
  this.path = `projects/${this.name}`;
  this.route = `/projects/${this.name}`;
  this.slidesPath = `/projects/${this.name}/slides/`;
  this.hiDefAffix = '@2x';
};

If all this does is just set props to an instance, then you probably don't even need a constructor. You can simply use a factory function that accepts a project object and returns an object with properties.

function createProject({name, order, title, date, tags, logo, html, agency, slides, name}){
  return {
    name,
    order,
    title,
    date,
    tags,
    logo,
    html,
    agency,
    slides: Object.values(project.slides),
    path: `projects/${this.name}`,
    route: `/projects/${this.name}`,
    slidesPath: `/projects/${this.name}/slides/`,
    hiDefAffix: '@2x'
  };
}

Object.values(project.slides).map(slide => slide);

Looks like project.slides is an object. Object.values creates an array of values. array.map just creates a copy of that array, which is useless.

const all = {};
Object.values(projectsData).map(project => all[project.name] = new Project(project));

You are misusing array.map. array.map is for transforming one array into another in a 1-to-1 transformation. What you are doing here is creating an object. This is a job for array.reduce.

const all = Object.values(projectsData).reduce((all, project) => {
  return { ...all, [project.name]: createProject(project)};
}, {});

try {
  if (this.all[project]){
    return this.all[project];
  } else {
    throw new Error(`Project "${project}" not found.`);
  }
} catch (error) {
  return false;
}

The try-catch is pointless. You are immediately catching the error and simply returning false. Why not return false in the first place?

return this.all[project] || false;

toJSON() {
  return JSON.stringify(this.all);
}

I believe this is a practice commonly done by Java developers to have an intermediate function to handle special properties. But this is unnecessary in most cases since any simple JS object is immediately serializable by JSON.stringify, and you don't appear to use any of the new data types.

  How can I make this Javascript code more OO

This is the wrong way to think in terms of programming, locking yourself to a paradigm. What you should be asking is "How to make this code simpler?" or "How to make this code easier to understand?".

Also, OO isn't about classes, or constructors or methods and properties. It's about working with objects, whether they are instances of classes or simple data structures like object literals or arrays. You can do a lot with just object literals and arrays. You aren't going to need the class and methods fluff in most cases.


Split string into "n" lengths with padding

My first impression is that we would probably wish to avoid copying and shuffle data as much as possible.

The code as presented does the following:

conditionally remove items (worst case time complexity occurs when every char is a space, in which case it's \$\mathcal{O}(\frac{n^2}{2})\$ (more or less))
append padding (worst case will involve a reallocation plus copy \$\mathcal{O}(n)\$)

I think we can do better, performing the entire operation in linear time and guaranteeing no memory reallocations. This involves iteratively conditionally copying the bytes. We can do this because std::string's iterators are random-access, so we can compute distances in constant time.

I have presented it here as a simple composition of methods in a lightweight engine object. Another way would be to create a state machine which could be chained to another encryption stage:

#include <iostream>
#include <algorithm>

struct squish_engine
{
    squish_engine(std::size_t blockSize, char paddingChar)
            : blockSize(blockSize)
            , paddingChar(paddingChar)
    {

    }

    // useful for initial allocation of destination string
    std::size_t estimate_size(std::size_t plaintext_length) const {
        return plaintext_length + blockSize;
    }

    // a predicate
    static bool matchesSpace(char c) {
        return c == ' ';
    }

    // operation in terms of iterators
    template<class FromIter, class ToIter>
    ToIter operator()(FromIter first, FromIter last, ToIter first2) const
    {
        // use stl algorithms where possible
        auto last2 = std::remove_copy_if(first, last, first2, matchesSpace);
        auto pads = std::distance(first2, last2) % blockSize;
        if (pads) {
            pads = blockSize - pads;
        }
        last2 += pads;
        return last2;
    };

    // this is the public interface
    template<class Iter>
    std::string operator()(Iter first, Iter last) const
    {
        // build an overly-large string to accept the result.
        // we may as well pad it now, as it's no extra cost compared
        // to zero-filling
        std::string result(estimate_size(std::distance(first, last)), paddingChar);
        // our internal operator will compute the end point of the
        // padded area for us
        auto last2 = (*this)(first, last, std::begin(result));

        // so we can simply truncate any padding chars we don't need
        result.erase(last2, result.end());

        // and return the cypher
        return result;
    }

    // convenience interface
    std::string operator()(const std::string& s)
    {
        return (*this)(std::begin(s), std::end(s));
    }

    std::size_t blockSize;
    char paddingChar;
};

// the concept of making a copy while filtering
template<class Filter>
std::string filter_copy(const std::string& source, Filter&& filter)
{
    return filter(source);
}

int main(){

    std::size_t blockSize = 11;
    char paddingChar = 'X';

    std::string str = "Tis' but a scratch!";

    // now we can conceivably choose the encryption engine at the
    // client call site
    auto compressed = filter_copy(str, squish_engine(blockSize, paddingChar));

    std::cout << compressed << '\n';
    return 0;
}


For some inputs where there is no solution, gaussian_reduce returns an array of NaNs:

>>> gaussian_reduce(np.zeros((2, 2)), np.ones((2, 1)))
__main__:63: RuntimeWarning: invalid value encountered in double_scalars
array([[nan, nan]])

A better way to handle an exceptional situation is to raise an exception, like np.linalg.solve:

>>> np.linalg.solve(np.zeros((2, 2)), np.ones((2, 1)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "numpy/linalg/linalg.py", line 390, in solve
    r = gufunc(a, b, signature=signature, extobj=extobj)
  File "numpy/linalg/linalg.py", line 89, in _raise_linalgerror_singular
    raise LinAlgError("Singular matrix")
numpy.linalg.linalg.LinAlgError: Singular matrix

It looks as though you attempted to do this:

matrix = np.append(matrix, b, axis=1)
matrix = to_row_echelon(matrix)
if all(matrix[-1,:] == 0):
    raise Exception("System of equations is inconsistent")

but it doesn't work, because in this case (a zero matrix) the last row gets filled with NaNs rather than zeros:

>>> m = np.append(np.zeros((2, 2)), np.ones((2, 1)), axis=1)
>>> to_row_echelon(m)
array([[ 0.,  0.,  1.],
       [nan, nan, nan]])

The NaNs result from the division in subtract_rows:

return row - (row[0]/top_row[0])*top_row

This division needs to be skipped if top_row[0] is zero. For example, in pivot you would have:

if matrix[0, 0]:

before the call to np.apply_along_axis. (But see below for further improvements here.)
In mathematical code, you should be on the lookout for division by zero. Every division operation is suspicious: what if the divisor is zero? There are some more division operations in backsolve which lead to this kind of incorrect result:

>>> gaussian_reduce(np.ones((2, 2)), np.array([[2], [3]]))
__main__:70: RuntimeWarning: divide by zero encountered in double_scalars
array([[-inf, inf]])

In this case you need to raise an appropriate exception, again like  np.linalg.solve:

>>> np.linalg.solve(np.ones((2, 2)), np.array([[2], [3]]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "numpy/linalg/linalg.py", line 390, in solve
    r = gufunc(a, b, signature=signature, extobj=extobj)
  File "numpy/linalg/linalg.py", line 89, in _raise_linalgerror_singular
    raise LinAlgError("Singular matrix")
numpy.linalg.linalg.LinAlgError: Singular matrix

gaussian_reduce returns the result as a row vector (an array with one row):

>>> A = np.diag((1., 2.))
>>> b = np.array([[4.], [5.]])
>>> gaussian_reduce(A, b)
array([[4. , 2.5]])

But in the equation \$Ax = b\$ the solution \$x\$ is a column vector (an array with one column). And this is what np.linalg.solve returns:

>>> np.linalg.solve(A, b)
array([[4. ],
       [2.5]])

Returning a column vector means that we can verify the solution by multiplying:

>>> A @ np.linalg.solve(A, b)
array([[4.],
       [5.]])

which is equal to b as required. Whereas in the gaussian_reduce case, it doesn't work:

>>> A @ gaussian_reduce(A, b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: shapes (2,2) and (1,2) not aligned: 2 (dim 1) != 1 (dim 0)

The name gaussian_reduce could be improved. It's better to name a function based on what it computes, not after the algorithm it uses to compute it. For example, if you want to find the strongly connected components of a graph, you'd rather have a function named strongly_connected_components than one named tarjans_algorithm (Robert Tarjan invented many algorithms). Naming a function after its result rather than its method also allows you to change the method if you find a better one.

Since gaussian_reduce is a function that returns a solution to a system of linear equations, a name like linear_system_solution (or some suitable abbreviation) would be clearer.
When writing NumPy code, it's a good idea to be clear about when you are modifying arrays in-place and when you are returning new arrays. If you don't keep this distinction clear, then you are at risk of either (i) modifying an array that you didn't mean to, for example one passed by the caller; or (ii) making an unnecessary copy of an array when you could have just modified the original.

There are a couple of things you can do to keep this distinction clear. First, distinguish between functions that construct new arrays and functions that modify their input arrays, by having the former return the new array, and the latter return nothing (consider the difference between Python's built-in sorted, which returns a new list, and list.sort, which returns nothing). In this case, since to_row_echelon modifies its input, it should return nothing.

Second, avoid reusing a variable name to refer to a newly constructed array, because this will lead to confusion about whether it is safe to modify the array. For example, in gaussian_reduce you have:

matrix = np.append(matrix, b, axis=1)

The function np.append always constructs a new array, and so the original matrix and b are unchanged. This means that the copy and the deletion are unnecessary in the following lines:

b = matrix[:,-1].copy()
matrix = np.delete(matrix, -1, axis =1)
b = backsolve(matrix, b)

So to improve this code I would give the full matrix a new variable name to avoid confusion:

augmented_matrix = np.append(matrix, b, axis=1)

Then since to_row_echelon modifies its input, it should not return a result:

to_row_echelon(augmented_matrix)

Then the copy and deletion are unnecessary, because I can just index into augmented_matrix:

solution = backsolve(augmented_matrix[:,:-1], augmented_matrix[:, -1])

Note the use of the new variable name solution to avoid confusion with b.

Finally, instead of constructing yet another array:

return np.array([b])

we could reshape the array we already have:

return solution.reshape(1, -1)

but in fact as discussed above we should return a column vector here, not a row vector, so we actually need:

return solution.reshape(-1, 1)

Similarly, pivot modifies the input and so should not also return it.
The docstring for pivot says:

... to set all other elements of the first row to be zero

but this should say "column", not "row".
pivot needs to find the row with the largest absolute value in the first column, which it does like this:

idx_of_max = np.argmax(list(map(abs, matrix.T[0])))

It is clearer, I think, to get the first column of the matrix using matrix[:, 0] instead of transposing. Then you can just call abs(matrix[:, 0]), which returns a new array containing absolute values element-wise. This avoids the need for map and list.
Instead of calling subtract_rows for each row:

matrix[1:,] = np.apply_along_axis(subtract_rows, 1, matrix[1:], matrix[0])

do all the subtractions in one go, avoiding the need for subtract_rows:

matrix[1:] -= (matrix[0] / matrix[0, 0]) * matrix[1:, 0]

But to avoid division by zero you will need to guard this, as discussed above:

pivot_value = matrix[0, 0]
if pivot_value:
    matrix[1:] -= (matrix[0] / pivot_value) * matrix[1:, 0]

In swap_rows, it is misleading to name the arguments a and b, since elsewhere in the code you are using b for a column vector, but here b needs to be an index. It helps the reader to follow the code if you are consistent about the use of variable names. In this case I would use the names i and j.
swap_rows can be implemented more simply like this, using NumPy's "fancy indexing":

def swap_rows(a, i, j):
    "Swap rows i and j in the array a."
    a[[i, j]] = a[[j, i]]

This is now so simple that you would probably want to inline it at its single point of use.


An iterator which behaves like an array with uniform values

As I alluded to in my question in the comments I think you should consider having a past-the-end iterator that would allow your iterator to be used with standard algorithms. Example:

std::copy(iterate_n_wrapper<int>(42, 4), iterate_n_wrapper<int>(), std::ostream_iterator<int>(std::cout, " "));

See std::istream_iterator for an example from the standard library of this concept in action.

cppreference.com has a nice example of how to achieve this.

It doesn't seem like an iterator is actually required to implement "past-the-endness" (note: I haven't dug into the standard to check), but it's something I, and I think most other C++ users, would expect. And the text in the link strongly hints that it's expected.

Normally you'd only supply operator* for an iterator and not operator[], but that's up to you.

Also I don't see a reason for using size_t as the difference_type (third template parameter to std::iterator) - why not stick with the default of std::ptrdiff_t?

You also need to implement Swapability for it to be satisfy the iterator concept.

Except for the missing past-the-end iterator, these are all minor quibbles. Building on std::iterator is was until C++17 (see @Olzhas comment) the right choice and I don't see anything wrong with the rest of your implementation.


Counting the number of points that have both a larger theta and a larger radius than a given point

First, your query is written fine. Its structure is not a concern; the order of the froms is clearly correct, the select is appropriate. Where you could look for improvement that could change the query (code and possibly performance) would be in the GetData method. If, for example, GetData is getting data from an external, queryable source, then you may want to offload the filtering to it rather than getting all of the data points and filtering it inside your application, particularly since you have so many points of data (potentially). So maybe your query could instead be

(from type in ValidTypes()
 select GetData(type, referencePoint).Count())
.Sum();

// or same meaning, different phrasing

(from type in ValidTypes()
from point in GetData(type, referencePoint)
select point).Count();


Monitoring navigation function: logic judgment

A few comments:

Array.forEach takes a callback, this can be done directly as so:  ems.forEach(watchNav)
Also, you have scope conflicts: the global variable em, and the function parameter em
A third comment: You should n ot edit your question based on feedback in comments.
Your if statement is fine.

<script>
    var ems = document.querySelectorAll(".panel"),
        viewHeight = window.innerHeight,
        clientHeight = document.body.clientHeight,
        timeOut = null;

    ems.forEach(watchNav);

    function watchNav(em) {
        var emHeight = em.offsetHeight;
        var emTop = em.offsetTop;
        clearTimeout(timeOut);

        window.addEventListener("scroll", function (e) {
            var scrollY = window.scrollY;

            timeOut = setTimeout(function () {
                // Logical judgment: how to optimize, want better implementation.
                // Such as reducing the if statement
                // ++++++++++++++++
                if (scrollY > emTop || scrollY + viewHeight / 2 > emTop || scrollY + viewHeight > emTop + emHeight) {
                    console.log("...activing...");
                    em.classList.add("view-focus");
                } else {
                    console.log("none");
                    em.classList.remove("view-focus");
                }

                if (scrollY > emTop + emHeight / 2) {
                    console.log("none");
                    em.classList.remove("view-focus");
                }
                // ++++++++++++++++
            }, 40);
        }, false);
    }
</script>
```


Disclaimer: I'm not sure if this code will be the solution for SPOJ.

You don't check if the input number is an int.

if (scanf("%d", &i) == 1)
{
    printf("OK\n");
}
else
{
    printf("Not an integer.\n");
}

You don't ever tell the user what to enter.

printf("%s\n", "Enter what you think the answer is to life, the universe, and everything (hint: it's a number).");

This is more of a nitpick, but the while loop could be created in a better fashion instead of breaking.

while (i != 42)

Another nitpick, you don't add a newline after printing the int.

printf("%d\n", i);


A warning on version
Many of the following suggestions assume that you are using Python 3.
Bare inheritance
class SegmentationType(object):

can be
class SegmentationType:

Abstract statics
DISPLAY_NAME = "invalid"

should not really assign a value. Instead,
DISPLAY_NAME: str

Unpacking imread
The documentation is deeply unhelpful: it says that imread returns "retval". Given your usage it's obvious that reality is more complicated, because you're indexing into it. Try to unpack instead:
_, self.input_data = cv2.imread(self.path + self.filename)

Abstract methods
process should raise NotImplementedError in the base.
Factory
You have a factory dictionary that should be turned into a method, something like
def get_segmenter(name: str) -> Type[SegmentationType]:
    return {
        t.DISPLAY_NAME: t
        for t in (HSVSegmenter, LABSegmenter)
    }[name]

Outer parentheses
Neither of these:
nr_of_sublists = (int(len(image_lst)/2.5))
image_sub_lst  =(np.array_split(image_lst, nr_of_sublists))

needs outer parentheses.
Syntax
Surely this is a typo? This will not run:
processor =  = segmenter_class(img, img_dir, procedure)

nor will this:
pool.map(?, sub_lst)


Finding the longest substring in a string

The algorithm has linear (\$O(n)\$) time complexity, which is good; you can't do better. It also has a linear space complexity, which is not so good; only a constant space is really required. Notice that you don't need to build substr (substr consumes memory!). It suffices to keep track of the start and end indices.
The test for index < len(s) - 1 is un-pythonic. Don't ask permission, ask forgiveness.
The intention to

  minimize the number of loops

is dubious. Does it improve run time? Most likely, no (if you doubt, measure). Does it improve readability? Most likely, no. Consider the pseudocode

  while start_index < string_length:
      length = scan_ordered_substring(string, start_index)
      do_business_logic
      start_index += length

I don't think that

    print(substr);

was intended.


Implementation of merge sort and bubble sort

I don't see any major problems but there are a number of (really very minor) little nits.

First, the trend seems to be for people to like very few blank lines.  I think this trend is driven by the prevalence of syntax highlighting.  I recently I had the occasion to program on a machine without syntax highlighting and found that I wanted more blank lines again for readability.  Anecdotes aside though, try using fewer blank lines and see if you like it after you get used to it.

In your first if statement, you could use the "simple statement" form

if _, err := fmt.Scanf("%d", &n); err != nil {
    fmt.Println("Error:", err)
    return
}

Most Go programmers like that this form more clearly associates the if statement with the code that is being tested and that the scope of err here is limited to the if body.  It also saves a line of screen real estate.

Consider replacing sequences of if statements with a single switch statement.

switch _, err := fmt.Scanf("%d", &n); {
case err != nil:
    fmt.Println("Error:", err)
    return
case n > 1000:
    fmt.Println("Error:", n, "> 1000 - too long!")
    return
case n < 1:
    fmt.Println("Error:", n, "< 1")
    return
}

The usual arguments for preferring switch over a chain of ifs are that the logic is easier to follow and the code is more readable.  As with the simple statement form of if, this form also restricts variable scope and tends to need few lines on the screen.

array := make([]int, n) presents some issues.

The word "array" has a general meaning in computing, but has a specific meaning in Go.  Some Go programmers are bothered when Go slices are incorrectly called arrays.  It's disturbing in the way something like var integer float64 would be.  You might still argue that array is appropriate here because it identifies the conceptual thing you have obtained from the user and retains the language of the user interface.  Or in the interest of code readability, you might consider other names, or consider different terminology in the user interface.

In BubbleSort, you can replace

array := make([]int, len(inputArray))
copy(array, inputArray)

with

array := append([]int{}, inputArray...)

if you like.  The first form is easy to understand and is arguably more readable.  The second form is a little tricky but is listed on Slice Tricks on the Go Wiki and I think is pretty common.

It looks like your for loops in BubbleSort could use the range clause form.

And then you have some if statements with unnecessary parentheses.  Otherwise looks great.


Concatenating a SoundCloud Playlist Update JSON

You can make this easier with mapping.

So, let's clarify what we have.

playlist.tracks - An array of "tracks" which have an id property (which is what we need).
trackID - an integer representing our new track
myTracks - an array of dictionaries in the form of key "id" and value being the track ID.
myParams - a dictionary with the key of "tracks" and the value being the aforementioned myTracks array.

So we need to turn playlist.tracks into an array of ["id":id] dictionaries with the new track ID also in there.

First, let's ignore the new track, and map the existing tracks into an array of dictionaries:

var trackIDdicts: [[String:Int]] = playlist.tracks.map { ["id":$0.id] }

And now insert our new track ID at the front:

trackIDdicts.insert(["id":trackId], atIndex:0)

And now for myParams?

myParams["playlist"] = ["tracks":trackIDdicts]

Altogether, three simple lines of code:

var trackIDdicts: [[String:Int]] = playlist.tracks.map { ["id":$0.id] }
trackIDdicts.insert(["id":trackId], atIndex:0)
myParams["playlist"] = ["tracks":trackIDdicts]

I'd highly recommend converting your JSON/Dictionary keys into named constant variables however.

struct JSONKeys {
    static let TrackID = "id"
    static let Tracks = "tracks"
    static let Playlist = "playlist"
}

So now we have:

var trackIDdicts: [[String:Int]] = playlist.tracks.map { [JSONKeys.TrackID:$0.id] }
trackIDdicts.insert([JSONKeys.TrackID:trackId], atIndex:0)
myParams[JSONKeys.Playlist] = [JSONKeys.Tracks:trackIDdicts]


Yes, the implementation is short.  However, its efficiency is suspect.  That's due to:

Reassembling list every iteration
Testing every remaining member of list using % operator

The beauty of Eratosthenes' sieve is that it shouldn't need any division (including %).  With an array of values, we simply march along it in steps of n striking out members - that requires only addition, which is one of the cheapest operations in a digital computer.  (There's an optimisation that also requires multiplying a number by itself; that's only used because it's faster than the equivalent additions).

Removing the empty cells at every iteration prevents us from accessing every nth element in this way, as well as imposing its own overheads (for a start, we'll need lots of extra memory when building the new list from the old).


Union vs Concat

As you addmited, there is no need to use the Union extension because no two items will ever have the same value. Concat would be more appropriate because it'll better show what is going on.

Difference between the two is that

[ 1, 2 ].Union([2, 3]) = [1, 2, 3]

whereas the same with Concat would be

[ 1, 2 ].Concat([2, 3]) = [1, 2, 2, 3]

because of the not clear intention I had a hard time understanding this short code. The descriptions says something else then the implementation.

Zip

I don't know any extension that could do the same job but I think this one could be expressed cleaner by first producing the results and then zipping each result with the corresponding item that lead to this result using the Zip extension. I also think that it's nicer to use Enumerable.Repeat rather then  new []{}

return
    src
        .Select(x => elems(x))
        .Zip(src, (results, x) => results.Concat(Enumerable.Repeat(Observable.Return(x), 1)))
        .SelectMany(z => z)
        .SelectMany(x => x);

Functional

To make it even cleaner I suggest encapsulating the Concat in its own method so the final extension could be:

public static IObservable<T> MergeWithResultPropagation3<T>(this IObservable<T> values, Func<T, IEnumerable<IObservable<T>>> factory)
{
    return
        values
            .Select(x => factory(x))
            .Zip(values, AppendValue())
            .SelectMany(z => z)
            .SelectMany(x => x);

    Func<IEnumerable<IObservable<T>>, T, IEnumerable<IObservable<T>>> AppendValue()
    {
        return (results, value) => results.Concat(Enumerable.Repeat(Observable.Return(value), 1));
    }
}

yield return

Alternatively to new []{} and Concat you could make the helper work with yield return

public static IObservable<T> MergeWithResultPropagation3<T>(this IObservable<T> values, Func<T, IEnumerable<IObservable<T>>> factory)
{
    return
        values
            .Select(x => factory(x))
            .Zip(values, (results, value) => AppendValue(results, value))
            .SelectMany(z => z)
            .SelectMany(x => x);

    IEnumerable<IObservable<T>> AppendValue(IEnumerable<IObservable<T>> results, T value)
    {
        foreach (var result in results) yield return result;
        yield return Observable.Return(value);
    }
}


The list_free has a small error.
Whether the function should free the list is up to the API design. Maybe you did not want dangling pointers. Then the name should be better list_clear.

void list_free(struct list_handler *list)
{
    struct list_node *current = list->head;
    struct list_node *previous;

    while (current != NULL)
    {
        previous = current;
        current = current->next;

        //- free(current);
        free(previous); //+

        list->head = current;
        --list->count;
    }

    list->tail = NULL;
    free(list); //+
}

Freeing the data is a non-list issue, misleading, especially with a void*.

void list_free_data(void *data)
{
    //int *temp = (int*) data;
    //free(temp);
    //data = NULL;
    free(data);
}

Assigning NULL to data has no effect.

However if you want to free the list with freeing the data:

list_foreach(list, free);
list_free(list);
free(list);

The list_foreach is limited as it must work with side-effects, storing results or other context in global variables. Better provide a for-each with an additional parameter. So bad coding style is not inevitable.

For the remainder: I like APIs to provide a full set of operations, that is with a remove too.


Definitely not. You can do that all in a single query.

SELECT employeename, DATE(reattemptdate) as date, COUNT(*) as count
    FROM orders
    WHERE employeename in ('name1', 'name2', 'name3', '...')
        AND DATE(reattemptdate) > DATE(NOW() - INTERVAL 7 DAY)
    GROUP BY employeename, date

This will give you data in the form of

name1 | 2018-09-05 | 5
name1 | 2018-09-06 | 7
name1 | 2018-09-07 | 12
name1 | 2018-09-08 | 9
name1 | 2018-09-09 | 22
name2 | 2018-09-05 | 3
name2 | 2018-09-06 | 5
name2 | 2018-09-07 | 9
name2 | 2018-09-08 | 11
name2 | 2018-09-09 | 16
...

All you need is to iterate over the data.

Of course you can drop the employeename in ('name1', 'name2', 'name3', '...') condition if you want to search over ALL employees and not just "specific n" ones.


jQuery marquee, without flickering, less memory consumption, and no plugin

A few points:

$(this).html('') will throw away the contents of #div1 (on the first iteration) and #div2 (on the second iteration). If you want the marquee to loop, that's not going to work.
This is a perfect use case for a simple jQuery plugin (see the documentation).
You should probably use next() instead of the eq selector, to make your code work with any number of children (or at least any number above 1).
To stop the animations on hover, you'll have to call stop() on any elements that may be half-way into an animation. Pausing and continuing the marquee would be good use cases for plugin methods.
You could consider using the position and top attributes to position the children; this is exactly what position: absolute is for.

Given below is an example of a simple plugin that does roughly what you want. To keep in theme with this site, I've stuck with your approach -- animation is done on margin-top and, as you can see, only the first child is animated.

Because of this, the marquee won't loop until all children are outside the parent div. To make it wrap sooner, I would advise rewriting the plugin to use position: absolute and the top attribute on each child. That way, each child can be idependently animated and the marquee can be looped earlier.

Finally, keep in mind that this example is far from perfect. For example, the total height of the children is re-calculated on each run. The plugin could be made more efficient simply by maintaining state.

Plugin:

(function($) {

    var methods = {
        init: function(options) {
            this.children(':first').stop();
            this.marquee('play');
        },
        play: function() {
            var marquee = this,
                pixelsPerSecond = 100,
                firstChild = this.children(':first'),
                totalHeight = 0,
                difference,
                duration;

            // Find the total height of the children by adding each child's height:
            this.children().each(function(index, element) {
                totalHeight += $(element).innerHeight();
            });

            // The distance the divs have to travel to reach -1 * totalHeight:
            difference = totalHeight + parseInt(firstChild.css('margin-top'), 10);

            // The duration of the animation needed to get the correct speed:
            duration = (difference/pixelsPerSecond) * 1000;

            // Animate the first child's margin-top to -1 * totalHeight:
            firstChild.animate(
                { 'margin-top': -1 * totalHeight },
                duration,
                'linear',
                function() {
                    // Move the first child back down (below the container):
                    firstChild.css('margin-top', marquee.innerHeight());
                    // Restart whole process... :)
                    marquee.marquee('play');
                }
            );
        },
        pause: function() {
            this.children(':first').stop();
        }
    };

    $.fn.marquee = function(method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.marquee');
        }

    };

})(jQuery);

Usage:

var marquee = $('#mydiv');

marquee.marquee();

marquee.hover(function() {
    marquee.marquee('pause');
}, function() {
    marquee.marquee('play');
});

This example can also be found on jsfiddle: http://jsfiddle.net/PPvG/LgsrU/


This depends on a few things (keep reading).
Not necessarily. This is a question of optimization. You could fetch a vote's book by using Chapter as an intermediary (vote.getChapter().getBook()), but this would obviously require sequential trips to the database - one to get the vote, followed by one to get the chapter, and finally one to get the book. Do you plan on fetching a book for a vote frequently? If so, save some resources and stick with what you've got.
From a dependency standpoint, this seems counterintuitive, but since a chapter cannot exist without a book (can it?), I would say this is fine and simply a matter of preference. This always seems awkward to me as well, so maybe someone else can provide more info.
You can, again, this is a question of optimization and convenience. When you have questions like this, ask yourself, "will I really need this?". If the answer is no, or you're unsure, leave it out; you can always add it later if your needs change (the relations are setup correctly to do the joins, right?).
See above.
I would provide a Chapter.getVotesSum() and/or Book.getVotesSum(). These methods would include GQL queries to aggregate the appropriate rows from the votes table into a sum.

(Sorry if I'm missing something, I don't use GAE)


Set a UITableViewAccessoryType in a single UITableViewController used for two different purposes

1 You can clean switch as:

var accessoryType: UITableViewCellAccessoryType {
    if selectForFilter && liftsDictionary[UserDefaults.logFilterLiftUuid()!] != nil {
        return .checkmark
    }
    if liftsDictionary[UserDefaults.lift()] != nil {
        return .checkmark
    }
    return .none
}

2 From your code, I can assume that SelectionsRepresentable is like:

protocol SelectionsRepresentable {
    var text: String { get }
    var accessoryType: UITableViewCellAccessoryType { get }
}

Here, as name suggest, this protocol is only related to cell selection.
It has nothing to do with text.
Try to remove that variable from protocol.


Replace all occurrences with the properties of an object

You can do it in one loop instead of getting all the indexes separately. Just off the top of my head:

        string str = "Your invoice [%InvoiceNo%] will be due on [%DueDate%]";

        int startIndex = 0;

        while ((startIndex = str.IndexOf("[%", startIndex)) > -1)
        {
            int endIndex = str.IndexOf("%]", startIndex);
            string exp = str.Substring(startIndex, endIndex - startIndex + 2);
            string field = str.Substring(startIndex + 2, endIndex - startIndex - 2);
            str = str.Replace(exp, invoice.GetValueByName(field).ToString());
            startIndex = 0;
        }

Some points to note here:

I assume you are guaranteed to see the %] if you find the [%
I didn't test for edge cases like what if str = "[%invoice%]"

This is a neat solution but the more I think about your problem the more I wonder if you can engineer it so you pass what fields you want to your invoice object and it just returns you the correct string so you don't need to mess around with placeholders... food for thought :)


Concerning the comment you got about passing an ID, note that it's better to put search parameters in the URL, since it allows users to link to that search and refresh the page without having issues. All search engines do that.
Make sure to test for null without using type coercion: if(criteria.JobTypes !== null). It's a best practice that will avoid you a few surprises.
As for passing an array of values, I don't know much about ASP.NET but it looks like you can pass an array of values with Html.ActionLink. I don't know what version you're using but this seems specific to ASP.NET MVC 2.


Character creator for a role-playing game

One of the first things I would do is try and group your information into neater packages, rather than having a bunch of free variables. I assume you're not too familiar with classes, but try putting your character's attributes into a data structure like a List, or even better - a Dictionary:

attributes = {'health': 0, 'strength': 0, 'wisdom': 0, 'dexterity': 0 }

If you want to change attributes, you can then do

attributes['health'] = some_value

or to increment,

attributes['health'] += some_value

Secondly, the best way to improve your program is to make it more readable by splitting your code up into functions. For instance, the code below is an example of what it may look like if you took some of the stat changing logic out of the main program:

if choice=="1":
    stat = input("Which stat? ")
    modifier = input("By how much? ")
    add_stats(modifier, stat)
elif choice=="2":
    stat = input("Which stat? ")
    modifier = input("By how much? ")
    take_stats(modifier, stat)
elif choice=="3":
    print(show_player_stats())

In general, any where you find yourself getting "too deep" in nests of if statements and loops, or you find yourself repeating your code, try and break it out into a function. Bear in mind this is a crude example, and you'll have to develop your own solution, but in terms of readability it's a vast improvement.

I've made a start on a version of your game using my own approach, although I haven't implemented all of it (you can't subtract points for instance). However, you can probably already see where the program has improved on things.

Things to note about my version compared to yours:

There is commenting (although basic). Commenting code is a MUST, even if it's for yourself. It will help you understand your own code and help anyone else who uses it, even if it's just to show different parts of the program.
The code is broken down into functions, which improves readability and allows you to re-use bits of code in the future. For instance, every time you want to print your character's info, you just call print_character()!
The code is neater - I'm packing information into a data structure, strings are formatted with linebreaks, logic is compartmented into smaller, manageable chunks.

However, I have used some Python you may not be familiar with, like the keys() method. But it's important to go through the code and try and work out what's happening. This will help to expose you to the "Python" way of doing things.

##### GAME FUNCTIONS #####

def add_character_points():
    attribute = raw_input("\nWhich attribute? Strength, Health, Wisdom or Dexterity?\n")

    if attribute in my_character.keys():
        amount = int(raw_input("By how much?"))

        if (amount > my_character['points']) or (my_character['points'] <= 0):
            print "Not enough points!"
        else:
            my_character[attribute] += amount
            my_character['points'] -= amount
    else:
        print "\nThat attribute doesn't exist!\n"

def print_character():
    for attribute in my_character.keys():
        print attribute, " : ", my_character[attribute]

##### MAIN FUNCTION #####

my_character = {'name': '', 'strength': 0, 'health': 0, 'wisdom': 0, 'dexterity': 0, 'points': 20}
running = True

print "Create a character! You have points to assign to strength, health, wisdom, and dexterity."

my_character['name'] = raw_input("What is your character's name? ")

while running:
    print "\nYou have ", my_character['points'], " points left.\n"
    print "1. Add points\n2. Remove points\n3. See current attributes\n4. Exit\n"

    choice = raw_input("Choice:")

    if choice == "1":
        add_character_points()
    elif choice == "3":
        print_character()
    elif choice == "4":
        running = False
    else:
        pass


Standard naming convention in C is usually lower_case_with_underscore.
You should be using void * rather than char *
I would consider making the return value deterministic when the new size is 0 by always returning NULL rather than the implementation defined behaviour (which could technically be a pointer which is not NULL but still not allowed to be dereferenced). free guarantees by spec that free(NULL) is legal.


Two error-reporting conventions for a command-parser

Given the additional context, I don't think exceptions are warranted here.

Exceptions are most useful when the code that generates an error condition is far away from the code that handles that error condition.

In this code, the error condition is handled immediately after it's generated.

So I'd prefer the bool-returning version rather than throw/catch.


HTML/JavaScript temperature converter with rounding

Keep it simple
Your code is overly complex as you are doing too many conversions C <=> F, C <=> Ra, and Ra <=> F can all be avoided.
When doing any type of unit conversion select a base unit and then only convert between the base unit and other units.
By using a base unit you can do all the conversions with only 6 formulas, rather than the 12 you are currently using.
General review
HTML
It is important for the content of a web page to have machine readable information that is unambiguous and semantically meaningful. Many people need assistance to interact with web pages, if the machine can not understand the content these people can not use the page.
Also bots (such as search engines use to rank pages) can not accurately assess a page's content if it does not understand what the page contains.
I am not HTML expert so these are just the basic points. See rewrite for more info

Use appropriate elements

Use the Labels to label inputs
The different units temperatures are a list, use an unordered list to hold the inputs and labels.

Related data
Do NOT! use id to store semantic information. That does not mean you should not use meaningful id names, rather you should add the semantic information using more appropriate attributes and or elements.
For example you use the event.target.id to determine which unit is being changed. Rather than use the id store the input elements unit type as a dataset attribute. See rewrite

JavaScript

window
Your use of window is redundant as window is the global this (scope).
window.oninput = function(event) { is identical to  oninput = function(event) {

Add listeners don`t set listeners
You should avoid assigning event listeners directly as they can be overwritten, by you accidentally, or by 3rd party content. E.G. adverts.
Use addEventListener as it adds listeners
E.G. oninput = function(event) { /*... code ... */ } should be addEventListener("input", function(event) { /*... code ... */ });
NOTE: The event name when using addEventListener does not include the on prefix. "oninput" becomes "input"

Constants
For variables that do not change declare them as constants. eg const campo = event.target.id;

Indentation
Watch your indentation, the four lines below var i = document.ge... are incorrectly indented.

Use standard keyboard characters
The use of º via the keyboard dance LEFT ALT 167 is unnecessary as it adds nothing to the quality or readability of the code.

Magic Numbers
Numbers seldom have meaning on there own. They are also easy to get wrong it you have a lot of them. Give numbers names by defining them as constants.
1.8 could mean anything... so remove the guess work with const RANKINE_SCALE = 1.8

Problem
Inputs can get stuck because the input step and min values are not set or incorrect
Changing the number of decimal points means you must change the step value for each input. E.G. Decimal 0 step 1, Decimal 1 step 0.1, 2 step 0.01, and so on.
To control the step position you can not set the min attribute to be a value that is not divisible by step.  For all by Kelvin and Rankine the min value is problematic.
But using Kelvin as a the base unit we need only define its min attribute and in JS make sure its >= 0 so that the other units don't go out of bounds.
Rewrite
The rewrite add some CSS, a lot of HTML and splits the JS into many parts.

Only the Kelvin input value is defined with a min and step and value. The other values are set when the JavaScript first runs by calling decimalEvent

Each temperature input uses data-unit="" to name the unit used. This name is used to lookup the correct conversion function in the object toKelvin.

Temperature and decimal input events are split. The decimal listener will call the Temperature listener which will use the default target kelvin if called without an event

const F_SCALE = 1.8, F_OFFSET = 459.67;
const C_OFFSET = 273.15;
const toKelvin = {
    Celsius:   t => t + C_OFFSET,
    Farenheit: t => (t + F_OFFSET) / F_SCALE,
    Rankine:   t => t / F_SCALE,
    Kelvin:    t => t,
};
const fromKelvin = {
    Celsius:   k => celsiusIn.value =   round(k - C_OFFSET),
    Farenheit: k => farenheitIn.value = round(k * F_SCALE - F_OFFSET),
    Rankine:   k => rankineIn.value =   round(k * F_SCALE),
    Kelvin:    k => kelvinIn.value =    round(k),
};
const round = val => Math.round(val * round.scale) / round.scale;

decimalIn.addEventListener("input", decimalEvent);
temperatureList.addEventListener("input", temperatureEvent);
decimalEvent();

function decimalEvent() {
    const step = 1 / (round.scale = 10 ** decimalIn.value);
    celsiusIn.step = step;
    kelvinIn.step = step;
    farenheitIn.step = step;
    rankineIn.step = step;
    temperatureEvent();
}
function temperatureEvent({target = kelvinIn} = {}) {
    if (target.value !== "") {
        const unit = target.dataset.units;
        const kelvin = Math.max(0, toKelvin[unit](round(Number(target.value))));
        for (const convert of Object.values(fromKelvin)) { convert(kelvin) }
    }
}
label {
    font-size: large;
}
input {
    width: 3em;
}
ul {
    width: 220px;
    display: flex;
    flex-direction: column;
    list-style-type: none;
    padding-inline-start: 0px;
}
li input {
    float: right;
    width: 7em;
}

Temperature unit converter

 <input type="number" min="0" max="5" value="0" step="1" id="decimalIn">
Decimals

    Celsius (ºC)
    <input id="celsiusIn" type="number"  data-units ="Celsius">

    Kelvin (K)
    <input id="kelvinIn" type="number" min="0" value="293" step="1" data-units="Kelvin">

    Farenheit (ºF)
    <input id="farenheitIn" type="number" data-units="Farenheit">

    Rankine (ºRa)
    <input id="rankineIn" type="number"  data-units="Rankine">

Update
The original rewrite had a few problems.

Could not type negative values in some situations
Was converting digits past the decimal count
Was displaying trailing zeros. Eg 0.000 should be just 0

The code has been changed to ignore partial inputs. E.G. the negative sign '-' before the numbers are added.
Using Math.round rather than Number.toFixed to set the number of decimal places.
Round the decimals before converting to base unit (kelvin) to stop fractions past the number of decimal making changes to other units.


The slowness comes from the sort algorithm you've chosen. It's \$O(N^2)\$ and you can do better by using a faster sort algorithm,
such as merge sort or quicksort.
Once you do that, the solution will pass with flying colors.

You could simplify the loop that checks the maximum difference by initializing unfairness to the diff of the first interval:

int unfairness = list[set] - list[0];

And then start the loop from 1, and simplify:

for (int x = 1; x < N - set; x++) {
    int diff = list[x + set] - list[x];
    if (diff < unfairness) {
        unfairness = diff;
    }
}

Also, it would be good to put this code in a separate function.
It's good to have many short functions that do one thing,
than one long function that does many things.

Instead of initializing i at the top of the function,
it would be better to do that inside the for-loop where you use it,
just like you did for other loops.

I recommend to avoid using l as a variable name,
because on some displays and fonts it's too hard to distinguish from 1 or I.


I completely agree with you that such tasks is a good opportunity to learn new concepts and the language itself. And, as you asked, I have a few comments on your code

Do not call variables by reserved names

I mean, I was sweating to understand what is going on here the first time

Action = Convert.ToString(userInput[i]);

Better to call such variable as

private static string OperationString { get; set; }

Split complex task on simpler ones - one logic per function

Your function ParseInput is doing not just parsing, but also reading from standard input. So split this task - ParseInput will just do parsing.

private static double ParseInput(string inputString)

Using the == operator to compare floating-point numbers is, generally, a bad idea

So instead of

if (Action.Equals("/") && Item2 == 0)

better to use this

if (Action.Equals("/") && Math.Abs(Item2) < Double.Epsilon)

Be aware of the difference between || and | logic operations

And without a need, do no mix up this two operators. So use

if ( userInput[i].Equals('+') || userInput[i].Equals('-') || userInput[i].Equals('*') || userInput[i].Equals('/'))

instead of

if ( userInput[i].Equals('+') || userInput[i].Equals('-') || userInput[i].Equals('*') | userInput[i].Equals('/'))

Better to avoid static not-readonly field

I don't see any actual reason for you to keep variables Item1, Item2 and OperationString as private static fields - make them as local variables. In general, based on my experience, many nasty bugs (especially in multi-thread applications) happen because of an inappropriate usage of static fields. I know, this problem is far away from this simple calculator application, but anyway.

Good regular expression would solve many problems, including

code will become simpler and cleaner, so easy to debug and read
easier to solve your "serious flaw" - input validation

I would suggest to use Regular Expressions instead of buggy for-if construction.

// \d+\.? supports xxx. and xxx
// \.\d+ - .xxx
// \d+\.\d+ - xxx.xxx
Regex InputRegex = new Regex(@"^\s*([-+]?)(\d+\.?|\.\d+|\d+\.\d+)(.)(\d+\.?|\.\d+|\d+\.\d+)\s*$");

// match.Groups[0] whole pattern
// match.Groups[1] sign of the first value
// match.Groups[2] first value (without sign)
// match.Groups[3] operation
// match.Groups[4] second value
Match match = InputRegex.Match(userInput);

if (!match.Success)
{
    // we didn't find a match
}
double item1 = match.Groups[1].Value == "-" ? -Double.Parse(match.Groups[2].Value) : Double.Parse(match.Groups[2].Value);
string actionString = match.Groups[3].Value;
double item2 = double.Parse(match.Groups[4].Value);

Let user know that calculation was successful or not

Let's check which error can happen in your code:

RegexNotSuccess Regular expression doesn't find a match
DivisionByZero Second item is 0, so we have the division by zero
NoSuchOperation User specified not [+-*/] operation

I would suggest to create enumerated list of those errors, return one enum element as output of your function.

public enum ErrorCode
{
    Success,
    NoSuchOperation,
    DivisionByZero,
    RegexNotSuccess
}

public static ErrorCode ParseInput(string userInput, out double result)
{
    //...
    if (!match.Success)
    {
        result = Double.MinValue;
        return ErrorCode.RegexNotSuccess;
    }
    //...
    switch (actionString)
    {
        //...
        case "/":
            if (Math.Abs(item2) < Double.Epsilon)
            {
                result = Double.MinValue;
                return ErrorCode.DivisionByZero;
            }
        //...
        default:
            result = Double.MinValue;
            return ErrorCode.NoSuchOperation;
    }
    result = handler(item1, item2);
    return ErrorCode.Success;
}

The final code looks like this

Program.cs

using System;

namespace CalculatorTest
{
    class Program
    {
        private static void Main()
        {
            while (true)
            {
                Console.WriteLine("Enter a mathematical expression, please");
                string userInput = Console.ReadLine();
                Calculator.ErrorCode stdout = Calculator.ParseTwoNumberOperation(userInput, out double result);
                if (stdout == Calculator.ErrorCode.Success)
                {
                    Console.WriteLine(result);
                }
                else
                {
                    Console.Error.WriteLine("Error: " + stdout + "\t" + userInput);
                }
            }
        }
    }
}

Calculator.cs

using System;
using System.Text.RegularExpressions;

namespace CalculatorTest
{
    public static class Calculator
    {
        public enum ErrorCode
        {
            Success,
            NoSuchOperation,
            DivisionByZero,
            RegexNotSuccess
        }

        private delegate double Handler(double a, double b);
        /// <summary>
        /// \d+\.? supports xxx. and xxx
        /// \.\d+ - .xxx
        /// \d+\.\d+ - xxx.xxx
        /// </summary>
        private static readonly Regex InputRegex = new Regex(@"^\s*([-+]?)(\d+\.?|\.\d+|\d+\.\d+)(.)(\d+\.?|\.\d+|\d+\.\d+)\s*$");
        public static ErrorCode ParseTwoNumberOperation(string userInput, out double result)
        {
            Handler handler;
            // match.Groups[0] whole pattern
            // match.Groups[1] sign of the first value
            // match.Groups[2] first value (without sign)
            // match.Groups[3] operation
            // match.Groups[4] second value
            Match match = InputRegex.Match(userInput);
            if (!match.Success)
            {
                result = Double.MinValue;
                return ErrorCode.RegexNotSuccess;
            }
            double item1 = match.Groups[1].Value == "-" ? -Double.Parse(match.Groups[2].Value) : Double.Parse(match.Groups[2].Value);
            string actionString = match.Groups[3].Value;
            double item2 = double.Parse(match.Groups[4].Value);
            switch (actionString)
            {
                case "+":
                    handler = GetSum;
                    break;

                case "-":
                    handler = GetDif;
                    break;

                case "*":
                    handler = GetMul;
                    break;

                case "/":
                    if (Math.Abs(item2) < Double.Epsilon)
                    {
                        result = Double.MinValue;
                        return ErrorCode.DivisionByZero;
                    }
                    handler = GetDiv;
                    break;

                default:
                    result = Double.MinValue;
                    return ErrorCode.NoSuchOperation;
            }

            result = handler(item1, item2);
            return ErrorCode.Success;
        }

        private static double GetSum(double a, double b) => a + b;
        private static double GetDif(double a, double b) => a - b;
        private static double GetMul(double a, double b) => a * b;
        private static double GetDiv(double a, double b) => a / b;
    }
}


Namespacing jQuery/jQueryUi into markup that I don't control

I've worked for a media company where ads had to run with their own version of JavaScript libraries, in the end we preferred to let ads run in their own iframe. Especially since some ads required access to document.write which creates havoc to your content ;)

It is a bit scary that your solution has to modify jquery-ui.js, I would be very (very) hesitant to do that. I also dont understand why you employ })(myJQuery, myJQuery); there, since you know you only need 1 of the parameters to initialize jQuery UI.

The worst part is that I played around a bit with a fork and I could not get to a superior solution easily, so if this works for you, then perhaps you should stop researching and just go forth ;)


The way constructors work is that the engine creates an object, and calls the constructor passing the object as context. Essentially, the constructor is being run like a function.

console.log('indeed'); runs because you created an instance of Widget, which calls the constructor and runs your iife. The following code alone works in the same way.

document.addEventListener("click", function(e) {
  var widgets = new Widgets();
});

function Widgets(){
  console.log('indeed');
}

Now your code creates a Widgets instance regardless of the presence of data-widget. If you only deal business when it has data-widget, I suggest you create the instance within the if block.

I'm not sure what your goal with widgets[w] is, but if you mean storing w's value as a property of an instance of Widgets, I it's best if you define the object's properties in the constructor in advance. While this sacrifices dynamicity, it eliminates guesswork as to what properties an instance of Widgets contain.

Additionally, delegating all the way up to document is slow. That's one reason jQuery deprecated live and provided you on instead. live bound all handlers to document, while on gives you flexibility to where you want the delegate target bound.


Cracking the code interview: Problem 1 .6 basic string compression

A call to strlen(compress) is unnecessary. You already know the length of the compressed string; it is j.
You may (in fact, you should) terminate the loop as soon as j reaches the length of the original. Once it happened, the compressed string will for sure be longer than original.
nc + '0' assumes that nc is a single digit. The problem statement doesn't say anything about that.
The size of buffer[20] is pretty arbitrary. Since the function provides guarantees about the size of the compressed string, consider allocating strlen(original) bytes for compressed.


Eliminate for loops where you can

You can probably be more aggressive with list comprehensions. I would replace your for programme in all_programmes with a list comprehension that calculated the date and created a list of indices to delete (but I suspect many others would vehemently disagree with this advice):

enumerated_programmes = enumerate(all_programmes)
to_keep = [i for i,p in enumerated_programmes if datetime.datetime.strptime(p.get('start'), DATETIME_FORMAT) < svn_wks]
...
all_programmes = [all_programmes[i] for i in to_keep]

You can make a second list of indices that should be replaced with a newer record, using similar logic.

Naming

Why not use old_programmes as a name instead of all_programmes to make the binary nature of the code clear?

Confusing code

Why is there a return statement at the bottom of your code? I didn't see any def statements so it's not clear what/why you're returning/

Use available Python functions

There is no need to combine append with a for loop. Instead you can extend one list with another. Say you have list a and list a. Use a.extend(b) rather than appending each element of b. The code will be clearer, shorter, and more efficient.
Similar to my advice above about using list comprehensions more aggressively, you could also using filter rather than if, else statements. This would take more logic out of your for loops, which is always a good thing.

DRY

You compute svn_weeks in each iteration of each of your for loopsbut it's a constant for whatever day you are running it. You should compute it once, before either of your for loops.


Right, a short and simple answer to each of your questions, for now. I'll be expanding on each of the issues through updates:

Is it efficient
Define efficient. If by that, you mean: is it fast, then yes, it probably is. Not as fast as non OO code, but faster than most form builders out there.
If by efficient, however you mean: portable, easy to use (as in clear API), robust and flexible then no. It's not. You can't handle nested forms, validators and to use this code, you need to know what type of array this class expects. Programming by array is not the way to go.

Are there flaws?
Yes, there are, apart from those mentioned above, some other omissions/flaws:

buildField is public, but contrary to what I'd assume, it is incapable of adding fields to the form. The buildForm is a one-shot deal: it returns an HTML string, that is, to all intents and purposes, static.
Stringing together markup is tedious, horrible to debug, and equally pointless to test. If things do go worng, it'll probably result in malformed markup, and the source of the problem will be hard to track.
Forms and ajax are used very often. Ajax implies JS, which in turn implies using meaningful selectors: I can't set ID's here, though. That's an issue!

More to come, because there are a lot of things that need addressing, outside of these primary issues.

Good use of concepts?
IMHO, no. A class should have only 1 job, and yours does. It has only 1 job: to generate a string. But HTML is not just any string: there's grammar and rules involved. It's part of a DOM. PHP ships with the DOMDocument class (and all of its derivatives. That class ensures the markup is valid. You can also add elements to an existing dom, assign and remove attributes, ... the works. Use helper classes. Generating markup is done using objects, too.

Are there any security issues?
Yes, quite a few. If I pass '"><script>location.href=\'spam-site-url\';</script>' as the value for the form name, then the resulting markup will be:

<form method="post" name=""><script>location.url='spam-site-url';</script>

XSS attacks, through any of the fields is easily done

Coding style

Looks alright, apart from the closing ?> tag. According to the official docs, it is optional and even discouraged in PHP-only scripts. But when it comes to coding style/conventions, why not see for yourself if you adhere to them: the coding standards are open to anyone, read through them, and apply them to your code.

Suggestion
If you don't want to use one of the many forbuilders that have been written before, then that's your right. But that doesn't mean you should close your eyes to what they have to offer, and how they do what they do. Check out the Symfony2 form component, or the Formbuilder of Zend, or any of the other frameworks. See how they do things, "borrow" the ideas you like, add your own, and if you find the time: try giving back to the respective communities by contributing...

Update

Is it efficient

Seeing as you're writing object, I'm going to interpret efficiency in an OO context: efficient code abstracts the nitty gritty, while allowing the user to customize almost every aspect through a clean, and concistent API, all the time being reasonable certain that the end-result will be valid, usable markup.

To acchieve all this, you can't just string together markup like you are doing now. OO is about hierarchy, dependency and inheritance.
Think of a form, what defines it behaviour (ie is inherent to the form), and what does it contain (most likely optional).

A form is an element, that uses attributes to define its behaviour. A form element consists of zero or more child elements (inputs, selects, buttons, textarea's, but also fieldsets, labels, etc...). All of these child elements belong to the form, but have their own behaviours (attributes). Some elements, like select, or fieldset can, and often will consist of more than one child element.
Adding these children, or setting their attributes is something that one might do as you go along (ie fetching select options from the db, adding options after constructing the base form). This means that addField has to be matched with a getField method, to get a reference to an existing form element, so the user can alter it.

It is also likely to happen that, for whatever reason, the user wants to pre-set some values, just as it is likely for the user to add form validation, and a method to validate the form, sanitize the submitted data and extract it, either as an array or an object.
All the while, the form should be mutable: it has to be possible to add and remove elements on the fly. That's a lot of work, so I'm not going to write a fully fledged example of how to implement this. Instead, here's how I'd start:

Write 2 distinct classes: FormElement and FormBuilder. The latter takes instances of FormElement, and adds them to its internal FormElement that represents the actual <form> tag.
the FormElement class needn't be used by the user, provided the FormBuilder has some methods like addElement, getElement, removeElement, and so on
the FormBuilder could then be altered, to use FormValidator elements, attached to each of its elements. Once you do this, the form should also implement getFormData and setAll methods, to process and pre-set the form elements.
By this time, you ought to realize that you no longer have a formBuilder class. Instead, you are building a form module. Which opens up the possibility of adding model mapping, form events, plugins, helpers and all that...

Now, notice that I said that a <form> tag is a FormElement, but that it's contained within the FormBuilder. That is because, unlike otehr FormElements, the form needs another abstraction layer. It's a DOM element that contains all of the input fields within the form. It stands to reason, then, that this will be the FormElement that the user will want to use for form validation, and extracting data. This, too, requires a consistent and tidy API, if you want a form module worth using. I therefore suggest to create a third class: class Form extends FormElement, where all of the bulk form interactions live.

Adding FormElements should be as simple as this:

$element = $builder->addElement(
    FormBuilder::ELEMENT_TEXT,//type
    array(
        'id'    => 'txtId',
        'name'  => 'txtName',
        'value' => ''
    )
);//creates DOMNode, adds it to form, and returns a reference to the newly created node
$element->getAttribute('value')->value ='new value value';//or nodeValue

As you can see, I can alter nodes I've added to the form, but it looks kind of faffy and messy. That's why I suggest you wrap the DOMNodes that make up your form in a generic FormElement class, and give it methods like setValue:

public function setValue($val)
{
    //$this->node === the raw DOMNode instance
    $attr = $this->node->getAttribute('value');
    if ($attr === null)//no value attribute yet, create it
        $attr = new DOMAttr('value', $val);
    else//set new value
        $attr->value = $val;
    $this->node->setAttributeNode($attr);
    return $this->node;
}

This is just a crude example, but you get the idea

Update 2:

Are there flaws

Well, I've stated there are quite a few of them already, so I'll just suggest an approach that, IMO, will help you to build a more robust and reliable module. Beginning with something I hinted at in my previous update:

I suggested adding a form element could be done using something along the lines of:

$builder->addField(FormBuilder::ELEMENT_TEXT, $attributesArray);

Let's look into the arguments, first, then how to sanitize and validate them, and finally, how to process them.

the arguments

The first argument is a class constant. For each form element you want to support (select, textarea, radio's, checkboxes, ...) you'll have to create a constant. This makes the user code a lot easier to read/understand. Anyone can see that the snipped above adds a text input to a form, with an array of attributes. Change the first argument to FormBuilder::ELEMENT_TEXTAREA obviously adds a textarea element and so on.
The second array is an (optional) array of attributes. Your method's signature,then, should use type-hinting to ensure that an array is passed. You could create an Attributes class, but in this case, I feel an array will do. The only thing the user must ensure is that the array is associative, because the keys are the attribute names, and the values will be the attribute's value...

Sanitation/validation

How to validate the first argument is up to you, either define each constant to be an int, that is a power of 2: 1, 2, 4, 8, 16, 32, 64, 128, and so on, and use bitwise operators to check if the argument is an int and a power of two, or use a private array where and fill it with all of the constants, and use isset to check if the value passed is a valid constant. I'd opt for the second option, simply because you can then assign a string to each content that you can use to create the node, and use this array to define a couple of basic, but essential attributes for each tag (ie: hidden and text elements will both be input tags, but have a different type-attribute).

The second argument is ensured to be an array (thanks to type-hint). Next step, although this might not be an issue at first, is to map the array, and invoke strip_tags on each value, since attributes shouldn't contain markup.
Also validate the keys of the array, matching them against an array of valid attributes. By this I mean: style and onclick are, in HTML-land, valid attributes, but these kind of attributes should be discouraged. Any decent front-end developer will be more than able to bind event handlers to the form elements without the need to set an onclick attribtue. He'll also be more than capable to churn out CSS that presents the form in any way you like. That's the job of a front-end developer.
Think of it like this: you're creating a FormBuilder, not a FormDesigner, just like you'd expect a builder to build your house, but you have to ask a decorator or interior architect to design what it looks like.

Processing

Well, since I've already stated you should wrap the form element in a Form instance, the same applies to the form elements: they should be instances of the DOMElement class, wrapped in a FormElement instance. Pass those instances on to the form, and let the form instance handle the rest (adding, wrapping in containers etc...).
If anywhere along the line, an invalid argument is passed, or a bad attribute (like style) is being set: don't ignore it, don't try to make sense of things: the code that called your class might have a bug in it, and it should be fixed: Throw an exception to notify the user something is seriously wrong.

To round up, here's a short example of what the FormBuilder class could look like:

class FormBuilder
{
    const ELEMENT_HIDDEN = 'input';
    const ELEMENT_TEXT = 'input';
    const ELEMENT_TEXTAREA = 'textarea';

    /**
     * @var array
     */
    private $constants = array(
        self::ELEMENT_HIDDEN   => array('type' => 'hidden'),
        self::ELEMENT_TEXT     => array('type' => 'text'),
        self::ELEMENT_TEXTAREA => array()
    );

    /**
     * see setAttributes method for usage example
     * @var array
     */
    private $bannedAttributes = array(
        'type'    => 'type is set by FormBuilder',
        'style'   => 'Front-end is not the job of a builder',
        'onclick' => 'Learn JS'//add other on* attributes
    );

    /**
     * @var Form
     */
    private $form = null;//the actual form we're building

    /**
     * Optionally make this final, this constructor creates the form
     * @param array $options = null
     */
    public function __construct(array $options = null)
    {//allow for user to pass specifics, like form attributes
        $formNode = new DOMElement('form');
        if ($options && isset($options['attributes']))
        {
            $formNode = $this->setAttributes(
                $formNode,
                $options['attributes']
            );
        }
        $this->form = new Form($formNode);//create Form wrapper...
    }

    /**
     * Add field to form, after setting optional attributes
     * @param string $type
     * @param array $attribtues = array()
     * @return FormElement
     * @throws InvalidArgumentException
     */
    public function addField($type, array $attribtues = array())
    {
        if (!isset($this->constants[$type]))
        {//optionally allow for direct DOMElement injection here, but I wouldn't
            throw new InvalidArgumentException(
                sprintf(
                    '%s is not a valid type (use %s::ELEMENT_* constants)',
                    $type,
                    __CLASS__
                )
            );
        }
        foreach ($this->constants[$type] as $name => $val)
            $attributes[$name] = $val;//re-assign default attributes, like type
        $node = $this->setAttributes(
            new DOMElement($type),
            $attributes
        );
        $node = new FormElement($node);//set in wrapper
        $this->form->addElement($node);
        return $node;
    }

    /**
     * Set attributes for node
     * @param DOMElement $node
     * @param array $attributes
     * @return DOMElement
     * @throws InvalidArgumentException
     */
    protected function setAttributes(DOMElement $node, array $attributes)
    {
        foreach ($attributes as $name => $val)
        {
            if (isset($this->bannedAttributes[$name]))
            {//symfony2 style exception throwing...
                throw new InvalidArgumentException(
                    sprintf(
                        '%s attribute not allowed: %s',
                        $name,
                        $this->bannedAttributes[$name]
                    )
                );
            }
            //strip_tags to make sure
            $attr = new DOMAttr($name, strip_tags($val));
            $node->setAttributeNode($attr);
        }
        return $node;
    }
}

This really ought to give you some idea as to how to set about building a form module. But this also shows how complex things are about to become. One special attribute you will want to add is the label attribute. This shouldn't be set on the element itself, but rather create a secondary DOMElement with a for attribute. But no matter, we have bigger fish to fry: At the moment, we can't, for example, add fieldsets yet, nor can we remove elements, or determine in which order the elements will be rendered. Look into how other frameworks handle this (often, they wrap elements in divs, and have the Form instance track those, which makes the removeChild calls a lot easier).
I'm not going to do that for you (I'm reviewing code, not writing it), so I say again: look at what is already out there, and let that code inspire you!

Coding style

The code above follows the PHP-FIG standards quite closely (with the exception of Allman-style indentation). I've adopted the Symfony2 way of throwing exceptions, too, because I find it helpful in forcing me to throw exceptions with meaningful messages, and the sprintf reminds me to put some variables in there, so I can see what value was being passed when the exception was thrown.
It's a matter of personal preference, perhaps, but the rest of it (all caps for constants, doc-blocks, camelCased method names and type-hinding) is all conform the standard.


Find the letter 'z' within three characters after an 'a'

Riffing on @Shepmaster's excellent answer:

def nearby_az(string)
  !!string.match(/a.{,2}z/)
end

['baz', 'abz', 'abcz'].each do |s|
  puts "nearby_az('#{s}') expect true: #{nearby_az(s)}"
end
['a', 'z', 'za'].each do |s|
  puts "nearby_az('#{s}') expect false: #{nearby_az(s)}"
end


Your implementation, to me at least, doesn't seem correct. You need to remove adjacent duplicates, but looking at your last example, the sequence acaaabbacdddd completely removes the b and d characters from the slice. You're also using an awful lot of code to do a simple thing. What I'd do is quite simply this:

Iterate over the slice from index 0 to the next to last character
For each character, iterate over the remainder of the slice (nested loop) until you find a character that doesn't equal the current index
For each character at the current position + 1 that matches the current one, remove it, as it's an adjacent duplicate.

The code itself is quite simple:

func dedup(s []string) []string {
    // iterate over all characters in slice except the last one
    for i := 0; i < len(s)-1;i++ {
        // iterate over all the remaining characeters
        for j := i+1; j < len(s); j++ {
            if s[i] != s[j] {
                break // this wasn't a duplicate, move on to the next char
            }
            // we found a duplicate!
            s = append(s[:i], s[j:]...)
        }
    }
    return s
}

Given an input like [g e e k s f o r g e e g], the output of this is [g e k s f o r g e g]

Demo

The only trickery here is this line: s = append(s[:i], s[j:]...). What this effectively does is reassign the slice s to contain i values starting at 0 (so if i is 2, the slice will be [g, e]). The second part is creating a slice starting at j, until the end of s. Again, if j is 2, this slice will be all values starting at offset 2 until the end ([e k s f o r g e e g]).

So let's look at an actual example:

i == 1
j == i+1 (2)
s[i] == e, s[j] ==e`

We have a duplicate, so we'll reassign s like so:

 s = append(s[:1], s[2:]...)`

This means we're appending [e k s f o r g e e g] to [g], removing the duplicate e. Job done.

Note:

I've used []string here, but it should go without saying that a slice of characters is probably best represented as either []byte or []rune (for full UTF-8 support). Regardless of the type you end up using, the code above will work with with any type that can be compared with the == operator