ValueAnimator for IOS - Did I butcher it up?

Is there a way to tidy up the numerous functions into something like a dictionary?

Sure, there are various options. But first the functions should be made independent of maxIterations, i.e. the computation

Double(currentIteration) / Double(maxIterations)

should be done in the caller so that the functions simplify to

private func sine010(x: Double) -> Double {
    return (-cos(2 * .pi * x) + 1)/2
}

thus avoiding code duplication. Note also the use of the “implicit member expression” .pi – the type Double is automatically inferred from the context.

Now you could define a dictionary mapping a function types to functions. The functions can be embedded directly as closures instead of defining global functions:

let functionDict : [FunctionType: (Double) -> Double] = [
    .SINE_WAVE_FROM_0_TO_1_TO_0: { (1 - cos(2 * .pi * $0)) / 2 },
    .SINE_WAVE_FROM_0_TO_1: { (1 - cos(.pi * $0)) / 2 },
    .SINE_WAVE_FROM_1_TO_0: { (1 + cos(.pi * $0)) / 2 },
]

The disadvantage is that you are now responsible to update the dictionary if new function types are added.

A perhaps better alternative is to make the function a computed property of the function type enumeration:

enum FunctionType {
    case SINE_WAVE_FROM_0_TO_1_TO_0
    case SINE_WAVE_FROM_0_TO_1
    case SINE_WAVE_FROM_1_TO_0

    var f: (Double) -> Double {
        switch self {
        case .SINE_WAVE_FROM_0_TO_1_TO_0: return { (1 - cos(2 * .pi * $0)) / 2 }
        case .SINE_WAVE_FROM_0_TO_1: return { (1 - cos(.pi * $0)) / 2 }
        case .SINE_WAVE_FROM_1_TO_0: return { (1 + cos(.pi * $0)) / 2 }
        }
    }
}

Now everything is in “one place” and the compiler can check the exhaustiveness of the switch statement.

A disadvantage of all the above definitions is that they can not be extended: There is no way that a user can define its own interpolation function and pass it to the value animator.

So what I would really do is to define a struct as the function wrapper, with static properties for predefined functions. I am calling it Interpolator now (resembling the Android TimeInterpolator).

class ValueAnimator {

    struct Interpolator {
        // A function mapping [0, 1] to [0, 1].
        let f: (Double) -> Double

        // Predefined interpolation functions
        static let sineWaveFrom0To1To0 = Interpolator(f: { (1 - cos(2 * .pi * $0)) / 2 } )
        static let sineWaveFrom0To1 = Interpolator(f: { (1 - cos(.pi * $0)) / 2 } )
        static let sineWaveFrom1To0 = Interpolator(f: { (1 + cos(.pi * $0)) / 2 } )
    }

    // ...
}

Note also that I switched to lower camel case for the property names, which is the standard for all Swift identifiers except for types.

Now a user can easily add more interpolation functions, e.g.

extension ValueAnimator.Interpolator {
    static let linear = ValueAnimator.Interpolator(f: { $0 } )
}

  Is there a way of accomplishing the same functionality ... but without using a selector? ... I ask because of the nasty "MyNSDoubleObject" workaround.

First: The wrapper object is not needed even if you use selectors: Swift automatically wraps values in Objective-C compatible types if necessary. Which means that you can pass a floating point value through the selector:

let value: Double = ...
target.perform(selector, with: value)

and the receive can (conditionally) cast it back to a Double:

@objc func animate(obj: AnyObject) {
    guard let value = obj as? Double else { return }
    print(value)
}

So the MyNSDoubleObject workaround is not needed.

But it becomes much simpler if you replace the target/selector method by a simpler callback with a closure. Similarly for the local timer: With a block-based timer, the timer callback need not be Objective-C compatible, and the ValueAnimator class does not have to subclass NSObject anymore.

Some minor remarks: The

private let sampleRate: Int

property is not needed. Instead of initializing with an (inactive) timer

private var timer = Timer()

I would use an optional:

private var timer: Timer?

X_currentRepIndex and F_of_X to not follow the Swift naming conventions, the latter name is quite non-descriptive.

Putting it all together, the ValueAnimator class could look like this:

class ValueAnimator {

    struct Interpolator {
        // A function mapping [0, 1] to [0, 1].
        let f: (Double) -> Double

        // Predefined interpolation functions
        static let sineWaveFrom0To1To0 = Interpolator(f: { (1 - cos(2 * .pi * $0)) / 2 } )
        static let sineWaveFrom0To1 = Interpolator(f: { (1 - cos(.pi * $0)) / 2 } )
        static let sineWaveFrom1To0 = Interpolator(f: { (1 + cos(.pi * $0)) / 2 } )
    }

    // args
    private let interpolation: Interpolator
    private let callback: (Double) -> Void

    // computed from args
    private let maxIterations: Int
    private let timeInterval: Double
    private var currentIteration: Int = 0

    // Other properties
    private var timer: Timer?

    init(durationInSeconds: Int, sampleRate: Int, interpolation: Interpolator,
         callback: @escaping (Double) -> Void) {
        self.maxIterations = durationInSeconds * sampleRate
        self.timeInterval = 1.0 / Double(sampleRate)
        self.interpolation = interpolation
        self.callback = callback
    }

    func start() {
        timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true) { (timer) in
            let val = Double(self.currentIteration)/Double(self.maxIterations)
            self.callback(self.interpolation.f(val))
            self.currentIteration += 1
            if self.currentIteration > self.maxIterations {
                self.stop()
            }
        }
    }

    func stop() {
        timer?.invalidate()
        timer = nil
    }
}

and a sample usage could look like this:

class ViewController: ViewController {

    var valueAnimator: ValueAnimator?

    override func viewDidLoad() {
        valueAnimator = ValueAnimator(durationInSeconds: 2, sampleRate: 2,
                                      interpolation: .sineWaveFrom0To1To0)
        { [weak self] value in
            guard let self = self else { return }

            // Do something with value ...
        }
        valueAnimator?.start()
    }

}

Note the use of weak self in the closure to avoid a reference cycle.

Further thoughts:

Since  ValueAnimator is a “pure Swift” class now it can be made generic to support other value types, such as integers.
Finally: If the goal is to animate visual elements: don't reinvent the wheel, use Core Animation.


Using binary search to find the index of an item in a sequence

seq = set(seq)

This will cause index calculations to be incorrect. Consider this invocation:

index([1, 1, 2, 3], 2)

This should return 2 but your function returns 1. As a caller of your index method, I would expect the returned index to have item in seq.

    seq.update([item])

This is a bug. It's causing print(index([1, 1, 2, 3], 15)) to return 3, when it should return -1 or some other sentinel value to denote absence of an item in seq.

EDIT: The function's documentation clearly says that index will return the final index after insertion if item does not exist in seq.

sorted_seq = sorted(seq)

This is unnecessary. Validate/assume your input seq to be sorted. This should be the standard expectation from any caller invoking your index function.

Be careful about:

first_half = sorted_seq[:middle]
second_half = sorted_seq[middle:]

Python fortunately will not create copies of the list but other languages may create copies of the original list for this operation.

After you have removed seq.update([item]), you will need to check for the base of your recursion, namely when seq is empty, causing

middle_value = sorted_seq[middle]

to fail.

As an aside, try implementing this as an iterative algorithm.

It will run faster
The recursive version will crash for large seq.

Totally aside, have a look at Binary Search tutorial on TopCoder Its a pretty good article.


I swear I've seen this approach somewhere before, I'll have to see if I can't find that link again. Anyways, a couple of drawbacks of this approach is lack of portability and lack of familiarity. Portability meaning no one can move that code without also taking that class with it. Familiarity meaning not well known. Though I do have to admit, I would love to see PHP natively adopt an xpath navigation style for arrays. Would make life so much easier.

I would steer clear of using method names that are similar to PHP's reserved words. In other words get() would be better as fetch() or query() or something similar. Same for set() and exists(). This helps avoid confusion. The only time "get" or "set" is generally used is when defining a specific getter or setter such as getPath() or setPath(). _engine() is also oddly named, would expect _parse() or _evaluate() or something similar. But this is all stylistic.

The only "real" criticism I have for this bit of code is that occasionally you neglect your braces. These are always important. Please remember them.

if ($this->_useCache && isset($this->_cache[$section]))
    return $this->_cache[$section];

The only improvement I can suggest is to abstract your caching to a different class in case you ever decide to change it.

Have you thought about creating relative pathing support? In other words, using your example, you could get the same results by using just "//date3"? The previous project I was thinking about did this and I was quite impressed. If there was more than a single match it would return a set of results. It also knew only to look one level deep relative to the array passed to it.

Overall, very impressive though. Sorry I couldn't add more to it.


Counting vowels and consonants in a string

To count the occurrences of things, use collections.Counter.

The lowercase letters are available as a predefined constant string.ascii_lowercase.  You can use a generator expression to filter out the vowels and obtain the consonants.  PEP 8, the official style guide, suggests using ALL_CAPS as names for constants.

I've used the * operator when calling print() to treat each element of a tuple or list as a separate argument.

Note that your formatting will break when any character has more than 9 occurrences.

from collections import Counter
from string import ascii_lowercase

VOWELS = tuple("aeiou")
CONSONANTS = tuple(c for c in ascii_lowercase if c not in VOWELS)

print("PROGRAM: Vowel count\n")
s = input("Please, enter a text string: ")
counts = Counter(s)

print('{0} characters'.format(len(s)))
print(*VOWELS)
print(*[counts[c] for c in VOWELS])
print(*CONSONANTS)
print(*[counts[c] for c in CONSONANTS])


It doesn't use 300 megabytes of heap, it peaks at a little over 20 megabytes. Total allocation is not peak allocation and Haskell has cheap short-lived allocations so total alloc isn't always a good heuristic for GC time or steady-state heap usage. The heap profiling stuff is giving data designed for tuning code rather than for analytics and total alloc is often more helpful when comparing code for overall memory usage.

Here's a screenshot from a memory profile:

I don't think it necessarily bit you here, but in future, add explicit types to functions you are benchmarking. See here for an example of why you want to do that.

Here's the command I wrote to profile your code:

$ rm -f collatz
$ stack ghc -- -prof -fprof-auto -rtsopts -O2 collatz.hs -o collatz
$ ./collatz +RTS -hc -p
$ hp2ps collatz.hp
$ evince collatz.ps

