A very interesting question. I can identify two main differences between your implementation (using variadic templates) and the linked article's implementation (using Boost.Fusion):

The definition of function composition. A call to your make_composite_function(f1, f2, f3)(x) is semantically equivalent to f1(f2(f3(x))). Calling the linked article's compose(f1, f2, f3) is semantically equivalent to f3(f2(f1(x))).

Which definition is more natural is completely up to the reader. Both are perfectly valid. Your make_composite_function has the nice property that it is very easy to implement with variadic templates (since the recursion uses "pop front" logic). This is actually mentioned as an alternative in the linked article.

Furthermore, they argue for their definition of function composition because it follows the reading direction. E.g., compose(receive, decode, store)(data) is semantically equivalent to store(decode(receive(data))) which follows the expected behaviour of first receiving data, then decoding it, and finally storing it. To get the same semantics with your definition, we would have to write make_composite_function(store, decode, receive). Again, this does the same thing but is arguably harder to decipher during a cursory read-through.

Alas, the linked article goes through a world of trouble to get that "pop back" recursion logic to work (using Boost.Fusion). So they do as they do not because they are oblivious of variadic templates but because variadic recursion simply doesn't cut it. Here's a quote from the article:

  Variadic templates unfortunately work in a "pop front" logic, making the code actually much less straightforward (because these unintelligible recursive preprocessor macros are obviously mundane). You could nevertheless write a pop front variadic template version with an adapter that reverses the list of parameters.

Note the proposed alternative implementation using a reversion adaptor. That would be a nice C++ exercise. I wonder how that would compare complexity-wise.
The linked article's implementation supports std::tuple arguments such as compose(std::make_tuple(f1, f2, f3)). Yours don't. Of course, this adds extra complexity to their implementation compared to yours. There's not much more to say on this point.

To sum up, the difference in complexity is because you seek different interfaces. Both interfaces are valid and work. Which one is more natural depends on the application.

Edit: Here is a code sample of your version. Note that I just use auto return type deduction (as you suggested yourself in the code comment).


`Maybe` handling in Matrix manipulation in Elm

I like your code a lot more than the original! It is definitely cleaner and more obvious than the first example you gave. However, there still seems to be a process you’re repeating — get value from array, pattern match on it, update array — that you can still factor out. (The original code is guilty of this, too.)

I tried to rewrite your function in a matter that avoids this, and my code’s at the bottom; see if you find it more readable. But first, some stylistic advice on writing Elm:

Generally, instead of writing things like Array.Array, it's useful to expose the type name from the data structure package you're using. Also, type parameters don’t need parentheses around them (except for grouping).

So you can rewrite:

type alias Board = Array.Array (Array.Array (Slot))

to

import Array exposing (Array)

type alias Board = Array (Array Slot)

which I think is a bit more Elm-y.
A useful design guideline (for packages, but  it’s a good idea for code in general): the data structure is always the last argument. You’ve reordered them from your first example, but the original order was there for a good reason: if your types look like

f : (extra params) -> Container -> Container

you can partially apply your function and end up with:

f "extra" "arguments" : Container -> Container

which is very useful for function composition and piping: often you want to take a Container and pipe it through a bunch of Container -> Container functions, like so:

result =
    initialContainerValue
    |> f "hello" "world"
    |> someOtherStep
    |> f "oak" "fir"

The Elm style guide contains some more recommendations that could apply to your code, but they’re more subjective. The two big ones I could think of have to do with whitespace.

Always have 2 empty lines between top-level declarations.
The examples in the guide have single empty lines between case branches, too.

My version

{-| Apply a function at the given index in the array.

     applyAt 2 negate (fromList [50, 60, 70]) == fromList [50, 60, -70]
-}
applyAt : Int -> (a -> a) -> Array a -> Array a
applyAt i f array =
    case Array.get i array of
        Nothing ->
            array

        Just a ->
            Array.set i (f a) array

