You could also use a map, associative array, or dictionary to implement a heap (like the following):

class Heap(dict):

    "Heap() -> Heap instance"

    def retrieve(self, address):
        "Get the virtual value stored at the address."
        return self.get(address, 0)

    def store(self, value, address):
        "Set the virtual value meant for the address."
        if value:
            self[address] = value
        else:
            self.pop(address, None)


Here are a few things:

good you're using ` (template literals) to format your HTML inside the JavaScript code
don't use innerHTML += as it forces the browser to re-render the DOM when called. Read more here: Why is Element.innerHTML += bad code?. Instead create an HTML element with .createElement and append it to an existing DOM element .appendChild.

So instead of appending the the HTML string
...
 to the parent div you can:

create a wrapping div element:

const div = document.createElement('div');

append the HTML string to the div wrapper (remember div is an object of type Element but it's not already rendered in the page DOM). You can use all of Element's methods on it, including .innerHTML:

div.innerHTML = `

    ...

`;

then append the wrapper's first child to the parent element:

divParent.appendChild(div);

you can use .querySelectorAll instead of .getELementByClassName. The former allows you to pass in an actual CSS selector instead of a className (the latter method). In your case you only want the first matching element, so use .querySelector instead.
I always use single quotes ' for JavaScript strings and double quotes " when I need quotes inside the strings e.g. with HTML attributes. That's personal preference though.
no need to define the variable docData as doc.data() is already pretty self-explanatory
you can use arrow functions outside also (arg1, arg2, ...) => {} or if you have a single argument arg => {} (no need for the parenthesis).
you could use const for constant variable to make sure they don't get their values changed: for instance itemsDiv (fyi: renamed to itemsParent for clarity) can be defined with const instead of var.

Here's a possible refactoring of your code:

const itemsParent = document.querySelector('.items')[0];
let items = [];

const renderItems = items => {

  items.forEach(item => {

    const div = document.createElement('div');

    div.innerHTML = `

        ${item.name}
        ${item.condition}
        ${item.price}

    `.trim();

    itemsParent.appendChild(div.firstChild);

  });
}

db.collection('items').get().then((querySnapshot) => {

  querySnapshot.forEach(doc => {
    items.push(doc.data());
  });

  renderItems(items);

});

Edit: testing div creation, it appears you need to trim the string first:

const div = document.createElement('div');
div.innerHTML = `

`.trim();

console.log(div.outerHTML)
console.log(div.firstChild.outerHTML)


One way to simplify this would be to create a collection with collect() and then call getName() on each route using Collection::map(). Then use collection::filter() to filter out the routes that don't start with rt_ using the string helper method Str::startsWith()
class RouteController extends Controller {
    public function getRoutes()
    {
        // call getName on each route and then get unique values
        $uniqueRoutes = collect(Route::getRoutes())
            ->map(fn($route) => $route->getName())
            ->unique();

        //filter out any routes not starting with rt_
        $filteredRoutes = $uniqueRoutes->filter(function($name) {
             return Str::startsWith($name, 'rt_');
        });
        return response()->json($filteredRoutes, 200);

    }
}

Note - the uses the PHP 7.4 arrow function syntax could be used to simplify the callback to the filter() method
One could also use collection::reduce() to only add routes to the list that contain the desired prefix.

The existing code contains this block:

          //Filering duplicates
           foreach ($array as $item) {
               if ($item == $route->getName()) {
                   $found = TRUE;
               }
           }

That could be simplified using the PHP function in_array().

Another suggestion is to always use strict equality comparisons (i.e. === and !==) when possible - e.g. when $found should either be true or false then compare without the possibility of type conversion (i.e. with ==).


Fetching AJAX results from three endpoints, with error handling

I would suggest passing in an array of endpoints so you can have one loop that calls an endpoint and looks at the result without repeating any code:

function checkForData(endPoints) {
    let i = 0;

    function next() {
        if (i < endPoints.length) {
            return myAjaxFunction(endPoints[i++]).then(function(data) {
                if (data && data.d && data.d.results && data.d.results.length > 0) {
                    return data.d.results;
                } else {
                    return next();
                }
            });
        } else {
            return null;
        }
    }

    return Promise.resolve().then(next);
}

checkForData([endPoint1, endPoint2, endPoint3]).then(function(result) {
    // result here
    if (result) {
        console.log(result);
    } else {
        console.log("no data found");
    }
}).catch(function(err) {
    // error here
});

Note: I also put .then() on the same line as its parent function to avoid an extra level of indent.


A fast approach to prime number sieving (non-threaded array)

Just some minor comments to the code style. Let's start with your fileheader...in these times and days it should be unnecessary. First it doesn't make sense to have the file/classname in the comment, it's only something that will get out of date because refactoring can't reach it. Second, the other parts should be in the JavaDoc of the class.

Variable names. I know it is hard to find good names for such...mathematical stuff, but try to find them. 'a', 'b', 'z' are meaningless. It is hard to read the code if variables have meaningless names.

The code formatting is partly a bloody mess. If you use an IDE, make use of these formatting features. It is so much easier to read code if it is well formatted.

First, don't omit braces, even if it is just a one line 'if' or 'for' block. Second, be consistent about your brace style, and be consequent.

System.out.print(i + " ");

I still don't understand why the Java compiler does allow this. This is not a "cast", this is a hack in the best of cases.

System.out.print(Integer.toString(i) + " ");


Concatenate disjoint Excel ranges to use as a single range in a formula

To answer your question, no. There is no "idiomatic" way to combine multiple arrays together without creating a bigger array (or extending one of the originals) and manually copying in the array contents.

Anyway, while I'm here,

Miscellaneous Points

I don't know if you just left it out, but if it's not there, Option Explicit should be at the top of every single code module everywhere. IF you don't have it enabled, go to Tools --> Options --> Require Variable Declaration.

Your function is implicitly public because you didn't scope it. Explicitly scope everything. Assuming you want to use it in other modules, it should be Public Function VERTCAT() as Variant.

Integer is outdated. Unless you're in a position where 4 bytes of memory has serious performance impacts, use Long instead. Integer will fail if you give it a number greater than about 33,000, that's a number that could reasonably occur when dealing with big spreadsheets. Long will handle numbers up to 2.1 Billion and is also (marginally) faster.

Variable Naming

First off, VERTCAT violates several good practices.

Standard VBA convention for function/procedure names is PascalCase. VERTCAT is also distinctly unclear and ambiguous. Names should always be clear, concicse and most importantly, unambiguous.

If I see VERTCAT I'm going to think "What does this do? Vertically... catenate?". Okay, but catenate what? Strings? Lists? Ranges? Arrays? VerticallyConcatenateRanges really isn't very long, and is absolutely clear on what it takes as parameters, and what it does to them. Depending on your style, you might consider ArrayFromConcatenatedRanges to be even better.

If in doubt, always err on the side of more verbose.

VBA conventions you should be aware of:

Function/Procedure names are PascalCase.

Local variable names are camelCase so nCols instead of ncols and col instead of Col.

N.B. if Col is capitalised because it's a module-level variable, that's an even worse offence (unnecessarily broad scope) than bad naming.

Module/Global variable names are PascalCase so if I see ReferenceVariable in the middle of a procedure, I know to look for it outside of that procedure's scope.

And now for your variables

R1 and R2 are terrible variable names. Variables should always sound like what they are. I suggest topRange,bottomRange. Suddenly, it's clear that they are ranges, and that the first one is the one that's going to end up on top of the final concatenation.

Similarly, ncols,nrows1,nrows2 are not great. It should be nCols, nRows1, nRows2 anyway, and then numColumns,rowsInTopRange,rowsInBottomRange still sound like counts of rows/columns, but it's much clearer what they are/should be. Similarly, arr1 and arr2 could do with the same treatment.

This is your code, with better naming, and it is so much easier for someone to read/follow:

Option Explicit
Option Base 1

Public Function VerticallyConcatenateRanges(topRange As Range, bottomRange As Range) As Variant

    Dim row As Long, col As Long

    Dim numColumns As Long
        numColumns = topRange.Columns.Count

    Dim rowsInTopRange As Long
        rowsInTopRange = topRange.Rows.Count

    Dim rowsInBottomRange As Long
        rowsInBottomRange = bottomRange.Rows.Count

    Dim totalRows As Long
        totalRows = rowsInTopRange + rowsInBottomRange

    Dim arrTopRange As Variant
        arrTopRange = topRange

    Dim arrBottomRange As Variant
        arrBottomRange = bottomRange

    Dim concatenatedArray As Variant
    ReDim concatenatedArray(1 To totalRows, 1 To numColumns)

    Dim ix As Long

        For col = 1 To numColumns

            For row = 1 To rowsInTopRange
                concatenatedArray(row, col) = arrTopRange(row, col)
            Next row

            For row = 1 To rowsInBottomRange
                ix = row + rowsInTopRange
                concatenatedArray(ix, col) = arrBottomRange(row, col)
            Next row

        Next col

        VerticallyConcatenateRanges = concatenatedArray

End Function

And, crucially, if you took any of those lines out of context and gave them to someone, that person would be able to figure out very easily what the variables were and what the code was doing.


Indentation is your best friend when nesting SQL Queries
Be consistent with your casing on keywords, SCREAMCASE is the standard for keywords in SQL
Be consistent with your Alias syntax, sometimes it was written table t and others it was written table AS t
Use newlines in your select statements, especially when they are complex
INT is not a good table alias, change it
I have no clue what any of these tables are, and I can't tell from the aliases either.
Naming,

I recognized like 4 field names

MonthName
WeekOfMonth
StartDate
EndDate

Some Temp Tables
and some variables that aren't assigned anywhere in the code you have given us.

Spacing in your equations

I took your code and I cleaned up the formatting so that it might be easier for others to read it and provide you a better review, here is the cleaned up code using standard spacing, casing, and other standards that I could implement.

SELECT
    Id
    ,Fees
    ,WeekOfMonth
    ,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate
    ,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate
    ,'Temp Fees                      ' AS FeesName
    ,@MonthName AS [MonthName]
INTO ##TempFeesMonthly
FROM
(
    SELECT DISTINCT
        1 AS Id
        ,sum((CNTI_THPAYE * (CNTI_THFACT / CNTI_THPAYE)) * (CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO / 5 END) * @NumberOfDays) AS Fees
        ,WeekOfMonth
        ,StartDate
        ,EndDate
    FROM SCHHAYS.dbo.WTVTAT AS TAT
        LEFT JOIN SCHHAYS.dbo.WTTIEINT [INT]
            ON TAT.TIE_ID = INT.TIE_ID
            AND TAT.VTAT_IORDRE = INT.TIEI_ORDRE
        LEFT JOIN SCHHAYS.dbo.PYCONTRAT CC
            ON TAT.PER_ID = CC.PER_ID
            AND TAT.CNT_ID = CC.CNT_ID
        LEFT JOIN SCHHAYS.dbo.CMTIERS T
            ON TAT.TIE_ID = T.TIE_ID
        LEFT JOIN SCHHAYS.dbo.WTMISS M
            ON CC.PER_ID = M.PER_ID
            AND CC.CNT_ID = M.CNT_ID
        LEFT JOIN ##WTCNTIWeek COT1
            ON M.PER_ID = COT1.PER_ID
            AND M.CNT_ID = COT1.CNT_ID
        INNER JOIN SCHHAYS.dbo.WTPRH AS PRH
            ON M.PER_ID = PRH.PER_ID
            AND M.CNT_ID = PRH.CNT_ID
            AND M.TIE_ID = PRH.TIE_ID
        INNER JOIN ##tempStartEndWeekDates AS Tsed
            ON PRH_DTEDEBSEM >= Tsed.StartDate
            AND PRH_DTEFINSEM <= Tsed.EndDate
        LEFT JOIN SCHHAYS.dbo.WTSCCT C
            ON CC.RGPCNT_ID = C.RGPCNT_ID
            AND CC.PER_ID = C.PER_ID
            AND CC.CNT_ID = C.CNT_ID
        INNER JOIN ##TempHaysStaffWeek HF
            ON C.VAPO_CODE = HF.onetouch  COLLATE Latin1_General_CI_AS
    GROUP BY WeekOfMonth, StartDate, EndDate
) AS t

UNION ALL

SELECT
    2
    , SUM(Fees) AS Fees
    , WeekOfMonth
    , CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate
    , CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate
    , 'Temp Margin ' AS FeesName
    , @MonthName AS [MonthName]
FROM
(
    SELECT DISTINCT
        SUM((CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO / 5 END) * @NumberOfDays) - (CNTI_THPAYE * (CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO / 5 END) * 1.453 * 1.21 * @NumberOfDays) AS Fees
        , WeekOfMonth
        , StartDate
        , EndDate
    FROM SCHHAYS.dbo.WTVTAT TAT
        LEFT JOIN SCHHAYS.dbo.WTTIEINT AS [INT]
            ON TAT.TIE_ID = INT.TIE_ID
        AND TAT.VTAT_IORDRE = INT.TIEI_ORDRE
        LEFT JOIN SCHHAYS.dbo.PYCONTRAT AS CC
            ON TAT.PER_ID = CC.PER_ID
            AND TAT.CNT_ID = CC.CNT_ID
        LEFT JOIN SCHHAYS.dbo.CMTIERS AS T
            ON TAT.TIE_ID = T.TIE_ID
        LEFT JOIN SCHHAYS.dbo.WTMISS AS M
            ON CC.PER_ID = M.PER_ID
            AND CC.CNT_ID = M.CNT_ID
        LEFT JOIN ##WTCNTIWeek AS COT1
            ON M.PER_ID = COT1.PER_ID
            AND M.CNT_ID = COT1.CNT_ID
        INNER JOIN SCHHAYS.dbo.WTPRH AS PRH
            ON M.PER_ID = PRH.PER_ID
            AND M.CNT_ID = PRH.CNT_ID
            AND M.TIE_ID = PRH.TIE_ID
        INNER JOIN ##tempStartEndWeekDates AS Tsed
            ON PRH_DTEDEBSEM >= Tsed.StartDate
            AND PRH_DTEFINSEM <= Tsed.EndDate
        LEFT JOIN SCHHAYS.dbo.WTSCCT AS C
            ON CC.RGPCNT_ID = C.RGPCNT_ID
            AND CC.PER_ID = C.PER_ID
            AND CC.CNT_ID = C.CNT_ID
        INNER JOIN ##TempHaysStaffWeek AS HF
            ON C.VAPO_CODE = HF.onetouch  COLLATE Latin1_General_CI_AS
    GROUP BY WeekOfMonth, StartDate, EndDate, CNTI_THPAYE, CNTI_DURHEBDO
) AS t
GROUP BY WeekOfMonth, StartDate, EndDate

The only thing that I can suggest that might speed things up is a complete guess because you haven't provided the full code or table schemas

In both queries on either side of the UNION ALL  you join almost every table to another table on 2-3 fields, if this isn't necessary you are forcing the query to perform a lot of stuff that it doesn't need to

Another thought, you are calling COLLATE on both Queries as well, that probably doesn't need to done at all on this level, your SQL Server most likely already has Latin1_General_CI_AS as a default collation on the entire server, so calling it here is wasting processing power, twice.


Changing the ACL on a folder through Wscript.Shell within VBA

CodeReview

Why use the Scripting.FileSystemObject?  MyFolder is just returning the folder name

  MyFolder = Worksheets("Config").Range("D4").Value & ActiveSheet.Range("C21").Value

I would also write a function to return the folder path and a second function to create the icacls commands.

Fun Part: My Own Solution

The class below will create a self-deleting batch file.  Running it in silent mode will hide the command window.  The advantage of using a batch file is that you can add a pause that will allow you to inspect the results of your commands.

Note: pause will have no effect in silent mode and the files do not delete themselves immediately but they will automatically delete after a short time.

Class: BatchFile

Attribute VB_Name = "BatchFile"

Option Explicit
Public FileText As String
Private Const DeleteCommand As String = "DEL ""%~f0"""

Public Sub AppendLine(Text As String)
    If Len(FileText) > 0 Then FileText = FileText & vbNewLine
    FileText = FileText & Text
End Sub

Public Sub AddICacls(ByVal FolderName As String, ByVal Parameters As String)
    AppendLine "icacls " & Chr(34) & FolderName & Chr(34) & Parameters
End Sub

Public Sub Execute(SilentMode As Boolean)
    Dim FilePath As String
    FilePath = getTempBatchFileName

    CreateFile FilePath

    Dim oShell As Object
    Set oShell = CreateObject("WScript.Shell")

    If SilentMode Then
        oShell.Run Chr(34) & FilePath & Chr(34), 0
    Else
        oShell.Run Chr(34) & FilePath & Chr(34)
    End If

    Set oShell = Nothing
End Sub

Private Sub CreateFile(FilePath As String)
    Dim Text As String
    Text = FileText & vbNewLine & DeleteCommand

    Dim FileNumber As Long
    FileNumber = FreeFile
    Open FilePath For Output As FileNumber
    Print #FileNumber, Text
    Close FileNumber

    Debug.Print Text
End Sub

Private Function getTempBatchFileName() As String
    Dim n As Long
    Dim FilePath As String

    Do
        n = n + 1
        FilePath = Environ("Temp") & "\" & n & ".bat"
    Loop While Len(Dir(FilePath)) > 0

    getTempBatchFileName = FilePath
End Function

Usage

Sub RunICalcs()
    Const DebugMode As Boolean = True

    Dim Batch As New BatchFile
    Dim FolderName As String
    FolderName = getFolderPath

    Batch.AddICacls FolderName, " /r /d y"
    Batch.AddICacls FolderName, " /setowner mydomain\admin"
    Batch.AddICacls FolderName, " /grant mydomain\StudentExam101:(OI)(CI)F /T"
    Batch.AddICacls FolderName, " /grant mydomain\DAdmins:(OI)(CI)F /T"
    Batch.AddICacls FolderName, " /grant mydomain\admin:(OI)(CI)F /T"
    Batch.AddICacls FolderName, " /grant SYSTEM:(OI)(CI)F /T"
    Batch.AddICacls FolderName, " /grant CREATOR OWNER:(OI)(CI)F /T"

    If DebugMode Then
        Batch.AppendLine "pause"
        Batch.Execute False
    Else
        Batch.AppendLine "pause"
        Batch.Execute True
    End If
End Sub

Function getFolderPath() As String
    getFolderPath = Worksheets("Config").Range("D4").Value & ActiveSheet.Range("C21").Value
End Function


You could write it like this:

for (val method <- clazz.getMethods) {
  val methodAndAnnotation = method.getAnnotation(annotationType) match {
    case annotation: MessageHandler => Some((method, annotation))
    case _                          => getMethodAndAnnotationFromInterfaces(clazz.getInterfaces, method, annotationType)
  }

  methodAndAnnotation match {
    case Some((method, annotation)) => // do something
    case None => //whatever is relevant
  }
}

Or shorter:

for (val method <- clazz.getMethods) {
  method.getAnnotation(annotationType) match {
    case annotation: MessageHandler =>  // do something with method and annotation
    case _                          => {
      val v = getMethodAndAnnotationFromInterfaces(clazz.getInterfaces, method, annotationType)
      //whatever is relevant
    }
  }
}

But it depends on what you want to do / if you have something to do when getMethodAndAnnotationFromInterfaces returns None.


Simple simulated annealing template in C++11

I think the algorithm is well abstracted and the code is nicely written, so there is not all too much you can do in order to make it more efficient. Still I have some minor suggestions for improvement:

First, regarding the algorithm itself:

When the check if(e_new < e_best) is successful, you can directly treat the step as accepted. Although this might be negligible, you avoid one more check.

In your check whether to accept the new step, you can think about choosing a cutoff (say ~ 10.0) parameter to bypass the relatively expensive calculation of std::exp as well as the random number generation.

Summarizing 1. and 2., one gets a slightly more verbose but hopefully more efficient code:
    if(e_new < e_best){
        i_best =           i_new ;
        e_best =           e_new ;
        i_old  = std::move(i_new);
        e_old  = std::move(e_new);
        continue;
    }

    auto t = tf(c);
    auto delta_e = e_new - e_old;

    if( delta_e > 10.0 * t) continue;  //as std::exp(-10.0) is a very small number

    if( delta_e <= 0.0 || std::exp( - delta_e / t ) > rf(g) ){
        i_old  = std::move(i_new);
        e_old  = std::move(e_new);
    }

Next, regarding your choice of functions: Here I would try to avoid expensive functions as well. I know, this might often not be possible as the functions are determined by your problem at hand. However, for example, in your temperature function you can think about replacing the std::exp(-20*k) by something more efficient such as 1/(k*k).

Regarding the language:

You can get a bit more of a C++11 touch if you use universal references instead of lvalue references.
template<typename status, typename count, typename energy_function
       , typename temperature_function, typename next_function, typename generator>
status simulated_annealing(status&& i_old, count&& c, energy_function&& ef
                         , temperature_function&& tf, next_function&& nf, generator&& g)
{
    //...
}

This is maybe also a bit more consistent with your std::move's of your status and count-type variables (which, as a side node, will resolve to simple copies when fundamental types such as double or size_t are used).
Further, you can think  about replacing your type count by size_t, since that is what this type is for. But this just because I personally try to avoid template parameters when possible.

Regarding the design:

The nf function can be made more generic by defining a static generator inside
long double nf(long double x){
    static std::mt19937_64 g(std::random_device());
    std::normal_distribution<decltype(x)> d(0, 1);
    return x + d(g);
}

I wouldn't pass a generator here, as it doesn't fit well into a generic desing. (For instance, the next state could also be found deterministically).

The same holds for your main simulated_annealing function. I wouldn't bother the user to define a random number generator, but just define it inside -- moreover since it is used "only" to create random numbers in [0,1] (once you've followed suggestion 4.).

        template<typename status, typename count, typename energy_function
               , typename temperature_function, typename next_function>
        status simulated_annealing(status&& i_old, count&& c, energy_function&& ef
                             , temperature_function&& tf, next_function&& nf)
        {
            std::mt19937_64 g(std::random_device());
            //...
        }