Last bits are just converting the hp heap profiling data to a postscript file and then I'm opening it in my PDF reader.


Throwing Swift errors is a mechanism how a function/method can report a failure to its caller. Your code throws and catches the error within the
same method, and I can see no advantage of using try/catch in that
situation. Your code is equivalent to

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    guard status == .authorizedWhenInUse else {
        print("User has not authorized us to use location")
        return
    }
    guard CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) else {
        print("User has not authorized us to use location")
        return
    }
    guard CLLocationManager.isRangingAvailable() else {
        print("User's device does not support ranging")
        return
    }
    startScanning()
}

which is

shorter and easy to understand,
makes the enum LocationError obsolete (which is fileprivate,
and therefore apparently not used anywhere else),
makes the catch-all with fatalError() obsolete.

I would even go a step further: guard is useful in connection with
optional binding (to avoid the "optional binding pyramid of doom").
In your case, the same can be achieved with a simple if/else if/.../else statement:

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if status != .authorizedWhenInUse {
        print("User has not authorized us to use location")
    } else if !CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
        print("User has not authorized us to use location")
    } else if !CLLocationManager.isRangingAvailable() {
        print("User's device does not support ranging")
    } else {
        startScanning()
    }
}


Since this is the backend to a login request, I assume that you expect just 2 inputs, the password and one of the others.  So why not use the following:

//gets an array of all inputs: email & pass or ssn & pass or phone & pass...
$credentials = $request->all();

try{
    if(!$token = JWTAuth::attempt($credentials)){
        return response()->json(['error' => 'invalid_credentials'], 401);
    }

} catch (JWTException $e){
    return response()->json(['error' => 'could_not_create_token'], 500);
}

  i would like to minimise my if and else what would you guys recommend?

Hint: If you find yourself doing something over and over and over, you probably need a loop. Since this is a login form and that you expect just 1 variable besides the password, don't have so many vars in your script: $email, $ssn, $pager, badgenumber, ophone, fphone, ssn... just use $identifier.  If you really need to cycle through all possibilities build an array and loop until you find the one the user submitted:

$possibilities = ['email','ssn','badgenumber','ophone'...];
$identifier = '';
foreach ($possibilities as $i){
    if($request->has($i)){
        $identifier = $request->input($i);
        break; //exit the foreach loop b/c we've found the identifier
    }
}
$credentials = [$identifier, $request->input('password')];

Then you can attempt to create the token with those credentials.  Beware I've never used Laravel, but I wrote my answer after going over this helpful page on how to access requests.

Quick sidenote: I notice that you have a check that can be true only if email has length < 6, and another that can be true only if email has length > 6.  What if email has length===6 ?


SQL design for representing a two-level hierarchy of objects with containment

According the the MySQL reference for character types, varchar is limited to 65,535 characters (regular char is limited to 255).

There is also a text type which, according to the reference comes in 4 styles. The longest goes up to 4GB, which should be more than enough.


Do these unit tests cover my method under test?

About the function comment:

You're over-complicating the summary. As of how I understand the function does Get the first <paramref="maxLength"> characters as a summary. Special conditions are mentioned bellow. Those should be simplified as well.
For  maxLength I'd check for min/max integer as well as for -1/0/1 (does the function behave correctly at the limits?)
Check input for null and additionally for those combinations:

input.length < maxLength
input.length = maxLength
input.length > maxLength

You're not testing your code when testing for MB-functionality.
Test one thing at a time. If NullOrEmpty fails, how to you know which of those assertions failed? Does it fail if input is empty or if it is null?\
Remove comments, make the test-names more clear instead. Tests are simple and easy to understand (at least they should be :)). Safe your time of writing comments and improve the test instead.

For most of the functions you're just repeating the behavior asserted. However this is already written down by the assertion itself. The comment just duplicates the code.
In my opinion, test names should be speaking of what they do. NullOrEmpty doesn't state anything about what actually happens. NullInputReturnsNull and EmptyInputReturnsEmptyString do however. Furthermore speaking test-names can be used as a documentation (i.e testdox).

When are you done? Never. Eventually you (or someone else) will find bugs, misbehavior, ... (e.g. during integration). It's more important to keep the tests up to date at those times as well.

Update

On 2. I'm testing for MAX_INT because your promise is this functions accepts integer values between [0, MAX_INT]. Imagine at some time there is a maxLength + 1 statement for some reason. As a rule of thumb: always test the border values of parameters. Further reading: equivalence partitioning and boundary value analysis

On 3. That'd be four tests. You should split those.

On 4. The point is your are testing the c# library, not your code. You don't have any code dedicated for MB handling. What you are actually doing is testing the Substring method and Length property for MB handling.


Function to return the closest Date to Today (inclusive) from Ordered list

Because this method is Public you should check if lstOrderedDates is Nothing and you should't believe that the passed List really is ordered.

Doing the check on lstOrderedDates.Count for 0 and 1 first will save one indentation for the meat of the code.

Placing Dim dateToCheck = lstOrderedDates.ElementAt(1) inside the loop will remove the need for the  third if inside the loop.

The second if isn't needed at all because of the first if. You can just set selectedDate = dateToCheck.

Would lead to:

Public Shared Function GetClosetDateToToday(lstOrderedDates As List(Of Date)) As Date

    ' Select the closest Delivery date to TODAY (inclusive) from the list of Ordered dates
    If lstOrderedDates is Nothing OrElse lstOrderedDates.Count = 0 Then
        Return Nothing
    ElseIf lstOrderedDates.Count = 1
        Return lstOrderedDates.ElementAt(0)
    End If
    Dim ordered as List(Of DateTime) = lstOrderedDates.OrderByDescending(function(d) d).ToList()
    Dim selectedDate = ordered.ElementAt(0)
    For i = 1 To ordered.Count - 1

        Dim dateToCheck = ordered.ElementAt(i)

        If dateToCheck < Date.Now.Date Then
            Exit For
        End If

        selectedDate = dateToCheck

    Next i
    Return selectedDate

End Function

In C# I would do it using some Linq magic like so

    public static DateTime GetClosetDateToToday(List<DateTime> ordered)
    {
        if (ordered == null || ordered.Count == 0) { return default(DateTime); }

        var result = ordered
                     .OrderByDescending(item => item)
                     .LastOrDefault(item => item >= DateTime.Now);

        if (result == default(DateTime))
        {
            return ordered[0];
        }
        return result;
    }

which should be equal to the VB.NET version but without guarantee

Public Shared Function GetClosetDateToToday(lstOrderedDates As List(Of Date)) As Date

    ' Select the closest Delivery date to TODAY (inclusive) from the list of Ordered dates
    If lstOrderedDates is Nothing OrElse lstOrderedDates.Count = 0 Then
        Return Nothing
    End If

    Dim found as DateTime = lstOrderedDates
                            .OrderByDescending(function(d) d)
                            .LastOrDefault(function(d) d >= DateTime.Now)
    If found is Nothing then
        found = lstOrderedDates.ElementAt(0)
    End If

    Return found

End Function


There is a of lot room for improvements in your code so let us start straight ahead with your class
functions

Based on the .NET Naming Guidelines classes should be named using PascalCase casing which isn't the only problem here. Naming things is hard but its much harder to grasp at first glance what a class, method or field is used for if one uses names like function, MyFun or fun1..fun3. If you come back in a few weeks/months to fix a bug or to add a feature you still need to understand quickly what the code is doing which will be harder if you keep these names.

Math.Pow(x,2) should always be replaced by x * x which will be faster

Bisection

You are executing fun(start) at least one time but up to four times. By storing the result of the method call inside a variable you code will be easier to read and also be faster. The same applies to fun(end).

double avg,tolerance,sign; don't do this. Its to hard to read. Always declare one variable per line.

omitting braces {} is valid in C# but it is dangerous as well because it can lead to hidden and therefor hard to find bugs. But if you decide for yourself to take the risk you should at least be consequent with your style. Right now you are sometimes using braces and sometimes you don't.

If a value of a method parameter doesn't fit in the range of an expected value one should throw an ArgumentOutOfRangeException or if the value is plainly wrong one should throw an ArgumentException instead of writing to the console and returning a magic number (-1).

Numbers used like tolerance > 0.0001 should be stored in a meaningful named constant so every reader of the code exactly knows what 0.0001 represents.


Using std::chrono to make custom "SI unit" types

Meters are Not Seconds

using meters = std::chrono::seconds;

I know it's obvious, but it bears stating. A meter is not a second. You compare a meter and a second, you cannot add them, etc. They are different types completely. So what you want is to make a different type:

template <typename T, class Ratio = std::ratio<1>>
class distance;

using meters = distance<int64_t>;

I'll leave the implementation of distance up to you. But it should absolutely be a different class than seconds!

Use the Standard Ratios

<ratio> actually provides a bunch of standard ratios for your use. You should use them:

using centimeters = distance<int64_t, std::centi>;

You'll note that std::centi is std::ratio<1, 100>, which makes more sense for centimeters than std::ratio<100>.

Use integral types

You'll notice I used int64_t instead of float or double. Prefer using integers whenever possible to simply sidestep the issue of floating point arithmetic altogether.


How can I make this CouchDB view code more "correct"?

You can use CouchRest::Database.get_bulk API:

hash[row['key']] = database.get_bulk(row['value']).sort_by(&:pulled_at).reverse


Don't Repeat Yourself

Okay, a good way of getting rid of repeated formulas is to use move them into a CROSS APPLY.

We can move the following into a CROSS APPLY, which I named Calcs.

, SUM((ISNULL(Price,0) * Qty)) -- Subtotal
, SUM(CAST((ISNULL(SalesTaxRate,0) * ISNULL(Price,0) * Qty) / 100 AS DECIMAL(6,2)))
, SUM(CAST((ISNULL(ImportTaxRate,0) * ISNULL(Price,0) * Qty) / 100 AS DECIMAL(6,2)))

I'm actually not going to include the divide by 100 bit in my CROSS APPLY, which makes stuff a little easier for us later.

Applying Yourself to the Problem

For now I'm going to ignore the Totals bit, you'll see why a little later.
This is what the query looks like now:

SELECT
    Id,
    Product,
    [Price] = COALESCE(Price,0),
    Qty,
    [Subtotal] = Calcs.Item_Price,
    [Sales Tax] = CAST(Calcs.Sales_Tax / 100 AS DECIMAL(6,2)),
    [Import Tax] = CAST(Calcs.Import_Tax / 100 AS DECIMAL(6,2)),
    [Total Tax] = COALESCE(CAST((Calcs.Sales_Tax + Calcs.Import_Tax) / 100 AS DECIMAL(6,2)),0),
    [Line Total] =
    Calcs.Item_Price
    + COALESCE(CAST((Calcs.Sales_Tax + Calcs.Import_Tax) / 100 AS DECIMAL(6,2)),0)
FROM #Sales
CROSS APPLY
(
    SELECT
        ISNULL(Price,0) * Qty AS Item_Price,
        (ISNULL(SalesTaxRate,0) * ISNULL(Price,0) * Qty) AS Sales_Tax,
        (ISNULL(ImportTaxRate,0) * ISNULL(Price,0) * Qty) AS Import_Tax
) Calcs

Rollup, Rollup!

Now, a SQL keyword you don't see used very often. We are going to use GROUP BY X WITH ROLLUP to automatically generate a total column for us.

What you want to do is add a GROUP BY Product WITH ROLLUP below the CROSS APPLY. The query needs a couple of modifications now though, because we've added aggregation.

Basically for anything that will be included in both the data and the totals, you take either the SUM, if it is a numeric column, or either the MIN or MAX for text fields.

For fields that you only want to include in either the data or totals, you have to add a CASE statement to the select query similar to one of the following:

--For the total column, GROUPING(Product) will be 1
-- for the data columns it will be equal to 0
CASE
    WHEN GROUPING(Product) = 0
    THEN MAX(Product) --For data rows, return the product
    ELSE 'Totals' --For the total row, return the text 'Totals'
END AS Product,

CASE
    WHEN GROUPING(Product) = 0
    THEN MAX(Price) --For data rows, return the price
    --We don't include an else because we don't want to
    -- want anything to be returned for this field in the totals column.
END AS Price,

All Together Now!

Here is what I ended up with, which I think has much less repeated formulas and avoids having to basically repeat the entire query twice.

SELECT
    CASE
        WHEN GROUPING(Product) = 0
        THEN MAX(Id)
    END AS Id,
    CASE
        WHEN GROUPING(Product) = 0
        THEN MAX(Product)
        ELSE 'Totals'
    END AS Product,
    CASE
        WHEN GROUPING(Product) = 0
        THEN ISNULL(MAX(Price), 0)
    END AS Price,
    CASE
        WHEN GROUPING(Product) = 0
        THEN MAX(Qty)
    END AS Qty,
    [Subtotal] = SUM(Calcs.Item_Price),
    [Sales Tax] = SUM(CAST(Calcs.Sales_Tax / 100 AS DECIMAL(6,2))),
    [Import Tax] = SUM(CAST(Calcs.Import_Tax / 100 AS DECIMAL(6,2))),
    [Total Tax] = SUM(COALESCE(CAST((Calcs.Sales_Tax + Calcs.Import_Tax) / 100 AS DECIMAL(6,2)),0)),
    [Line Total] =
    SUM(Calcs.Item_Price
    + COALESCE(CAST((Calcs.Sales_Tax + Calcs.Import_Tax) / 100 AS DECIMAL(6,2)),0))
FROM #Sales
CROSS APPLY
(
    SELECT
        ISNULL(Price,0) * Qty AS Item_Price,
        (ISNULL(SalesTaxRate,0) * ISNULL(Price,0) * Qty) AS Sales_Tax,
        (ISNULL(ImportTaxRate,0) * ISNULL(Price,0) * Qty) AS Import_Tax
) Calcs
GROUP BY Product WITH ROLLUP
ORDER BY GROUPING(Product),Id


Your fibonacci function is veryyyyyy slow.
Why? Well

fibonacci 5 = fibonacci 3 + fibonacci 4
            = fibonacci 1 + fibonacci 2 + fibonacci 2 + fibonacci 3
            = 1 + 2 + 2 + fibonacci 1 + fibonacci 2
            = 8

Do you see what's wrong? That's right, you computed fibonacci 3 two times.
So, for high values of n, you are going to compute it a lot!
The naive linear fibonacci is usually written as fibonacci = 0 : 1 : (zipWith (+) fibonacci (tail fibonacci)) and is explained here: https://stackoverflow.com/questions/43486880/take-n-with-zipwith-and-tail

Another tip: Do not overuse list comprehension, it tends to get very unreadable fast. For instance your:

evenFibonacci' = [eF' | eF' <- evenFibonacci, eF' <= 4000000]

Is misleading because it wouldn't work if evenFibonacci is infinite (but it really should). I believe that is why you declared fibonacciList as finite, while there wasn't any reason to.
So how could we make it so it does? Well we know evenFibonacci is strictly increasing, so we could take advantage of it:

evenFibonacci' = takeWhile (<= 40000) evenFibonacci

Similarilly fibonacci <$> [1 .. 32] is even shorter than your version.
(I'll let you rewrite evenFibonacci on your own ;) )

Finally I advise you not to do so many variable declarations, declarations are fine when those variables can be standalones, but it isn't really the case of your evenFibonacci'. You really should either compose variables or use some where

Have fun!


Does this PDO process look protected from SQL injection?

It looks like your script is part of a basic ajax searching technique.

$_POST is typically used when writing to the database (or when there is a distinct reason that $_GET is unsuitable). Since you are merely SELECTing data, just use $_GET.
if you are going to validate your incoming data, don't bother acquiring resources until after you have validated the incoming data and determined that it qualifies for a trip to the database.  If you are going to default to SELECTing the whole table, then it doesn't matter.
it looks like if params 1 and 2 are missing, you are happy to perform a full table SELECT.  So why deny the full table SELECT if details isn't declared?
empty() is greedy -- it is looking for any falsey value.  Even the string 0 - which has a length of 1 - is deemed empty. Perhaps do a strlen() check instead.
I don't think that trimming should be forced on the data if part of a search string -- maybe the user wants to include the space.
don't htmlspecialchars() as an attempt to improve security.  The prepared statement is going to protect you from string injections.  This call should be used when printing to screen, not querying the db.
I think you have a typo in your second WHERE condition in that you mean to use a second LIKE but you have used = and kept the % appended to the value.
I recommend that you design your table names and column names as lowercase strings to differentiate them from MYSQL keywords.
you are not performing an data manipulations on the result set in this layer, so it will be more direct to fetchAll()
always provide a response string from this script; ideally every response should be json so that your response receiving script can be simpler.
never show end users the raw error message. Give them a vague indication of an error and nothing more.
As @YourCommonSense commented, you should move your $conn->setAttribute call your include file.
Normal execution of your script will not be generating any errors.  Catching the errors will prevent the logging of the errors.  I recommend removing the try catch block.  For continued researching, start here.

Code:

$conditions = [];
$parameters = [];

foreach (['param1' => 'COLUMN1', 'param2' => 'COLUMN2'] as $param => $column) {
    if (isset($_GET['details'][$param]) && strlen($_GET['details'][$param])) {
        $conditions[] = $column . " LIKE ?";
        $parameters[] = $_GET['details'][$param] . "%";
    }
}

include("../include/database.php");
$select = "SELECT COLUMN1, COLUMN2 FROM table";
if ($conditions) {
    $select .= " WHERE " . implode(" AND ", $conditions);
}
$stmt = $conn->prepare($select);
$stmt->execute($parameters);
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));

In your ajax call, do not tell declare the response type as html -- it's not html, it is json.  In doing so, you won't need to parse it.


All in all it seems OK to me. A couple of things though:

1)

  const int validCodePointCount = 10;
  const int validCodePointOffset = 48;

The names of these constants are hard to distinguish from each other and to understand in the context and they blur the behavior of the algorithm.

Better names could be:

const int numberBase = 10;
const int zero = '0';

Here I use '0' instead of 48 because the first is much more recognizable to programmers than the latter, and we instantly grasp the meaning. In fact in such a relatively small algorithm, I would prefer to use the literals directly in the code than the named constants like:

var digit = (value[index] - '0');

This is such a common operation and we all know what it's about immediately when seeing it.

In general it is wise to avoid magic numbers, but in some situations it is preferable in order to improve readability - IMO.

2)

You don't have to iterate backwards because you can determine the initial parity from the length of the input string:

var parity = value.Length % 2 != 0;

You can then iterate forward:

foreach (int n in value.Select(c => c - '0'))
{
  ...
  parity = !parity;
}


I'm going to intersperse bits of code with my comments on them:

template <typename F>
struct testfunc {
    F *fn;
    const char *name;
};

testfunc isn't an entirely self-explanatory name (especially given that it's a template, so F could be pretty much anything. A comment about the basic intent would be quite helpful.

#define TEST(x) { x, #x }
template <typename T>

I'd rather see a blank link after the end of TEST to make it clear that the subsequent template isn't particularly closely related. Other than that, the same comment as previously applies: the name TEST doesn't tell us much, so a comment (or more explanatory name, or both) might be helpful here.

static constexpr unsigned incr = 13;

Two points here. First, I'm not entirely excited about the name: the value is used as an increment in one place (which seems to fit well with the name) but as the upper limit on a loop in another place (which doesn't fit quite so well).

Second, I'm left wondering exactly what (if any) significance the value 13 has. Is it arbitrary, or does it matter that it happens to be odd, or perhaps it matters that it's prime. Or maybe it's really a carriage return in disguise (oh, but only some crusty old assembly language programmer would notice that; no wonder it never occurred to you:-) !)

std::cout << std::endl;

It seems likely that this is one of the (rare) times that somebody is using std:endl because they really want what it does. Personally, I'd rather do that a bit more explicitly with std::cout << "\n" << std::flush; though. Otherwise, some busybody might conclude you're part of the crowd that routinely uses endl when they really just want a carriage return, and change it to the latter.

As far as the test method goes, it only tests one very specific pattern. It fits well with the Sieve of Eratosthenes, but doesn't tell you much about (for example) repeated manipulations of the same parts of the vector. If that fits closely with your intended usage pattern, that's fine--but there are clearly a lot of other possible uses about which this is likely to tell us little or nothing.


Reading a dynamic record length binary file

open (FILE, $ARGV[0]) or die $!;