{-| Update a slot: the given player occupies it, but only if it's empty. -}
setSlot : Player -> Slot -> Slot
setSlot player slot =
    case slot of
        Empty ->
            PlayedBy player

        s ->
            s

{-| Update a slot somewhere in a board. -}
setPosition : Position -> Player -> Board -> Board
setPosition (row, column) player =
    applyAt row
        (applyAt column
            (setSlot player))


Let's address your questions:

I don't think that storing the calculated values in public properties is a good idea, mainly because If I call calculateValuesWithMonthlyRevenue with say, 1000, and then afterwards call calculateYourPay with 400, the other properties don't change to reflect my different monthly revenue. Therefore, I'm not sure why these should be stored as properties at all. I would eliminate calculateValuesWithMonthlyRevenue, and make this class a singleton with only static methods.
In most cases, static constants are written in ALLCAPS or ALL_CAP, depending on your prefered style. I would define these in your header file (if you want these values to be public) or in your implementation file (if you want the values to be private) with #define instead, but that's a matter of personally preference.
You don't show us what you do with this delegate method, so I can't exactly be sure what the point of it is. I would omit it for now.
Using floats is a bit dangerous as it lends itself to annoying floating-point errors such as .3 turning into .299999999. This is really a question of desired precision. If you're fine with being off by a bit, then floats are pretty decent. If not, you will have to define your own type to represent money.


Formatting dates

Simpler way to produce your required the formats is using the strftime symbols, for example:

# yesterday's date in format ddmmyyyy (e.g. 08122016)
strDate = '{:%d%m%Y}'.format(d - timedelta(1))

# yesterday's date in format yymmdd (e.g 161208)
DateStr = '{:%y%m%d}'.format(d - timedelta(1))

Formattings dates to use in filenames

I would strongly discourage using any of these formats in filenames.
Consider adopting the yyyymmdd format instead.
The good thing about this format is that the alphabetic ordering is the same as chronological ordering,
which is often very practical.

String conversions

The format function of a string returns a string.
So the second line here is unnecessary:

strDate = '{d.year}{d.month:02}{d.day:02}'.format(d=datetime.datetime.now()- timedelta(1))
strDate = str(strDate)

String concatenation

String concatenation like this is not recommended:

fpath = strDate + "_" + str(day)  + "_" +  str(week) + ".zip"

Better use the format function:

fpath = '{}_{}_{}.zip'.format(strDate, day, week)

Other Python conventions

The strDate and DateStr variable names go against the recommended naming convention.
I suggest to read PEP8, it explains this and other recommendations to follow.


The very first thing we need to do is fix the indentation. If we can't read the code, we can't make it better. Everything inside of Sub...End Sub should be one level in. Add another level when you enter an If, For, For Each, or Select.

Sub Foo

    ' some code

    Set colSF = GetSubFolders(CSVfolder)
    For Each vFile In colSF
        fname = Dir(CSVfolder & vFile & "\" & "*.csv")
        Do While fname <> ""
            bHadFiles = True
            Application.ScreenUpdating = False
            Set wBook = Workbooks.Open(CSVfolder & vFile & "\" & fname, Format:=6, Delimiter:=",")
            wBook.SaveAs CSVfolder & vFile & "\" & Replace(fname, ".csv", ""), xlOpenXMLWorkbook
            Application.CutCopyMode = False
            wBook.Close False
            fname = Dir()
        Loop
        If bHadFiles Then Kill CSVfolder & vFile & "\" & "*.csv"
    Next

    ' more code

End Sub

You had the right idea with the loop. A loop will definitely clean this up immensely, but before we get to a loop, first let's extract a method to remove the duplication.

Private Sub CommandButton1_Click()
    Application.ScreenUpdating = False

    Dim CSVfolder As String, CSVfolder1 As String, CSVfolder2 As String
    CSVfolder = "C:\Charts\1\"
    CSVfolder1 = "C:\Charts\2\"
    CSVfolder2 = "C:\Charts\3\"

    TransformFile CSVfolder
    TransformFile CSVfolder1
    TransformFile CSVfolder2

    Application.ScreenUpdating = True
End Sub

Private Sub TransformFile(ByVal CSVfolder As String)
    Dim fname As String
    Dim vFile
    Dim colSF As Collection
    Dim wBook As Workbook

    Set colSF = GetSubFolders(CSVfolder)
    For Each vFile In colSF
        fname = Dir(CSVfolder & vFile & "\" & "*.csv")
        Do While fname <> ""
            bHadFiles = True
            Set wBook = Workbooks.Open(CSVfolder & vFile & "\" & fname, Format:=6, Delimiter:=",")
            wBook.SaveAs CSVfolder & vFile & "\" & Replace(fname, ".csv", ""), xlOpenXMLWorkbook
            Application.CutCopyMode = False
            wBook.Close False
            fname = Dir()
        Loop
        If bHadFiles Then Kill CSVfolder & vFile & "\" & "*.csv"
    Next
End Sub

Note that all I did was move the code into it's own method and call it appropriately. There's still no loop, but now moving to a loop is both trivial and almost unnecessary. We like clean code around here though, so let's go ahead and do that.

Private Sub CommandButton1_Click()
    Application.ScreenUpdating = False

    Dim folders As New Collection
    folders.Add "1"
    folders.Add "2"
    folders.Add "3"

    'must be a variant in order to loop over a string collection
    'using a string array instead of a collection is another good option
    Dim CSVFolder As Variant
    For Each CSVFolder In folders
        TransformFile CSVFolder
    Next

    Application.ScreenUpdating = True
End Sub

I noticed you have this is a code behind, you may want to move this code to it's own module or class and call it from the click handler. That way your logic isn't bound up in the GUI where it can't be re-used. The only other thing to mention here is that if you're turning the screen updating off, then you must use an error handler to ensure that it always gets turned back on.

But we're not done yet, we extracted that method out, but left our mess hidden away in there. Let's clean it up too.

Private Sub TransformFile(ByVal CSVFolder As String)
    Dim fname As String
    Dim vFile
    Dim colSF As Collection
    Dim wBook As Workbook

    Set colSF = GetSubFolders(CSVFolder)
    For Each vFile In colSF
        fname = Dir(CSVFolder & vFile & "\" & "*.csv")
        Do While fname <> ""
            bHadFiles = True
            Application.ScreenUpdating = False
            Set wBook = Workbooks.Open(CSVFolder & vFile & "\" & fname, Format:=6, Delimiter:=",")
            wBook.SaveAs CSVFolder & vFile & "\" & Replace(fname, ".csv", ""), xlOpenXMLWorkbook
            Application.CutCopyMode = False
            wBook.Close False
            fname = Dir()
        Loop
        If bHadFiles Then Kill CSVFolder & vFile & "\" & "*.csv"
    Next
End Sub

How many times do you need to concatenate this path together?

CSVFolder & vFile & "\" & "*.csv"

Yikes! Do it once before you enter the while loop.

For Each vFile In colSF

    filePath = CSVFolder & vFile & "\"

    fname = Dir(filePath & "*.csv")
    Do While fname <> ""
        bHadFiles = True
        Set wBook = Workbooks.Open(filePath & fname, Format:=6, Delimiter:=",")
        wBook.SaveAs filePath & Replace(fname, ".csv", ""), xlOpenXMLWorkbook
        Application.CutCopyMode = False
        wBook.Close False
        fname = Dir()
    Loop
    If bHadFiles Then Kill filePath & "*.csv"
Next

No offense, but WTF is colSF? It's a collection of folder names, right? Then just call it that. While we're at it, burn the hungarian notation. The name hadFiles already tells us that it's a boolean. I'm also going to add some vertical white space to group related actions together. Oh, and I'm going to remove Application.CutCopyMode = False. I seriously have no idea what it's doing here. It's not doing anything important at least.

Private Sub TransformFile(ByVal CSVFolder As String)
    Dim filename As String
    Dim vFile As Variant
    Dim folderNames As Collection
    Dim wBook As Workbook
    Dim hadFiles As Boolean
    Dim filePath As String

    Set folderNames = GetSubFolders(CSVFolder)
    For Each vFile In folderNames

        filePath = CSVFolder & vFile & "\"

        filename = Dir(filePath & "*.csv")
        Do While filename <> ""
            hadFiles = True

            Set wBook = Workbooks.Open(filePath & filename, Format:=6, Delimiter:=",")
            wBook.SaveAs filePath & Replace(filename, ".csv", ""), xlOpenXMLWorkbook
            wBook.Close False

            filename = Dir()
        Loop

        If hadFiles Then Kill filePath & "*.csv"
    Next
End Sub

In general, don't oneline If statements. It makes them hard to visually parse. This is doubly important on lines of code that Kill files.

If hadFiles Then
    Kill filePath & "*.csv"
End If

Things are getting better, but there's still a lot of variables. We can remove one by leaning on the face that colSF (i.e. folderNames) is never used as anything but an iterator.

    Set folderNames = GetSubFolders(CSVFolder)
    For Each vFile In folderNames

Becomes

    For Each vFile In GetSubFolders(CSVFolder)

Don't worry about the function getting called repeatedly, it won't. It executes once and then we're iterating over the collection that it returned.

Here's the code I ended up with. It's probably not getting much simpler unless you switch to the more powerful FileSystemObject in the Scripting Runtime. I encourage you to take a look at what's available there and leave it as an exercise for you to implement this using it instead.

Private Sub CommandButton1_Click()
    Application.ScreenUpdating = False
    Const rootFolder As String = "C:\Charts\"

    Dim folders As New Collection
    folders.Add "1"
    folders.Add "2"
    folders.Add "3"

    Dim CSVFolder As Variant 'must be a variant in order to loop over a string collection
    For Each CSVFolder In folders
        TransformFile rootFolder & CSVFolder & "\"
    Next

    Application.ScreenUpdating = True
End Sub

Private Sub TransformFile(ByVal CSVFolder As String)
    Dim filename As String
    Dim vFile As Variant
    Dim wBook As Workbook
    Dim hadFiles As Boolean
    Dim filePath As String

    For Each vFile In GetSubFolders(CSVFolder)

        filePath = CSVFolder & vFile & "\"

        filename = Dir(filePath & "*.csv")
        Do While filename <> ""
            hadFiles = True

            Set wBook = Workbooks.Open(filePath & filename, Format:=6, Delimiter:=",")
            wBook.SaveAs filePath & Replace(filename, ".csv", ""), xlOpenXMLWorkbook
            wBook.Close False

            filename = Dir()
        Loop

        If hadFiles Then
            Kill filePath & "*.csv"
        End If
    Next
End Sub


A partition algorithm for positive integers

Yes, more efficient algorithms do exist.

\$O(n*\log(n))\$:

Let's fix the end of the first part. Now we are interested in finding the end of the second one. I claim that we need to check only two candidates: the last index such that the sum of the second part is not greater then the sum of the third part and the one immediately after it (I will not post a formal proof here, but intuitively it is clear that we want keep these two sums as close to each other as possible.
To do it in efficient manner, we can use a binary search and prefix sums:

// Returns the sum of the [left, right] subarray in O(1) time.
int getSum(int left, int right)
    // Prefix sums are used here.
    ...

// Checks if the current answer is better than the current best
// and makes appropriate updates.
void updateAnswer(int firstEnd, int secondEnd)
    ...

// Corner cases are ignored here.
// This piece of code just represents an idea of the algorithm, it can
// contain bugs.
for (int first <- 0 ... n - 1)
    int low = first
    int high = n - 1
    while (high - low > 1)
        int mid = (low + high) / 2
        if (getSum(first + 1, mid) <= getSum(mid + 1, n - 1))
            low = mid
        else
            high = mid
    updateAnswer(first, low)
    updateAnswer(first, low + 1)

Now we can use the following observation: when the first variable increases in the code above, the low value either increases or stays the same, too. That's why we can apply two pointers technique and get an \$O(n)\$ time complexity.


Computing the item price and vat for a given pricing, order, and exchange rate

As a general rule it is best not to nest comprehensions. It makes code hard to read. You are better off just writing a for loop and appending the results to a list or using a generator.
Here are a couple rules with comprehensions that will make your code less brittle and easy for others to work with:

Don't nest comprehensions.
If a comprehension is too long for one line of code, don't use it.
If you need an else, don't use a comprehension.

Of course there are exceptions to these rules, but they are a good place to start.
One of the reasons nested list comprehension is an issue is it often results in a exponential increase in computation needed. For each item in the order you have to loop through every product. This is not efficient. You want to go from O(n x m) to O(n + m). You should loop through products once and through order items once.
You can see in the updated code below that I loop through the list of products and create a dictionary with the key as the product ID. This makes it so that, while looping through the order items, I can simply get the product by looking up the key. It is much more performant and readable.
pricing = {
    "prices": [
        {"product_id": 1, "price": 599, "vat_band": "standard"},
        {"product_id": 2, "price": 250, "vat_band": "zero"},
        {"product_id": 3, "price": 250, "vat_band": "zero"},
    ],
    "vat_bands": {"standard": 0.2, "zero": 0},
}
order = {
    "order": {
        "id": 12,
        "items": [{"product_id": 1, "quantity": 1}, {"product_id": 2, "quantity": 5}],
    }
}
exchange_rate = 1.1

def calculate_exchange_rate(price, rate=None):
    if rate is None:
        rate = exchange_rate
    return round(price * rate, 2)

def items():
    """
    computes the item price and vat for a given pricing, order, and exchange rate.
    returns list of items dictionaries
    """
    item_list = []
    products = {p["product_id"]: p for p in pricing["prices"]}

    for item in order["order"]["items"]:
        product = products.get(item["product_id"])
        vat = 0
        if product["vat_band"] == "standard":
            vat = pricing["vat_bands"]["standard"] * product["price"]
        item_list.append(
            {
                "product_id": item["product_id"],
                "quantity": item["quantity"],
                "price": calculate_exchange_rate(product["price"]),
                "vat": calculate_exchange_rate(vat),
            }
        )
    return item_list

print(items())


Switch an image based on click coordinate

Overly complex

The code you have is overyly complex

Some issues

Don't use classes to locate single items.

If you wish to identify single elements use the id property to create a unique name and use that to locate and element.

Don't define what is not needed.

At the beginning of your function you define each image's src but the function will only ever use one of them. Rather than define them all set the src in the individual condition blocks. The same with var main_image = $(this); there is no reason you need to do this, just use the reference $(this) or better yet this. You don't have to wrap it in jQuery's code if not needed.

Don't mix and match naming styles.

You name a variable using snake_case in one spot then in others you use camelCase. Not that it affects your code, but later when you need to recall a variable, you remember it by its name, if you mix and match, can you be sure you remember if it is snake_case or camelCase.

Use the one style (camelCase) as that is what JavaScript uses and you will never have to guess, or look up what style a variable used.

Use else

If you have a set of mutually exclusive conditional statement you should use else. Only one of the conditions will pass so there is no need to test other conditions if one has passed. Also as at least one condition has to pass the last else need not have the if statement it is the last and only option left so it must pass.

Use constants if a variable will not change.

var foo = "data" the variable foo can be assigned a new value which is all good if that is the intention. But many time you assign a variable a value only once. If you at some stage accidentally assign that variable a value due to a typo in the source code, you may spend hours, days even looking for the problem, as where the problems occur may not be where the problem starts. And worse, you may not spot the problem due to lack of testing until your code is out there.

const foo = "data" This tells Javascript that the variable foo is a constant and will never change. If you try to change it (via typo in source code) Javascript will throw an error, letting you detect the problem and direct you to the location of the problem. You can fix it there and then saving a lot of time and effort.

Though it is not a major point in this example, using the correct variable type in every situation helps build good habits.

Don't repeat

Modern languages came from a need to keep lazy programmers happy. There is nothing worse than having to repeat the same code over and over. For you typing it, it means you are more likely to make a mistake, it means it takes longer to get a result, and it means (mostly but not always) your code will take longer to run. The worst bit about repeating code is when you have to change it.

You have the variables width and height and for each test you do the same thing offsetX < width / 2, repeating the same code.

Do it once const halfWidth = $(this).width() / 2; event better do the width test only once const leftClicked = (e.pageX - offset.left) < ($(this).width() / 2);

Rewrite of your code.

// Note for lines assigning leftClicked, rightClicked
// I use (...) to wrap expressions though not needed,
// it is good habit to do so for readability
$(".main-image").click(function(e) {
    const images = $(this).siblings(".single-page-image");
    const offset = $(this).offset();
    const leftClicked = (e.pageX - offset.left) < ($(this).width() / 2);
    const topClicked = (e.pageY - offset.top) < ($(this).height() / 2);
    var imageIndex = 2; // default image index for bottom right
    if (topClicked){
        if (leftClicked) {
            imageIndex = 0;
        } else {
            imageIndex = 3;
        }
    } else if (leftClicked) {
        imageIndex = 1;
    }
    $(this).attr("src", images.eq(imageIndex).attr("src"));
});

Is there a better way?

It is often better to embed as much context / semantic specific information in the page.

In this example you could have used a map element to define the click areas and used Javascript just to change the image src.

Example

The example shows it done with minimum required code. I know that the sandboxed page is completely under my control and can thus reliably use directly referenced elements to add functionality. It is done without jQuery to keep it simple.

imageMap.addEventListener("click", (e) => {
  mainImage.src = window[e.target.dataset.imageId].src;
});
.hide { display: none; }
<map id="imageMap" name="imageAreas">
  <area shape="rectangle" coords="0,0,200,200" title="One" data-image-id = "image1"/>
  <area shape="rectangle" coords="200,0,400,200" title="Two"  data-image-id = "image2"/>
  <area shape="rectangle" coords="0,200,200,400" title="Three"  data-image-id = "image3"/>
  <area shape="rectangle" coords="200,200,400,400" title="Four"  data-image-id = "image4"/>
</map>

A word about jQuery

A word of warning. JQuery is a popular library, and in its day was a good solution to the problem of cross browser compatibility, and has some relevance today (dam IE11). Unfortunately it has produced a generation of front end coders that are unable to use the DOM directly. As a beginner you are training your self for the future, jQuery is struggling to stay relevant now. Don`t invest precious time where you don't need to. The step from vanilla to JQuery is a lot easier than the other way around, so be careful where you invest your time.


!empty() check before a foreach statement

The loop won't be executed if $terms is false/null/an empty array.

As such: you don't need the empty check. It doesn't hurt, but it's simply not required.

If $terms is sometimes not an array

You can just cast it to an array before use:

$terms = get_the_terms( $postid, 'fecha' );
foreach((array) $terms as $term) {
    $myterm = $term->slug;
    if(in_array($myterm, $queried_terms)) {
        continue;
    }
    $queried_terms[] = $myterm;
}

The code would work with or without casting to an array - the only difference is that if $terms is not an array, a notice would be thrown without it.

if this is part of another function

you can simply return-early to keep your code concise:

function foo() {
    $terms = get_the_terms( $postid, 'fecha' );
    if (!$terms) {
        return array();
    }

    $queried_terms = array();
    foreach($terms as $term) {
        $myterm = $term->slug;
        if(in_array($myterm, $queried_terms)) {
            continue;
        }
        $queried_terms[] = $myterm;
    }
    return $queried_terms;
}

But, any way you slice it - the empty check isn't strictly required, and deeper code nesting is something to be aware of and avoid.


In this example, your code is used as the starting point. I moved the logic
around a bit -- notably, separating things into other functions -- and
suggested various other changes for you to consider.
# Except for special reasons, put all imports at the top.
import math
import sys

# Put almost all code inside functions.

def main(args):

    # When feasible, use variable names that sound like ordinary English (eg,
    # inputs) rather than awkward computer-science-like names (eg,
    # list_of_inputs). Similarly, if a variable holds one thing, use a singular
    # variable name (eg, num, book, or x). And if the variable holds a
    # collection of things, use plural (eg, nums, books, or xs).

    # Also, list/set/dict comprehensions can often make code easier to
    # understand, especially when they are fairly short.

    # For scripts like this, it's often useful to allow the possibility for
    # command-line arguments.

    if args:
        nums = [int(a) for a in args]
    else:
        # Provide users at least some minimal guidance.
        prompt = 'Integer: '
        nums = [int(input(prompt)) for _ in range(5)]

    # Computing the number with the most divisors is pure mathematical
    # algorithm: keep it that way. The function should do its work and return a
    # value. Do the printing elsewhere -- for example, in main().

    # By default, print() takes a list of values and prints them
    # separated by spaces. If that's all you need, there's
    # no reason to use a format string.

    num, n_divisors = find_integer_with_most_divisors(nums)
    print(num, n_divisors)

# If a function returns True/False, intuitive names often take the
# form of is_X, has_X, contains_X, and so forth.

def is_prime(n):
    if n < 2:
        return False
    # You don't need to check beyond the square root of N.
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

# Your version of this function used some good techniques, but it was more
# complex and harder to understand than necessary, mostly because the function
# was doing too many jobs at the same time: computing divisors for each number,
# finding the number with the most divisors, and reporting to the user. Keeping
# things separate often increases flexibly and code clarity.

# Let's start by moving the divisor computation to its own function. Again, we
# only need to check up to square root. There are faster ways to compute
# divisors, but this example prioritizes simplicity.

def divisors(n):
    divs = {1, n}
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            divs.add(i)
            divs.add(n // i)
    return sorted(divs)

# Now the program's primary function because very easy to write and understand.
# Also, we continue with the theme of selecting variable names that approximate
# ordinary English-language usage.

def find_integer_with_most_divisors(nums):
    counts = []
    for num in nums:
        divs = divisors(num)
        primes = [d for d in divs if is_prime(d)]
        # If you put the count first in the tuple, functions like
        # sort(), max(), min() will work exactly as desired.
        counts.append((len(primes), num))
    count, num = max(counts)
    return (num, count)

# Invoke main() with any command-line arguments, if the code was executed as a
# script. If the code is imported, main() won't be called. This device makes
# your script easier to test.

if __name__ == '__main__':
    main(sys.argv[1:])


Overriding equals and hashCode vs providing only Single Instance on immutable Objects

Your approach is flawed in both ways. I see some fundamental misunderstanding of equals, hashcode and == operator.

To Option A

  Pros of A ... Can also be used with mutable Objects

Overriding hashcode and equals on mutable objects will lead to unaccessable elements within hash-based datastructures like HashMap or HashSet. Always make sure your objects are immutable when overriding these methods.

Furthermore your implementation of equals is semantically wrong. This is because you make "equals" dependent on hashcode only.

Maybe you can precheck the hashcode to avoid a complex equals-evaluation if the hashcodes aren't equal.

hashcode has a totally other purpose. It provides a value that is used in hash-based datastructures to balance lookup tables to increase lookup performance and minimze the binary search path.

You may say that Integer.hashcode(int i) always returns i. Yes, but you depend on implementation details for a totally different semantic.

A correct implementation for your SomeInt:

public class SomeInt {

    private final int value;

    public SomeInt(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }

    @Override
    public boolean equals(Object object) {

        boolean equals = false;

        if (object instanceof SomeInt) {

            SomeInt that = (SomeInt) object;

            equals = this.value == that.value;

        }

        return equals;
    }

    @Override
    public int hashCode() {
        return this.value;
    }

}

To Option B

Yes you can do so. But the achieve the same with the correct hashcode equals implementation on immutable datastructures with less overhead.

Logical path

If you override equals you have to override hashcode
hashcode is used within hash-based datastructures to put objects into  buckets
If you change the value hashcode depends on AND you have put the object into a hash-based datastructure before, it is very probable that you never find this object again.
Therefore values that are used to generate the hashcode must not change if you want to use the objects within hash-based datastructures.


BFS implementation that walks a tile-based field

I managed to make it five times faster but my solution uses some ad-hoc hacks.

First, I replaced queue with a set. This makes checking for solution faster and allows to update visited with single set-union operation.

bfs field start end = minSteps H.empty (H.singleton start) 0
    where
        minSteps visited queue steps
            |end `H.member` queue = steps + 1
            |otherwise = minSteps newVisited newQueue (steps + 1)
            where
                -- add whole frontier to visited set
                newVisited = queue `H.union` visited
                -- make next frontier from non-visited neighbors
                newQueue
                  = H.fromList (concatMap neighbors $ H.toList queue)
                  `H.difference` newVisited

This change makes the program slightly slower but it allows further optimizations.

Now to the ugly hack. Assuming you are on 64-bit machine and coordinates of empty tiles are in the range [0..2^31), it is possible to pack pair of coordinates into single Int. This will reduce memory footprint, improve cache locality and simplify hash calculation.

Here are two functions to pack/unpack coordinates:

enc :: (Int,Int) -> Int
enc (x,y) = shiftL (x .&. 0xFFFFFFFF) 32 .|. (y .&. 0xFFFFFFFF)

dec :: Int -> (Int, Int)
dec z = (shiftR z 32, z .&. 0xFFFFFFFF)

Use them to store packed coordinates in visited and queue and this will give you small improvement over the original code.

So, we made some ugly changes but gained very small speedup. Now it's time for magic. Changing single line of code will make the code 5 times faster.

Just import Data.IntSet instead of Data.HashSet.
Here is full code:

import qualified Data.IntSet as H
import Data.Bits

bfs field start end = minSteps H.empty (H.singleton $ enc start) 0
    where
        minSteps visited queue steps
            |enc end `H.member` queue = steps + 1
            |otherwise = minSteps newVisited newQueue (steps + 1)
            where
                newVisited = queue `H.union` visited
                newQueue
                  = H.fromList (concatMap (map enc.neighbors.dec) $ H.toList queue)
                  `H.difference` newVisited

                neighbors (nx, ny)
                  = filter (uncurry field)
                  $ map (\(x, y) -> (nx + x, ny + y))
                    [(1, 0), (0, -1), (-1, 0), (0, 1)]

enc :: (Int,Int) -> Int
enc (x,y) = shiftL (x .&. 0xFFFFFFFF) 32 .|. (y .&. 0xFFFFFFFF)

dec :: Int -> (Int, Int)
dec z = (shiftR z 32, z .&. 0xFFFFFFFF)

hugeField x y = x >= 0 && x <= 1000 && y >= 0 && y <= 1000

main = print $ bfs hugeField (0, 0) (1000, 1000)

The reason of such a speedup is that IntSet represents dense sets in much more compact form than HashSet. And this makes union and difference faster.


Instead of do ... while loop you can use SpinWait.SpinUntil:

bool dataHaveBeenFetched = SpinWait.SpinUntil(() => TrytoFetchData((CServer)sender))

And as @t3chb0t noted it seems strange to sleep 1 second between TrytoFetchData calls.


Query for finding possible "Not An Answer" posts

Firstly, I would avoid using JOIN on it's own. INNER JOIN should be used instead, it's much easier to understand what is happening at a glance if you see INNER JOIN over JOIN

I would capitalise the AS and AND's, it just makes it more consistent.

Otherwise, the general formatting is pretty nice.

I would maybe argue that the table aliases are a little unnecessary, Posts and Users are already pretty short and are more meaningful than the single letter aliases you gave them. I would consider aliasing the joined Posts table Answers or something similar.

Lastly, the largest point. You are checking if both the body and title do not contain the same string. You can concatenate body and title together, with a space to separate them, and check for the word/phrase you are searching for in that instead, effectively halving the size of your where statement.

SELECT
Posts.Id AS [Post Link],
LEN(Posts.Body),
Posts.CreationDate AS Date

FROM Posts

INNER JOIN Users
ON Posts.OwnerUserId = Users.Id

INNER JOIN Posts AS Answers
ON Posts.ParentId = Answers.Id

WHERE Users.Reputation < 126
AND LEN(Posts.Body) < 300
AND Posts.Body LIKE '%a href=%'
AND Posts.Score < 3
AND Posts.PostTypeId = 2
AND Posts.CommentCount < 3
AND Answers.ClosedDate IS NULL
AND Answers.FavoriteCount < 3
AND Answers.CommunityOwnedDate IS NULL
AND Answers.Body+' '+Answers.Title NOT LIKE '%plugin%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%plug-in%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%tool%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%framework%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%API%'
AND Answers.Body+' '+Answers.Title NOT LIKE '%IDE%'
AND Answers.Body+' '+Answers.Title NOT LIKE '%library%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%cms%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%open source%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%application%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%software%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%tutorial%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%book%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%module%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%resource%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%engine%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%lightweight%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%opensource%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%technologies%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%simulator%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%compiler%' COLLATE SQL_Latin1_General_CP1_CI_AS
AND Answers.Body+' '+Answers.Title NOT LIKE '%editor%' COLLATE SQL_Latin1_General_CP1_CI_AS

ORDER BY LEN(Posts.Body) ASC

Here is the SEDE Query


Meta functions for sequences of exponents of 2

Certainly your definitions of printing_type and print could be shortened. You're currently doing
print(t...)  // print(a,b,c,d)

but what you actually want to happen is
print(t)...  // print(a), print(b), print(c), print(d)

So then you have to do a bunch of extra work to transform the former into the latter. Instead of all that extra work, you could just write
void print(size_t val) {
    std::cout << val << " ";
}

template<template<size_t...> class T, size_t... S>
void printing_type(T<S...>) {
    (print(S) , ...);
}

Notice that the single-argument print doesn't have to be a template, because val is always a size_t.
In fact, we can inline print into printing_type if we want:
template<template<size_t...> class TT, size_t... Values>
void printing_type(TT<Values...>) {
    ((std::cout << Values << " ") , ...);
}

The (ts , ...) syntax is a C++17 fold-expression. If you aren't on C++17, then you can use an initializer list to accomplish the same thing:
template<template<size_t...> class TT, size_t... Values>
void printing_type(TT<Values...>) {
    int dummy[] = {
        ((std::cout << Values << " "), 0) ...
    };
}

Your definition for sequence is pretty confusing. Your code could benefit from some unit tests. Compile-time unit tests are easy:
static_assert(std::is_same<create_int_seq<0>, int_seq<1>>::value, "");
static_assert(std::is_same<create_int_seq<1>, int_seq<1,2>>::value, "");
static_assert(std::is_same<create_int_seq<2>, int_seq<1,2,4>>::value, "");
static_assert(std::is_same<create_int_seq<3>, int_seq<1,2,4,8>>::value, "");
static_assert(std::is_same<create_int_seq<4>, int_seq<1,2,4,8,16>>::value, "");

As a bonus, these five lines serve as excellent documentation about what this code does... to the extent that I no longer mind the lack of code comments explaining how it might work.
FWIW, if I wanted to make these test cases pass, I'd implement create_int_seq like this:
template<class> struct powers_of_two;
template<size_t... Is>
struct powers_of_two<std::index_sequence<Is...>> {
    using type = int_seq<(size_t(1) << Is)...>;
};

template<size_t N>
using create_int_seq =
    typename powers_of_two<std::make_index_sequence<N+1>>::type;

Relevant blog post of mine: "Template metaprogramming: Iteration is better than recursion" (July 2018).


Use the android:onClick attribute to get rid of the boilerplate calls to setOnClickListener and findViewById.

The giant if-else statement is very repetitive. The actions taken in all branches are assigning a value to the value variable and appending a digit to the phone number. You could convert the code to data by mapping the button label to a value and a string.

final String label = ((Button) view).getText();
final int value = buttonLabelToValue.get(label);
phoneNo += buttonLabelToPhoneNumberDigit.get(label);

Handle the two special cases '#' and '*' by mapping the PhoneNumberDigit to an empty string.

I never write code to prepare for an UI component calling a wrong listener method. I define the UI and the listeners and if my UI calls the wrong method then it's a bug. My tests must be good enough to catch such scenarios. In this example, not checking the return value of buttonLabelToValue.get(...) for nulls results in NullPointerException instead of the IllegalStateException thrown in your version. Not much difference for the user as the app crashes in both cases.


Merging every two objects into single single object making group by a property C# LINQ

If you want to reduce the iteration to get the value for ColumnC and ColumnD and make the code cleaner, you can try using Aggregate instead.
var output = input
             .GroupBy(d => new {d.ColumnA, d.ColumnB})
             .Select(
                 g => g.Aggregate(
                     new MappingClass {ColumnA = g.Key.ColumnA, ColumnB = g.Key.ColumnB},
                     (result, next) =>
                     {
                         result.ColumnC ??= next.ColumnC;
                         result.ColumnD ??= next.ColumnD;
                         return result;
                     }))
              .ToList();


Generate line chart from SQL database output using Morris

I like to keep the Javascript in one echo at the bottom, like this:

<?php

unset($data0);
unset($data1);
unset($data2);

$sth = $dbh->prepare("SELECT a, b, c FROM t");
$sth->execute();

$data = '';
while ($row = $sth->fetch(FETCH_ASSOC)) {
  extract($row);
  $data .= "{ m: '$c', a: $a, b: $b },".PHP_EOL;
}

echo "<script>
Morris.Line({
  element: 'morris-line-chart',
  data: [$data],
  xkey: 'm',
  xLabels: 'month',
  ykeys: ['a', 'b'],
  labels: ['2014', '2015']
});
</script>";

I had to make the assumptions that you're using PDO and that $c is your m in the morris line.


Prim's algorithm for finding the minimum spanning tree

#n is the number of nodes m is the number of edges
n, m = [int(x) for x in raw_input().split(" ")]

well, instead of writing this comment it would be much better to give your variables meaningful and descriptive names, In this way you won't have to read the comment and the variables to know what they are about.

The same applies to g, pq, a.........etc.etc


Gathering response from a pagable service

You might want to try Scala Streams.

val Quota = 3

def find(service: Service) = {
    def chunks(lastIdOption: Option[Long]): Stream[Stream[Int]] = {
        Stream.cons(response, chunks(response.last.id))
    }
    chunks(None).take(Quota).flatten
}

The chunks function returns an infinite stream of pages. The take(3) limits it to three pages. The flatten method joins the inner list in a large stream.

Stream is lazy, so it should fetch only the data that are needed. However, you should not expect some artificial intelligence in the Streams. For example this will always fetch the first page even if quota is zero. I hope this is not an issue in your case. If you are in doubt with the laziness, you can add some print in the chunks function to check (or falsify) your assumptions.


As a general rule, when you are trying to define a recursive function that operates on a data type like this:

data Expr = Plus Expr Expr | Value Int

you want to first try to define your function using one pattern per constructor:  one pattern for Plus and another pattern for Value.  For some functions, you may find that this isn't sufficient, and then you will have to add additional patterns, but you'll be surprised how many useful functions can be written using this "one pattern per constructor" rule.

So, you want a pattern that can match all Value x expressions, and you already have that:

evaluate (Value a) = a

If you want a second pattern that can match ALL Plus e1 e2 expressions, then you can't write something like this:

evaluate (Plus (Value a) (Value b)) = ...

because that will only match some Plus expressions (namely those that are adding two Value expressions).  If you want to match them all, you need to start with:

evaluate (Plus left right) = ...

Now, on the right-hand side, left and right are expressions, and the only thing we can do with them is evaluate them to integers, and then it becomes pretty obvious that you want to write:

evaluate (Plus left right) = evaluate left + evaluate right

You basically already figured this out, but you did it inside special cases like the pattern Plus (Plus left right) (Value b) instead of realizing that you could do it in the general Plus left right case.

And that's it!  The full definition is:

evaluate :: Expr -> Int
evaluate (Value a) = a
evaluate (Plus left right) = evaluate left + evaluate right

and you'll find it works perfectly on all expressions.  For more complicated expressions, the recursion automatically breaks it down:

evaluate (Plus (Value 1) (Plus (Value 2) (Value 3))
-- apply second pattern w/ left=(Value 1) and right=(Plus (Value 2) (Value 3))
=== evaluate (Value 1) + evaluate (Plus (Value 2) (Value 3))
-- apply first pattern w/ a=1
=== 1 + evaluate (Plus (Value 2) (Value 3))
-- apply second pattern w/ left=(Value 2) and right=(Value 3)
=== 1 + (evaluate (Value 2) + evaluate (Value 3))
-- apply first pattern w/ a=2
=== 1 + (2 + evaluate (Value 3))
-- apply first pattern w/ a=3
=== 1 + (2 + 3)
=== 6


You run all the computations in the main method. It's not a good practice. One method should do one focused thing. That's why I'd recommend to create a separate method for "step" of your computation:

converting measurements (something like double poundsToKilograms(double weightInPounds)
computing the BMI given the height and the weight of the user
converting a numeric value of the BMI to a human-readable message

This way, you main method would just read the input, call these methods and print the result. It would make your code more readable and testable (you would be able to test your methods separately)
The comments should explain what the code does and why it does what it does. They shouldn't describe how it works. That is, it's a good idea to create a doc comment for each method saying what it does, how it behaves if it gets an incorrect input and so on. Conversely, comments like //declare variables or //create scanner actually harm the readability. They just create noise. They don't add anything useful to the code itself.  Writing self-documenting code is a good practice (that is, ideally it should be clear what your code does from the code itself).
ComputeBMI doesn't sound like a good class name to me. I'd rather call it a BMICalculator (it's conventional to name classes with nouns and methods with verbs).
The message Enter feet: looks kind of strange. I think it should say that it requests the user's height (it's not clear from the message itself).
It's fine to keep the height as an int, but I would show a message to the user saying that. Otherwise, they may get an unexpected error.
You could also add some kind of input validation and error handling so that your program doesn't fail with an exception (it might be confusing for the user) but rather prints a more suitable message and possible prompts the user again.


My first implementation of a client/server application

Naming

Usually, local variables start with a small letter.

StartListening

If the method is called multiple times, it will throw an exception that the endpoint is already in use. Not very robust.
Task.Run(action) uses a thread from the thread pool. Those threads are usually pooled for short running actions. TaskFactory.StartNew(action, TaskCreationOptions.LongRunning) creates a new thread to run the action in. That is more appropriated for long running tasks.
You should use try / catch or using to ensure that the client will be disposed, even if an error occurs.
You should provide a way to shut down the server - closing the application is IMHO not the right way.

HandleClientData

If the incoming data size is bigger than 1024, only the last chunk is received. You would probably add the chunk to the string: clientData += Encoding.ASCII.GetString(buffer, 0, i);


Image placed with username in recent post of WordPress

Take a look at filter_input(). It allows you to sanitize and validate GET/POST variables whether they exist or not. If no variable in that scope exists it will be set to FALSE/NULL which means all you have to do is set it to a variable and ensure it has a value.

$tempPart = filter_input( INPUT_GET, 'including_template_part', FILTER_SANITIZE_STRING );
$part = filter_input( INPUT_GET, 'load_part', FILTER_SANITIZE_STRING );
if( $tempPart && $part ) {

You should avoid internal comments. Internal comments adds clutter to your code and if overused can make your code difficult to read. If your code is self documenting most comments become unnecessary. Anything else should be limited to doccomments.

Ternary statements are good if used properly, but they can become difficult to read if they get too large or if you nest them. Try to keep your ternary statements short and uncomplicated. Here for instance, it is not even necessary. explode() will return an array with the string as the only element if the delimiter does not exist. So you can just call explode() immediately to the same effect.

$params = explode( ',', $params );

You should avoid using exit or die() to force your program to stop. It is inelegant. If you must stop execution use a return or throw an error.

There is a principle called the arrow anti-patern. It dictates that you should avoid having heavy/unnecessary indentation in your code to aid in legibility. To avoid violating it you should return early from your statements or refactor them so that only small portions of code are indented. Returning early sometimes also makes else statements unnecessary. If we reverse that first if statement we can return early allowing us to remove an entire level of indentation from our function.

if( ! $tempPart || ! ! $part ) {
    return FALSE;//or throw error
}

//rest of function here...

Your second function has a $numberposts argument that is unused. You immediately create an array with the same values though. If you need to do something like this you should either immediately inject it that way or you can use compact() to the same effect.

$args = compact( 'numberposts' );

Now, as to your problem with the images. Since they are originating on another part of your domain, I would hazard to guess that the path to said images is not being updated for the new domain path. This means that you will need to somehow modify the path you are given to reflect the differences. Seen as none of the code you provided has images in it I have no idea what the culprit is.


I'll only be reviewing the binary search portion of the code since that's what it seems like you're asking for.

Separation of Concerns

You should separate I/O from processing and let the user control what kind of I/O they'd like to have. So I would remove the output statements from your binarySearch function and find a better way to indicate the element was not found. The solution I'll go with is that we'll return the index of the element if it is found and -1 otherwise (since -1 is never a valid array index).

Better Naming

You call the middle element guess even though it is not a guess. Someone unfamiliar with binary search would read this code and assume that you guessed the element was in the middle. This is not true so I would rename that variable to pivot or middle. Moreover, you can move the calculation of it to be inside the while loop.

Miscellaneous

Use consistent bracing style (e.g. always use them. They never hurt).
The if statement at the end of the binary search is unnecessary since when we exit the while loop, we know that low > high.
Since middle won't be changing in one while loop cycle, we can mark it final.

Here is a possible implementation taking into account all of the above.

    private static int binarySearch(int[] array, int searchkey) {

        int low = 0; // lowest index
        int high = array.length - 1; // highest index

        while (low <= high) {
            final int middle = low + (high - low) / 2;
            if (array[middle] == searchkey) {
                return middle;
            } else if (array[middle] < searchkey) {
                low = middle + 1;
            } else {
                high = middle - 1;
            }
        }
        return -1;
    }


Dealing with multiple types in an excel sheet

A few nitpicks in general:

Your indentation is off

I'm not sure whether that's just a copy paste-error or actually intended, but it's convention to indent the class body by 4 Spaces.

public class MultiTypeValue {

    private Map //...

Eager initialization saves you some pain

Instead of initializing your values in the constructor, you might prefer to eagerly initialize the Map as a final field:

public class MultiTypeValue {

    private final Map<Class<?>, Optional<?>> values =
      new ConcurrentHashMap<>();
    // ...

Why do you disallow an empty map?

I don't think it's a wise choice to disallow an empty Map if you don't validate the class-object pairs you put in anyways. As such initializing the map with an empty Optional seems... unhelpful.

Either you stop requiring classes for construction or you make use of the classes by validating you're only updating a value of an allowed class instead of just silently taking it:

public void put(Class<?> clazz, Object value) {
    if (values.containsKey(clazz)) {
       values.put(clazz, Optional.ofNullable(value));
    }
}

Use generics when putting a value

You should really do some more checking when you put a value. Consider the following:

public void <T> put(Class<T> clazz, T value) {

this is where it gets really interesting, since you can just extract the relevant class from your argument:

public void <T> put(T value) {
    Class<T> clazz = value.getClass();

I'm not quite clear on how your requiremnts / usage of this class is though, so this may just completely miss your usecase.

The factory method is unnecessary

As of now you're simply misusing your factory method as a proxy for your constructor. Usually you'd implement a factory method to allow for caching and instance control. Since you don't do either of that here, the factory method isn't necessary and you should just expose the constructor directly to simplify things

Missing documentation

One of the reasons I wasn't sure what exactly you intend this class for is that it's completely undocumented.

You explain nothing on this class and as an external developer on your project I'd be very confused by it I daresay. Then again I haven't seen it in usage context, but either way:

This seems like a core class for your functionality and it should be documented accordingly


Is there a more optimized way for this MySql Query

As you have no range specific functions applied in the SELECT clause I don't understand why you need the GROUP BY clause.

The expression is way to simple to be optimized (its hard to see how you can go wrong).

For any optimization advice you will need to provide the table definitions and an explanation of the Normal Form the data has been decomposed to. Optimization of SQL queries usually lies in the table structure and not decomposing the data to full actualized third Normal Form.


Your definition of transpose is correct, although it can be written succinctly as:

(define (transpose mat)
  (accumulate-n cons null mat))

The remaining two definitions may be written more succinctly by using functions defined earlier.  Notice that multiplying a matrix to a vector is conceptually the same as obtaining the dot-product of the vector and each row of the matrix.  Thus, one may define matrix-*-vector as:

(define (matrix-*-vector m v)
  (map (lambda (row) (dot-product v row)) m))

The above definition satisfies the requirement of the exercise.

Similarly, matrix multiplication of A to B is the same as transposing B and performing a matrix-vector multiplication with each row of A.  Thus, one may define matrix-*-matrix as:

(define (matrix-*-matrix m n)
  (let
      ((cols (transpose n)))
    (map (lambda (row) (matrix-*-vector cols row)) m)))

If you wish to go farther than the exercise requires, you may consider using function currying.  Currying allows one to apply a function to arguments incrementally.  If your implementation of Scheme provides the curry function, you may write:

(define (matrix-*-vector m v)
  (map (curry dot-product v) m))

(define (matrix-*-matrix m n)
  (map (curry matrix-*-vector (transpose n)) m))


Multiple emails and attachments, reusing memory stream

Basically it is ok, to create a new MemoryStream 3 times, but I have to ask, why you don't create one Attachment adding it to each of the emails like so

var attachment = new Attachment(new MemoryStream(document.Draw()), "OrderForm.pdf");
useremail.Attach(attachment);
vendoremail.Attach(attachment);
internalemail.Attach(attachment);


Core location background update and upload to server

LocationManager Singleton

It is not necessary to use dispatch_once to make LocationService a Singleton.

This pattern can be achieved by doing the following:

Exposing a static type property that creates a new instance of LocationService
Marking the initializer of the class as private

For example:

class LocationService: NSObject, CLLocationManagerDelegate {
    static let shared = LocationSerivce()

    // This class cannot be instantiated outside of this class
    override private init() {
        // Initialization code
    }
}

shared is lazily instantiated. A performance benefit that you inherit by implementing the Singleton this way.

From Apple’s documentation on Type Properties:

  "Stored type properties are lazily initialized on their first access. They are guaranteed to be initialized only once, even when accessed by multiple threads simultaneously, and they do not need to be marked with the lazy modifier.”

The private initializer is key to the implementation of the Singleton pattern because it prevents anyone from outside of the class from creating another instance. That said, under other circumstances you may still want instances to be created to give your consumer more choices/functionality.

Ultimately these changes make your code easier to read, ensure you have Singleton and are inline with Apple’s documented approach to Singletons using Swift.

Private CLLocationManager

Your LocationSerivce appears to be a wrapper around Apple’s CLLocationManager class. It would probably be best to mark this constant as private. This prevents outside code from changing the reference or state of your locationManager property.

private let locationManager = CLLocationManager()

Self

In the following functions, the use of self is not required. The reference to locationManager is not ambiguous and self is not required to explicitly state otherwise.

func startUpdatingLocation() {
    print(“Starting Location Updates”)
    self.locationManager.startUpdatingLocation()
}

func stopUpdatingLocation() {
    print(“Stop Location Updates”)
    self.locationManager.stopUpdatingLocation()
}

CLLocationManager Desired Accuracy

You can remove the following code from your initializer:

locationManager.desiredAccuracy = kCLLocationAccuracyBest

On iOS, kCLLocationAccuracyBest is the default value of the desiredAccuracy property.

Accuracy Constants

In terms of accuracy, you have six options:

kCLLocationAccuracyBestForNavigation
kCLLocationAccuracyBest
kCLLocationAccuracyNearestTenMeters
kCLLocationAccuracyHundredMeters
kCLLocationAccuracyAccuracyKilometer
kCLLocationAccuracyThreeKilometers

At first glance one may think to use kCLLocationAccuracyBestForNavigation, however because increasing the accuracy requires more device resources (like GPS or Cellular Radio), it also means that more device power will be required. This can have a negative impact on the user experience if expectations are not set. There are also some other caveats that should be understood when setting the  desiredAccuracy property.

Apple’s desiredAccuracy documentation: https://developer.apple.com/reference/corelocation/cllocationmanager/1423836-desiredaccuracy

When deciding which constant to use, careful consideration will be required based on the app’s intended use and the user’s expectations (and delivering a great mobile experience). I recommend reading the CLLocationManager documentation to better understand its usage and how to strike a good balance between your app’s functionality and device performance.

Apple’s CLLocationManager documentation: https://developer.apple.com/reference/corelocation/cllocationmanager


This isn't really todo with the code, but, it's always a good idea to add comments to your code to make it more readable and understandable.


Referring to nested arrays and array_merge (php)

I don't know if I understand the question right. But this should work.

foreach ($keys as $key) {
    $arr2[$key]['subkey0'][] = $var1;
    $arr2[$key]['subkey1'][] = $var2;
}


I'm pretty sure you have the potential for a race condition if one thread releases the lock and removes it, after another thread has got the lock but not yet locked it.

Thread one GetLock(someKey) // Creates lock, returns dynamic key
Thread one Lock(dynamicKey)
Thread one complete processing (exits lock section)
Thread two GetLock(someKey) // returns existing key
Thread one RemoveLock // removes lock from collection (not yet being used)
Thread two Lock(dynamicKey) // Now we've locked an object no longer in collection
Thread two complete processing (exit lock block)
Thread two Remove lock // tries to remove a lock that's not in the collection


Processing lexical analyses of sentences using the Perl split function

Match and substitute are far better suited for this problem than split().
To delete all of the _XX things, use a substitute global s/(_\S+)//g;.
So generating your desired output is actually easy.

To see demo of this and how to parse your report, see the code below. Note that if the left hand side contains variables in a list context like:($gramFunc, $dep1, $dep2) then they will be assigned $1,$2,$3 from the match respectively. I check if $dep2 is defined to mean that the match succeeded because if that variable is defined, then the variables $gramFunc and $dep1 are too!

This line $sentNum = $1 if /\[sent\.\s*(\d+)/; has the same meaning as:

if (/\[sent\.\s*(\d+)/)
{
   $sentNum = $1;
}

I cannot assign to $sentNum directly in this case because I want to know if the match worked or not. $1 is undefined if the match fails and the scalar value of /\[sent\.\s*(\d+)/ will be zero. I presume that more such "[sent" lines will appear in the report that you are trying to parse. This statement just updates as necessary the current sent # for the report.

Code:

#!/usr/bin/perl -w
use strict;

my $str = '5.4_CD Passive_NNP Processes_NNP of_IN Membrane_NNP Transport_NNP 85_CD We_PRP have_VBP examined_VBN membrane_NN structure_NN and_CC how_WRB it_PRP is_VBZ used_VBN to_TO perform_VB one_CD membrane_NN function_NN :_: the_DT binding_JJ of_IN one_CD cell_NN to_TO another_DT ._.';

$str =~ s/(_\S+)//g;  # deletes all of the "_XX" tokens
print $str, "\n";

my $sentNum = 0;
while (<DATA>)
{
   $sentNum = $1 if /\[sent\.\s*(\d+)/;

   my ($gramFunc, $dep1, $dep2) = $_ =~ /\s+(\w+)\((\w+).*?(\w+)-/;
   if (defined $dep2)
   {
      printf "sent num=$sentNum %-10s %-15s %-15s\n", $gramFunc, $dep1, $dep2;
   }
}

=program output
5.4 Passive Processes of Membrane Transport 85 We have examined membrane structure and how it is used to perform one membrane function : the binding of one cell to another .
sent num=1 nsubj      85              Processes
sent num=1 nn         Transport       Membrane
sent num=1 prep_of    Processes       Transport
sent num=1 nsubj      examined        We
sent num=1 nsubjpass  used            it
sent num=1 xsubj      perform         it
sent num=1 conj_and   examined        used
sent num=1 xcomp      used            perform
sent num=1 dobj       perform         function
sent num=1 prep_of    binding         cell
=cut

__DATA__
Parsing [sent. 1 len. 31]:
        nsubj(85-7, Processes-3)
        nn(Transport-6, Membrane-5)
        prep_of(Processes-3, Transport-6)
        nsubj(examined-10, We-8)
        nsubjpass(used-17, it-15)
        xsubj(perform-19, it-15)
        conj_and(examined-10, used-17)
        xcomp(used-17, perform-19)
        dobj(perform-19, function-22)
        prep_of(binding-25, cell-28) <- refer to this for examples below


Is there any memory leak for the implementation of array of char arrays

You made an error here:
        urls[i] = malloc(sizeof(strlen(url) + 1));

strlen(url) + 1 is of type size_t, so you will allocate enough space for that, which could well be less than the amount you actually wanted (strlen(url) + 1).
If we fix that bug, and also change url to const char* (because it points at string literals, which are always const), then we get a clean Valgrind run from the test program.

What does the return value from add_to_urls indicate?  If you meant it to be true when the url was added, then the break should be replaced with return 1.
Always check the result of malloc() is not null.
Errors and warnings should be printed to the standard error stream, not to stdout.
Your main() doesn't check that we didn't add a duplicate.  In fact we did, but we never printed it.
Avoid writing constants (such as 100) in separate places if they need to agree with each other.
Instead of the break in free_urls(), we can make the test part of the loop's condition.

Improved code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int add_to_urls(char **urls, const char *url, size_t max_list)
{
    for (size_t i = 0;  i < max_list;  i++) {
        if (!urls[i]) {
            urls[i] = malloc(strlen(url) + 1);
            if (!urls[i]) {
                fprintf(stderr, "Failed to alloc for %s\n", url);
                return 0; /* failed allocation */
            }
            strcpy(urls[i], url);
            return 1;           /* we added it */
        }
        //make sure we don't add same site twice
        if (strcmp(urls[i], url) == 0) {
            fprintf(stderr, "%s already in list\n", url);
            return 0;           /* already present */
        }
    }
    return 0; /* ran out of room */
}

void free_urls(char **urls, size_t max_list) {
    for (size_t i = 0;  i < max_list && urls[i];  i++) {
        free(urls[i]);
    }
}

int main() {
    char *urls[100] = {NULL};
    const size_t url_len = sizeof urls / sizeof *urls;

    add_to_urls(urls, "www.youtube.com", url_len);
    add_to_urls(urls, "www.reddit.com", url_len);
    add_to_urls(urls, "www.reddit.com", url_len);

    for (size_t i = 0;  i < url_len && urls[i];  i++) {
        printf("URL[%zd]: %s\n", i, urls[i]);
    }

    free_urls(urls, url_len);
}


High-level comments:

There are several print statements left in this file which look like they were in for debugging purposes. Maybe useful to you, but means nothing to me when I’m running the file. These should be commented out, or (since you’re using source control) removed entirely.
There are no comments in this file. That makes it quite hard to follow what’s going on – even if this is a simple problem that you understand well, that won’t be the case when you come to re-read this in six months.

Explain why the code is written this way, and how the program structures relate back to the original problem. It makes it much easier to review and improve.
Everything runs at the top-level. You should break some of this down into functions – it will make the code easier to reuse and follow.

A few smaller suggestions:

On line 24, you’re using regexes to split a line on whitespace, but Python already has a string method split() that does this for you.

You can rewrite these few lines as:

for line in lines:
    fields = line.strip().split()

Notice that I’m also calling the strip() method directly on line, and I’ve renamed the loop variable to make it clearer what I’m doing.
On lines 25–7, a common antipattern:

int_fields = []
for f in fields:
    int_fields.append(int(f))

It’s cleaner and more Pythonic to do this with a list comprehension:

int_fields = [int(f) for f in fields]

Note also that you store the value of len(fields) in a variable here – but then never actually use it.
In lines 35-6, you have a common Python antipattern:

for z in range(0, rows):
    row = triangle[z]

It’s always better to iterate over the items directly, i.e. for row in triangle. In this case you’re actually using z further down, so you should use enumerate():

for idx, row in enumerate(triangle):
    # do stuff with idx and row

On lines 40–50, there are several problems:

You don’t need to initialise the variable adder to 0.
You can get its value in a single line:

adder = max(a, b)

The names a and b are not very meaningful, and are only used once. It would be cleaner to write this as:

triangle[z+1][y] += max(row[y], row[y+1])

You should also rename y and z to be more meaningful.

You’re calling range(0, x) in several places. Since it defaults to a start of 0, you can drop the first argument to reduce visual noise: range(x).


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

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

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

    return flag;
}

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

and:
Circle circle = (Circle) s;

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

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

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

    return true;
}


Sometimes you're skipping parentheses, sometimes you're not. Please be consistent
Sometimes you're accessing @members directly, sometimes you're using the members reader method. In some cases that might make sense to do one or the other, but here it's random. Again: Be consistent.
However, be careful about providing a reader. Right now, I could say a_multiset.members[some_item] = -100 or something, and things would get weird because I've messed with an internal data structure. A #members accessor might be better as simply an alias for #to_h
What is raise_error? I don't see it defined anywhere. Which, funnily enough, means that it does raise an error - an error telling you that raise_error isn't defined.
If you're going to raise an error, then raise the appropriate one:

raise ArgumentError, "enum must include the 'Enumerable' module"

enum.class.include?(Enumerable) is a roundabout way of writing enum.kind_of?(Enumerable)
Your initializer duplicates logic from you #add method; just call #add instead.
#remove can be cleaned up a little by postfixing the if members[item] < 1, just to get rid of the pyramid indentation.
Your #empty! method should probably be called #clear. That's the conventional name used by Hash, Array and Set (as you can tell, since that's what your method calls on the @members hash)
Pretty sure that your #multiplicity method is exactly backwards. You're returning nil if an item's count is zero. I think you want the exact opposite: Return zero if the item doesn't exist:

include?(item) ? members[item] : 0

Use your own methods when you can. You have an #include? method already, so there's no need to use @members.include? all over the place.
#cardinality can be written as just

members.values.reduce(0, :+)

If you provide an initial value to #reduce (the zero), you don't need the extra emptiness-check you have now
Pretty sure your union method is incorrect too. If a key doesn't exist, you simply add it - meaning it'll have a count of 1. But in fact, it should have the same count as it has in the other set.
And you can simplify the method, too:

def |(other)
  other.each do |key, count|
    members[key] = multiplicity(key) + count
  end
  self
end

Both the union and intersection methods should probably return a new MultiSet instance, rather than modify the receiver.


Updating WPF MainWindow from an async task

I would look into MVVM, then your async task will operate on the ViewModel and not the UI element. Then WPF will update the UI when it deem fit.

I like Caliburn.Micro for the MVVM parts

https://github.com/Caliburn-Micro


Nested trial and error in if-else condition

Some notes:

g: use meaningful names.
Don't mix code with parentheses and without.
Check the pattern Object#presence.
# if no address found, ...: declarative code makes this kind of comments unnecessary.

I'd write:

results = Geocoder.search(address).presence || Geocoder.search(latitude, longitude)
if results.present?
  # save
else
  log.info("Geocode failed for addr='#{search}' and coords=#{latitude}/#{longitude}")
end


What you are really trying to accomplish here is taking http requests and dispatching them to the correct class. This is much better handled by one of many mvc frameworks in existence. That said, I see several problems with what you have here.

Improper check for POST requests. $_POST is always available
No validation of input. Do you want to allow unrestricted access to classes and methods?
Gateway class (which seems more like a dispatcher) is concerned with too much. Not only is it dispatching the request, it is also formatting responses.
No use of http header to properly instruct the client. Put the status codes (200, 404, etc) in the response header, not in the payload.
You are potentially exposing sensitive information by passing back the Exception object's message. When things go wrong, YOU need to know what and why, but the client does not.

Here is a rough improvement:

GatewayExeption.php

<?php
//Use your own exception to distinguish from others
class GatewayException extends Exception {}

Gateway.php

<?php
class Gateway
{
    /**
     * @var array
     */
    private $apis;

    /**
     * Pass an array of pre-configured api class and actions
     *
     * array(
     *   'Foo' => array('bar', 'baz')
     * )
     *
     * @param array $apis
     */
    public function __construct($apis)
    {
        $this->apis = $apis;
    }

    /**
     * Invoke a pre-configured api
     *
     * @param string $apiName
     * @param string $action
     * @param null|array $args
     * @throws GatewayException
     */
    public function invokeApi($apiName, $action, $args = array())
    {
        if (! array_key_exists($apiName, $this->apis)) {
            throw new GatewayException('Invalid api name');
        }

        if (! in_array($action, $this->apis[$apiName])) {
            throw new GatewayException('Invalid action');
        }

        try {
            $obj = new $apiName;
            $result = call_user_func(array($obj, $action), $args);
            return $result;
        } catch (Exception $e) {
            throw new GatewayException('api error', null, $e);
        }
    }
}

Sites.php

<?php
class Sites
{
    public function getSites($params)
    {
        return array(
            'gotyou' => 'message'
        );
    }
}

index.php

<?php
require 'GatewayException.php'
require 'Gateway.php'

if ( $_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('HTTP/1.0 405 Method Not Allowed');
    exit;
}

//Provide an explicit list of available apis
$validApis = array(
    'Sites' => array('getSites')
);
$gateway = new Gateway($validApis);

//initialize request parameters with defaults
$api = array_key_exists('api', $_POST) ? $_POST['api'] : '';
$action = array_key_exists('action', $_POST) ? $_POST['action'] : '';
$params = array_key_exists('params', $_POST) ? $_POST['params'] : null;

//all responses at this point will be json
header('Content-Type: application/json');

try {
    $result = $gateway->invokeApi($api, $action, $params);
    echo json_encode($result);
} catch (GatewayException $e) {
    header('HTTP/1.0 400 Bad Request');
    echo json_encode( array(
        'status'=> $e->getMessage()
    ));
} catch (Exception $e) {
    header('HTTP/1.0 500 Internal Server Error');
    //you should log $e->getMessage()
    //you probably do not want to reveal the Exception's message
    echo json_encode( array(
        'status'=> 'A system error occurred'
    ));
}


Functions

The code can be more readable if it is broken into functions.  This also separates the concern of reading in the series and calculating the missing element(s).

function readSeries($fileHandle)
{
    $series = array();
    fscanf($fileHandle, "%d\n", $count);

    for ($i = 0; $i < $count; ++$i)
    {
        fscanf($fileHandle, "%d\n", $series[$i]);
    }

    return $series;
}

function findMissing(Array $series)
{
    sort($series);
    $start = reset($series);
    $finish = end($series);
    $step = ($finish - $start) / count($series);

    return array_diff(range($start, $finish, $step),
                      $series);
}

$series = readSeries(STDIN);
$missing = findMissing($series);
echo reset($missing);

The use of functions also help to make the code more reusable. The readSeries function can easily be used to read from standard input or another source.

The findMissing function takes advantage of some assumptions that can be made when a series is sorted:

It would be impossible to notice whether the beginning or end elements were missed, so they must both be present.
One the beginning and end values are known then every step along this range must be present.

It then uses the difference of the expected series calculated using the PHP range function.


Prefer Clear Naming over using namespace std

According to the [MSDN website]:

  Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

A collision is when 2 different functions have the same name, the same arguement types and a
similar functionallity (this is why they have the same name). Someone developing software may want
to override a function such as std::cout, std::cin or they may want to override the functionallity
of a class such as std::vector or std::stack. Namespaces allow these constructs to be overriden.

The use of the programming statement:

using namespace std;

hides the fact that cin, cout, vector and stack are coming from the namespace std where cin, cout,
vector and stack are used in the code. This can cause confusion of where the code is actually
coming from.

As the software becomes more complex and uses more libraries this becomes a bigger problem.

For a more detailed discussion of why it is a bad idea to use using namespace std;
see this stackoverflow question and this stackoverflow question.

The Use of new is Preferred Over malloc in C++
The code contains the line:

    int *arr = (int*)malloc(n * sizeof(int));

This is a C programming language construct. In C++ it is much more accepted to use

    int *a = new int[n];

Even this is out dataed because of all the container classes, and generally using pointers is
frowned upon in C++ because it is error prone.

Declare Variables When Needed
In the older versions of the C programming language one had to put the variable declarations at
the top. The current versions of C and C++ allow variables to be declared as needed.

An example of this is to move the variable toggle to be within the for loop.

Limit the Use of std::endl
It would be better to use '\n' to insert the new lines in the loops because std::endl does a file flush
each time it is called. This makes it an expensive operation.

Use Boolean Variables
In the C programming language there is no bool variable type unless one includes stdbool.h. In the
C++ programming language it would be better to implement the variable toggle as a bool variable
rather than as an int. Then you can use true and false rather than 1 and 0 respectively.


Many Lisp programs use cons cells quite liberally instead of adding a
separate stack structure, in that sense your concerns about complexity
are probably a bit less critical.  Since the stack is also carrying the
length of the list it actually supports at least the additional size
operator quite well.  Of course writing more code for an underlying
(resizable) vector could make sense, but again I wouldn't count on
that being necessary.

For the code I only have minor suggestions, as it's pretty well written
and clear what each part means; while I'm not that familiar with Racket
it's easily readable to me.

For the pattern (+/- x 1) there are also the functions add1 and
sub1 which could be used.
The non-empty-stack? could just check whether the buffer is
null? or empty? instead.  positive? sounds like there's some
risk that the stack size might get negative for some reason.  For the
same reason the contract can probably also be tightened to check for
non-negative integers.
(append (list x) y) is a bit shorter as (cons x y).


Printing integers up to 1000 and are not multiples of 5

Instead of jumping over a jump:

BLE LOOPBODY
B LOOPDONE
LOOPBODY:

you can just invert the condition and jump directly:

BGT LOOPDONE

However, as the first iteration will always happen, you can just put the check at the end of the loop instead:

LOOPHERE:

... the code in the loop

CMP R5, R7
BLE LOOPHERE

The jump to LOOPNEXT right before the label can be skipped:

B LOOPNEXT

LOOPNEXT:

So:

.equ SWI_PrStr, 0x69
.equ SWI_PrInt, 0x6b
.equ StDout, 1
.equ SWI_EXIT, 0x11

.global _start
start:

MOV R5, #1
MOV R6, #1
MOV R7, #1000

LOOPHERE:

CMP R6, #5
BLT LOOPIF
MOV R6, #0
B LOOPNEXT

LOOPIF:

MOV R0, #StDout
MOV R1, R5
swi SWI_PrInt

ldr R1, =EOL
swi SWI_PrStr

LOOPNEXT:

ADD R5, R5, #1
ADD R6, R6, #1

CMP R5, R7
BLE LOOPHERE

swi SWI_EXIT

.data

EOL: .asciz "\n"
.end


Note, you indicate in the text that you have quadrants:

 2 1
 3 4

But your code has the quadrants:

 1 0
 2 3

I recommend you have a function that works on just one point at a time. There are two points, the 'bottom left', and the 'top right'.

So, calculate the quadrant of each point. If they are both in the same quadrant, return the quadrant, otherwise return -1;

int getPointIndex(double horzMid, double vertMid , double x, double y) {
    int quad = 0;
    if (y < horzMid) {
        quad = x < vertMid ? 2 : 3;
    } else {
        quad = x < vertMid ? 1 : 0;
    }
    return quad;
}

Then, using this function you can:

int getIndex(AABB aabb) {

    double vertMid = bounds.getX() + (bounds.getWidth() / 2);
    double horzMid = bounds.getY() + (bounds.getHeight() / 2);

    // Quadrant of bottom-left point.
    int blQuad = getPointIndex(horzMid, vertMid, aabb.getX(), aabb.getY())
    // Quadrant of top-right point.
    int trQuad = getPointIndex(horzMid, vertMid, aabb.getX() + aabb.getWidth(), aabb.getY() + aabb.getHeight())

    if (blQuad == trQuad) {
        return blQuad;
    }

    return -1;
}


I'm a little unclear as to what your goal is here, but here are a few options, depending on which outcome you are hoping for...

If your goal is to take two arrays, combine them, and discard any duplicate values, using a Set will automatically discard the values that appear more than once for you.

Simply use:

var mySet = new Set(array1)
array2.forEach((item)=>{mySet.add(item)});

Then convert the set back to an array if you need it specifically in array form, using the spread operator:

var finalArray = [...mySet]

'finalArray' will now hold each unique value from the combination of your two original arrays.

If your goal is to compare two arrays, removing values from the first array that are present in the second, use filter:

var finalArray = array1.filter((item)=>{return !array2.includes(item)})

'finalArray' will now hold all values of array1 that do not also exist in array2.


You have several different options for this:

Guava

Google's Guava Library introduces the idea of a Multiset which is capable of counting the occurrences, and also provides a couple of other features.

Java 8

If you are using Java 8 (which I highly recommend if you have the ability to do so), your tokenFound method can simply be this:

occurrences.merge(token, 1, (oldValue, one) -> oldValue + one);

Or this:

occurrences.compute(token, (tokenKey, oldValue) -> oldValue == null ? 1 : oldValue + 1);

Note that as of Java 7, you can initialize the map with the "diamond operator":

Map<Token, Integer> occurrences = new HashMap<>();

Without Java 8, no libraries

If you are unable to use Java 8 and don't want to add Guava as a third party library to your project, there are a small part you can do to simplify your existing code:

Integer previousValue = occurrences.get(token);
occurrences.put(token, previousValue == null ? 1 : previousValue + 1);

More specifically:

Using the new Integer constructor is not necessary, Java automatically uses boxing to do this. For Integer values close to zero, this will actually save you a little bit because Java keeps some integers cached.
You don't need the newNumberOfOccurs variable as it's only used once.


Have a look at this. I think the real question is pass by value vs pass by reference.

More info here.

Edit:
The line could be modified to following:

CreateEmployee(ref employee);

and the method name would be:

private void CreateEmployee(ref employee)


Comparing XML string with different formats

Googling for xml compare c# produces countless results so I just review this code without suggesting anything alternative.

settings.IndentChars = "  ";

I find new string(' ', 3) is easier to understand then three (?) spaces.

    if (xmlA == null && xmlB == null)
        return true;

This is questionable. I'd say it should be false.

var settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;

Don't you like object initializers?

var settings = new XmlWriterSettings
{
    OmitXmlDeclaration = true
};


Calculating primes: Could this be any faster?

There are some optimizations that can make your code better, even with compiler optimizations turned on:
Pre-allocate the vector and treat it like an array.
Use a variable to keep track of the length.
Putting these together, I found about a 10% increase in speed:
vector<int> primes(size_t nb_primes)
{
    vector<int> p(nb_primes,2);
    int n = 2;
    size_t len_p = 0;
    while (len_p < nb_primes)
    {
        bool other = true;
        for (size_t i = 0; i < len_p; i++)
        {
            if (n % p[i] == 0)
            {
                other = false;
                break;
            }
        }
        if (other)
            p[len_p++] = n;
        n += 1;
    }
    return p;
}


The first thing that I see when I look at your code is that it is UGLY.  I appreciate it doesn't affect how well the code works, but it does affect how easy it is to read and if it is hard to read then you are more likely to miss important issues.  When you come back to this code in three months it will be like you are new to it.  So my first recommendation is adopt a common style for the language you are using and make sure you stick to it.  Look at other people's C# code on here, yours looks more like Java than C#.
You have defined neighbourIndex at the top and assigned an initial value to it a few lines later.  It is a good idea to always assign a value to a variable when you declare it.  To be honest this is less important in C# that C++, but you can still get in nasty situations when you assume an object has been assigned a value and it hasn't.
You have used a nice, descriptive name like neighbourIndex and then gone and used i and j.  If I have read the code correctly these are the x and y co-ordinates of a cell.  So why not use x and y?  Also since you have already used the Point class would it not be a good idea to use the Point class to store i and j in?
In C#, as far as I understand, there is no difference in the speed of execution of x++ and ++x, but in other languages with other compilers this may not be the case (C++ for instance) so I would recommend that if you are doing x++; you get into the habit of doing ++x; because this can sometime be faster for non simple data types.  HOWEVER in this case it would be better to do
neighbors[neighborIndex++] = new Point(i, j);
I agree with user673679 that there could be a significant amount of optimisation here, you are doing something very similar 4 times, that should scream out to you to be optimised.

And finally a positive, your code is littered with comments and that is brilliant, keep it up.  If you decide to make any changes then remember to check that your comments still make sense.  Also finish the job off with a nice descriptive comment at the top of the functions to explain what the function does, what the parameters are, what ranges they take and what the function returns.  If you really want to go all out, describe the expected pass and fail conditions so that it becomes easy to write tests for the function.

Hope that helps


Too fancy, too hard to read. The whole code can be compressed into something like
 BCrypt.Net.BCrypt.HashPassword(salt+password).ToArray()
Take a look at how to use this function here: https://jasonwatmore.com/post/2020/07/16/aspnet-core-3-hash-and-verify-passwords-with-bcrypt
Most importantly: there's no point in using mighty hashing like SHA3 and BCrypt only to use some made-up XOR encryption scheme. Use a standard encryption algorithm from a reputable library. If you don't trust any library or algorithm, then encrypt 2 times with two different algorithms, different keys and maybe using libraries from different vendors.
Beyond that, here are other issues I have with this code:

Is .Skip(7) supposed to somehow remove the salt? You can't "remove" the salt, the string you get from that function is not your input anymore, it's a completely different string (aka hash).

All these IEnumerable aren't efficient. Just use byte[].

there's an attempt to be efficient with bitshifts. Just use % and leave it to the compiler. Given the rest of the code doesn't look like the most efficient implementation (IEnumerable, yield...) it makes no sense to sacrifice readability

to that end - add other comments. It's not clear what GetBytes is supposed to achieve, given its generic name and lack of comments.

if the password is null, empty, or string below a certain length - throw an exception. There's no point in encrypting something with an empty password

name things properly. byte offset is not an offset (that would have been i % key.Length), it's a byte from the key

use constants instead of magic values sprinkled across the code.

get familiarized with common encryption libraries and try to follow their patterns, don't reinvent wheels that need no reinventing


What you need is a Money class.

class Money
{
    int   value;
    static int normalize(double dallarsAndCents)
    {
        return std::round(dallarsAndCents*100);
    }
    public:
        // Deliberately not using explicit (because I want double;s to auto convert)
        Money(double dallarsAndCents)
           : value(normalize(dallarsAndCents))
        {}

        friend std::ostream& operator<<(std::ostream& out, Money const& m)
        {
            return out << m.value / 100 << "." << std::setw(2) << std::setfill('0') << m.value % 100;
        }
        friend std::istream& operator<<(std::istream& in, Money& m)
        {
            double newValue;
            if (in >> newValue) {  // only do assignment if read works.
                m = Money(newValue);
            }
            return in;
        }

        // Define some arithmetic operations here.

};

You don't want to use new or delete in your code. If you are doing that (and you are not in the very bottom of a class doing resource management) then you are doing it wrong.

Local variables just declare locally. If you need a dyncmaically sized container of objects then use a standard container (std::vector is a good default to start with).

v = new float[n];
....
delete v;

This looks neat and tidy but is not good code. You are susceptible to a memory leak if an exception is thrown. You should be using a container that handles the memory for you.

 std::vector<float>  v(n); // Does the same thing but is exception safe
                           // Look up RIAA for why it is exception safe.

Don't use one line for multiple things.

int n; cin >> n;

This is just lazy. It reads nicer if you use more than one line.

Also read Why is “using namespace std;” considered bad practice? about using namespace;. The reason the standard library is named std and not standard is so that prefixing things is not a major burden. Prefer to use std::cin.

Again the one line thing.

float *v, sum, avg, dif;

It makes it hard to read. The * is on the wrong side because you are squishing things together. Note: The star is part of the type information not the object. This is the opposite of C style.

float*  v;
float   sum = 0.0;
float   avg = 0.0;
float   dif = 0.0;