This you can simply call the routine via
    root = simulated_annealing(root, count, ef, tf, nf);

which is more concise and better reflects the main components of a simulated annealing algorithm.


Swift 4

i would use the new swift 4 init(grouping:by:)

since you create always new Departments then the following code is possible.

if you have an existing [Department] then the code not fit your request.

enum Job {
    case developer
    case programmer
    case coder
}

struct Person {
    let id: Int
    let job: Job
}

struct Department {
    let job: Job
    var staff: [Person]

    mutating func addStaff(_ person: Person) {
        staff.append(person)
    }
}

let initial = [
    Person(id: 0, job: .developer),
    Person(id: 1, job: .developer),
    Person(id: 2, job: .programmer),
    Person(id: 3, job: .programmer),
    Person(id: 4, job: .coder)
]

let grouped = Dictionary(grouping: initial, by: { $0.job })
let departments = grouped.map{ key, value in Department( job: key, staff: value )}

( NOTE: i don't tested it in playground - just from head to the answer)

Swift 3

in Swift 3 you can use an extension to the array to resolve this grouping

public extension Sequence {
    func group<U: Hashable>(by key: (Iterator.Element) -> U) -> [U:[Iterator.Element]] {
        var categories: [U: [Iterator.Element]] = [:]
        for element in self {
            let key = key(element)
            if case nil = categories[key]?.append(element) {
                categories[key] = [element]
            }
        }
        return categories
    }
}

the extension is from here https://stackoverflow.com/a/31220067/1930509 and when you need a more performat grouping you can find it at the link


Use case instead of == and guards everywhere:

prevBracketIndex :: Int -> Int -> Array Int Char -> Int
prevBracketIndex i depth cs = case cs ! i of
    '[' -> if (depth - 1) == 0 then i else prevBracketIndex (i - 1) (depth - 1) cs
    ']' -> prevBracketIndex (i - 1) (depth + 1) cs
    _ -> prevBracketIndex (i - 1) depth cs

Use State and lens to carry state around instead of manual threading.

Use monad-loops to spin the loop instead of manual tail calls.

prevBracketIndex should avoid recursion too by using lists of indices.

Initial depth is always 0 in prevBracketIndex so it should be made local to improve readability. Also, cs is not changed across recursive calls so there is no need to pass it across. Applying both ideas:

prevBracketIndex :: Int -> Array Int Char -> Int
prevBracketIndex i cs = pbi i 0 where
    pbi i depth = case cs ! i of
        '[' -> if (depth - 1) == 0 then i else pbi (i - 1) (depth - 1)
        ']' -> pbi (i - 1) (depth + 1)
        _ -> pbi (i - 1) depth

For execCode we can do the same transformation: cs is invariant across loops, and initial positions are always 0.

Note also that prevBracketIndex can be completely precalculated (replaced by a single array lookup), as cs doesn't change.

Applying everything above but case we get:

import qualified Data.Sequence as S
import Data.Char (chr, ord)
import Data.Array
import Data.List

cachePrev cs = listArray (bounds cs) $ snd $ mapAccumL f [] $ assocs cs where
    f l (i, c) = case c of
        '[' -> (i : l, Nothing)
        ']' -> (tail l, Just $ head l)
        _ -> (l, Nothing)

cacheNext cs = listArray (bounds cs) $ snd $ mapAccumR f [] $ assocs cs where
    f l (i, c) = case c of
        ']' -> (i : l, Nothing)
        '[' -> (tail l, Just $ head l)
        _ -> (l, Just i)

cache arr i = case arr ! i of
    Nothing -> error "oops!"
    Just idx -> idx

execCode' :: S.Seq Int -> Array Int Char -> IO ()
execCode' ts cs = execCode 0 ts 0 where
    prev = cachePrev cs
    next = cacheNext cs

    execCode tapePos ts codePos
        | codePos == (snd . bounds $ cs) = return ()
        | cmd == '+' = execCode tapePos (S.update tapePos (value + 1) ts) nextPos
        | cmd == '-' = execCode tapePos (S.update tapePos (value - 1) ts) nextPos
        | cmd == '>' = execCode (tapePos + 1) ts nextPos
        | cmd == '<' = execCode (tapePos - 1) ts nextPos
        | cmd == '[' && value == 0 = execCode tapePos ts (cache next codePos + 1)
        | cmd == ']' && value /= 0 = execCode tapePos ts (cache prev codePos + 1)
        | cmd == '.' = putStr [chr $ S.index ts tapePos] >> execCode tapePos ts nextPos
        | cmd == ',' = do { c <- getChar; let newTape = S.update tapePos (ord c) ts in execCode tapePos newTape nextPos }
        | otherwise = execCode tapePos ts nextPos
        where
            value = S.index ts tapePos
            cmd = cs ! codePos
            nextPos = codePos + 1

For tests I found csFromString to be a convenient helper:

csFromString file = listArray (0, length file - 1) file

And it helps to write main in a more compact way:

main = readFile "example.bf" >>= execCode' tape . csFromString

Now let's apply the case proposal:

execCode _ _ codePos | codePos == (snd . bounds $ cs) = return ()
execCode tapePos ts codePos = case cs ! codePos of
    '+' -> execCode tapePos (S.update tapePos (value + 1) ts) nextPos
    '-' -> execCode tapePos (S.update tapePos (value - 1) ts) nextPos
    '>' -> execCode (tapePos + 1) ts nextPos
    '<' -> execCode (tapePos - 1) ts nextPos
    '[' -> if value == 0 then execCode tapePos ts (cache next codePos + 1) else execNext
    ']' -> if value /= 0 then execCode tapePos ts (cache prev codePos + 1) else execNext
    '.' -> putStr [chr $ S.index ts tapePos] >> execNext
    ',' -> do { c <- getChar; let newTape = S.update tapePos (ord c) ts in execCode tapePos newTape nextPos }
    _ -> execNext
    where
        value = S.index ts tapePos
        nextPos = codePos + 1
        execNext = execCode tapePos ts nextPos

Now cmd is not needed anymore, and [ and ] required some additional plumbing.

Now let's remove duplication in 3 symmetrical pairs of instructions - updatePos, updateVal and branch:

execCode _ _ codePos | codePos == (snd . bounds $ cs) = return ()
execCode tapePos ts codePos = case cs ! codePos of
    '+' -> updatePos succ
    '-' -> updatePos pred
    '>' -> updateVal succ
    '<' -> updateVal pred
    '[' -> branch (== 0) next
    ']' -> branch (/= 0) prev
    '.' -> putStr [chr $ S.index ts tapePos] >> execNext
    ',' -> do { c <- getChar; let newTape = S.update tapePos (ord c) ts in execCode tapePos newTape nextPos }
    _ -> execNext
    where
        value = S.index ts tapePos
        nextPos = codePos + 1
        execNext = execCode tapePos ts nextPos

        updatePos f = execCode tapePos (S.update tapePos (f value) ts) nextPos
        updateVal f = execCode (f tapePos) ts nextPos
        branch cond dir = if cond value then execCode tapePos ts (cache dir codePos + 1) else execNext

Now it's time to remove duplication between cachePrev and cacheNext:

mkCache cs mapAccumX bracketPush bracketPop = listArray (bounds cs) $ snd $ mapAccumX f [] $ assocs cs where
    f l (i, c)
        | c == bracketPush = (i : l, Nothing)
        | c == bracketPop = (tail l, Just $ head l)
        | otherwise = (l, Nothing)

cache arr i = case arr ! i of
    Nothing -> error "oops!"
    Just idx -> idx

execCode' :: S.Seq Int -> Array Int Char -> IO ()
execCode' ts cs = execCode 0 ts 0 where
    prev = mkCache cs mapAccumL '[' ']'
    next = mkCache cs mapAccumR ']' '['

    execCode _ _ codePos | codePos == (snd . bounds $ cs) = return ()
    execCode tapePos ts codePos = case cs ! codePos of
        '+' -> updatePos succ
        '-' -> updatePos pred
        '>' -> updateVal succ
        '<' -> updateVal pred
        '[' -> branch (== 0) next
        ']' -> branch (/= 0) prev
        '.' -> putStr [chr $ S.index ts tapePos] >> execNext
        ',' -> do { c <- getChar; let newTape = S.update tapePos (ord c) ts in execCode tapePos newTape nextPos }
        _ -> execNext
        where
            value = S.index ts tapePos
            nextPos = codePos + 1
            execNext = execCode tapePos ts nextPos

            updatePos f = execCode tapePos (S.update tapePos (f value) ts) nextPos
            updateVal f = execCode (f tapePos) ts nextPos
            branch cond dir = if cond value then execCode tapePos ts (cache dir codePos + 1) else execNext

Here is complete final source:

import qualified Data.Sequence as S
import Data.Char (chr, ord)
import Data.Array
import Data.List

mkCache cs mapAccumX bracketPush bracketPop = listArray (bounds cs) $ snd $ mapAccumX f [] $ assocs cs where
    f l (i, c)
        | c == bracketPush = (i : l, Nothing)
        | c == bracketPop = (tail l, Just $ head l)
        | otherwise = (l, Nothing)

cache arr i = case arr ! i of
    Nothing -> error "oops!"
    Just idx -> idx

execCode' :: S.Seq Int -> Array Int Char -> IO ()
execCode' ts cs = execCode 0 ts 0 where
    prev = mkCache cs mapAccumL '[' ']'
    next = mkCache cs mapAccumR ']' '['

    execCode _ _ codePos | codePos == (snd . bounds $ cs) = return ()
    execCode tapePos ts codePos = case cs ! codePos of
        '+' -> updatePos succ
        '-' -> updatePos pred
        '>' -> updateVal succ
        '<' -> updateVal pred
        '[' -> branch (== 0) next
        ']' -> branch (/= 0) prev
        '.' -> putStr [chr $ S.index ts tapePos] >> execNext
        ',' -> do { c <- getChar; let newTape = S.update tapePos (ord c) ts in execCode tapePos newTape nextPos }
        _ -> execNext
        where
            value = S.index ts tapePos
            nextPos = codePos + 1
            execNext = execCode tapePos ts nextPos

            updatePos f = execCode tapePos (S.update tapePos (f value) ts) nextPos
            updateVal f = execCode (f tapePos) ts nextPos
            branch cond dir = if cond value then execCode tapePos ts (cache dir codePos + 1) else execNext

tape = S.fromList $ replicate 30000 0

csFromString file = listArray (0, length file - 1) file

main = readFile "example.bf" >>= execCode' tape . csFromString

Note that my suggestions about monad-loops, lens and State are still to be applied.

The first step is to declare a datatype for our future state.

data M = M
    { _tapePos :: Int
    , _tape :: S.Seq Int
    , _codePos :: Int
    }

and make inner execCode accept a single parameter.

    execCode :: M -> IO ()
    execCode (M _ _ codePos) | codePos == (snd . bounds $ cs) = return ()
    execCode (M tapePos ts codePos) = case cs ! codePos of
        '+' -> updatePos succ
        '-' -> updatePos pred
        '>' -> updateVal succ
        '<' -> updateVal pred
        '[' -> branch (== 0) next
        ']' -> branch (/= 0) prev
        '.' -> putStr [chr $ S.index ts tapePos] >> execNext
        ',' -> do { c <- getChar; let newTape = S.update tapePos (ord c) ts in execCode (M tapePos newTape nextPos) }
        _ -> execNext
        where
            value = S.index ts tapePos
            nextPos = codePos + 1
            execNext = execCode (M tapePos ts nextPos)

            updatePos f = execCode (M tapePos (S.update tapePos (f value) ts) nextPos)
            updateVal f = execCode (M (f tapePos) ts nextPos)
            branch cond dir = if cond value then execCode (M tapePos ts (cache dir codePos + 1)) else execNext

M stands for machine state :) and underscores are signals to Data.Lens.TH template Haskell code we will start using a bit later.