It won't really make a difference in this script, but the standard is to use a variable rather than a bareword.

open (my $fh, $ARGV[0]) or die $!;

This gives you the benefits of lexical scoping.

while (<FILE>) {

What this says is while there are still lines in <FILE>, do the things in the block.  It separates lines by the line ending marker, which is normally a linefeed.  This would normally be used:

while ( my $line = <$fh> ) {
    chomp $line;

Then you could break the line up into parts with unpack.

    my ( $field1and2, $vector_count, $field4, $vector_field ) = unpack( 'A2395 A3 A254 A*', $line );

Note that I may have the format wrong.  It's easier if one can test against a valid file.  You may not even need that much:

    my ( undef, $vector_field ) = unpack( 'A2652 A*', $line );

It seems like you only use the vectors portion.

Instead, you use the while loop just to keep count.  However, that wouldn't normally work unless records were terminated with linefeeds.

open (my $fh, $ARGV[0]) or die $!;
while ( my $line = <$fh> ) {
    chomp $line;

    filewrite ($ARGV[1], recordparse($line));
}

See how that's simpler?  No more seeks.  This doesn't even require unpack, as it looks like you pass the whole line to recordparse.

One more thing:

filewrite ($ARGV[1], recordparse($string));

I'm not sure what this function does, but it looks like it takes a file name and writes to it.  This suggests that it opens the file each time.  Better would be to open the file once and pass a filehandle to it.

If you were getting multiple records with the original code but there are no linefeeds in the file, then I suspect that the seek and read commands are resetting the line input operator.

Alternate version to handle reading the entire file at once (assumes no linefeeds in the data).

open (my $fh, $ARGV[0]) or die $!;
my $file = <$fh>;
while ( '' ne $file ) {
    my $rep_factor = substr $file, 2396, 3;
    my $vector_count = undefined2defined(convert2ascii_decimal($rep_factor, 0));
    my $size = ($vector_count * 301) + 2652;

    my $record = substr $file, 0, $size;
    $file = substr $file, $size;

    filewrite ($ARGV[1], recordparse($record));
}

This uses substr rather than unpack because it's easier to specify different lengths with substr.  The first version asks for $size bytes starting at the beginning.  The second version says to return everything but the first $size bytes.

I'm a little worried that there is some maximum length that the <> operator returns, but I don't know what it might be.  Since I don't have an example file, I'm not testing the code at all.


Many onClick handlers that all append different text to one textarea

We can reduce duplication by using an object as a dictionary, and look up an output value based on an element's ID.

var messageMap = {
    "add_user": "Lorem",
    "add_disallow": "Ipsum",
    "add_wild": "Dolor",
    "add_comment": "Hey",
    "add_bb": "World",
    "add_gdrive": "Its Time",
    "add_gimage": "To Move",
    "add_gnews": "Again",
    "add_bash": "Thats it"
};

$(document).ready(function() {
    $.each(messageMap, function(key, value){
        $("#" + key).on("click",function() {
            $("#textareaFixed").append(messageMap[$(this).attr("id")]);
        });
    });
});


To answer your question directly, you can express a proc/block/lambda as

Proc.new do |...|
# or
lambda do |...|
# or
-> (...) do

Either syntax (and your current one) should work fine for this. To invoke the block, you can use square brackets like now, or use call.

Really, that's about it, unless I'm misinterpreting your question.

However, I see some other issues with your code:

Use a hash for the arguments. Please. The current construction is very un-Ruby-like. A hash will also "force" you to write the method (or block, in this case) in a more generic manner, since a hash can have any number of key/value pairs.
Why length? It's just a number. Whose to say it's the length of anything?
Also, why add 1 to length? Just wondering. If anything, going from an array's length to an index usually involves subtracting 1.

Something like this seems cleaner (though it's as much about FizzBuzz as it is about procs):

def custom_fizz_buzz(divisors = {"Fizz" => 3, "Buzz" => 5})
  divisors = divisors.sort_by { |_, value| value }
  -> (number) do
    output = divisors.map { |key, value| key if (number % value).zero? }.compact.join
    output.empty? ? number : output
  end
end

which'll give you

custom_fizz_buzz[7]                              # => 7
custom_fizz_buzz.call(9)                         # => "Fizz"
custom_fizz_buzz[15]                             # => "FizzBuzz"
custom_fizz_buzz("What's " => 3, "up?" => 7)[21] # => "What's up?"

or even

1.upto(100).map(&custom_fizz_buzz) # => [1, 2, "Fizz", 4, "Buzz", .... etc.]


Defining metaclass instance methods inside of the metaclass factory instead of the metaclass itself - flawed design?

It would seem to me that a simpler way (without a metaclass) to do more or less the same would be

Define a base class SlottedClass with empty __slots__.
Define  __init__, __call__, __repr__ etc. as normal instance methods in SlottedClass.
The class factory only needs to set __slots__ on the subclass it creates:

def mesh_class(name, fields):
    if isinstance(fields, str):
        fields = fields.replace(',',' ').split()
    ##Test for repeated fields
    if len(set(fields)) < len(fields):
        raise Exception
    ##Test for fields beginning with underscore
    for field in fields:
        if field[0] == '_':
            raise Exception
    new_class = type(name, (SlottedClass,), {'__slots__': fields})
    return new_class

Note by the way that list.sort() sorts in place and always returns None, so the code below does not do what it says. I've fixed it the code above.

    ##Test for repeated fields
    if list(set(fields)).sort() != list(fields).sort(): raise Exception


That's fine. You have exactly the includes you need, you didn't use using namespace, and you've used std::cin correctly.

However, I'd recommend you to use a code formatter next time, since some for your closing braces are misaligned. And if you use braces around a single statement in if, do the same for else.

Other than that, you can take a const auto & word instead of auto w to remove copies. Also word is a nicer name than w. Try to be more verbose, it helps when you read the code a second time.

Since we do not use temp after the while, should keep its scope smaller. We can use a for loop, wrap braces around the while and temp's declaration (which does the same), or write a small (inline) function.

We end up with

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> words;

    std::cout << "Enter a list of words.\n";

    for(std::string temp; std::cin >> temp;){
        words.push_back(temp);
    }

    for(const auto &word : words){
        if(word == "idiot" || word == "nonsense" || word == "hyper"){
            std::cout << "BlEEP" <<" ";
        } else {
            std::cout << word << " ";
        }
    }
}

I've added some whitespace to make the code slightly easier to read. However, our code works well for three words, but what about four, five or even ten? As soon as we have more words than fit in a single line, we probably want to store them in a container.

Exercise

Read the banned words from a file. Use those words to filter the text just like you did.


Personally I'm not sure why you're working so hard...

function validateNumber(valueToCheck) {
    return !isNaN(Number(valueToCheck));
}

or the more complete version from the question you've linked:

function validateNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

JavaScript already has a number parser.

This will allow values like '42', '1.456', '1.456e3', [42], etc. All valid Numbers.

And it passes your test suite better than the original: http://jsfiddle.net/nL4L13k2/4/ and http://jsfiddle.net/nL4L13k2/5/


Expose only desired functions to 3rd party plugins in JavaScript

Interesting question,

first things first, it does matter where you run the code. In web browsers, this will always be Window, so eval.call( {} , 'console.log(this)' ) will log Window. link

And, of course, any code reviewer worth his salt will tell you that eval is dangerous, can you update your question and tell us why you need eval ?

In general, I would point you to this for Node for possibly safer ways of accomplishing what you need. For web browsers I would look into running JS in it's own frame ?


It looks idiomatic and bug-free.

s++;

Perhaps ++s as a habit unless postfix s++ is required (as it is during the copy).

while((*s++ = *t++))

Could have just a single pair of parentheses.

void custom_strcat(char *s, char *t)

The signature of strcat is usually char* strcat(char* destination, const char* source). The const means that the source buffer is not modified. The return code is supposed to be a pointer to the original (unmodified) source value, so to implement this the implementation would need to increment a local variable copy of destination.

  This technique couldn't be applied in the first loop because when the loop stops s will point to an irrelevant value.

You could write that as, if (*s) while (*(++s));.


Firstly, you've hard-coded all of your key names instead of using the KEYS table for passing them to the script - this is both hard to maintain as well as incompatible with clustering.

Next, consider using MessagePack (cmsgpack in Redis' Lua) instead of JSON when serialiazing/deserializing questions (q) and users (u) - it is leaner and faster.

Also, the jdx, qtag loop looks like a membership test, so it should be replaced with a check against an associative table instead.

Overall, the code appears to be quite complex with multiple nested loops. Without more information on the values' sizes, it is hard to make an educated guess whether this is a viable approach, but intuitively I'd be hesitant about this. Furthermore, it is hard to understand the logic's purpose - it is perfectly possible that there are more efficient ways to do/model what you want/need, but it would be better if you'd provide an overview of the context and requirements before.


$("button").click(function(){
    if(clicked){
        $(this).css('background-color', 'red');
        clicked  = false;
    } else {
        $(this).css('background-color', 'blue');
        clicked  = true;
    }
});

You could do it like this instead

$("button").click(function(){
    var color = clicked ? 'red' : 'blue';
    $(this).css('background-color', color);
    clicked = !clicked;
});

We move the color picking to a single variable choice using a ternary statement and then we only have to write out the change to the CSS of the element once. then we flip the boolean.

I don't like the name of the boolean variable, it doesn't accurately describe what it is keeping track of, based on the way the code is written it should be named isButtonBlue.

If the button is blue, turn it red. If the button is not blue, turn it blue.

After looking at this a little bit longer I was thinking that you could make it one line shorter by making another line longer by moving the ternary statement into the CSS change

$("button").click(
    $(this).css('background-color', isButtonBlue ? 'red' : 'blue');
    isButtonBlue = !isButtonBlue;
});


A few things:

There's already a recursive overload of EnumerateFiles so you don't need getAllFiles. Your top level function would be:

let moveFrom source =
  Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)
    |> Seq.filter (fun f -> Path.GetExtension(f).ToLower() <> ".db")  //exlcude the thumbs.db files
    |> move """C:\_EXTERNAL_DRIVE\_Camera"""
  printfn "Done"

:? Exception is a type test pattern match, which is unnecessary in a try/with because with only fires for exceptions anyway. You could do this:

let getDateTaken file =
  try dateTakenFromExif file
  with _ -> File.GetLastWriteTime(file)

and this:

try File.Copy(file, newFile)
with e -> failwith (sprintf "error renaming %s to %s\n%s" file newFile e.Message)

instead.

addToFile could be merged into getNewFileName to form a simpler function without repetition:

let getNewFilename newFilePath =
  let rec loop file n =
    if File.Exists(file) then
      let fileDir = Path.GetDirectoryName(file)
      let nextFile = Path.GetFileNameWithoutExtension(file) + "-" + n.ToString() + Path.GetExtension(file)
      loop (Path.Combine(fileDir, nextFile)) (n+1)
    else file
  loop newFilePath 2

For easy parallelization you might try using PSeq ("parallel sequence") from the F# PowerPack. You might see some gains from simply doing this:

files |> PSeq.iter moveHelper


I feel there should be some way to iterate over the four properties instead of writing four separate lines.

You can use a higher-order function that takes in a function that returns a card property. Here is an example of how that could look. I've also simplified the code to the extent that none of the helper functions are needed, and changed some formatting to more idiomatic F#:

type Number = One | Two | Three
type Symbol = Round | Wavy | Diamond
type Shading = Empty | Lines | Full
type Colour = Red | Green | Blue

type Card =
    { Number: Number
      Symbol: Symbol
      Shading: Shading
      Colour: Colour}

let isSet card1 card2 card3 =
    let sameOrUniqueBy prop =
        let unique = [ card1; card2; card3 ] |> List.distinctBy prop |> List.length
        unique = 1 || unique = 3

    sameOrUniqueBy (fun c -> c.Number)
    && sameOrUniqueBy (fun c -> c.Symbol)
    && sameOrUniqueBy (fun c -> c.Shading)
    && sameOrUniqueBy (fun c -> c.Colour)

In this code, sameOrUniqueBy is a higher-order function because it takes a function as an argument. It is defined as a local function inside isSet so that the cards don't have to be passed in each time it's used.

Testing:

let card1 = { Number = Two; Symbol = Round; Shading = Lines; Colour = Green }
let card2 = { Number = One; Symbol = Round; Shading = Empty; Colour = Green }
let card3 = { Number = Three; Symbol = Round; Shading = Full; Colour = Green }

isSet card1 card2 card3 = true // ✔

isSet card1 card1 card3 = false // ✔


Searching for duplicates without any collection or sorting

As you may be aware, your solution takes O(n2) time.  Sorting can bring that down to O(n log n).  Hashing can produce an O(n) solution.  Of course, for a four-element array, performance isn't an issue at all.

Please take care to indent your code consistently.

This kind of loop structure…

int count = 0;
while (count < ar.length) {
    …
    count++;
}

… is more easily recognizable when written as a for-loop:

for (int count = 0; count < ar.length; count++) {
    …
}

Once you do that, you'll see nested for-loop, which is easier to understand:

for (int count = 0; count < ar.length; count++) {
    for (int i = 0; i < ar.length - 1; i++) {
        if (ar[count] == ar[i + 1] && cont != i + 1) {
            flag = true;
        }
    }
}

But you are inspecting almost every pair of elements twice.  Typically, the inner loop limits are written to avoid half the work:

for (int i = 1; i < ar.length; i++) {
    for (int j = 0; j < i; j++) {
        if (ar[i] == ar[j]) {
            // Duplicate found!
            …
        }
    }
}

Variables named flag (or that act as a flag) are usually a bad idea, because they express your intentions indirectly.  In the case of duplicate element detection, once you've found a single duplicate, you're all done.  There should be a break, or better yet, a return:

public static boolean duplicateExists(int[] ar) {
    for (int i = 1; i < ar.length; i++) {
        for (int j = 0; j < i; j++) {
            if (ar[i] == ar[j]) {
                return true;
            }
        }
    }
    return false;
}

public static void main(String[] args) {
    int[] ar = …;
    System.out.println(duplicateExists(ar) ? "Duplicate exists in array!"
                                           : "No duplicates in array!");
}


Create a tree from a list of nodes with parent pointers only

Your TreeNode class is mostly allright. But you have to be careful when handling trees with parent pointers, or the tree could go out of sync, and deteriorate to a weird class. A setParent on its own is silly. The setLeft and setRight should also make sure to set the parent of the new child node:

public void setLeft(TreeNode left) {
  this.left = left;
  left.parent = this;
}

Do not force a user of your class to do this bookkeeping.

Your item is weird. It is the only non-private field, and is an int. Use generics, so that your tree can carry any type.

A usable tree implementation will implement certain collection interfaces like Iterable.

Your Ebay class is very weird.

The methods getMap and constructTree are public, but are not very useful outside of that class. Both should also be static.

It is not immediately obvious what soStuff does. In seems to be a constructor, or initializer. Why not name it as such?

You use a HashMap, but do not provide a custom hashing method for TreeNode. While you inherit one from Object, this isn't terribly advisable.

What these three methods do is:

You get a list of TreeNodes which only point to their parent. The task is to link these to a full tree.
You build a map that maps parent nodes to a list of childs.
You then assign the first item in each list to parent.left, the 2nd to parent.right, if applicable.

Your solution has the advantage that it builds the tree top-down, recursively, and won't touch any nodes that will not be in the final tree. It comes at the cost of building an entirely unneccessary HashMap. The following implementation assumes that no unrelated nodes are in the input list:

/**
 * Expects a TreeNode collection where each node points to its parent.
 * Builds the full tree and returns the root (which has to have a
 * null parent).
 */
public static TreeNode linkToTree(Iterable<TreeNode> nodes) {
  /* Building the tree.
   *
   * At some point, we *will* find the root, thus getting a
   * handle on the tree. If not, "null" will be returned, which
   * is a good error case.
   *
   * Each node already knows its parent, so we just add the node
   * as a new child to the parent. We treat a "null" slot as empty.
   * First, we fill the left slot, then overwrite the right slot
   * without any checks – last one wins out.
   */

  TreeNode root;

  for (TreeNode node : nodes) {
    final TreeNode parent = node.getParent();

    // try to detect the root node
    if (parent == null) {
      root = node;
    }
    // add this node to the parent's left slot if it's empty
    else if (parent.getLeft() == null) {
      parent.setLeft(node);
    }
    // … else overwrite right slot
    else {
      parent.setRight(node);
    }
  }

  return root;
}

What did I do differently?

This method is public static. It is reusable, and does not modify any instance members.
It takes any Iterable, not just a List. Why be unneccessarily specific?
It is documented. Note that I have a large comment inside my method explaining why I wrote my code this way, and point out a certain edge case (not finding any root). Inside my if/else, I have smaller comments pointing out what each test means.
I did not use recursion. While recursion can be very elegant, it is to be avoided on the JVM.
It uses less memory than your solution, is shorter, and more elegant. Due to all of the comments, the implementation shouldn't be harder to understand than your code, even though the underlying algorithm is slightly more difficult.
I don't use nondescriptive variable names like map.


strTok function (thread safe, supports empty tokens, doesn't change string)

delimiterFound + strlen(delimiter) sounds like a bug. If the delimiter is longer than one character, *newString will point too far into the original, maybe even beyond the end. Correct me if I am wrong, delimiterFound + 1 is what you are actually after.
Modern C allows, and strongly encourages, to declare variables as close to their use a possible. Consider

char * delimiterFound = strstr(string, delimiter);
....
char * tok = malloc(tokLenght + 1);

etc.
Always test that malloc didn't fail.
More spaces - around keywords, braces, etc - definitely improve readability:

    if (....) {
        ....
    } else {
        ....
    }


There is no improvement which can be done on the code you show us. If the function constructSomething really needs to be called for each combination of the parameters, there is nothing better you can do.

You should try to optimizie the function, maybe it is possible to cache some part of the construction which is common if one of the parameters is fixed.

For example you can pop the computation cWord->getWorldId() in the outer loop, so that you make it once for every Word (instead of once for every City). But I think this is a slight improvement.


Culling strings from a list that are substrings of other list elements

All in all this looks good already.

A few tips:

continue

If you change the test in explode from if s: to

if not s:
    continue

You can save a level of indentation for the rest of the loop

collections.defaultdict

checking whether a key is in a dict, and adding it if it isn't is why there is collections.defaultdict which can simplify explode a lot:

def explode(subject: Iterable[str]) -> Exploded:
    heads_to_tails = defaultdict(list)
    for s in subject:
        if not s:
            continue
        heads_to_tails[s[0]].append(s[1:])
    return {h: prune_or_follow(t) for (h, t) in heads_to_tails.items()}

tuple unpacking

A matter of style, but in most situations where you use my_list[0] and my_list[1:], you can use tuple unpacking. You can use this in prune_or_follow

def prune_or_follow(tails: List[str]) -> Union[Exploded, str]:
    start, *rest = tails
    if rest:
        return explode(tails)
    else:
        return start

Whether this is more clear is a matter of taste.

This tuple unpacking does not work as clean in explode because it converts the string into a list of 1-character strings.

Exploded

You can use a string in typing so you can do:

Exploded = Dict[str, Union["Exploded", str]]

without the Exploded = None

cull typing

cull can accept any iterable. For the result, I don't think the order of strings is important, so there is no need to limit you to a list. The signature can then be def cull(subject: Iterable[str]) -> Collection[str]:. Whether you return a list or a set is a matter of implementation.

If the result is just used for iteration, you can even forgo the list call, and just return the implode generator, and let the caller decide whether he needs in in a list, set or whatever data structure he wants.

implode

now you use e as argument name. One-letter variable names are unclear in general, and to be avoided most of the time*. Since it is a kind of a tree, I would change this variable.

A slightly different take in implode which doesn't use string concatenation but tuple unpacking:

def implode(tree: Exploded, previous=()) -> Generator[str, None, None]:
    for root, branches in tree.items():
        if isinstance(branches, str):
            yield "".join((*previous, root, *branches))
        else:
            yield from implode(branches, *previous, root)

or equivalently:

def implode(tree: Exploded, previous=()) -> Generator[str, None, None]:
    for root, branches in tree.items():
        if isinstance(branches, str):
            yield "".join((*previous, root, *branches))
        else:
            yield from implode(branches, (*previous, root))

The choice between your version and this is a matter of taste, but I wanted to present the different possibilities.

Another variation, is using try-except ArgumentError instead of the isinstance:

def implode_except(tree: Exploded, previous=()) -> Generator[str, None, None]:
    for root, branches in tree.items():
        try:
            yield from implode(branches, (*previous, root))
        except AttributeError:
            yield "".join((*previous, root, *branches))

'* I find i, j etc acceptable for a counter or index, and x and y for coordinates, but in general I try not to use one-letter variable names.


Pulling from data from SQLite DB on Android

Updating collections

Many things can be simplified around this snippet:

for (PriceTable pt1 : allList) {
    ArrayList<PriceTable> set = valueMap.get(pt1.getItemType());
    if (set == null) {
        set = new ArrayList<PriceTable>();
        set.add(pt1);
    } else {
        set.add(pt1);
    }
    valueMap.put(pt1.getItemType(), set);

}
cursor.close();

This is equivalent:

for (PriceTable pt1 : allList) {
    String itemType = pt1.getItemType();
    ArrayList<PriceTable> set = valueMap.get(itemType);
    if (set == null) {
        set = new ArrayList<PriceTable>();
        valueMap.put(itemType, set);
    }
    set.add(pt1);
}

What I did:

Moved set.add(pt1); out of the if-else
Moved valueMap.put(itemType, set); inside the if
No need for an else
Extracted pt1.getItemType() to avoid an extra lookup
cursor.close(); doesn't belong here, it should be done before this snippet. It makes the code easier to read if you don't delay actions like this.

Use interfaces types instead of implementations

When the interface type is enough, you should use that instead of the specific implementation type. For example instead of this:

public HashMap<String, ArrayList<PriceTable>> getPromoForViewGroup(
            String condition) {
    String custGroup = "custType";
    String itemGroup = "itemType";
    HashMap<String, ArrayList<PriceTable>> valueMap = new HashMap<String, ArrayList<PriceTable>>();

This is recommended:

public Map<String, List<PriceTable>> getPromoForViewGroup(String condition) {
    String custGroup = "custType";
    String itemGroup = "itemType";
    Map<String, List<PriceTable>> valueMap = new HashMap<String, List<PriceTable>>();

Notice all the rewritten types.

Mutually exclusive if-else

This conditions will not be both true at the same time,
so instead of two separate if, they should be joined with an else if:

if (condition.equals(CUST)) {
    getPromoForViewGroupHelperCust(custGroup, condition, valueMap);
}

if (condition.equals(ITEM)) {
    getPromoForViewGroupHelperItem(itemGroup, condition, valueMap);

}

Don't Select *

It's not recommended to select columns using * wildcard.
Different versions of the database might have columns in different order than you expect. There might be more columns than you expected, selecting more data than necessary, causing slowness. It's recommended to name the columns you need explicitly, and access their values by name.

Misc

  Apart from merging the 2 get methods, what else can I do to optimise this?

Oh definitely merge those methods...

  Is there a way to iterate a map while writing to it?

Kind of. You can iterate over a copy, while writing to the original. For example:

Map<String, Integer> map = new HashMap<>();
map.put("hello", 2);
map.put("world", 7);
for (Map.Entry<String, Integer> entry : new HashMap<>(map).entrySet()) {
    if (entry.getValue() > 5) {
        map.remove(entry.getKey());
    }
}
System.out.println(map);

Prints {hello=2}.


Copying the string in step 3 is unnecessary

You can iterate through the characters of a std::string s using std::string::operator[] and std::string::size():

for (std::string::size_type pos = 0; pos < s.size(); pos++) {
    char c = s[pos]; // do something with the char now
}

Alternatively, you can use std::string::iterator to iterate through the string.

Avoid std::endl in favor of \n

std::endl flushes the stream, which can cause a loss in performance.

Use more whitespace in your code

It's difficult to read code like for(int i=0;temp[i];++i). Instead, use more whitespace as in for (int i = 0; temp[i]; ++i).

I would take a different approach to solve the problem. With your approach, you have to iterate through the string at least once to sort it (step 1), then again to remove the whitespace (step 2), then a third time to look for duplicates. If you copy the string in step 3 that's yet another iteration.

You only need to iterate through the string once. Here's one way to do that:

Iterate through the string's characters (skipping the whitespace characters) and put each character in a std::set<char> if you haven't encountered it before. If you've already encountered it (it's in the std::set) put it in a separate std::set of duplicates. Once you've iterated through the string's character's once, you can iterate through the set of duplicates to print them.

Here's a demo:

#include <iostream>
#include <string>
#include <cctype>
#include <set>

int main() {
    std::string s("Hello world");
    std::set<char> characters;
    std::set<char> duplicates;

    for (std::string::size_type pos = 0; pos < s.size(); pos++) {
        char c = s[pos];

        // std::isspace() accepts an int, so cast c to an int
        if (!std::isspace(static_cast<int>(c))) {
            if (characters.count(c) == 0) {
                characters.insert(c);
            } else {
                duplicates.insert(c);
            }
        }
    }

    std::cout << "Duplicates: ";

    for (std::set<char>::const_iterator it = duplicates.begin(); it != duplicates.end(); ++it) {
        std::cout << *it << " ";
    }

    return 0;
}

Note that it's better to use std::isspace() instead of ' ' to check if a character is whitespace.

If you need to count how many times each character occurs in the string, simply replace std::set<char> duplicates with a std::map<char, int> which maps each character to the number of times it occurs (as shown in @TobySpeight's answer).


Optimizing a raycasting/voxelspace algorithm in Pygame

Below is the code I have come up with. It basically follows the code used for the web demo in the github repo you had linked to. I will add some explanation to this answer on how I had made some basic optimizations to better fit cython's memoryview model as well as potential room for improvement later, but figured I should post the code now as it might be another few days before I can get back to it.

cimport libc.math as c_math
from libc.stdint cimport *
import math
import numpy as np
from PIL import Image

import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
import sys
import time

ctypedef struct Point:
    float x
    float y

ctypedef struct Color:
    uint8_t r
    uint8_t g
    uint8_t b

cdef class Camera:
    cdef:
        public int x
        public int y
        public int height
        public int angle
        public int horizon
        public int distance

    def __init__(self, int x, int y, int height, int angle, int horizon, int distance):
        self.x = x
        self.y = y
        self.height = height
        self.angle = angle
        self.horizon = horizon
        self.distance = distance

cdef class Map:
    cdef:
        int width
        int height
        int shift
        const uint8_t[:, :, :] color_data
        const uint8_t[:, :] height_data

    def __init__(self, int width=1024, int height=1024, int shift=10):
        self.width = width
        self.height = height
        self.shift = shift
        self.color_data = None
        self.height_data = None

    def load_color_data(self, str color_path):
        cdef object image
        image = Image.open(color_path).convert("RGB")
        self.color_data = np.asarray(image)

    def load_height_data(self, str height_path):
        cdef object image
        image = Image.open(height_path).convert("L")
        self.height_data = np.asarray(image)

cdef class Window:
    cdef:
        int width
        int height
        str title
        object screen
        object clock
        int32_t[:] hidden_y
        uint8_t[:, :, :] output
        Color background_color
        Camera camera
        Map map

    def __init__(self, int width, int height, str title):
        self.width = width
        self.height = height
        self.screen = pygame.display.set_mode((self.width, self.height))
        self.title = title
        pygame.display.set_caption(self.title)
        self.hidden_y = np.zeros(self.width, dtype=np.int32)
        self.output = np.zeros((self.width, self.height, 3), dtype=np.uint8)
        self.clock = pygame.time.Clock()

    def set_background_color(self, uint8_t r, uint8_t g, uint8_t b):
        self.background_color.r = r
        self.background_color.g = g
        self.background_color.b = b

    def set_camera(self, Camera camera):
        self.camera = camera

    def set_map(self, Map map):
        self.map = map

    cdef void draw_background(self):
        cdef int x, y
        for x in range(self.width):
            for y in range(self.height):
                self.output[x, y, 0] = self.background_color.r
                self.output[x, y, 1] = self.background_color.g
                self.output[x, y, 2] = self.background_color.b

    cdef void draw_vertical_line(self, int x, int y_top, int y_bottom, Color *color):
        cdef int y

        if y_top < 0:
            y_top = 0
        if y_top > y_bottom:
            return
        for y in range(y_top, y_bottom):
            self.output[x, y, 0] = color.r
            self.output[x, y, 1] = color.g
            self.output[x, y, 2] = color.b

    cdef display(self):
        surf = pygame.surfarray.make_surface(np.asarray(self.output))
        self.screen.blit(surf, (0, 0))
        pygame.display.flip()
        pygame.display.set_caption("{0}: {1} fps".format(self.title, <int>self.clock.get_fps()))

    def render(self):
        cdef:
            int map_width_period = self.map.width - 1
            int map_height_period = self.map.height - 1
            float s = c_math.sin(self.camera.angle)
            float c = c_math.cos(self.camera.angle)

            float z = 1.0
            float delta_z = 1.0
            float inv_z
            Point left, right, delta
            int i
            int map_x
            int map_y
            int height_on_screen
            Color color

        for i in range(self.width):
            self.hidden_y[i] = self.height
        self.draw_background()
        while z < self.camera.distance:
            left = Point(
                (-c * z) - (s * z),
                (s * z) - (c * z),
            )
            right = Point(
                (c * z) - (s * z),
                (-s * z) - (c * z),
            )
            delta = Point(
                (right.x - left.x) / self.width,
                (right.y - left.y) / self.width,
            )
            left.x += self.camera.x
            left.y += self.camera.y

            inv_z = 1.0 / z * 240
            for i in range(self.width):
                map_x = <int>c_math.floor(left.x) & map_height_period
                map_y = <int>c_math.floor(left.y) & map_width_period
                height_on_screen = <int>((self.camera.height - self.map.height_data[map_x, map_y]) * inv_z + self.camera.horizon)
                color.r = self.map.color_data[map_x, map_y, 0]
                color.g = self.map.color_data[map_x, map_y, 1]
                color.b = self.map.color_data[map_x, map_y, 2]

                self.draw_vertical_line(i, height_on_screen, self.hidden_y[i], &color)
                if height_on_screen < self.hidden_y[i]:
                    self.hidden_y[i] = height_on_screen
                left.x += delta.x
                left.y += delta.y

            delta_z += 0.005
            z += delta_z

        self.display()
        self.clock.tick(60)#60 fps

pygame.init()

window = Window(width=800, height=600, title="VoxelSpace")
window.set_background_color(144, 144, 224)

map = Map()
map.load_color_data("./images/C1W.png")
map.load_height_data("./images/D1.png")
window.set_map(map)

camera = Camera(x=512, y=800, height=78, angle=0, horizon=100, distance=800)
window.set_camera(camera)

while True:
    #win.handle_input()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                print("up")

    camera.y -= 1
    window.render()


Run and address feedback from automated tools to get easy feedback without having to make use of another human's time. Possible tools include:

The Rust compiler. Don't turn off warnings.
Rustfmt is a tool for automatically formatting Rust code to the community-accepted style.
Clippy is a tool for finding common mistakes that may not be compilation errors but are unlikely to be what the programmer intended.

These detect things like:

incorrect / inconsistent indentation.
unneeded usages of return
non-idiomatic Rust naming

Your variables have useless prefixes and suffixes. Don't blindly use Hungarian notation in a strongly typed language (e.g. nb). Dnt ndlssly abbv vrbs (don't needlessly abbreviate variables).

With this initial clearing of the underbrush, we can start to look at the code.

Don't use extern crate in modern Rust (What's the difference between use and extern?).
Don't use self::cratename, just use cratename.
I prefer to group all imports from the same crate into a single use statement.
Declare your variables as close as possible to where they are defined. Declare them inside of loops, especially if they aren't used outside of the loop or are reset inside the loop.
Use an infinite range instead of manually incrementing a variable.
Your function documentation is mostly useless. It's not using a doc comment (///). It repeats things like the function name. (How do you document function arguments?)
The type (String) has an unneeded parenthesis.
Your number formatting is grossly inefficient. You allocate many strings when you only need to extend an existing one. (What is the easiest way to pad a string with 0 to the left?; How can I append a formatted string to an existing String?)
Don't use _x if the variable is never used. Just use _.
Don't use magical values like "failed". Make use of Rust's Result type (What's the benefit of using a Result?)
There's no need to slice the string with [..]. Most of the time, a reference to a String will suffice (How does a reference to a String become a string slice?)
There's no need to return an owned String; a &'static str will suffice (What are the differences between Rust's String and str?)
Avoid using as to convert numbers. Prefer From::from instead (How do I convert between numeric types safely and idiomatically?)
It's inefficient to convert the digest result to a string, slice the string, then convert back to a number. Perform the operations directly on the digest buffer. (How can I convert a buffer of a slice of bytes (&[u8]) to an integer?; How to get a slice as an array in Rust?)
Don't use an i64 when you mean to use an u32
Using a match is cleaner than multiple if/else statements.

use crypto::{digest::Digest, sha2::Sha256};
use rand::Rng;
use std::{convert::TryInto, fs, process, time::Instant};

fn main() {
    // Local variables
    let winners = [
        "black", "green", "orange", "orange", "orange", "black", "black", "orange", "black",
        "black", "black", "orange", "black", "black", "orange", "orange", "green", "black",
        "orange", "black", "black", "orange", "orange", "black", "black", "black", "orange",
        "black", "black", "orange", "orange", "orange", "orange", "black", "orange", "black",
        "black", "orange", "orange", "black", "black", "orange", "green", "black", "orange",
        "orange", "orange", "orange", "green", "black",
    ];
    let public_seed = "2132110516";
    let round = 4_645_230;

    let now = Instant::now();

    for tries in 0.. {
        let random_seed = &create_seed(32);
        let mut predict = predict_color(random_seed, public_seed, round).unwrap();
        let mut round_verifications = 0u8;

        // Check if the hash is correct by predicting the first 50 round of the day
        while predict == winners[usize::from(round_verifications)] {
            round_verifications += 1;
            predict = predict_color(random_seed, public_seed, round + u32::from(round_verifications))
                .unwrap();

            if round_verifications > 45 {
                fs::write("seed.txt", random_seed).expect("Unable to write file");
                process::exit(1);
            }
        }

        if tries % 1_000_000 == 0 {
            println!("{}", tries);
            println!("In {} seconds", now.elapsed().as_secs());

            if tries == 5000000 { return }
        }
    }
}

/// Creates a random seed with a length of `2 * bytes`
fn create_seed(bytes: usize) -> String {
    let mut rng = rand::thread_rng();
    let mut seed = String::with_capacity(2 * bytes);

    for _ in 0..bytes {
        use std::fmt::Write;
        write!(&mut seed, "{:02x}", rng.gen::<u8>()).unwrap();
    }
    seed
}

/// Predict the roll
fn predict_color(
    server_seed: &str,
    public_seed: &str,
    first_round_of_the_day: u32,
) -> Result<&'static str, ()> {
    let mut hasher = Sha256::new();

    // Hash everything
    let to_hash = format!("{}-{}-{}", server_seed, public_seed, first_round_of_the_day);
    hasher.input_str(&to_hash);

    let mut hash = [0; 32];
    hasher.result(&mut hash);

    let leading_bytes: &[u8; 4] = hash[..4].try_into().unwrap();
    let number = u32::from_be_bytes(*leading_bytes);

    match number % 15 {
        0 => Ok("green"),
        1..=7 => Ok("orange"),
        8..=14 => Ok("black"),
        _ => Err(()),
    }
}

Running this in release mode:

% time ./target/release/review
0
In 0 seconds
1000000
In 2 seconds
2000000
In 4 seconds
3000000
In 7 seconds
4000000
In 9 seconds
5000000
In 11 seconds

real    12.078  12077581us
user    11.879  11879005us
sys 0.033   33467us
cpu 98%
mem 968 KiB

Compared to your original:

% time ./target/release/review
1000000
In 14 secondes
2000000
In 28 secondes
3000000
In 42 secondes
4000000
In 56 secondes
5000000
In 70 secondes

real    1:10.49 70485131us
user    1:10.16 70162635us
sys 0.137   136869us
cpu 99%
mem 980 KiB

The improved version takes 17% of your original time (a 5.8x speed increase).

Using a random number generator for the seed is probably a bad idea. It's totally reasonable for a RNG to repeat a value, but that won't change your results. You might as well start at 0 and work your way up. This also makes it trivial to stop and resume.

The problem appears to be embarrassingly parallel, so that would also be an avenue to investigate.


There is one huge security oversight here, and that's the use of extract().

What you're doing is extracting $_POST data straight into $variables.

Suppose someone was to edit your form, or the POST request, and add a field of "woocommerce", $_POST['woocommerce'] would then become $woocommerce.

This would overwrite whatever your existing $woocommerce variable is storing, and as it'a global I'm guessing it's pretty important.

You can avoid overwritting existing variables by using EXTR_OVERWRITE and EXTR_SKIP.
See the PHP documentation for more information.

I advise you drop the extract() function, especially for $_POST/$_GET/$_FILES, $_REQUESTS.
In your case, it's much safer to rely on isset() or empty(). This will also prevent any E_NOTICES occurring when referencing a variable which may not exist, when using extract().

extract($_POST);

if($firstname == '' )
{
    $reg_errors->add( 'registration-error', __( 'Please enter First Name.', 'woocommerce' ));
}

Should become,

if(empty($_POST['firstname']))
{
    $reg_errors->add( 'registration-error', __( 'Please enter First Name.', 'woocommerce' ));
}


Unless this is a homework assignment, you should probably not be writing your own linear algebra routines, but rely on libraries instead. Not only is it very hard to write correct and efficient general-purpose algorithms, for numerical algorithms there is an added requirement of numerical stability. For those reasons it is best to use established libraries such as Eigen.

A determinant can be done using the example in the documentation

#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
int main()
{
    Matrix3f A;
    A << 1, 2, 1,
         2, 1, 0,
        -1, 1, 2;
    cout << "Here is the matrix A:\n" << A << endl;
    cout << "The determinant of A is " << A.determinant() << endl;
}

Output

Here is the matrix A:
1 2 1
2 1 0
-1 1 2
The determinant of A is -3

Granted, for binary matrices the numerical stability argument that holds for floating point matrices is not really relevant, but the correctness and efficiency arguments remain important enough to warrant library use over hand-written implementations.

UPDATE: I just noticed that you got the same suggestion to start exploring Eigen in your other CodeReview question. I really encourage you to do so because it lets you focus on your application rather than on low-level implementation details that have been solved by others already. Unless of course, learning such details is what you are interested in.


Python example to save file with same name like `somefile(n).txt`

One aspect I'd like to mention is sorting:

The contain does a max(myfiles), which is on the filenames.

In particular, out of "somefile(9).txt" and "somefile(10).txt", the max will be "somefile(9).txt". It will then choose "somefile(10).txt" as the new filename, overwriting its original content.

This is because 9 is larger than 1.


Test whether target string is substring of source string

A BUG

Your method fails on string "baaaba" whenever searching for "aab". The problem here is that when you reset pointTarget to 0, you may ignore a prefix of the pattern.

NAMING

I suggest you rename src to text or string, and rename target to pattern.

CODE

After simplifying your code, you may get something like:

public static boolean isSubstringOf(char string[], char pattern[]) {
    int pointTarget = 0;

    for (int cursor = 0; cursor < string.length; cursor++) {
        if (pointTarget == pattern.length) {
            break;
        }

        if (string[cursor] == pattern[pointTarget]) {
            pointTarget++;
        } else {
            cursor -= pointTarget - 1;
            pointTarget = 0;
        }
    }

    return pointTarget == pattern.length;
}

The above runs in time \$\mathcal{O}(nm)\$, where \$n\$ is the length of the text to search and \$m\$ is the length of the pattern string. If you want to find the pattern in the text in linear time, you could use Knuth-Morris-Pratt algorithm.


Drawing dragon curves using Turtle graphics

Whitespace
There should be a blank line between two method definitions.
Also, some blank lines inside of the methods would give the code room to breathe, and allow you to visually separate individual "steps" from each other, for example in your main method:
int n = Integer.parseInt(args[0]);
double step = Double.parseDouble(args[1]);
Turtle turtle = new Turtle(0.67, 0.5, 0);

drawDragonCurve(n, step, turtle);

Magic values
There are several magic values in your code. While it is probably clear what 90 means in a turtle graphic environment, the values 0.67 and 0.5 mean nothing to me. What are they? And more importantly: Why are they the values that they are? Why not 0.66 or 0.68?
Variables allow you to give explanatory, intention-revealing names to your values.
final var initialXCoordinate = 2.0 / 3.0;
final var initialYCoordinate = 0.5;
final var initialAngle = 0;
turtle = new Turtle(initialXCoordinate, initialYCoordinate, initialAngle);

Type inference
I am a big fan of type inference, especially in cases where the type is obvious:
double step = Double.parseDouble(args[1]);

How often do I have to told that this is a double? I get it!
var step = Double.parseDouble(args[1]);

Same here:
Turtle turtle = new Turtle(0.67, 0.5, 0);

This almost sounds like someone stuttering. I don't need the turtle variable to be explicitly annotated with the Turtle type to understand that a variable called turtle being initialized with a Turtle is probably a turtle:
var turtle = new Turtle(0.67, 0.5, 0);

final
I am also a big fan of making everything that can be made final explicitly final. And even for things that can't be made final as written, I'd investigate whether it can be rewritten so it can be made final.
Note, by "everything" I mean primarily variables and fields. However, unless a class is explicitly designed to be extended, it should also be marked final. And of course, immutable classes need to be final anyway.
private
None of your methods are used by any outside client (except for main), so they should all be private.
Naming
n is a terrible name. I have no idea what it means. I promise you, your keyboard is not going to wear out from making your variable names a little more descriptive. I believe it is referring to the order of the fractal.
Also, I have no idea what a Nodrag is.
Scope
It seems that step is always the same. There is no need to pass it as an argument if it is always the same. The purpose of a parameter is to allow a method to differ in its behavior. There is no need for it if it is never different.
The same applies to Turtle.
Code Duplication
This is the big one. There is a lot of code duplication. In fact, drawDragonCurve and drawNodragCurve are 100% identical except for one single character.
The only thing that is changing is the sign of the turn angle, or in other words, the direction of the turn. We can turn the sign into a parameter of the method, and pass it along accordingly.
I will keep the original drawDragonCurve method in place as an overload, which calls the new overload with the correct starting parameter, because a client should not need to know whether 1 or -1 is the correct starting value.
public class Dragon {
    private static double step;
    private static Turtle turtle;

    private static void drawDragonCurve(final int order) {
        drawDragonCurve(order - 1, 1);
    }

    private static void drawDragonCurve(final int order, final int sign) {
        if (order == 0) {
            turtle.goForward(step);
            return;
        }

        drawDragonCurve(order - 1, 1);
        turtle.turnLeft(sign * -90);
        drawDragonCurve(order - 1, -1);
    }

    public static void main(final String[] args) {
        final var order = Integer.parseInt(args[0]);
        step = Double.parseDouble(args[1]);

        final var initialXCoordinate = 2.0 / 3.0;
        final var initialYCoordinate = 0.5;
        final var initialAngle = 0;
        turtle = new Turtle(initialXCoordinate, initialYCoordinate, initialAngle);

        drawDragonCurve(order);
    }
}

Note that I might have made a mistake with the flipping of the sign. However, there is no way for me to test your code, because Dragon is intimately linked to Turtle and Turtle is intimately linked to StdDraw, which I don't have access to.
This brings me to my last point:
Testability, Modularity, Overall Design

All your methods are static, in other words, they aren't really methods at all, they are glorified procedures. There are no objects!
All your methods return void, in other words, they don't return anything, they purely perform side-effects.
All your classes are intricately linked to each other, there is no way to separate them, to use them independently, to test them independently.

It is hard to test code if I can't instantiate an object that I can test. It is hard to test code if everything is just a side-effect, and I can't simply compare return values. It is hard to test code if I always need the entire thing and can't test pieces independently or swap out pieces for test versions.
At the moment, the only way to test your code, is to run the entire thing, take a screenshot and compare it with a pre-recorded one. This adds a huge amount of complexity to the tests, and is very slow. Ideally, you want to be able to run your tests every couple of seconds.
For example, Dragon should be a true object, not a static class. It should have the dependency on Turtle injected, not hard-coded. The Turtle dependency should be abstracted behind an interface, so that, for testing purposes, I can replace the turtle with a version that records the commands and compares them to a pre-recorded sequence instead of drawing on the screen.
Likewise, StdDraw should be a true object as well, hidden behind an interface, and I should be able to instantiate a version that uses ASCII art instead of Swing, or that simply creates a bit matrix that I can compare with a pre-recorded one for testing.
At least, Turtle is a class that can actually be instantiated, and has behavior.
This is just a sketch:
App.java
class App {
    public static void main(final String[] args) {
        final var order = Integer.parseInt(args[0]);
        final var step = Double.parseDouble(args[1]);

        final var initialXCoordinate = 2.0 / 3.0;
        final var initialYCoordinate = 0.5;
        final var initialAngle = 0;
        final var turtle = new StdDrawTurtle(initialXCoordinate, initialYCoordinate, initialAngle);

        final var dragon = new Dragon(order, step, turtle);

        dragon.drawDragonCurve();
    }
}

Dragon.java
public record Dragon(final int order, final double step, final Turtle turtle) {
    public void drawDragonCurve() {
        drawDragonCurve(order - 1, 1);
    }

    private void drawDragonCurve(final int order, final int sign) {
        if (order == 0) {
            turtle.goForward(step);
            return;
        }

        drawDragonCurve(order - 1, 1);
        turtle.turnLeft(sign * -90);
        drawDragonCurve(order - 1, -1);
    }

Turtle.java
public interface Turtle {
    public void turnLeft(final double delta);
    public void goForward(final double step);
}

StdDrawTurtle.java
public class StdDrawTurtle implements Turtle {
    private double x;
    private double y;
    private double angle;

    public StdDrawTurtle(final double x, final double y, final double angle) {
        this.x = x;
        this.y = y;
        this.angle = angle;
    }

    public void turnLeft(final double delta) {
        angle += delta;
    }

    public void goForward(final double step) {
        final double oldX = x, oldY = y;

        x += step * Math.cos(Math.toRadians(angle));
        y += step * Math.sin(Math.toRadians(angle));

        StdDraw.line(oldX, oldY, x, y);
    }
}

FakeTurtle.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FakeTurtle implements Turtle {
    record TurtleState(double x1, double y1, double x2, double y2) {}

    private final List<TurtleState> recording;
    private double x;
    private double y;
    private double angle;

    public FakeTurtle(final double x, final double y, final double angle) {
        recording = new ArrayList<>();
        this.x = x;
        this.y = y;
        this.angle = angle;
    }

    public List<TurtleState> getRecording() {
        return Collections.unmodifiableList(recording);
    }

    public void turnLeft(final double delta) {
        angle += delta;
    }

    public void goForward(final double step) {
        final double oldX = x, oldY = y;

        x += step * Math.cos(Math.toRadians(angle));
        y += step * Math.sin(Math.toRadians(angle));

        recording.add(new TurtleState(oldX, oldY, x, y));
    }
}
```


To appreciate a power of non-type templates, try to implement body and append_body in plain C. You will see immediately why your approach is an abuse of templates.
Most important

body() returns a temporary object:

    stringstream stream;
    ...
    return stream.str();

and clang expectedly complains:

error: non-const lvalue reference to type
  'basic_string<[3 * ...]>' cannot bind to a temporary of type
  'basic_string<[3 * ...]>'
string& wtail = body<true>(head, num);
        ^       ~~~~~~~~~~~~~~~~~~~~~


Parsing Placeholders as SQL Arguments in PHP

If this is a whole SQL class of sorts, then I think you can improve your design a bit.  What if you want people who aren't archived and names match certain things? 'dan,john&steven', 'username' doesn't really work.  You need something more like:

$sql
    ->select(...)
    ->from(...)
    ->where('=dan|=john&=steven', 'username')
    ->andWhere('>0', 'archived')
    ->execute();

Notice that I didn't use your grammar.  I'd recommend the following shorthand grammar notation:

//& means AND
//| means OR
//~ means LIKE

//operator means &, |
//comparator means things like !=, =, <>, <, >, <=, >=, ~
//identifier means things like dan, john, or jo%

//The pseudo regular expession:
//{comparator} {identifier} ({operator} {comparator} {identifier})*

Doing that, you can turn: '=john | !=jamison & =james | ~%jo_n' into name = 'john' OR name != 'jamison' AND name = 'james' OR name LIKE '%jo_n' quite easily:

    function parse($string, $name) {
            //add in quote marks
            $string = preg_replace('/[A-Za-z0-9%_-]+/', "'$0'", $string);

            //add in name:
            $string = preg_replace('/\=|\!\=|<>|<|<=|>|>=|~/', "$name $0 ", $string);

            //replace ~ with LIKE
            $string = str_replace('~', 'LIKE', $string);

            //expand '&' and ',' to ' AND '
            $string = preg_replace('/\&|\,/', ' AND ', $string);

            //expand '|' to ' OR '
            $string = str_replace('|', ' OR ', $string);

            return $string;

    }

Also note that you should be able to escape things properly.  We don't want SQL injection going on 'round here!  I'd recommend a syntax like:

where('=? | =? & =?', array('dan', 'john', 'steven'), 'username')

The function I provided could easily be modified to do that.  You simply use the mysqli or PDO engine to do the replacing.  You  just have to store the arguments in your structure so you can do it proper.


Implementation of system() function in Linux using fork() , exec() and waitpid() system calls

I think the biggest mistake is the return after the exec.  If you reach that point, and return, you have returned to the calling function in the subprocess.  Use exit() instead.  Note that the value you pass to exit should come out in wstatus.  Note also, if execle returns, it must have failed, so don't even both checking the status.  (For this to happen, the path must be invalid.  Change it for testing, and set it back afterwards.)

The use of execle() is a mistake.  You didn't pass an environment.  Use execl() instead.

You have at least one case where you return -1 without having set errno.  Set errno.  (Many cases, something else has already set errno for you.)

One other thing that can bite you:  If the caller has made another subprocess, and it terminates while you are waiting for your subprocess, you will return the result of the wrong subprocess.  To fix this, pass the pid as the first parameter to waitpid().

As a style issue, I would recommend moving wstatus completely into the last block.  And nothing should ever come out of the compound if statement.

As a personal style point: I tend to use switch to test for -1, 0, or other.  if statements work equally well.