We will need a state monad transformer ran on top of IO monad. Let's declare the type of our monad stack:

type ExecT a = StateT M IO a

Our future execCode'' will be of type ExecT () instead of current M -> IO (). To execute it and discard the state (as we do now) we'll use evalStateT:

execCode' :: S.Seq Int -> Array Int Char -> IO ()
execCode' ts cs = evalStateT execCode'' (M 0 ts 0) where
    prev = mkCache cs mapAccumL '[' ']'
    next = mkCache cs mapAccumR ']' '['

    execCode'' :: ExecT ()
    execCode'' = do
        s <- get
        lift (execCode s)

    execCode :: M -> IO ()
    execCode = ... -- unchanged

Now execCode'' is just a wrapper around our old inner execCode. And we fix execCode so it can be called directly. Note that we should do the following:

lift all IO
Replace recursive calls execCode (M ...) with put (M ...) >> execCode
move where statements around so M tapePos ts codePos is in scope
replace old termination guard with when

Here is the result:

execCode' :: S.Seq Int -> Array Int Char -> IO ()
execCode' ts cs = evalStateT execCode (M 0 ts 0) where
    prev = mkCache cs mapAccumL '[' ']'
    next = mkCache cs mapAccumR ']' '['

    execCode :: ExecT ()
    execCode = do
        M tapePos ts codePos <- get
        let value = S.index ts tapePos
        let nextPos = codePos + 1
        let execNext = put (M tapePos ts nextPos) >> execCode
        let updatePos f = put (M tapePos (S.update tapePos (f value) ts) nextPos) >> execCode
        let updateVal f = put (M (f tapePos) ts nextPos) >> execCode
        let branch cond dir = if cond value then put (M tapePos ts (cache dir codePos + 1)) >> execCode else execNext

        when (codePos /= (snd . bounds $ cs)) $ case cs ! codePos of
            '+' -> updatePos succ
            '-' -> updatePos pred
            '>' -> updateVal succ
            '<' -> updateVal pred
            '[' -> branch (== 0) next
            ']' -> branch (/= 0) prev
            '.' -> lift (putStr [chr $ S.index ts tapePos]) >> execNext
            ',' -> do { c <- lift getChar; let newTape = S.update tapePos (ord c) ts in put (M tapePos newTape nextPos) >> execCode }
            _ -> execNext

Now note that all branches of case end in >> execCode. So it can be moved around to form a nice while control structure:

execCode :: ExecT ()
execCode = do
    M tapePos ts codePos <- get
    let value = S.index ts tapePos
    let nextPos = codePos + 1
    let execNext = put (M tapePos ts nextPos)
    let updatePos f = put (M tapePos (S.update tapePos (f value) ts) nextPos)
    let updateVal f = put (M (f tapePos) ts nextPos)
    let branch cond dir = if cond value then put (M tapePos ts (cache dir codePos + 1)) else execNext

    when (codePos /= (snd . bounds $ cs)) $ do
        case cs ! codePos of
            '+' -> updatePos succ
            '-' -> updatePos pred
            '>' -> updateVal succ
            '<' -> updateVal pred
            '[' -> branch (== 0) next
            ']' -> branch (/= 0) prev
            '.' -> lift (putStr [chr $ S.index ts tapePos]) >> execNext
            ',' -> do { c <- lift getChar; let newTape = S.update tapePos (ord c) ts in put (M tapePos newTape nextPos) }
            _ -> execNext
        execCode

Now it's finally time for lens to shine.

{-# LANGUAGE TemplateHaskell  #-}
import Control.Lens.TH
import Control.Lens
import Control.Applicative

...

data M = M
    { _mTapePos :: Int
    , _mTape :: S.Seq Int
    , _mCodePos :: Int
    }

$(makeLenses ''M)

type ExecT a = StateT M IO a

execCode' :: S.Seq Int -> Array Int Char -> IO ()
execCode' ts cs = evalStateT execCode (M 0 ts 0) where
    prev = mkCache cs mapAccumL '[' ']'
    next = mkCache cs mapAccumR ']' '['

    execCode :: ExecT ()
    execCode = do
        M tapePos ts codePos <- get
        let value = S.index ts tapePos
        let nextPos = codePos + 1
        let execNext = mCodePos += 1
        let updatePos f = mTape %= S.update tapePos (f value) >> execNext
        let updateVal f = mTapePos %= f >> execNext
        let branch cond dir = if cond value then mCodePos %= succ . cache dir else execNext

        when (codePos /= (snd . bounds $ cs)) $ do
            case cs ! codePos of
                '+' -> updatePos succ
                '-' -> updatePos pred
                '>' -> updateVal succ
                '<' -> updateVal pred
                '[' -> branch (== 0) next
                ']' -> branch (/= 0) prev
                '.' -> lift (putStr [chr $ S.index ts tapePos]) >> execNext
                ',' -> do { c <- lift getChar; mTape %= S.update tapePos (ord c) >> execNext }
                _ -> execNext
            execCode

I did the following:

Added imports and TemplateHaskell pragma
Added a template Haskell call to generate definitions for mTapePos from _mTapePos
replaced all put calls with one or many lens-based state modifiers, joined by >>. E.g. if 2 fields of M are modified I chain 2 modifiers. If just 1 - no need to chain. Basically it's just >> execNext instead of nextPos.
removed unused nextPos

Now it turns out that branch has its own hidden execNext (note succ . in the code above):

let branch cond dir = if cond value then mCodePos %= cache dir >> execNext else execNext

So we can transform it to when easily:

let branch cond dir = when (cond value) (mCodePos %= cache dir) >> execNext

And now it turns out that >> execNext is everywhere. We can move it after case and  inline:

execCode' :: S.Seq Int -> Array Int Char -> IO ()
execCode' ts cs = evalStateT execCode (M 0 ts 0) where
    prev = mkCache cs mapAccumL '[' ']'
    next = mkCache cs mapAccumR ']' '['

    execCode :: ExecT ()
    execCode = do
        M tapePos ts codePos <- get
        let value = S.index ts tapePos
        let updatePos f = mTape %= S.update tapePos (f value)
        let updateVal f = mTapePos %= f
        let branch cond dir = when (cond value) (mCodePos %= cache dir)

        when (codePos /= (snd . bounds $ cs)) $ do
            case cs ! codePos of
                '+' -> updatePos succ
                '-' -> updatePos pred
                '>' -> updateVal succ
                '<' -> updateVal pred
                '[' -> branch (== 0) next
                ']' -> branch (/= 0) prev
                '.' -> lift (putStr [chr $ S.index ts tapePos])
                ',' -> do { c <- lift getChar; mTape %= S.update tapePos (ord c) }
                _ -> return ()
            mCodePos += 1
            execCode

After some more cleanup we get:

{-# LANGUAGE TemplateHaskell  #-}
import Control.Lens.TH
import Control.Lens
import Control.Applicative

import qualified Data.Sequence as S
import Data.Char (chr, ord)
import Data.Array
import Data.List
import Control.Monad.State

mkCache cs mapAccumX bracketPush bracketPop = listArray (bounds cs) $ snd $ mapAccumX f [] $ assocs cs where
    f l (i, c)
        | c == bracketPush = (i : l, Nothing)
        | c == bracketPop = (tail l, Just $ head l)
        | otherwise = (l, Nothing)

cache arr i = case arr ! i of
    Nothing -> error "oops!"
    Just idx -> idx

data M = M
    { _mTapePos :: Int
    , _mTape :: S.Seq Int
    , _mCodePos :: Int
    }

$(makeLenses ''M)

type ExecT a = StateT M IO a

execCode' :: S.Seq Int -> Array Int Char -> IO ()
execCode' ts cs = evalStateT execCode (M 0 ts 0) where
    prev = mkCache cs mapAccumL '[' ']'
    next = mkCache cs mapAccumR ']' '['

    execCode :: ExecT ()
    execCode = do
        M tapePos ts codePos <- get
        let value = S.index ts tapePos
        let tapeAtPos = mTape . ix tapePos
        let branch cond dir = when (cond value) (mCodePos %= cache dir)

        when (codePos /= (snd . bounds $ cs)) $ do
            case cs ! codePos of
                '+' -> tapeAtPos += 1
                '-' -> tapeAtPos -= 1
                '>' -> mTapePos += 1
                '<' -> mTapePos -= 1
                '[' -> branch (== 0) next
                ']' -> branch (/= 0) prev
                '.' -> lift (putChar $ chr value)
                ',' -> do { c <- lift getChar; mTape %= S.update tapePos (ord c) }
                _ -> return ()
            mCodePos += 1
            execCode

tape = S.fromList $ replicate 30000 0

csFromString file = listArray (0, length file - 1) file

main = readFile "example.bf" >>= execCode' tape . csFromString

One more iteration of tuning for execCode' to make code more uniform which is good for readability and maintenance:

tapeAtPos is made a self-contained compound lens, without reliance on tapePos and
tapeAtPos is moved out of execState' body to global scope, and renamed to mTapeAtPos uniformly with other lenses
value is renamed tapeAtPos as it corresponds to mTapeAtPos
mTapeAtPos is used uniformly for both getting and updating the value everywhere including the getChar branch
unsafeUse helper is used to get tapeAtPos uniformly with codePos. It is called unsafe because tapeAtPos may fail if mTapePos is out of range!
lens API is used to read code uniformly with reading tape
extra parenthesis/$ are removed from when condition
M ... <- get is removed as it is not used anymore

The code:

mTapeAtPos f m = (mTape . ix (m ^. mTapePos)) f m

unsafeUse traversal = (^?! traversal) <$> get

execCode' :: S.Seq Int -> Array Int Char -> IO ()
execCode' ts cs = evalStateT execCode (M 0 ts 0) where
    prev = mkCache cs mapAccumL '[' ']'
    next = mkCache cs mapAccumR ']' '['

    execCode :: ExecT ()
    execCode = do
        tapeAtPos <- unsafeUse mTapeAtPos
        codePos <- use mCodePos
        let branch cond dir = when (cond tapeAtPos) (mCodePos %= cache dir)
        when (codePos /= snd (bounds cs)) $ do
            case cs ^?! ix codePos of
                '+' -> mTapeAtPos += 1
                '-' -> mTapeAtPos -= 1
                '>' -> mTapePos += 1
                '<' -> mTapePos -= 1
                '[' -> branch (== 0) next
                ']' -> branch (/= 0) prev
                '.' -> lift (putChar $ chr tapeAtPos)
                ',' -> do { c <- lift getChar; mTapeAtPos .= ord c }
                _ -> return ()
            mCodePos += 1
            execCode

It can be made even more uniform:

at this point tapePos is used only in branch it can be moved into branch
branch then can be moved outside of execCode as it doesn't a closure any more
it seems inner execCode is better named loop, and ExecT is LoopStateT

The code:

branch cond dir = do
    tapeAtPos <- unsafeUse mTapeAtPos
    when (cond tapeAtPos) (mCodePos %= cache dir)

execCode :: S.Seq Int -> Array Int Char -> IO ()
execCode ts cs = evalStateT loop (M 0 ts 0) where
    prev = mkCache cs mapAccumL '[' ']'
    next = mkCache cs mapAccumR ']' '['

    loop :: LoopStateT ()
    loop = do
        codePos <- use mCodePos
        when (codePos /= snd (bounds cs)) $ do
            case cs ^?! ix codePos of
                '+' -> mTapeAtPos += 1
                '-' -> mTapeAtPos -= 1
                '>' -> mTapePos += 1
                '<' -> mTapePos -= 1
                '[' -> branch (== 0) next
                ']' -> branch (/= 0) prev
                '.' -> unsafeUse mTapePos >>= lift . putChar . chr
                ',' -> lift (ord <$> getChar) >>= (mTapeAtPos .=)
                _ -> return ()
            mCodePos += 1
            loop

At this point it seems branch and ./, symmetry aren't worth it, so I inlined branch, reverted getChar branch to use do-notation and moved tapeAtPos <- to the top of loop:

    loop :: LoopStateT ()
    loop = do
        tapeAtPos <- unsafeUse mTapeAtPos
        codePos <- use mCodePos
        when (codePos /= snd (bounds cs)) $ do
            case cs ^?! ix codePos of
                '+' -> mTapeAtPos += 1
                '-' -> mTapeAtPos -= 1
                '>' -> mTapePos += 1
                '<' -> mTapePos -= 1
                '[' -> when (tapeAtPos == 0) (mCodePos %= cache next)
                ']' -> when (tapeAtPos /= 0) (mCodePos %= cache prev)
                '.' -> lift $ putChar (chr tapeAtPos)
                ',' -> do { c <- lift getChar; mTapeAtPos .= ord c }
                _ -> return ()
            mCodePos += 1
            loop

Another improvement is better diagnostics of match failures in cache:

cache arr i = case arr ! i of
    Nothing -> error $ "No matching bracket at offset " ++ show i
    Just idx -> idx

So we get:

{-# LANGUAGE TemplateHaskell  #-}
import Control.Lens.TH
import Control.Lens
import Control.Applicative

import qualified Data.Sequence as S
import Data.Char (chr, ord)
import Data.Array
import Data.List (mapAccumR, mapAccumL)
import Control.Monad.State (lift, get, evalStateT, when, StateT(..))

mkCache cs mapAccumX bracketPush bracketPop = listArray (bounds cs) $ snd $ mapAccumX f [] $ assocs cs where
    f l (i, c)
        | c == bracketPush = (i : l, Nothing)
        | c == bracketPop = (tail l, Just $ head l)
        | otherwise = (l, Nothing)

cache arr i = case arr ! i of
    Nothing -> error $ "No matching bracket at offset " ++ show i
    Just idx -> idx

data M = M
    { _mTapePos :: Int
    , _mTape :: S.Seq Int
    , _mCodePos :: Int
    }

$(makeLenses ''M)

type LoopStateT a = StateT M IO a

mTapeAtPos f m = (mTape . ix (m ^. mTapePos)) f m

unsafeUse traversal = (^?! traversal) <$> get

execCode :: S.Seq Int -> Array Int Char -> IO ()
execCode ts cs = evalStateT loop (M 0 ts 0) where
    prev = mkCache cs mapAccumL '[' ']'
    next = mkCache cs mapAccumR ']' '['

    loop :: LoopStateT ()
    loop = do
        tapeAtPos <- unsafeUse mTapeAtPos
        codePos <- use mCodePos
        when (codePos /= snd (bounds cs)) $ do
            case cs ^?! ix codePos of
                '+' -> mTapeAtPos += 1
                '-' -> mTapeAtPos -= 1
                '>' -> mTapePos += 1
                '<' -> mTapePos -= 1
                '[' -> when (tapeAtPos == 0) (mCodePos %= cache next)
                ']' -> when (tapeAtPos /= 0) (mCodePos %= cache prev)
                '.' -> lift $ putChar $ chr tapeAtPos
                ',' -> do { c <- lift getChar; mTapeAtPos .= ord c }
                _ -> return ()
            mCodePos += 1
            loop

tape = S.fromList $ replicate 30000 0

csFromString file = listArray (0, length file - 1) file

main = readFile "example.bf" >>= execCode tape . csFromString


Well, firstly: "string".to_s is entirely redundant. That's already a String, so converting it again is just wasting your (processor's) time.

Secondly, writing if blocks with just one line and no else wastes a good deal of vertical real estate. I'd recommend that instead of

if condition
  statement
end

you should write

statement if condition

Ruby has unless as the opposite to if, and when you find yourself writing if !..., it's better to use unless ... instead. This is mostly because of convention -- Ruby programmers use unless a lot more, so it's quicker to parse.

As for shortening the method calls themselves, you could just pass strict: false in with the name, so each individual call becomes more like this:

db.create_collection('name', strict: false)

Then you don't need the condition at all.

Then, since you have three objects on which you want to perform the same action, you can put them in an array:

['reports', 'days', 'users']

(or use the fancier %w{ reports days users }, like I do below, but you'll want to read up on its gotchas first)

Then we can loop through that array:

%w{ reports days users }.each do |name|
  #...
end

And in place of #... we put the code to create the table:

db.create_collection(name, strict: false)

Or, if you don't want to rely on swallowing errors:

db.create_collection(name) unless db.collection_names.include?(name)

If we put that all together, it becomes this:

%w{ reports days users }.each do |name|
  db.create_collection(name) unless db.collection_names.include?(name)
end

Now, to add a collection, all you have to do is add it to the list. For example, if you wanted to add one called "years", add years in to the %w:

%w{ reports days users years }.each do |name|
  db.create_collection(name) unless db.collection_names.include?(name)
end


Minimise function with single minimum and no maximums

This is actually pretty functional.

The only thing I'd recommend is to avoid comparing floating-point numbers for exact match. Because arithmetic happens in binary, not in decimal, multiplying and dividing by nice-looking decimal numbers will produce ugly-looking binary ones, and more importantly, lose precision. As a result, depending on the input, your terminating condition may literally never become true - e.g. lmid may come out just a bit higher than lower at every step, and your function will recurse indefinitely.

The bottom line is, you can't trust direct comparison of floating-point numbers. Instead, compare their difference with a very small number (aka "margin of error"). But even then, you can't just use a constant for this, because you never know if it will be "small enough" for the inputs. The accepted way of doing this is to use a fraction of the inputs - aka "relative margin of error" (as opposed to "absolute").

 if x = y ...  // bad
 if abs (x-y) <= 0.00001 ... // better
 if abs (x-y) <= (abs x * 0.00001) ... // even better


The if statements could be cleaner:

    if ($("input:checkbox").length > 0 && $("input:checkbox:checked").length == 0)
    {
        shouldSubmit = false;
    }

    if ($("input:radio").length > 0 && $("input:radio:checked").length == 0)
    {
        shouldSubmit = false;
    }

    if (!shouldSubmit)
    {
        alert("All form fields must be filled out.");
    }


Using dependency injection for Node payment system

It looks good to me, very SOLID.

Here are a couple of suggestions:

I'm not really seeing the value in the PaymentRepository layer. If the Stripe wrapper is following a strict interface then just import it directly as your payment gateway i.e.

import PaymentGateway from './stripe';
...
charge(new PaymentGateway());

This still gives you the flexibility & testability but with one less layer. If you introduced a new payment gateway all that changes is the import e.g.

import PaymentGateway from './worldpay.js'

Also, you may have gone a bit overboard with your use of async / await. This code:

async x() {
  try {
    const result = await promise();
    return result;
  } catch (e) {
    throw e;
  }
}

Is effectively the same as:

x() {
  return promise();
}

Because you don't actually use the result (or error) until further up the callstack. Although having said that, you might want to consider deserializing your Stripe API responses to avoid leaking internal data through the layers.


Your Employee is frozen in time; they can never get any older!

Age should be calculated from date-of-birth and “today”, not stored in an immutable field.

The getCompanies() method could be written simply as:

return new ArrayList<>(this.companies);

Or perhaps:

return Collections.unmodifiableList(this.companies);


Matching whitespace and non-whitespace characters with RegEx

{1} is redundant, it's better to remove it.
When {2} follows a specific character,
it's is longer to type than the character itself twice,
so I would simply write the character twice.

/\S\S\s\S\S\s\S\S/

As Mike Brant pointed out, some duplication could be reduced by grouping:

/(\S\S\s){2}\S\S/

But this is not as clear as the first example, so I would stick with that.


Java recursive sort verification function for a linked list

I would like to add few improvements for better readability.

You don't need an else statement; rather you should directly return it.

For every if and else statement, even if it is a single line and Java allows it without braces, it's not preferable because of possible code bugs which may arise in future due to missing braces.

Better to put (this.value < this.next.value) in brackets for better readability.

So the updated code should look like:
public boolean isSorted() {
    if (this.next == null) {
        return true;
    }

    return (this.value < this.next.value) && this.next.isSorted();
}


Docstrings: You should include a docstring at the beginning of every method/class/module you write. This will help any documentation indentify what your code is supposed to do.
solve(): My biggest problem with this method was the beginning. You create eight different variables for your methods and total, then put them into a list. Instead of having these eight one time use variables, just set the default values inside the list. Since you don't work with any of the eight variables after putting them into the list, they are obsolete, so can be removed.
Variable/Parameter/Method Spacing: There shouldn't be spaces between the method name and the opening parentheses.
Parameter Reassignment: In unpack you have a passed parameter method. You then reassign that parameter to a variable string. This is very unnecessary. You have simply have the parameter string, so you're working directly with what is passed, instead of taking the time and trouble to reassign to a variable.
Use of global: It's not recommended to use global variables in python, or any language. This StackOverflow answer provides more insight.
Boolean Comparison: Instead of checking if variable == True, you can simply check the variable itself, like so: if variable:.
Unused Exceptions (as e): If you don't intend to work with an exception that you catch, it is unnecessary to have the extra code as e, since that will be a variable you never use. You can simply remove that code.
Unused Parameters: In solve, you never use the list_method=[] that is passed. You should remove any parameters you don't use, you risk adding complexity and reducing readability.
Constants Naming: Any constants in your code should be UPPERCASE, so make it clear to anyone reading your code, including yourself, that they are constant variables.
in list vs in [...]: You create a list of operators for the sole purpose of checking if an operator is in that list of operators. This is unnecessary. You can simplify your code by creating an anonymous list to check containment. This reduces the amount of variables in your code, increasing readability and reducing complexity.
if name == main guard: Any code that isn't contained in a method or class should be contained in a if __name__ == '__main__' guard. This will prevent any of that code from being executed if you decide to import the file, for other uses.
_ for unused variables: Your last line of code is a variable that allows the user to exit when they want, by pressing any key. You create a variable for this purpose alone. Since you never use this variable, and it's only used to exit the program, you can use a _, to make it clear that that variable is to be, essentially, ignored.

Updated Code

"""
Module Docstring:
Explanation of your code goes here
"""

import re

def unpack(string):
    """ Unpacks the passed `string` """
    list_sum = []
    list_special = []
    numbers = (re.findall(r"[\w']+", string))
    for char in string:
        if char in ["*", "+", "-", "/"]:
            list_special.append(char)

    for index in range(len(numbers) - 1):
        to_eval = numbers[index] + list_special[index] + numbers[index + 1]
        list_sum.append(f'{to_eval} = {eval(to_eval)}')
        numbers[index + 1] = str(eval(to_eval))

    return list_sum

def evaluate(method, running_sum):
    """ Evaluates the passed `method` """
    if eval(method) == TARGET:
        if method not in LIST_METHODS:
            LIST_METHODS.append(method)
            print(f'Eval: {method}')
            clear_status = True
        return True
    if running_sum == TARGET:
        if method not in LIST_METHODS:
            LIST_METHODS.append(method)
            print(f'Running sum: {unpack(method)}')
            clear_status = True
        return True
    clear_status = False
    return False

def new_total(total, item, operation):
    """ Determines the operator and returns the new total """
    if operation == "+":
        return total + item
    if operation == "-":
        return total - item
    if operation == "*":
        return total * item
    if operation == "/" and item != 0:
        return total / item
    return ""

def solve(array, total=0, method=""):
    """ Solves the passed numbers and target """
    if not array:
        return

    for index, item in enumerate(array):

        #Assign methods and totals to a list:
        methods = ["", "", "", ""]
        totals = [0, 0, 0, 0]
        str_func = ["+", "-", "*", "/"]

        #Create new array
        remaining = array[:index] + array[index+1:]

        #Sets new totals and new "methods"
        for index_1 in range(len(methods)):
            if method == "":
                if str_func[index_1] != "/" and str_func[index_1] != "*" and str_func[index_1] != "-":
                    methods[index_1] = str(array[index])
                    totals[index_1] = new_total(total, item, str_func[index_1])
            else:
                methods[index_1] = method + str_func[index_1] + str(array[index])
                totals[index_1] = new_total(total, item, str_func[index_1])

        #Evaluates each total and method
        for index_2, value_2 in enumerate(methods):
            try:
                if evaluate(value_2, totals[index_2]):
                    if clear_status:
                        methods[index_2] = ""
                        totals[index_2] = 0
                    return
            except Exception:
                pass

        #Recursively calculates next move
        for index_3, value_3 in enumerate(methods):
            try:
                solve(remaining, total=totals[index_3], method=value_3)
            except Exception:
                pass

if __name__ == '__main__':
    clear_status = None
    STR_ARRAY = input("Please enter the starting numbers, separated by commas: ")
    ARRAY = ARRAY = [int(item.strip()) for item in STR_ARRAY.split(",")]
    TARGET = int(input("Please enter a target value: "))
    print(f'Solutions for {ARRAY} to reach {TARGET}')
    LIST_METHODS = []
    solve(ARRAY)
    if LIST_METHODS == []:
        print("Unsolvable countdown problem")
    _ = input("Press any key to exit...")


First drafts of Ultima-like adventure code

Actually, I agree with Quentin. For a first effort, your code looks pretty good. You have a hero class called Erdrick and an Enemy class instantiated as a Slime.

A class structure like what I show below would allow you more flexibility with less repetition. See what you think...

You might want to work out some way for specialized weapons to increase the damage a hero deals and for armor to reduce the damage suffered.

class Character():
    def __init__(self, name, health, damage,
                 level=None, experience=None, equipment=None):
        self.name = name
        self.health = health
        self.damage = damage
        self.level = level or 1
        self.experience = experience or 0
        self.equipment = equipment or {}

    def strikes(self, other):
        other.health -= self.damage

    def alive(self):
        return 0 < self.health

class Hero(Character):
    level_thresholds = {10: 2, 30: 3, 60: 4, 100: 5}
    def grows(self):
        self.experience += 1
        curlev = self.level
        for thresh in level_thresholds:
            if thresh <= self.experience and self.level < level_thresholds[thresh]:
                self.level = level_thresholds[thresh]

        if curlev < self.level:
            print("{0} leveled up!".format(self.name))

class Monster(Character):
    ...

erdrick = Hero('Erdrick', 100, 2, equipment = {'Copper Sword': 3,
                                               'Leather Tunic': 3})
slime = Monster('Slimebot', 50, 3)
while erdrick.alive() and slime.alive():
    erdrick.strikes(slime)
    slime.strikes(erdrick)

if erdrick.alive():
    print("{0} has defeated the {1}!".format(erdrick.name, slime.name))
    erdrick.grows()
else:
    print("The {0} has killed {1}... );".format(slime.name, erdrick.name)


I have two comments.

First, what is the purpose of $current_key? Since you're not changing it, just use $key.

Second, by your usage, I'd say that

foreach ($haystack as $key => $item)
    if ($item["md5"] === $needle) return $key;
return false;

is quite enough. Of course, if the above was just an example and you really want to check all the values in (sub)arrays, then the above is O.K.

Of course, be careful when using this function, because key 0 may be interpreted as false.

A bit neater (but essentially the same) function was provided on Stack Overflow here. I like the additional $strict argument there (which you may or may not need).


Search suggestion box with jQuery and AJAX

You should ensure your spacing is consistent.
Since you're using a function expression rather than a declaration, you should terminate the line with a semicolon.
You aren't making any use of the request variable, so why even declare it?
You aren't taking advantage of method chaining. This is causing you to construct two jQuery objects for #search-box when you only need one.
You're right in that this is not the best way to handle it; consider returning JSON or XML.
You have a success callback but not an error callback. In this particular case I don't imagine it would be too bad (your search box will just remain hidden, presumably), but you may want to add one anyway.

Here's how I think your code could look.

var searchUser = function(searchQuery) {
    $.ajax({
        url: "search.php",
        type: "POST",
        data: { search: searchQuery },
        dataType: "json",
        success: function(response) {
            var resultList = response.reduce(function(accumulator, value) {
                return accumulator + "
" + value + "
";
            }, "
");
/* alternative for older browsers:
            var resultList = "
";
            $.each(response, function(index, element) {
                resultList += "
" + element + "
";
            });
*/
            resultList += "
";
            $("#search-box").html(resultList).show();
        },
        error: function() {
            $("#search-box").html("An error occurred. Search suggestions could not be loaded.");
        }
    });
};

search.php would then have to do something like:

$results = array("suggest", "suggestion", "suggested", "suggesting");
die(json_encode($results));


Calculation of next week number (constrained by max 3) with rollover

You can use the modulo operator to wrap around your week counter:

public int calculateNextWeek(int week, int day) {
    if (day == 3) {
        return (week % 3) + 1;
    }

    return week;
}


Headers and Names

You are using the system function that is declared in stdlib.h but you don't #include <stdlib.h>.
The name getline is already taken by many C implementations for an extension to the standard library's I/O functions. You shouldn't use it for your own function names.

Program structure
Your program basically consists of the main function. While simple it is, this is not a very modular design and in particular hostile to unit testing. I suggest you decouple the I/O logic from the tab expansion logic. Have one function read the input line-by-line and for each line it reads, make it call another function that processes the line and places the results in a separate buffer. It could look like this:
size_t
expand_tabs(int tabwidth, const char * input, char * output, size_t length);

The first function then outputs that buffer. This way you can, for example, unit test expand_tabs with an array of strings.
Don't put
system("pause");

in your programs.  I know many tutorials targeted at people using the Windows operating system suggest this but it is poor advice. If your program is done, make it exit. If this causes your terminal emulator to close the window before you wanted it to, fix the way you use the terminal emulator, not your program.
I/O Handling
Avoid character-based I/O.  It's slow and painful. Instead of your hand-rolled getline function, you could have used the standard library fgets function. From its man page:

Synopsis
#include <stdio.h>

char *fgets(char *s, int size, FILE *stream);

Description
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.  Reading stops after an EOF or a newline.  If a newline is read, it is stored into the buffer.  A terminating null byte ('\0') is stored after the last character in the buffer.
Return Value
fgets() returns s on success, and NULL on error or when end of file occurs while no characters have been read.

This is just what your getline function does but faster and cleaner.
Never use the seemingly simpler gets function.  It is broken and C11 removed it from the standard library.
While using stack-allocated buffers like
char line[MAXLINE];

is fast, the hard-coded limit is a little awkward. You actually took care to make your program process files with lines longer than MAXLINE correctly too. Congratulations for that. Another option would be to use a dynamically allocated buffer. If your implementation has it, the aforementioned getline function comes in handy, here. If you are following the book, I'm not sure if you've already learned about dynamic memory yet, though.
Style
While declaring functions as
int my_getline(char s[], int len);

is valid syntax, it is misleading because the first argument actually is a pointer and not an array.  So I prefer the (functionally equivalent)
int my_getline(char * s, int len);

syntax.
As long as you want to use MAXLINE to create an array, it needs to be a macro, unfortunately.  For TABSTOP there is no such need. Avoid macros if possible. Here, a static const int would have been perfectly fine. Note that in the expand_tabs function suggested above, I'm even passing it as a parameter so it doesn't depend on global constants. Of course, the constant has to be coded at some point in your program.


C function to fully consume a Python iterator

You’ve got an object leak.

PyObject_GetIter() returns a new instance, which you aren’t calling Py_DECREF() on.

If you pass in an iterable object to your function (a list, a tuple, a dictionary, etc), PyObject_GetIter() will return a brand new iterator over than object.  You test the return value, discover it is not NULL, and then lose the returned value, since it was not stored in a local variable.  Then, you try to retrieve tp_iternext from the iterable’s type, which is likely not defined, so chaos will ensue.

If you pass in an iterator object to your function, PyObject_GetIter() will return it, but also increment the reference count of that object by one.  At the end of your function, you don’t call Py_DECREF() on the returned iterator, so the reference count will remain incremented, and the iterator will never be released.

static PyObject *
consume(PyObject *self, PyObject *iterable)
{
    PyObject *(*iternext)(PyObject *);
    PyObject *item;
    PyObject *iterator;

    iterator = PyObject_GetIter(iterable);  // No references to iterable beyond this point.
    if (iterator == NULL)
        return NULL;

    iternext = *Py_TYPE(iterator)->tp_iternext;
    while ((item = iternext(iterator)) != NULL)
        Py_DECREF(item);

    Py_DECREF(iterator);

    if (PyErr_Occurred()) {
        if (PyErr_ExceptionMatches(PyExc_StopIteration))
            PyErr_Clear();
        else
            return NULL;
    }

    Py_RETURN_NONE;
}


200_success' comment is right, that the context and the content of the component is important for semantics. I assume, from the linked page, that you want to display a list of short articles that lead to more detailed information.

That being said. Let's look at your rewrite:

Outer section-element.

While a section might be fine, to me this looks more like a list of short articles. So I would use an article-element here.

  The article element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

From w3.org 4.4.4 The article element

Also interesting on Stackoverflow: Semantic HTML of an articles list

header-element

If you only have a heading-element and no other content for the the header of a sectioning-element, you should drop the extra header-element, as:

  These elements [h1 … h6] represent headings for their sections.

From w3.org 4.3.6 The h1, h2, h3, h4, h5, and h6 elements

Nested section-element

The paragraph is the actual content of this item. Its context is not a standalone section, as implied, when wrapping it in another section-element:

  The HTML  element represents a standalone section

From MDN
: The Generic Section element

So drop that section as well.

footer-element

Using a footer-element here is debatable (as all other points as well). From the docs point of view it's absolutely fine:

  A footer typically contains information about its section such as who wrote it, links to related documents, copyright data, and the like.

From w3.org 4.4.9 The footer element

However, personally I would drop it for simplicity.

Finally we remove everything that is not needed for styling – in regard of your linked layout – and end up with this:

Card heading

Some teaser …

    Learn more …


Parsing HTML knock-off for answering queries for values

It is good to see that you've avoided the use of using namespace std;.

Coding

Declare variables as close to their initial use as possible, and prefer construction of that initial value to default constructing an object then assigning the initial value.  lines and querrys can be declared when they are assigned:

auto lines = atoi(cin_buffer.c_str());
// ...
auto querrys = atoi(cin_buffer.c_str());

name can be declared where it is used.  strg_it can also be declared (in both places) as auto.  This can help the compiler improve the code by letting it know the value isn't needed after the erase call.

auto strg_it = remove_if( begin(cin_buffer), end(cin_buffer),
                    [](unsigned char c){return c=='<' || c=='>';});
cin_buffer.erase(strg_it, end(cin_buffer));

Alternatively, when using the erase-remove idiom, you can put the erase and remove in one statement

    cin_buffer.erase(remove_if( begin(cin_buffer), end(cin_buffer), [](unsigned char c){return c=='<' || c=='>';}), end(cin_buffer));

and not need the variable at all.

You have no error checking on your inputs.  You should check for failed input, non-integer conversions from atoi, etc.  One alternative (since you have a std::string) is to use std::stoi, which will throw an exception if there is an error during conversion.

cin_buffer.at(0) will throw with an empty string, and cin_buffer.at(1) will throw an exception if the string only has one character in it.

variables[name]=cin_buffer; will replace any existing value for name if one already exists.  This may be the expected behavior.

In your final search loop, store the result of find in a variable to avoid having to look it up again.

auto it = variables.find(cin_buffer);
if (it != end(variables)) {
    std::cout << it->second << `\n`;
} else

You should avoid using std::endl unless absolutely necessary.  Since it flushes the output, there can be a considerable performance hit when using it.

Readability

You should put more spaces in your code, rather than jamming all those characters together.  Put spaces around binary operators

for (int lines_processed = 0; lines_processed < lines; ++lines_processed) {

which also makes it clearer that lines_processed < lines is an expression and not part of a possible template lines_processed<lines>.

The parentheses around (scope.length()) are unnecessary.

Spelling is important.  Variable names should be spelled correctly to make it easier to read and easier to search for.  querrys should be spelled queries.


Project Euler Problem 18 (Haskell) - Maximum path sum I

I'll focus on maxPathSum as this is the core part of the algorithm.

The approach of zipWith max ys (tail ys) is correct and very nice, this is the essence of the recursive step.

But first, you're doing a lot of unnecessary computations at every step. In particular, you're reversing the argument list every time (reverse xs) and at the same time, you're computing its initial part (init . init $ xs), they're all O(n). If you instead start with an already reversed list, you can save all this effort, replacing O(n) init with O(1) tail, and O(n) ++ [...] with O(1) : ...:

maxPathSum2 :: [[Int]] -> Int
maxPathSum2 = mps . reverse
  where
    maxPairs ys = zipWith max ys $ tail ys
    mps [[x]] = x
    mps sx = mps $ (zipWith (+) (maxPairs (head sx)) (sx !! 1)) : (tail . tail) sx

Note that placing maxPairs out of mps also helps the readability as it's now clear nothing there depends on sx.

Next thing is that you're combining the intermediate results with the data structure you're processing. While conceptually it isn't incorrect, in this case it makes the algorithm harder to understand and more complex. So let's add a parameter to mps that will hold the intermediate path lengths (and initialize it with an infinite list of 0s):

maxPathSum3 :: [[Int]] -> Int
maxPathSum3 = mps (repeat 0) . reverse
  where
    maxPairs ys = zipWith max ys $ tail ys
    mps [r] [] = r
    mps rs (s:ss) = mps (zipWith (+) (maxPairs rs) s) ss

Not only this is much simpler;
notice that now we've just reinvented a fold over the list! We're consuming the list, passing the rest for further processing, and accumulating a result. Since we're consuming the elements from the start, this is a left fold. So let's rewrite it as

maxPathSum4 :: [[Int]] -> Int
maxPathSum4 = head . foldl f (repeat 0) . reverse
  where
    maxPairs ys = zipWith max ys $ tail ys
    f rs s = zipWith (+) (maxPairs rs) s

But left fold over a reversed list is just a right fold. So we get

maxPathSum5 :: [[Int]] -> Int
maxPathSum5 = head . foldr f (repeat 0)
  where
    maxPairs ys = zipWith max ys $ tail ys
    f s rs = zipWith (+) (maxPairs rs) s

And this is actually a very natural way how to express the solution: If we already know the longest paths in the part below a particular level (represented by rs and in recursive right-fold), we can compute the paths for this level as well.


AsyncTask which allows to handle exceptions on UI

First of all, a few notes:

ResultHolder<Result> can be a public static class.
This just feels wrong:

catch (Throwable e) {
    new ResultHolder<Result>(e);
    return null;
}

You should probably return that ResultHolder, shouldn't you?
Avoid @SuppressWarnings({"UnusedDeclaration"}). If you have a warning there, then find out why it is there and solve it. Don't mark it as ignored. Sometimes, marking warnings ignored this way is fine, I would never do it with an UnusedDeclaration warning though.

As for your question about the Throwable, you are right that it is not a good idea to use that there. You can solve this by wrapping the exception in another.

public class AsyncException extends Exception {
    public AsyncException(String message, Throwable cause) {
        super(message, cause);
    }
}

And then:

public abstract Result doInBackground(Params ... params) throws AsyncException;

public Result getResult() throws AsyncException {

private ResultHolder(AsyncException throwable) {

@Override
protected ResultHolder<Result> doInBackground(Params... params)  {
    try {
        return new ResultHolder<Result>(AsyncTaskWithThrowable.this.doInBackground(params));
    }
    catch (Exception e) {
        return new ResultHolder<Result>(new AsyncException("Error while performing doInBackground", e));
    }
}

Problem solved! Note that I changed to catching Exception instead of Throwable as Errors (throwables that are not exceptions) shouldn't really be caught, they are much more serious so they are meant to crash everything.


Rspec - testing basic functionality - redundant testing?

Doesn't this just check basic rails functionality?

Yes and no. Yes in the sense that if you run the scaffold command, and follow the usual RESTful conventions, then that's what you get. But that's not Rails; it's just your specific use/application of the Rails framework.

You could easily make a controller that doesn't have an index action. Or you could make a controller where the index action renders the edit template for some strange reason. And you tests would help you verify and/or avoid that, depending on your needs.

True, there'll be repetition across controllers, but repetition in tests not quite as concerning as repetition in your app code. But you can look at RSpec's"shared examples" if you want to share common specs.

Now, RSpec is about specifications, so when you write a test that checks whether a variable has been assigned, you're specifying and checking the contract between the controller and the view; the view will expect that variable to be there, so you ensure that the controller sets it.

Similarly, when you specify that expect(response).to render_template :show it's because that's what that action is supposed to do. Yes, it's usually ok to assume that the show action will render the show template - but it's not a law.

If you run rspec with the --format documentation option, what you'll see is a detailed explanation of what your code does - or is supposed to do, e.g.:

RestaurantsController
  GET #show
    assigns @restaurant
    renders :show

And yes, that's indeed what it's supposed to do. It's the conventional setup for a show action, so you might think "that goes without saying!". And yeah, it kinda does... if you indeed wrote it that way. Maybe there's a bug.

You current code looks fine by the way. A few notes though:

it "renders the :dailycious view" do
  expect(response).to render_template :index
end

Your spec says "renders the :dailycious view", but you're actually checking something else? If the idea is that the index template renders a partial called "dailycious" then you should check that in a view spec. Right now your spec is like asking someone "Did you remember to buy milk?", and the person answering "I went to the store". Well... good for you, but that doesn't answer the question.

Also,

GET #show
  it "assigns @restaurant"

This is just me being super-duper pedantic, but consider rewording that more like "assigns the requested Restaurant record as @restaurant". If you look at the "documentation" output above, all it just tells you that something's been assigned to @restaurant. Not what it is.
Admittedly, this is not a great example, since it's pretty clear already.  But being descriptive is a good habit to get into. Try to keep that "documentation" output in mind, and ask yourself if the spec your writing is sufficiently explanatory. Just imagine that every other part of the app is written by someone else entirely, and, besides yourself, that's who your specs are for. As though they're looking at the documentation output to learn how your code works.

On a practical note, you probably don't need to create 5 restaurant records when testing the index action. It's a good idea to create more than 1 record, to ensure that the controller does load multiple records, but you don't need more than 2 records to check that. FactoryGirl has a create_pair method you can use for just this sort of thing.


I can't quite figure out in which situation you would use approximatelyEqual() and in which essentiallyEqual(). and what the difference really should be.

I made some tests and overall it seems to work. I did though find the below strange behavior:

Testing with these two values:

    float a = 1.0f;
    float b = 1.0f + 1e-6f;

    Console.WriteLine($"a: {a:F15}");
    Console.WriteLine($"b: {b:F15}");
    Console.WriteLine($"a - b: {a - b:F15}");
    Console.WriteLine($"b - a: {b - a:F15}");
    Console.WriteLine();

    Console.WriteLine($"approximatelyEqual: {approximatelyEqual(a, b)}");
    Console.WriteLine($"essentiallyEqual: {essentiallyEqual(a, b)}");
    Console.WriteLine($"definitelyGreaterThan: {definitelyGreaterThan(a, b)}");
    Console.WriteLine($"definitelyLessThan: {definitelyLessThan(a, b)}");
    Console.WriteLine();
    Console.WriteLine($"HEquals: {HEquals(a, b)}");
    Console.WriteLine($"HGreaterThan: {HGreaterThan(a, b)}");
    Console.WriteLine($"HLessThan: {HLessThan(a, b)}");

I get the expected output:

a: 1.000000000000000
b: 1.000001000000000
a - b: -0.000000953674300
b - a: 0.000000953674300

approximatelyEqual: True
essentiallyEqual: True
definitelyGreaterThan: False
definitelyLessThan: False

HEquals: True
HGreaterThan: False
HLessThan: False

But if I try this:

    float a = 0.0f;
    float b = 1e-6f;

I get this:

a: 0.000000000000000
b: 0.000001000000000
a - b: -0.000001000000000
b - a: 0.000001000000000

approximatelyEqual: False
essentiallyEqual: False
definitelyGreaterThan: False
definitelyLessThan: True

HEquals: True
HGreaterThan: False
HLessThan: False

But I would have expected the same result?

The H-functions is my own naive implementations:

public static bool HEquals(float a, float b)
{
  return Math.Abs(a - b) < Accuracy;
}

public static bool HGreaterThan(float a, float b)
{
  return a - b >= Accuracy;
}

public static bool HLessThan(float a, float b)
{
  return a - b <= -Accuracy;
}

Disclaimer: I'm not using Unity3ds Mathf.Abs() but System.Math.Abs()


Is this Recursion + Linq example inefficient?

return featureWeightGroup.ChildGroups.Aggregate(Enumerable.Empty<IFeatureWeightGroup>(),
                                                    (allGroups, group) =>
                                                    allGroups.Concat(GetLeafGroupsRecursive(group)));

It looks like it can be replaced with:

return featureWeightGroup.ChildGroups
           .SelectMany(g => GetLeafGroupsRecursive(group));

Which probably will not be much better from performance point of view, but looks cleaner.


I would actually recommend you to use the (Constructor) Builder pattern if you are only doing this for easier object initialization:

public class RouteValueDictionaryBuilder
{
    private List<Tuple<string, object>> values_ = new List<Tuple<string, object>>();

    public RouteValueDictionaryBuilder WithValue(string key, object obj)
    {
        values_.Add(Tuple.Create(key, obj));
        return this;
    }

    public RouteValueDictionary Build()
    {
        var dict = new RouteValueDictionary();
        foreach (var value in values_)
        {
            dict.Add(value.Item1, value.Item2);
        }
        return dict;
    }
}

To use:

var dict = new RouteValueDictionaryBuilder()
    .WithValue("controller", "Home")
    .WithValue("action", "Index")
    .WithValue("id", 3)
    .Build();

This avoids the higher coupling (inheritance) between the dictionary and its subclass, which is there only to help with initializing the dictionary.


Ruby can be an extremely concise language, where your programs are almost already written for you:

def sum(array)
    array.inject(0, :+)
end

Where the docs say:

  inject { |memo, obj| block } → obj

  Combines all elements of enum by applying a binary operation,
  specified by a block or a symbol that names a method or operator.

In fact reading the docs can go a long way in shortening your programs.

Reading the docs for Array tells us that sorting is built-in and last (the twin of first) are too, also, we just wrote a handy sum function.

def max_2_sum(array)
    sum(array.sort.last(2))
end

This is slower than needed, that is O log n instead of O n but it may be optimized iff it becomes a performance bottleneck (improbable).

Your last function is indeed nice, but the assignment was not necessary and you did not use the handy built-in any?

def sum_to_n?(array, val)
    array.product(array).any? {|couple| sum(couple) == val}
end


You can start with how you code. Have them indented properly and checked by a quality-check tool. Code-review doesn't only deal with optimization, but also maintainability of your code and that includes making it readable.
After running it in JSHint, I found some minor problems in your code. Most notable are missing semi-colons. Although semi-colons in line endings are optional in JS, it's still best practice to include them. You could also avoid code packer/compressor errors by actually putting them in. This avoids your lines from being connected to the next line.
Use strict comparison as much as possible in JS. JS treats "falsy" values as false, which includes null, undefined, 0, false, a blank string and  NaN. For example, `"" == false is actually equal.
Place your code in a namespace, or some inner-scope to avoid polluting the global scope.

For code related stuff:

(function (ns, $) {
  "use strict"; //prevents "bad practice"

  //variables needed for localStorage test
  var storage, fail, uid;

  //For flexibility, it would be best if your code
  //wasn't build for a specific form only
  //instead, allow it to create instances and attach
  //to different forms with different default data
  function FormSave(selector, defaultValues) {
    this.defaultValues = defaultValues || {};
    this.dataName = selector;
    this.form = $(selector);
    this.userFields = $('.formFieldUserData', this.form);
  }

  //our save function
  FormSave.prototype.save = function () {

    var userData = {};

    //using the "early return" pattern to avoid further
    //code exectution if condition fails, and avoid
    //deep indentation
    if (!storage) {
      return;
    }

    //since each() assigns the current DOM element in
    //the collection as this, we can get name and value
    //directly from the DOM element, saving you function calls
    this.userFields.each(function () {
      userData[this.name] = this.value;
    });

    //set the items
    localStorage.setItem(this.dataName, JSON.stringify(userData));
  };

  //our setting function
  FormSave.prototype.set = function () {

    //cache the default values into this scope
    var defaultValues = this.defaultObject,
      retrievedValues;

    //if local storage is present, get and parse
    if (storage) {
      retrievedValues = JSON.parse(localStorage.getItem(this.dataName));
    }

    this.userFields.each(function () {

      //cache the current key
      var currentKey = this.name,
        //then the value to be used is:
        //if storage is present, use either the retrieved values or the default
        //if not, then use the present value or the default
        value = ((storage) ? retrievedValues[currentKey]: this.value) || defaultValues[currentKey];

      //for safe text insertion, use text() since it escapes the value first
      $("#" + currentKey + "Txt").text(value);
      $("#" + currentKey).val(value);
    });

    //our easy binding function exposed to our FormSave namespace
    ns.bind = function (selector) {
      return new FormSave(selector);
    };
  };

  //a quick test for localstorage
  //from: http://mathiasbynens.be/notes/localstorage-pattern
  try {
    uid = new Date();
    (storage = window.localStorage).setItem(uid, uid);
    fail = storage.getItem(uid) !== uid;
    storage.removeItem(uid);
    fail && (storage = false);
  } catch (e) {}

}(this.FormSave = this.FormSave || {}, jQuery));

//usage:

//bind this functionality to a form id'ed "someForm" with
//the given default values
var someForm = FormSave.bind('#someForm', {
  name: 'John',
  email: 'john@example.com',
  phone: '9999999999',
  desc: 'some description'
});

//then with the given reference, call save and set
someForm.save();
someForm.set();

When packed, it's this small!

(function (ns, $) {
  "use strict";
  var storage, fail, uid;

  function FormSave(selector, defaultValues) {
    this.defaultValues = defaultValues || {};
    this.dataName = selector;
    this.form = $(selector);
    this.userFields = $('.formFieldUserData', this.form)
  }
  FormSave.prototype.save = function () {
    var userData = {};
    if (!storage) {
      return
    }
    this.userFields.each(function () {
      userData[this.name] = this.value
    });
    localStorage.setItem(this.dataName, JSON.stringify(userData))
  };
  FormSave.prototype.set = function () {
    var defaultValues = this.defaultObject,
      retrievedValues;
    if (storage) {
      retrievedValues = JSON.parse(localStorage.getItem(this.dataName))
    }
    this.userFields.each(function () {
      var currentKey = this.name,
        value = ((storage) ? retrievedValues[currentKey] : this.value) || defaultValues[currentKey];
      $("#" + currentKey + "Txt").text(value);
      $("#" + currentKey).val(value)
    });
    ns.bind = function (selector) {
      return new FormSave(selector)
    }
  };
  try {
    uid = new Date();
    (storage = window.localStorage).setItem(uid, uid);
    fail = storage.getItem(uid) !== uid;
    storage.removeItem(uid);
    fail && (storage = false)
  } catch (e) {}
}(this.FormSave = this.FormSave || {}, jQuery));


Unlike Java Lists, C# lists can be pre-initialized with values, like this:

List<string> names = new List<string>()
{
    "arco01_2_prefab",
    ...
};

This eliminates the need to call .Add, and improves code readability as well.

In the future as well, if you ever plan to add more buildings, it'll be a pain to edit this script to include the new building names. Instead, you could declare a public variable which allows you to drag and drop the model prefabs instead:

public List<GameObject> buildings;

This also eliminates the need to call Resources.Load.

In addition, the namespace UnityEngine provides a class Random which can be used over the default System.Random. Unlike System.Random, UnityEngine.Random is a static class doesn't need to be instantiated, and you can just call Random.Range like this:

int randomNumber = (int)Random.Range(0, names.Count);

Other than that, there are just a few things I want to nitpick.

You don't need to call Instantiate from the GameObject class. It can just be called with out the GameObject. prefix.
In addition, the accepted Unity style for storing an instantiated GameObject is like this:

GameObject gameObject = Instantiate( ... ) as GameObject;

If you're feeling up to dynamic typing, this also works as well (Thanks @Kroltan):

var gameObject = Instantiate( ... ) as GameObject;

You can also remove the Update function. It doesn't do anything, and can decrease performance, due to the fact that it's running many times per frame.
The general style for braces in C# is to put them on the next line, not like Java braces.
You aren't using System.Collections, so you can remove the using System.Collections;.


There's nothing wrong with what you're doing... well, not as such.
I would, however, like to stress that methods do not echo. If an exception is thrown, and all you do is catch it to echo the message, then the loop (and the rest of the code) will continue to be executed as if everything was fine.

However, you don't know if there is any code to come that will attempt to set the header(), or set a cookie or something. That code will then break (because echo has sent output to the client). This will result in lots of errors popping up all over the place, and will leave you puzzled as to what actually is the piece of code where all evil begins.

If an exception is thrown, the calling code must be notified. Let it fly, and let the registered handlers deal with it, or let the app crash.

Next: DRY (do not repeat yourself). While there is little repetition in your code, there is this one tiny block that I'd like to focus on:

if (method_exists($geolocation, "set" . ucfirst($keyName))) {
    call_user_func(array($geolocation, "set" . ucfirst($keyName)), $keyValue);
}

Within the if statement, you're calling ucfirst and concatenating a new string. Only to repeat the same function call + concatenation if the expression evaluates to true.
The way you call the method is questionable, too. call_user_func is, again, a function call that will only forward to a method call. I'd simply write the code like so:

$setter = 'set'.ucfirst($keyName);//create setter name
if (method_exists($geolocation, $setter))
{
    $geolocation->{$setter}($keyValue);//invoke method directly
}

That, to my eye, looks a lot cleaner.

More general issue
A more general issue I have with this code, is where and how you are calling these setters. What you're basically doing is constructing a new instance, and setting its properties.
It might happen that you want to set the properties of an instance that already exists, too. I, therefore, tend to create a bulk-setter on the model itself.
Because json_decode returns (on success) either an associative array or an instance of stdClass, and because both are iterable, you could add a method like this to your models:

function setByJSON($jsonData)
{
    foreach ($jsonData as $name => $val)
    {
        $setter = 'set'.ucfirst($name);
        if (method_exists($this, $setter))
            $this->{$setter}($val);
    }
    return $this;
}

This is just a basic example, though. But as luck would have it, I have an actual, real-life example of models that do exactly what you're trying to do: extract data out of the parsed json, and map the properties to their own setters. check out the setAll method of this class as an example.

The entire wrapper is still under development, though, but the models are quite handy already. Oh, and if you are fed up with creating all those pesky models for json data, check out the entire repo: the Freshdesk\Tool\Generator generates a class, complete with getters and setters for each property, and adds type-hints where possible.


Overall it looks like you have created a clean and simple piece of code there. I still have some suggestions for you:

Nitpicks:

Your indentation could use  some rethinking. By convention everything in curly braces is indented by one level (4 spaces / 1 tab). Your class body isn't indented "properly"
Your Prefix tree could use some eager initialization. Your constructor is completely superfluous if you just declare your fields (which should be private, btw.) like the following:

public class PrefixTree {
    // isLeaf [...]
    private boolean isLeaf = false;
    private Map<Character, PrefixTree> map = new HashMap<>();

I have additionally changed the type of map to a Map (which is an interface) instead of HashMap. The advantage of that is: you can change the map implementation at any time you like.

Comments:

Your comments are overall clear and simple. They explain the why and the what though, which is not desirable for comments IMO. Comments in code should be explaining why some decisions were made. The code should be clean enough that the why is obvious.

Also there is a huge load of spelling mistakes in the comments. These mean additional mental strain, because the reader has to decode the actual word from the sentence context.

Additionally I see that many of your methods are commented wrt what they do. You should definitely use javadoc for that. It allows you to document methods (and their purpose) in a way readable to both the programmer and easily usable by IDEs:

/**
 * Insert a new word into the tree
 *
 * @param s The word to be inserted
 */
public void put(String s) {

Scoping:

As mentioned in a sidenot earlier on in the nitpicks: Your fields should be private. I'd even go so far to say that map should also be final.

Additionally you are exposing a helper function (travelTree) to the public. IMO that method should definitely be private.

Your concerns:

Have you settled for the correct data structures?
To me this one looks like a yes. Good job on chosing a map to represent the character choices at each tree node.

But there is one big problem I have with the Type you're assuming to be used with the tree, namely String. While a String is rather "universal" I'd rather see you using CharSequence which is a superclass of String. It also exposes .length() and .charAt() methods. Only your call to .substring()  would have to be changed to .subsequence(1, len - 1)
Is this a scalable solution? What kind of problems can I run into if this is a huge tree?
Well it's rather simple. This solution is quite scalable, mostly since you're really effective with the memory you're using and since traversing the tree is mostly following pointers in a HashMap. What you have to expect though for large trees is extremely large memory consumption (unsurprisingly) and increased traversal times.

You currently have no way of shortcutting a traversal through a solitary branch with a "long" word like "Xylophone". This means you might be "wasting" some time in traversal.

Summa Summarum:

The code is clean and relatively simple. There is minor violations of java conventions all over the place, comments have too many spelling errors, but your choice of data structure is a good one.

Overall: Well done, but you can do better ;)