How to design shopping cart Java application which satisfy modular, extensible and maintainable

I separated the calculatePrice method into calculatePremiumPrice and calculateRegularPrice methods.  This made the code easier to visually inspect.

I also made the two blocks of if statements consistent, starting with the lower discounts and working my way up to the larger discounts.  Again, this makes the code easier to visually inspect.

I was more measured in my use of blank lines.  There's no need to put a blank line after every statement.  Use blank lines to separate logical concepts within a method.

If the method code fits on one screen, it's easier to visually inspect.

Finally, I ran all the test cases and formatted the output into currency.

import java.text.NumberFormat;

public class ShoppingCartDiscount {

    static NumberFormat formatter = NumberFormat.getCurrencyInstance();

    public static void main(String args[]) {
        System.out.println("Price for the regular customer: "
                + formatter.format(calculatePrice("Regular", 5000)));
        System.out.println("Price for the regular customer: "
                + formatter.format(calculatePrice("Regular", 10000)));
        System.out.println("Price for the regular customer: "
                + formatter.format(calculatePrice("Regular", 15000)));

        System.out.println();

        System.out.println("Price for the premium customer: "
                + formatter.format(calculatePrice("Premium", 4000)));
        System.out.println("Price for the premium customer: "
                + formatter.format(calculatePrice("Premium", 8000)));
        System.out.println("Price for the premium customer: "
                + formatter.format(calculatePrice("Premium", 12000)));
        System.out.println("Price for the premium customer: "
                + formatter.format(calculatePrice("Premium", 20000)));
    }

    static float calculatePrice(String customerType, float purchaseAmount) {
        float total = 0f;

        if (customerType.equalsIgnoreCase("Regular")) {
            total = calculateRegularPrice(purchaseAmount);
        } else if (customerType.equalsIgnoreCase("Premium")) {
            total = calculatePremiumPrice(purchaseAmount);
        }

        return total;
    }

    static float calculateRegularPrice(float purchaseAmount) {
        float total = 0f;

        if (purchaseAmount <= 5000) {
            total = purchaseAmount;
        } else if (purchaseAmount > 5000 && purchaseAmount <= 10000) {
            float firstSlab = purchaseAmount - 5000;
            firstSlab = firstSlab - (float) (firstSlab * 0.1);
            total = 5000 + firstSlab;
        } else {
            float secondSlab = purchaseAmount - 10000;
            secondSlab = secondSlab - (float) (secondSlab * 0.2);
            float firstSlab = 10000 - 5000;
            firstSlab = firstSlab - (float) (firstSlab * 0.1);
            total = 5000 + firstSlab;
            total = total + secondSlab;
        }

        return total;
    }

    static float calculatePremiumPrice(float purchaseAmount) {
        float total = 0f;

        if (purchaseAmount <= 4000) {
            total = purchaseAmount - (float) (purchaseAmount * 0.1);
        } else if (purchaseAmount > 4000 && purchaseAmount <= 8000) {
            float secondSlab = purchaseAmount - 4000;
            secondSlab = secondSlab - (float) (secondSlab * 0.15);
            float firstSlab = 8000 - 4000;
            total = firstSlab - (float) (firstSlab * 0.1);
            total = total + secondSlab;
        } else if (purchaseAmount > 8000 && purchaseAmount <= 12000) {
            float thirdSlab = purchaseAmount - 8000;
            thirdSlab = thirdSlab - (float) (thirdSlab * 0.20);
            float secondSlab = 8000 - 4000;
            secondSlab = secondSlab - (float) (secondSlab * 0.15);
            float firstSlab = 8000 - 4000;
            total = firstSlab - (float) (firstSlab * 0.1);
            total = total + secondSlab + thirdSlab;
        } else {
            float fourthSlab = purchaseAmount - 12000;
            fourthSlab = fourthSlab - (float) (fourthSlab * 0.30);
            float thirdSlab = 8000 - 4000;
            thirdSlab = thirdSlab - (float) (thirdSlab * 0.20);
            float secondSlab = 8000 - 4000;
            secondSlab = secondSlab - (float) (secondSlab * 0.15);
            float firstSlab = 8000 - 4000;
            total = firstSlab - (float) (firstSlab * 0.1);
            total = total + secondSlab + thirdSlab + fourthSlab;
        }

        return total;
    }

}

Based on the comment by the OP, I created more adaptable code.  I'm not sure what pattern this is, except I used a factory to build the rewards.

I created a Tier class to hold a tier, a Reward class to hold a reward, and a RewardFactory to define the rewards.  This should make it easier to change tiers or add new reward types.

If a new reward concept is created, then some code would have to be added.

Here's the revised code.

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

public class ShoppingCartDiscount {

    static NumberFormat formatter =
            NumberFormat.getCurrencyInstance();

    public static void main(String args[]) {
        ShoppingCartDiscount scd = new ShoppingCartDiscount();
        RewardFactory rewardFactory = scd.new RewardFactory();

        String rewardType = "Regular";
        float amount = 5_000f;
        float discount = rewardFactory.calculateDiscount(
                rewardType, amount);
        displayDiscount(rewardType, amount, discount);

        amount = 10_000f;
        discount = rewardFactory.calculateDiscount(
                rewardType, amount);
        displayDiscount(rewardType, amount, discount);

        amount = 15_000f;
        discount = rewardFactory.calculateDiscount(
                rewardType, amount);
        displayDiscount(rewardType, amount, discount);

        System.out.println();

        rewardType = "Premium";
        amount = 4_000f;
        discount = rewardFactory.calculateDiscount(
                rewardType, amount);
        displayDiscount(rewardType, amount, discount);
        amount = 8_000f;
        discount = rewardFactory.calculateDiscount(
                rewardType, amount);
        displayDiscount(rewardType, amount, discount);
        amount = 12_000f;
        discount = rewardFactory.calculateDiscount(
                rewardType, amount);
        displayDiscount(rewardType, amount, discount);
        amount = 20_000f;
        discount = rewardFactory.calculateDiscount(
                rewardType, amount);
        displayDiscount(rewardType, amount, discount);
    }

    static void displayDiscount(String rewardType,
            float amount, float discount) {
        System.out.print(rewardType);
        System.out.print(" customer spends ");
        System.out.print(formatter.format(amount));
        System.out.print(", so we discount ");
        System.out.print(formatter.format(discount));
        System.out.print(", so he owes ");
        amount -= discount;
        System.out.print(formatter.format(amount));
        System.out.println(".");
    }

    public class RewardFactory {

        private List<Reward> rewards;

        public RewardFactory() {
            this.rewards = new ArrayList<>();
            createRewards();
        }

        private void createRewards() {
            Reward reward = new Reward("Regular");
            Tier tier = new Tier(0f, 5_000f, 0.00f);
            reward.addTier(tier);
            tier =  new Tier(5_000f, 10_000f, 0.10f);
            reward.addTier(tier);
            tier =  new Tier(10_000f, Float.MAX_VALUE, 0.20f);
            reward.addTier(tier);
            rewards.add(reward);

            reward = new Reward("Premium");
            tier = new Tier(0f, 4_000f, 0.10f);
            reward.addTier(tier);
            tier = new Tier(4_000f, 8_000f, 0.15f);
            reward.addTier(tier);
            tier = new Tier(8_000f, 12_000f, 0.20f);
            reward.addTier(tier);
            tier = new Tier(12_000f, Float.MAX_VALUE, 0.30f);
            reward.addTier(tier);
            rewards.add(reward);
        }

        public float calculateDiscount(String rewardType,
                float amount) {
            float discount = 0f;

            for (Reward reward : rewards) {
                if (reward.isDiscountApplied(rewardType)) {
                    discount += reward.calculateDiscount(amount);
                }
            }

            return discount;
        }
    }

    public class Reward {

        private final String rewardType;

        private List<Tier> tiers;

        public Reward(String rewardType) {
            this.rewardType = rewardType;
            this.tiers = new ArrayList<>();
        }

        public void addTier(Tier tier) {
            this.tiers.add(tier);
        }

        public boolean isDiscountApplied(String type) {
            return (rewardType.equalsIgnoreCase(type));
        }

        public float calculateDiscount(float amount) {
            float discount = 0f;

            for (Tier tier : tiers) {
                if (tier.isDiscountApplied(amount)) {
                    discount += tier.calculateDiscount(amount);
                }
            }

            return discount;
        }

    }

    public class Tier {

        private final float lowerAmount;
        private final float upperAmount;
        private final float percentDiscount;

        public Tier(float lowerAmount, float upperAmount,
                float percentDiscount) {
            this.lowerAmount = lowerAmount;
            this.upperAmount = upperAmount;
            this.percentDiscount = percentDiscount;
        }

        public boolean isDiscountApplied(float amount) {
            return (lowerAmount < amount);
        }

        public float calculateDiscount(float amount) {
            if (amount > upperAmount) {
                return (upperAmount - lowerAmount) *
                        percentDiscount;
            } else {
                return (amount - lowerAmount) * percentDiscount;
            }
        }

    }

}


Bash is not well-suited for transforming JSON. But jq is. But calling jq 3 times for each line of input is certainly going to be slow.

There are several other issues too with the script. The `...` syntax is obsolete in favor of $(...); the counting can be simplified, or even better, eliminated using tail -n +5; and the repeated bulk_result.bulk would be good to put in a variable.

But none of that matters much, as it seems the entire script can be replaced with a single line:

tail -n +5 "$1" | jq -rc '{index: {_index: ._index, _type: ._type}}, ._source'


Observation
You can simplify this using arrays.
You don't need two numbers for each type (max and current). Simply track the number of open spots (per type) and count down.
if you are not using arrays consider a switch statement.
Code Review:
Prefer "\n" over std::endl.
If your main() does not return anything but 0 at the end.
Then leave out the return. It is auto added by the compiler.
Re-Design
template<std::size_t typeCount = 3>
class ParkingSystem
{
    int openSlots[typeCount];

    public:
        template<typename... Args>
        ParkingSystem(Args... args)
            : openSlots{args...}
        {}

        bool addCar(int type)
        {
            if (openSlots[type - 1] == 0) {
                return false;
            }
            --openSlots[type - 1];
            return true;
        }
};

int main()
{

    ParkingSystem parking_system(1, 1, 0);

    std::cout
        << "parking_system.addCar(1) " << parking_system.addCar(1) << "\n"
        << "parking_system.addCar(2) " << parking_system.addCar(2) << "\n"
        << "parking_system.addCar(3) " << parking_system.addCar(3) << "\n"
        << "parking_system.addCar(1) " << parking_system.addCar(1) << "\n";
}


Optimizing a particle filter weighted selection step

I don't see any need for that goto, and it should be avoided whenever possible.  It would be better to just perform the action after the condition, then break from the loop.

if (particlesCounter == 0)
{
    ROS_INFO_STREAM("Observation step complete");
    break;
}

Although this will only break from the for loop, the state of particlesCounter at that point will stop the while loop as well.


Write your own extractor:

object Big {
  def unapply(n:BigInt) = Some(n.toInt)
}

//usage
def f(b:BigInt) = b match {
   case Big(0) => "none"
   case Big(1) => "one"
   case _ => "many"
}

Obviously, this isn't the fastest solution, but I think, it's quite idiomatic...


Returning lines for a given function from a JavaScript file

Inefficient Array.forEach

The current implementation will needlessly iterate until the end of the array even after the function was found.
It would be better replace the .forEach with a regular counting loop,
and break out of it after you found the end of the function.

Avoid flag variables

Using a single loop and the copying_lines flag variable to alternate between processing logic (find start of function, copy content, find end), is not very easy to read.
It would be easier to use a nested loop after you found the start.
Something like this:

for (let i = 0; i < lines.length; i++) {
  if (lines[i].match(startPattern) !== null) {
    let function_lines = [];

    for (let j = i; j < lines.length; j++) {
      function_lines.push(lines[j]);

      if (lines[j] === '}') return function_lines;
    }

    throw new Error('Could not find end of function before end of content');
  }
}

return [];

Too weak start pattern

This condition is too weak to match the declaration of a function:

if (line.match("function " + funShun)) {

For example, if there are functions named convert_custom and convert,
and you call load_function_text('convert'),
it will find the first one.
I suggest to use a stronger pattern, for example:

startPattern = new RegExp("\\s*function " + funShun + "\\s*\\(");


Convert a Hex value string to an ASCII Text String

I'm surprised that, according to your code, C++ doesn't have a strip_prefix or without_beginning or skip_start function to skip over the initial "0x". If there were one, you should definitely use that instead of implementing your own. Do a little search, I'm sure such a function exists.

Even though this is C++, there is no need to write a class for a simple conversion function like this. In my experience, this task can be solved in less than 20 lines of code, and there is no state that you need to save between method calls, therefore a class is unnecessary. Just write an ordinary std::string hex_to_bytes(const std::string_view &hex) function.

As far as I remember, std::string has a push_back method, therefore there's no need to use an intermediate vector for building up the string.

My rough idea is:

std::string hex_to_bytes(const std::string_view &hex) {
    std::size_t i = 0, size = hex.size();
    if (size >= 2 && hex[0] == '0' && hex[1] == 'x')
        i += 2;

    std::string result;
    for (; i + 1 < size; i += 2) {
        char octet_chars[] = { hex[i], hex[i + 1], '\0' };

        char *end;
        unsigned long octet = std::strtoul(octet_chars, &end, 16);
        if (end != octet_chars + 2)
            throw std::some_exception();

        result.push_back(static_cast<char>(octet));
    }

    if (i != size)
        throw std::some_exception();

    return result;
}

I didn't test the above code.
It also doesn't look very C++-like to me because it accesses the character array directly. But probably, for this kind of functions, there is no high-level way of expressing the code.

By the way, instead of writing all this code, you could also write a Perl one-liner:

perl -pe '$_ = pack("H*", $1) if /([0-9a-f]+)/i'


Your functions are doing too much. Remember: one function, one responsibility. That is, the encode function actually both encodes and decodes and that behavior is controlled via its arguments. In particular, the choice of behavior is offloaded to shiftF based on a char. There is no error if that char is anything other than 'd' or 'e'. This is something that we should absolutely try to avoid: we want to catch as many problems as we can at compile-time, but even runtime errors are preferred to silent errors!

On closer inspection, there is no need for such a complication. In fact, the only difference between encoding and decoding is the sign of shift. So we could write:

std::string encode(const std::string& str, int shift)
{
    std::string tempMsg;

    std::transform(str.cbegin(), str.cend(), std::back_inserter(tempMsg), [&](char ch) -> char
    {
        if (isspace(ch))
            return ' ';

        return ch == 'z' || ch == 'Z' ? ch - 25 : ch + shift;
    });

    return tempMsg;
}

std::string decode(const std::string& str, int shift)
{
    return encode(str, -1 * shift);
}

What is happening here?

We pass the input message str as a const-ref and not by-value as in your original code. When you pass by-value, the object gets copied and in this case there is no reason for it. In this case, you could actually even pass the object by-reference only, and modify it in-place but we're not doing it here.
We use a standard function std::transform with a lambda function that encapsulates the logic of shiftF. You need to include <algorithm> for this use.
The third argument for std::transform is std::back_inserter found from <iterator>, which takes care of inserting at the back of the string tempMsg.
Conceptually, the division of encoding and decoding into separate functions is cleaner and more logical. Whenever you can implement another function in terms of other functions, it's likely a good idea because you don't have to repeat yourself leading to less maintenance decreasing the chances for bugs.

Once you adopt this approach, you can get rid of the const char variables from your main program, and just call the correct encode or decode function inside your if-statement. As a side remark, you could also return meaningful error codes in your main. For example, if the choice is invalid, return from the else-branch e.g., EXIT_FAILURE.


Pass an array of numbers into a method that's overloaded

The code produces the right output, which is good.  It has some problems, though.

The average() functions

As @ChrisW points out, the two average() functions you defined are not being used.  Since your inputs are doubles, you only need one of them: the double average(double[] array) function.

The average() functions are currently buggy:

total = 0, so of course they will each always return 0.  Copy the summation code from main() to fix that.
The int version uses integer arithmetic, so division rounds the result to an integer (towards 0).  In general, the average of a set of integers is not an integer.  You should use double to store the total, even in the integer version.  (You did it correctly in main().)

In case you're wondering, if you want to be able to handle integral and floating-point input arrays, you do need to write out both the int[] and double[] versions explicitly.

main()

If you open a Scanner, it's good etiquette to close it.  The idiom for doing that since Java 7 is to use a try-with-resources block:

try (Scanner input = new Scanner(System.in)) {
    …
}

Avoid declaring and defining variables avg and total until you need them.

The average array is poorly named.  It's an array of ten user input numbers, not an array of ten averages.

You hard-coded 10 twice.  The first for-loop should be more like the second, which uses average.length.

The average only needs to be computed once, not ten times.  Pull the division operation out of the loop.

Of all the comments in the class, the only one worth keeping is // enter 10 numbers to average.  All of the others are redundant noise.


only runs a target if the output hasn't changed since last run

Consider writing rules like this:

%.pdf: %.md
        pandoc -o $@ $<

For that to work, the current all: ... pdf would need to mention particular *.pdf files, perhaps by globbing: $(patsubst %.md,%.pdf,*.md)


Ruby Regex to update various variables inside a file

There might be two easier options:

Generate the file using a template file something like the following

major = {{major}}
minor = {{minor}}
patch = {{patch}}

that has strings that are easy to search for. You could also use ERB to generate the file.

Put the logic in your version.rb file something like:

PORTAL_VERSION = '1.2.3'
major, minor, path = PORTAL_VERSION.split('.').map(&:to_i)

This way you would just have to replace the first line.

If you want to do it using your logic I would change the regex from /(patch = \w)/ to /(patch\s*=\s*\w+)/ this would handle extra whitespace and version numbers bigger than 9
Note you can also do variable substitution in Regexes so you could write your code as:

['major', 'minor', 'patch'].each.with_index do |key, i|
  version_file.sub!(/(#{key}\s*=\s*\w+)/, "#{key} = #{version[i]}")
end

Note that gsub isn't necessary as you only expect one occurrence.


First, from a styling standpoint, your classes are structured strangely.  Typically, one would have all class properties defined as first thing in class, then the constructor as first method, then the other methods (oftentimes with public methods first with protected/private methods following).  Don't mix your properties throughout your class.

Be consistent with style around variable naming.  You probably should not be using first letter caps for any properties or variables in PHP (which is more or less industry standard).  See the PHP Standards Recommendations for good suggestions on standards to follow (particularly PSR-2 around coding style).

I have several concerns regarding class design:

I don't really understand need for singleton here.  I would actually suggest you consider dependency injection as a preferable way to inject dependencies into classes that need them.
It particularly doesn't seem to make sense to have late static binding in place like you do here if there is no intent to use inheritance.  Now if you had a Singleton base class from which you inherited singleton behavior for each of these classes, then use of late static binding might be appropriate.
Additionally, you make the options and panel properties on the Admin class mutable, so you are potentially allowing the caller to put the Admin class in a bad state.
I don't really even know why options are being held on Admin class at all.  Your dependency chain seems to be Options -> Panel -> Admin, so why put an Options dependency on Admin at all?
Why introduce run() alias to render() in Panel? This method adds nothing new.
I don't understand why you would call run() from Admin constructor when, in your usage example, you are adding options after the class is instantiated.  Would these options never be rendered?
I am  struggling to see the need for so much static/concrete duality across all these classes.  To me this could be greatly simplified using dependency injection with concrete implementations like shown below:

Example:

class Admin {
    // perhaps this should not really be public?
    // Do you really want this to be mutable outside the constructor
    public $panel;

    public function __construct(Panel $panel) {
        $this->panel = $panel;
    }

    protected function run() {
        $this->panel->render();
    }
}

class Options {
    protected $options = array();

    public function __construct() {}

    public function getOptions() {
        return $this->options;
    }

    public function addOption($option) {
        $this->options[] = $option;
    }
}

class Panel {
    protected $title = 'Panel';
    protected $optionContainer;

    public function __construct(Options $options) {
        $this->optionContainer = $options;
    }

    public function render() {
        $options = $this->optionContainer->get_options();
        foreach($options as $option) {
            echo $option['name'];
        }
    }
}

// usage
$options = new Options();
$options->addOption( array( 'name' => 'Test' ) );
$admin = new Admin(new Panel($options));
// maybe add more options
$admin->panel->options->addOptions( array( 'anotherName' => 'Another Test' )
$admin->run();


As you are effectively reading the whole file test_in into memory in lots of small independent chunks, consider a different approach:

Read the whole file as one big chunk, or preferably simply map it.
Put std::string_views into that array in the vector, instead of strings.

Most std::strings employ SSO, meaning there are two possible states (external string, active SSO), in contrast to the single one for std::string_view. Thus, no branch-misprediction.

Additionally, std::string is generally at least twice the size of std::string_view, so this about halves the size of the vector's data.
Due to allocator overhead, all the small bits of string data would also together likely need considerably more space than that one big chunk.
You copy the prefix on calling find_prefix(). Better pass a view.
When you know where the range you want starts, you know it won't end earlier.
++prefix.back(); is blatantly wrong.

If the prefix is empty, it's Undefined Behavior.
If it causes signed overflow, it's Undefined Behavior.
If it causes unsigned wrap-around, you simply get a completely wrong end-position, which might even lie before the start-position.

I suggest simply writing your own comparator and using std::upper_bound() too, as it is intended to be used.

Be aware that char is treated as unsigned char for comparison by std::char_traits<char>. You probably want to mirror that, especially as you used that rule when sorting... I won't go to the trouble of staying that general.
std::equal_range() with a custom comparator does what you want:

template <class RandomAccessIterator>
auto find_prefix(RandomAccessIterator first, RandomAccessIterator last, std::string_view prefix) {
    return std::equal_range(first, last, prefix,
        [n = prefix.size()](std::string_view a, std::string_view b) noexcept {
            return a.substr(0, n) < b.substr(0, n);
    });
}

You don't need std::make_tuple in C++17. Just use std::tuple directly:

return std::tuple{low, up};

By the way, return 0; is implicit for main().


Finding the highest values a and b from an array

What you are doing is just normal search for a max pair using lexicographical ordering.

The issue with your code is that, it is linear O(n). While for a single use, this might be the best way, if you have to do it repeatedly, it would be better to build a priority queue [O(n)] with the comparison operator defined as pair compare, and then extract the top. (Even better if you can build the priority queue as you receive the elements.)

The pair comparison is derived directly from the definition

(a,b) ≤ (a′,b′) if and only if a < a′ or (a = a′ and b ≤ b′).

However you have mentioned the constraint that the loop shouldn't be changed. Is there a reason for that?


You could call itemList recursively for each object in x.materials:

var itemList = function(x) {
    for (var i = 0; i < x.materials.length; i++) {
        console.log(x.materials[i].name);
        if (x.materials[i].build !== "BasicFactory" && i !==0) {
            itemList(x.materials[i]);
        }
    }
};


Generic method for obtaining enum items in an ushort object

Code can be greatly simplified but first I'd list few things:

1) If your enum is a bitmap then you should mark it with [Flags].

[Flags]
public enum SampleCases
{
    Case1 = 0x1,
    Case2 = 0x2,
    Case3 = 0x4,
    Case4 = 0x8,
}

2) you shouldn't convert an enum value to ushort, enums default type is int and for [Flags] you may (easily?) run out of bits. If value is out of ushort range (your input) simply drop it, Convert.ToInt16() will throw OverflowException for out of range values.

3) You shouldn't create a new instance of CultureInfo every time you need it. It may be expansive. Moreover you're using en-US culture, you already have the CultureInfo.InvariantCulture.

3) To know if a value is valid you can use Enum.IsDefined().

To put all together:

public List<T> GetEnumItemsFromUshort<T>(ushort input)
    where T : struct, IComparable, IConvertible, IFormattable
{
    const int bitsInUInt16 = sizeof(ushort) * 8;

    return Enumerable.Range(0, bitsInUInt16 - 1)
        .Select(x => 1 << x)
        .Where(x => (input & x) == x && Enum.IsDefined(typeof(T), x))
        .Select(x => (T)Convert.ChangeType(x, typeof(T)))
        .ToList();
}

It's a minor change and a micro-optimization but I'd also change return type to IEnumerable<T>. If caller will need a list then it will be able to call ToList() itself and if it does not need it then you will avoid an unnecessary copy. Also first Select() may be dropped and embedded in Where() clause.

Note that 0 is not handled, you may want to include it or not; I'd leave it out because it's always matched unless you have input == 0. Note that to do not have a 0 default value for an enum is a dangerous practice, value types are 0 initialized and an uninitialized enum will have an unknown value.

Inverting point of view you may write:

public List<T> GetEnumItemsFromUshort<T>(ushort input)
    where T : struct, IComparable, IConvertible, IFormattable
{
    return Enum.GetValues(typeof(T))
        .Cast<object>()
        .Where(x => ((ushort)x & input) == (ushort)x)
        .Cast<T>()
        .ToList();
}

This 2nd version will also handle shared bits like GuestDefault, UserDefault and AdminDefault in this example:

[Flags]
enum SampleCases {
    None = 0,
    Read = 1,
    Write = 2,
    Execute = 4,
    GuestDefault = Read,
    UserDefault = Read | Execute,
    AdminDefault = Read | Write | Execute
}

Note the hacky .Cast<object>() to use .Where() over a non-generic enumeration (also paying boxing price). Here I tried to keep code short but I wouldn't implement this with LINQ (generated enumerator with yield return will be more clear, IMO). Also this code returns duplicates and aliases, if it's not what you want then you have to handle them (checking for distinct values and for multiple bits set on the same value).

Very last point: your constraints for generic parameter reduce wrong usage of your function but it doesn't really limit usage to enums: most primitive types implement same interfaces. I'd also add an explicit check:

if (!typeof(T).IsEnum))
    throw new ArgumentException("Template argument must be an enum type.");


Improving the code to turn a string into an array of numbers?

I'm partial to using LINQ here.  Jon has a point there on the conversion.

var str = "31654918562314";
var numbers = str.Select(c => c - '0').ToArray();


There is nothing inefficient about your loop.  You are simply counting from 1 to #str1.  Both bounds are known in advance.  This is as good as it gets with loops in Lua.

The only improvement I could think of was using string.byte instead of string.sub, avoiding the interning of 1-character substrings.  Even then, the difference is negligible, because the overhead of calling a C function (sub or byte) from the interpreter takes most of the CPU time.

Unless you run it under LuaJIT that is.  Under LuaJIT, byte will be inlined into the body of the loop (where is consists only of a bounds check + array access) and the string interning (which requires an allocation + hash table lookup) dominates the CPU time.


It seems a little risky to me to just blindly use the language designation that the URL contains. If it's possible to trick Express into looking somewhere in your file system besides where you expect (perhaps with dots in the path), then you could have a security issue.  It would be safer if you checked to see if it was one of a list of known-safe designations ("en", "fr", "ge", "sp", etc...). If you wanted, you could build a list of known safe designations by looking in the the file system at server startup and then just check it against that.

I would also recommend using path.join() instead of adding in the path separator yourself.  That will make your code more platform friendly should you ever want to run it on Windows.


Check your indentation, mostly for comments. While there are a lots of indent styles for C, none of them recommends removing the spaces after if and for.
Using recursive functions is not the idiomatic way of doing things in C, but that's OK.
It's generally better to check for error conditions before, and handle the general case afterwards. This is a good idea because the "error condition" is generally smaller. For example, if you check for root == NULL case first, the reader doesn't have to remember that there is possibly an else branch. This will also force you to make return false cases more explicit in your if/else branches. I think it's a good thing.
You can write if (root->mark) instead of if(root->mark==1).
This code is too long:

// Is it an unique key?
if (isFreeNode(root))
{
    return true;
}
return false;

Simple write return isFreeNode(root);. Same thing for (!isLeafNode(root) && isFreeNode(root))
*(key+level) should be written key[level].
You don't set trie->root to NULL after freeing it: this is not consistent with the earlier free().


Interface and implementation of this replacement for Rebol/Red REJOIN

Some thoughts:

Initialize String

unless into [
    out: make string! 10
]

Don't know how else to discern the initial string allocation, perhaps just start with zero?

OUT might be a strange word for a value that is both input and output. I'd also allow a NONE! value here.

/input out [any-string! none!]

Then you can initialize like:

out: any [out make string! 0]

Delimiter

if block? delimiter [
    delimiter: combine delimiter
]

Cool, a delimiter can be combined on the fly!

needs-delimiter: false
pre-delimit: does [
    either needs-delimiter [
        out: append out delimiter
    ] [
        needs-delimiter: true? with
    ]
]

Rather than an extra function and an extra value for this, why not just an extra value:

active-delimiter: none

Then set active-delimiter to delimiter after the first step through BLOCK.

Iteration

while [not tail? block] [
    set/any 'value do/next block 'block
    ...
]

I'm not certain about this, but I believe FOREACH is faster than WHILE. This seems like an inefficient way of expressing:

foreach value reduce block [
    ...
]

Functions

function? :value
closure? :value

Are you just testing for these two types of function? Otherwise ANY-FUNCTION? would catch both.

Throwing Errors

throw make error! "Evaluation in COMBINE gave function/closure"

I don't think this works in Rebol 3, at least not without wrapping the function call in a CATCH block. As I understand it, you need to DO an error to trigger it.

Coerce Output Type

An /AS refinement might be a good way to do this, so long as the type is with the ANY-STRING! typeset. It'd be a close call as to whether /INTO or /AS would take precedence for output type:

type: any [type string!]
out: any [out make type 0]

None/Empty

My opinion here is:

combine []
combine [none]

Should return ""

combine/with [none none] ","

Should return ","


PHP review of object oriented GeoIP class

I'm not a fan of magic getters. Without really good documentation, they're just a pain for consumers of your code. For example, when I first looked at your code, I had no idea at all what properties the class exposes. I basically had to follow the cURL request to find out. Proper documentation could fix this, but why not just have proper properties instead (or a getter)?
As a general rule of thumb, a class should never successfully construct if it will be left in a useless state. In other words, your constructor shouldn't finish unless the IP request actually went through and the data was retrieved.

If the IP is invalid, throw an exception.
If the cURL request fails, throw an exception

cURL isn't really necessary here (at least not with the way you're using it). Just use file_get_contents("http://.../...");
Your getter should return null if the property doesn't exist. null will be returned implicitly, but I think the code would be a bit clearer (alternatively, you could throw an exception depending on how you want the class to be used)
isset($var) && !empty($var) is redundant. !empty($var) is equivalent to isset($var) && $var meaning you can just do !$empty.
Your __toString doesn't have a real use at the moment. The return is too unpredictable to reliably use it to print the data. I would either normalize it to always print the same fields in the same format or get rid of it.

I've not a fan of __toString for most classes. Unless a class has a canonical string represenation (like a BigInt would, or a IPAddress, etc), I wouldn't bother having a __toString.
__toString can ease debugging though, so if you like to use it for that, it might be worth keeping it around

I think you need to decouple the data object (the city/state/area code/etc) from the retrieval of it. I would have two classes: GeoIP and GeoIPInformation (or whatever you want to call it).

GeoIP would then have a method public function getInformation($ipAddress); that returns a GeoIPInformation.

if you think there's a chance you'd ever want to have a different method for ipv4 or ipv6 or the ability to lookup host names, you might want to name it getInformationByIPv4

If you wanted to go all out, you could code the retriever to an interface. This would remove your ties to freegeoip.net (which might stop existing or working at any time)

A second retriever that immediately comes to mind is the maxmind geoip databases
Interfaces are good for decoupling, blah blah blah... ask me if you more details on this.

Update

Dave Jarvis had a very good point with the encapsulation issue. Concepts like a country should be stored as an object, not a simple scalar. This allows the consuming code to interact with the data in a much cleaner way. For example, imagine that one data source returns a 2 letter country code whereas another returns a country name. If the coutnry is a plain string, this presents a problem: how do we know what echo $loc->getCountry(); is going to be? Is it going to be a country code? Or a name? Or maybe an ID? Who knows.

But, if instead of leaving it a scalar we turn it into an object, we get the benefit of being able to do echo $loc->getCountry()->getName(); and knowing that it will be a proper name. There's an added benefit too of we now have much more data at hand. We are no longer constrained to one small snippet of data about the country. We now have the ability to have the name, code, etc all wrapped up in one convenient object.

Different strategies are possible to create these objects, but for your uses, I would just stick with a simple lookup table or something similar in this situation.

If you wanted to go all out, you could connect it to some kind of data source and then have your code interact with that to load a country. This would be a lot more flexible as the data is no longer part of the code (which tends to be bad), but it's also more complicated, and I'm lazy. If you did go this route, you could create a CountryFinder interface that knows how to create a Country based on a given criteria. You would then inject a CountryFinder implementation into your GeoIP implementations and it would use it.

I've updated my code below to reflect a basic sketch of these updates. I've only demonstrated by encapsulating the IP address and country, but hopefully the idea is clear. (Also, my error handling is pretty terrible in a few places such as the IP address constructor where an exception should be thrown if the argument is invalid).

Oh, and Location should either be named IpLocation to signify that it embodies a Location/IP pair, or it should have the IP address removed from it. (A Location object really has no business having an IP address as an attribute, but as it is actually GeoIP::Location, I might be tempted to leave it.)

All in all, I might consider something like this:

Note that this is a bit crude -- the error handling is bad, the exceptions should be subclasses, I put half a second of thought into names, etc

<?php

namespace GeoIP;

interface GeoIP
{
    /**
     * Retrieves geo information for an IP address.
     * @param string|IpAddress $ipAddress Either an IpAddress or an IP address formatted as a string in dotted decimal notation
     * @return \GeoIP\Location
     * @throws \InvalidArgumentException if the IP address is invalidly formatted
     * @throws \RuntimeException if some kind of network/disk/etc error occurs
    */
    public function getLocationByIpAddress($ipAddress);
}

class IpAddress
{

    private $_addr;

    public function __construct($addr)
    {
        //You can either guess what $addr is (string, 32 bit int, etc),
        //or you could provide static fromString, fromLong, etc methods.
        //For simplicity, I've assumed it's a decimal dotted string
        $this->_addr = $addr;
    }

    public function asDecimalDotString()
    {
        return $this->_addr;
    }

    public function asLong()
    {
        $octets = explode(".", $this->_addr);
        return ($octets[0] << 24) + ($octets[1] << 16) + ($octets[2] << 8) + $octets[3];
    }

}

class Location
{
    private $_ip;
    private $_country;

    public function __construct($ip, Country $country)
    {
        $this->_ip = $ip;
        $this->_country = $country;
    }

    /**
     * @return IpAddress The IP address that was used in retrieving this geo information
    */
    public function getIpAddress()
    {
        return $this->_ip;
    }

    /**
     * @return Country|null the country the IP belongs to or null is one could not be determined
    */
    public function getCountry()
    {
        return $this->_country;
    }

    // ...

}

interface CountryFinder
{
    public function findByCountryCode($code);
    public function findByCountryName($name);
}

class Country
{

    private $_name;
    private $_code;
    private $_population;

    public function __construct($name, $code, $population)
    {
        $this->_name = $name;
        $this->_code = $code;
        $this->_population = $population;
    }

    public function getName()
    {
        return $this->_name;
    }

    public function getCode()
    {
        return $this->_code;
    }

    public function getPopulation()
    {
        return $this->_population;
    }

}

class ArrayLookupCountryFinder implements CountryFinder
{

    private $_countryData = array(
        'US' => array('name' => 'United States', 'code' => 'US', 'population' => 300000000),
        'CA' => array('name' => 'Canada', 'code' => 'CA', 'population' => 34500000)
    );

    public function __construct(array $countryData = null)
    {
        if ($countryData) {
            $this->_countryData = $countryData;
        }
    }

    public function findByCountryCode($code)
    {
        if (isset($this->_countryData[$code])) {
            $country = $this->_countryData[$code];
            return new Country($country['name'], $country['code'], $country['population']);
        } else {
            return null;
        }
    }

    public function findByCountryName($name)
    {
        // Yeah...
        return null;
    }

}

class FreeGeoipNet implements GeoIP
{

    private $_countryFinder;

    public function __construct(CountryFinder $countryFinder)
    {
        $this->_countryFinder = $countryFinder;
    }

    public function getLocationByIpAddress($ipAddress)
    {

        if (!($ipAddress instanceof IpAddress)) {
            $ipAddress = new IpAddress($ipAddress);
        }

        $response = file_get_contents("http://freegeoip.net/json/" . $ipAddress->asDecimalDotString());
        if ($response === false) {
            throw new \RuntimeException("Request to freegeoip.net failed");
        }
        $data = json_decode($response, true);
        if (!is_array($data)) {
            throw new \RuntimeException("Parsing response from freegeoip.net failed: {$response}");
        }
        /* In a real application, you would likely want to somehow handle if the country code wasn't empty but a
         * country couldn't be found in your data source. I'm lazy though, so I've not done that. */
        return new Location($ipAddress, $this->_countryFinder->findByCountryCode($data['country_code']));
    }
}

Usage:

$geoip = new GeoIP\FreeGeoipNet(new GeoIP\ArrayLookupCountryFinder());

$location = $geoip->getLocationByIpAddress("x.x.x.x");

$ip = $location->getIpAddress();
$country = $location->getCountry();

echo $ip->asDecimalDotString() . " (" . $ip->asLong(). ") " . " is in " . $location->getCountry()->getName()
     . " which has a population of " . $location->getCountry()->getPopulation();


"Fast strlen" in C using scalar bithacks

Bug

strlen("\x80\x80\x80\x80\x80\x80\x80") does not return the expected 7.  The do loop does not distinguish between '\0' and '\x80'.

strlen("\x80\x80\x80") returns 0, 1, 2  or 3 depending on alignment.

These render  the function broken.

Why int32_t?

Certainly int32_t* marches down the sting at a 4x clip rather than a plodding char *.  Yet for a 16-bit int machine, int32_t* may be slower.  For a 64-bit machine, int64_t* could even be faster.   I'd expect a unsigned * to work fast or even fastest.  I guess that is why strlen() is a library function - each implementation is expected to use its own optimal approach.

Minor: Clearly use unsigned mask constants

With bit masking, shifts and subtraction, using unsigned math has less review concerns.

0x01010101 --> 0x01010101u.

Portability

while(... & (sizeof(uint32_t)-1)) is a reasonable alignment test but not a specified correct one.  Conversion of a pointer to an integer need not follow the usual linear expectations.  I do not know of any implementation where this will not work, but it is not C specified.

Notes:
uint32_t is an optional type.  A unicorn platform may not have it defined.
uintptr_t is also an optional type.

Could use something like

#include <stdint.h>
#ifndef UINTPTR_MAX
  #error "You are kidding me? An implementation without uintptr_t!"
#endif

Comment nit

Mask off high bit should be "Mask off high bits" or "Mask off each byte high bit", ...

/* Mask off high bit */
i &= HIGH_MASK;


This minimizes the interaction with the range (as mentioned by @M.Doerner)
and clears the previous data in one operation (mentioned by @Patrick)

Determines the range to work with

Minimum between arr().Rows and nRows, and arr().Cols and nCols
Establishes the UsedRange based on startCell, and Cells(nRows, nCols)

Clears entire UsedRange
If fromTop is True places arr() into the UsedRange
Else, reverses rows in arr() into variant array result, then places it into UsedRange

Rows: 100,001; Cols: 20; fromTop: True  - Time: 4.461 sec
Rows: 100,001; Cols: 20; fromTop: False - Time: 4.734 sec

Option Explicit

'writes the 2-D arr to startCell; if fromTop is False it starts from the last row
Public Sub WriteArrToWS(ByRef arr() As Variant, ByRef startCell As Range, _
                        ByVal fromTop As Boolean, nRows As Long, nCols As Long)

    nRows = IIf(nRows < UBound(arr, 1), nRows, UBound(arr, 1))
    nCols = IIf(nCols < UBound(arr, 2), nCols, UBound(arr, 2))

    Dim ws As Worksheet, fr As Long, fc As Long, ur As Range

    Set ws = startCell.Worksheet
    fr = startCell.Row
    fc = startCell.Column
    Set ur = ws.Range(ws.Cells(fr, fc), ws.Cells(fr + nRows - 1, fc + nCols - 1))
    ur.ClearContents

    Dim result As Variant, r As Long, c As Long, lr As Long

    result = ur
    result = arr            'Defaults to fromTop = True
    If Not fromTop Then     'If fromTop = False, reverses the rows in the array
        lr = nRows
        For r = 1 To nRows
            For c = 1 To nCols
                result(r, c) = arr(lr, c)
            Next
            lr = lr - 1
        Next
    End If
    ur = result
End Sub


Laravel Dependency Injection : Perfomace Issue And Architecture Style

I'll be curious to see if anyone else has an opinion here, but while we wait here is mine:

Architecture

I don't see anything obviously wrong with this code.  I presume that your view actually needs all of that data in order to generate all the necessary HTML/etc.  If that is the case you only have two options anyway: inject all your repositories or completely rebuild the actual HTML page so you don't need so much data.  Again, presuming that your page simply needs all this data on it, the only way to do that would be with a completely different architecture: namely, a front end application that hits up a variety of endpoints to get each piece of data separately and then builds the actual page.  That will substantially simplify your controllers (presumably they would just need one repository each), but it would also mean more controllers and a more complicated front-end, so I don't really see that as being much of an improvement.  All that to say this: If your page needs a lot of different "kinds" of data then you have no choice but to fetch lots of different "kinds" of data.

Performance

4 or 5 repositories doesn't seem like a terribly large number to me.  You could always find out by doing some profiling.  The best way to answer "does this cause performance problems" is by profiling and finding out how it actually performs.  Laravel has some easy-to-add-on tools for that.  As a (very) rough guideline, if your page can completely render in a tenth of a second or so, then it isn't terrible.  Ultimately though, performance is relative to page load and other factors.  A high traffic page obviously needs to have better performance than one visited once a month by a single person.  In essence, poor performance + high traffic = crashed server.  Ultimately, it is up to you to decide whether or not a given page is loading fast enough (i.e. performing well enough) given your available resources and the level of traffic the page receives.

Constructor injection vs method injection

Although I don't know enough about the innards of Laravel here to say for sure, I doubt there is a measurable difference in performance between injecting a repository in the constructor vs the method.  However, the way there can be a difference is because any constructor-dependencies are always injected, where as method ones are only injected when the particular endpoint is called.  So if you have a dependency injected in your constructor that is only used in one endpoint (or not at all), then that would be wasteful.  If, however, a dependency is used in all the endpoints in the controller, I would just inject it in the constructor and be done with it.  If you only have one method in your constructor, then it effectively shouldn't matter whether you inject in your constructor or method.

Injecting repositories in repositories

Whether or not that is a good idea or bad idea depends on the use case.  There isn't an example of that here, so I would suggest another question to address that.


Doubly circular link list implementation

You have done the correct thing by putting a sentinel element into the list.
This makes adding/removing and generally manipulating the list trivial because you don't need to handle NULL links in the list.

But you have done it using a two phase create.

You have to construct your list.
You have to call create to initialize it.

This is a very bad idea. Your object should be fully constructed at the end of the constructor. That way users can not incorrectly initialize your class.

There is also a bug in your create. You create a node but you don;t link it to anything:

void LinkList::create()
{
   Node start(0);  // This node is destroyed at the end of the function.
}

What you should be doing is:

LinkedList::LinkedList()
    : current(new Node(0, NULL, NULL))
    // , head(current)      You don't actually need head/tail
    // , tail(current)      since it is circular these are beside each other.
{
    current->prev = current;
    cureent->next = current;
}

Also your code can delete the sentinel and thus cause all sorts of problems. You should not allow the deletion of the sentinel and your other functions should check for a list with just a sentinel in them (this is the empty list).

Why are you giving back references to the Node? This is an internal implementation detail. Return a reference to the value (or throw an exception if the list is empty). By returning a node you are binding your self to use a specific implementation (take a leaf out of the standard library and just return a reference to the value).

const Node& LinkList::back()const

Same comment again:

const Node& LinkList::front() const

Not sure I have seen this functionality in a list before. It seems to allow you to move the head around inside the list.

void LinkList::move()

So this is why you have to return the node above?

void LinkList :: insert(const Node& a)

I would rather have insert_front/insert_back/insert_at functionality.

Remove has some issues:

void LinkList::remove(const Node& a)

Two problems:

You don't update current (so it points at the deleted node).
You allow the sentinel to be deleted.
If you delete the last node the easy insertion/deletion breaks down.

This is what I would do:

class LL
{
   struct Node {
       int value;
       Node* next;
       Node* prev;
       Node() // Sentinel
         : next(this)
         , prev(this)
       {}
       Node(int val, Node* prev, Node* next)
          : value(val)
          , next(next)
          , prev(prev)
       {
           prev->next = this;
           next->prev = this;
       }
       ~Node()
       {
           prev->next = next;
           next->prev = prev;
       }
    };
    Node* current;
    LL()
        : current(new Node)
    {}
    ~LL()
    {
        while(!empty())
        {
           delete current->next;
        }
        delete current;
    }
    bool empty() const { return current == current->next;}
    void insert_front()
    {
         new Node(current, current->next);
    }
    void insert_back()
    {
         new Node(current->prev, current);
    }
    void delete_front()
    {
         if (!empty())
             delete current->next;
    }
    void delete_back()
    {
         if (!empty())
             delete current->prev;
    }
    int& front()
    {
        if (empty()) {throw empty_exception();}
        return current->next->value;
    }
    int& back()
    {
        if (empty()) {throw empty_exception();}
        return current->prev->value;
    }
};


Script scraper for outputting variables and functions to a text file

A couple of suggestions:

make_readable has a very serious problem - what if two inputs have the same length? A dictionary can only have one value per key; I suggest making it a dictionary of lists of items (or a collections.defaultdict(list)) instead. Also, don't call the argument list - that's a built-in.

sort_this could be shortened (and the argument shouldn't be called dict):

def sort_this(d):
    return [d[key] for key in sorted(d)]

Iterating over a dictionary (e.g. in sorted) automatically iterates over the keys. Also, this will work without modification in Python 3.x (where fixed.sort() will fail).

The global variables (e.g. funcs) should either be explicitly global (i.e. put global funcs at the start of functions that use them) or, much better, passed as arguments to the functions:

def parse_match(match, funcs, varis, parse_next):

One bug you may want to look into - if a variable is defined over multiple lines:

my_list = [1, 2, 3,
           4, 5, 6]

Your code only gets the start of the definition.

Finally, it would be neat to not have to change the hard-coded strings to change the files to analyse and output to! Look into taking command line arguments (sys.argv) or using e.g. tkinter to put a GUI in. At the very least, have a higher-level function analyse(input_file, output_file) then call it at the end of your script:

if __name__ == "__main__":
    analyse("C:\\code\\test.txt", "C:\\code\\output.txt")

It is not best practice to put the variables you have to change somewhere in the middle of the file - top or bottom is easier to find!


Bug

I see no justification for or half - start < eps.  With that, you no longer guarantee that the return value is a root of f.


Processing XML configuration which stores regular expressions and format strings for a documentation tool

Any idea on how to improve lookUp?

Use a concurrent cache.  The point is, regardless how good or bad you lookup function is, nothing beats a cache-hit performance wise..

  Is there a better way to do simple caching than using withDefault to
  mutate the underlying map?

getOrElseUpdate(key, value)


The way you generate primes is very inefficient. There are a few quick fixes to speed it up. But first let's put the primality check into its own function:

def is_prime(n):
    prime = True
    for num in range(2, n):
        if n % num == 0:
            prime = False
    return prime

primes = [n for n in range(2, 100000) if is_prime(n)]

This uses a list comprehension, the fact that the default increment of range is 1 and follows Python's official style-guide, PEP8.

Now, if you know that a number is composite, there is no need to check for all other numbers if they divide the number:

def is_prime(n):
    for num in range(2, n):
        if n % num == 0:
            return False
    return True

All prime numbers except for 2 are odd. So just start with 2 in the list and increment by 2:

    primes = [2] + [n for n in range(3, 100000, 2) if is_prime(n)]

You could even hard-code all primes below 10, but the performance gain from that is very small.

And finally, if you know that k is a divisor of n, then so is n // k. In other words, as soon as you have checked all values smaller than sqrt(n), you have already checked all possible divisors.

from math import sqrt

def is_prime(n):
    for num in range(2, int(sqrt(n)) + 1):
        if n % num == 0:
            return False
    return True

There are even faster ways to generate all primes up to some number and they are known as sieves (since they sieve out multiples of numbers for which you know that they are prime). One possible implementation as a generator of the well-known Sieve of Eratosthenes is this:

def prime_sieve(limit):
    prime = [True] * limit
    prime[0] = prime[1] = False

    for i, is_prime in enumerate(prime):
        if is_prime:
            yield i
            for n in range(i * i, limit, i):
                prime[n] = False

primes = list(prime_sieve(100000))


Side effects in functions that find boolean conditions

The method name CanAdd implies that it won't have side effects. Therefore you could mistake the method in the future as a read-only method, while it isn't. Also because the relationship between checking whether it can be added to list A and adding it to another list is not strongly related, I would advice to make CanAdd a method that doesn't make any changes.

A better place to add the campaign to the conflicting list would be in execute or in a separate method called from execute.


Drag and drop selected array items in Javascript

So you don't need two loops here. You can just use one loop to

First, get the selected items
Remove the selected items from the actual array. So you can later put them in the index you want.

So to do that, first, you have to retrieve the indices where the selected obj is there. Then spice it. IN the loop

for (let index in list) {
    const item = list[index];

    if (item.selected) {
        selected.push(item);
        list.spice(index,1)
    }
}

So you don't have to run another loop to remove the null values. You can now simply just put the values using another spice. That saves you a loop.

You shouldn't be using for ... in for the reasons you have got in RoToRa's answer.

My approach: I prefer using just one filter. In that, you can do the same thing.

function drag_and_drop(list, before_index) {
  const selected = list.filter((obj,i) => obj.selected ? list.splice(i,1) : obj.selected)
  list.splice(before_index - selected.length , 0, ...selected)
  return list
}

So here, first we check if the object is selected and if it is then we'll just splice it off and if we didn't got a selected item then we can just return the selected item in the selected loop.

So now you have inside selected, the values which have item.selected as true and your list don't have them now because you did splice already in the filter, so you can just splice them with another splice.

Now the index is not anymore before_index it's two values more, because we took out two objects. So to balance that, we will do before_index - selected.length because that's the number of indexes we are going to drop.


Count the frequency of items in an array

Answer to the Performance Issue
Anytime there are a list of variables named NAMEi where i is an integer, there is a strong chance that a container such as std::array or std::vector should be used. Sometimes using a table rather than multiple if statements can improve performance.

Indexing into an array will prevent the repetitive code that is currently in the solution:

#include <array>

int main()
{
const int inputSize = 10;
const int frequencyCount = 6;
std::array<int, inputSize> inputValues;
std::array<int, frequencyCount> freqs;

    ...
}

The array freqs will contain the frequency of the occurrence, there are a couple of ways to index into the array freqs. One would be to subtract 80 from the input value.

This will reduce the multiple if statements into a simple increment of an item in an array. It will also reduce the amount of code necessary to print the frequencies.

When performance is an issue, prefer "\n" over std::endl. The use of std::endl flushes the output which may mean there is a system call for each use. A system call can add a great deal of time.

Remove the do/while loop in the error checking.

Use the Container Classes Provided by C++
The code currently appears to be C rather than C++. It is using the old style C arrays, C++ supplies an array container class as part of the standard library. Using the array container class would allow you to use iterators instead of indexes, at least for printing. Here is a second reference.

Avoid Using Namespace STD
If you are coding professionally you probably should get out of the habit of using the "using namespace std;" statement. The code will more clearly define where cout and other functions are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The function cout you may override within your own classes. This stack overflow question discusses this in more detail.

DRY Code
There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code mutiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.

Complexity
The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.

There is also a programming principle called the Single Responsibility Principe that applies here. The Single Responsibility Principle states:

  that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

There are at least 3 possible functions in main().
  - Get the user input
  - Get process the frequencies
  - Print the frequencies

Magic Numbers
There are Magic Numbers in the main() function (79 and 86), it might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintainence easier.

Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.


Most basic HTML website - naming and CSS rules

You should be using HTML 5 elements such as header and nav making some/all classes and IDs unnecessary:

Link

Link

Link


I would use an entirely different strategy to determine the number of times needed to rotate the string: addition.

Since rotating a string by a and then b yields the same result as rotating it a+b, we do not need to keep track of the string at all, only the equivalent rotation. However, we do need to be able to detect if the string is actually just concantenations of some substring; in that case we can treat it as if its length were the length of the repeated substring.

Here are the steps I would use for each string:

Match the string against the regular expression (.+?)\1+. This uses a backreference to find the iterated portions of the string. (FYI, this regex may need some adjustment.)

static final Pattern iteratedSubstring = Pattern.compile("(.+?)\\1+");
static int reducedLength(String string){
    Matcher m = iteratedSubstring.matcher();
    if(m.matches(input)) return m.group(1).length()

    return string.length()
}

Repeatedly accumulate the two rotations until the rotation is congruent to zero modulo the length.

static int identityRotationCount(final int length, int ... rotations){
    rotations = Arrays.stream(rotations).parallel().flatMap(i->i%length).toArray();

    /* alternately, if you can't use java 8 you can do this, although it's slower:
    for(int idx = 0; idx < rotations.length; idx++)
        rotations[idx] %= length;
    */

    int count = 0, rotation = 0;

    while(true)
        for(int rot: rotations){
            count++;
            rotation += rot;
            if(rotation == length) return count;
            if(rotation > length) rotation -= length;
        }
}

There may be even faster methods to compute this, including variants on algorithms for finding a GCD or other discrete algebra type things.
At least at first, you should be using a Scanner to process the input, because inevitable parsing logic bugs from doing the parsing yourself will make debugging anything else extremely difficult.

try(Scanner in = new Scanner(System.in), PrintWriter out = System.out){
    // ...
}

Finish the program:

in.nextInt(); //discard input entry count, don't need it.

while(true){
    if(!in.hasNextLine()) break;
    String string = in.nextLine();

    if(!in.hasNextInt()) break;
    int monkey = in.nextInt();

    if(!in.hasNextInt()) break;
    int po = in.nextInt();

    out.println(identityRotationCount(reducedLength(string), monkey, po));
}

If you do not want to use a Scanner, try something like this:

try(BufferedReader in = new BufferedReader(System.in), PrintWriter out = System.out){
    int n = Integer.parseInt(in.readLine());

    for(int idx = 0; idx < n; idx++){
        String string = in.readLine();

        String [] rots = in.readLine().split("\\s");

        int monkey = Integer.parseInt(rots[0]),
                  po = Integer.parseInt(rots[1]);

        out.println(identityRotationCount(reducedLength(string), monkey, po));
    }
}


Populate Comboboxes with Hashtables using PowerShell

The first thing to observe is that the five pieces of code are identical except for two parameters that are varying. We can capture the common the code in a function (let's call it populateComboBox), and call that five times:

populateComboBox $UI.Combobox1 $ColumnsHashTable.Column1
populateComboBox $UI.Combobox2 $ColumnsHashTable.Column2
populateComboBox $UI.Combobox3 $ColumnsHashTable.Column3
populateComboBox $UI.Combobox4 $ColumnsHashTable.Column4
populateComboBox $UI.Combobox5 $ColumnsHashTable.Column5

function populateComboBox($comboBox, $column)
{
    For($i = 0; $i -lt $column.Length; $i++) {
        $comboBox.Items.Add($column[$i])
    }
}

It's best not to use old C-style for loops with an index unless you need to because they add visual noise:

populateComboBox $UI.Combobox1 $ColumnsHashTable.Column1
populateComboBox $UI.Combobox2 $ColumnsHashTable.Column2
populateComboBox $UI.Combobox3 $ColumnsHashTable.Column3
populateComboBox $UI.Combobox4 $ColumnsHashTable.Column4
populateComboBox $UI.Combobox5 $ColumnsHashTable.Column5

function populateComboBox($comboBox, $column)
{
    foreach ($item in $column)
    {
        $comboBox.Items.Add($item)
    }
}

We could leave it there. I think that is acceptable code. If we wanted to however, we could take it further in one of two directions.

First, instead of the five calls to populateComboBox, we could make a loop from 1 to 5, and get the appropriate properties to pass to the function with Get-ItemProperty. (I'm assuming that ComboBox1 and so on are really named that way and are not just example names.)

The other idea would be to make an array of (ComboBox, Column) pairs and iterate through that. I quite like that idea because as a general rule it's good to put as much of your code as possible into datastructures. It might be overkill in this case however.

Added stuff:

To expand on the "other idea" above, we can make an array of (ComboBox, Column) pairs. We can use an array of arrays for this:

$comboVals = (
    ($UI.Combobox1, $ColumnsHashTable.Column1),
    ($UI.Combobox2, $ColumnsHashTable.Column2),
    ($UI.Combobox3, $ColumnsHashTable.Column3),
    ($UI.Combobox4, $ColumnsHashTable.Column4),
    ($UI.Combobox5, $ColumnsHashTable.Column5)
    );

(If you are wondering, I didn't put @ symbols on the arrays here because PowerShell is smart enough to figure out here that we are using arrays.)

We can then iterate through that data structure calling the same populateComboBox function we defined before:

foreach ($pair in $comboVals)
{
    populateComboBox $pair[0] $pair[1]
}

Below is the final script. Note that I haven't tried running this because it is not runnable for me since I don't have the ComboBoxes and columns to test with. I think it should be okay though.

$comboVals = (
    ($UI.Combobox1, $ColumnsHashTable.Column1),
    ($UI.Combobox2, $ColumnsHashTable.Column2),
    ($UI.Combobox3, $ColumnsHashTable.Column3),
    ($UI.Combobox4, $ColumnsHashTable.Column4),
    ($UI.Combobox5, $ColumnsHashTable.Column5)
    );

foreach ($pair in $comboVals)
{
    populateComboBox $pair[0] $pair[1]
}

function populateComboBox($comboBox, $column)
{
    foreach ($item in $column)
    {
        $comboBox.Items.Add($item)
    }
}


How could I reduce repetition with properties/methods?

As @Magus commented, this is as good as it gets.

...almost.

[DataContract]
public class ConcreteModel: ModelClass

[DataMember] public Guid m_id { get; set; }

[DataMember]
public string      m_name;

You're not consistent with how you're placing your DataMemberAttribute attributes; sometimes they're sitting on top of the decorated member, other times they're stuck in front, on the same line. I'd stick to consistently having them on top.

// Stuff we don't serialize
public Sector      m_sector;
public Theater     m_theater;
public Weather     m_weather;
public TerrainType m_terrainType;

Why are these fields public in the first place? You are breaking encapsulation!

[DataMember] private Guid m_sectorID
{
    get { return GetID(m_sector); }
    set { m_sector = FromID<Sector>(value); }
}

I'm not familiar with serialization using [DataMemberAttribute], but it's rather odd that you expose public fields and declare private serializable properties. Since the fields are exposed anyway, why not just do this?

private Sector m_sector;

[DataMember]
public Guid m_sectorID
{
    get { return GetID(m_sector); }
    set { m_sector = FromID<Sector>(value); }
}

The naming is, as @Magus commented already, breaking all C# naming conventions. Drop the m_ prefix, and use PascalCase for public members:

private Sector _sector; // or just "sector"

[DataMember]
public Guid SectorId
{
    get { return GetId(_sector); }
    set { _sector = FromId<Sector>(value); }
}

If ModelClass isn't intended to be instantiated and only serve as a base class, you should make it abstract - also "Class" at the end of a class name is rather useless. How about this?

public abstract class ModelBase

The public static members could made non-static, and be protected so as to only be exposed to the derived types.


Welcome to C++, and welcome to Code Review.
C++ memory management is, as you probably have realized, tough and
error-prone.  There are many things that can easily go wrong.
Assuming that no exception is thrown, I don't see obvious memory leaks
in your code; however, there are still some issues worth discussing.
You can take a look at my implementation of a non-resizable dynamic
array or a stack-based full-fledged vector for some
inspiration.
Special member functions
You have not defined copy constructors or move constructors, so the
compiler will synthesize corresponding constructors that simply copy
all the members — which is completely wrong, as now the two
dynamic arrays will point to the same memory.  Not only are the
elements shared between the copies, causing modifications to one array
to affect the other, but the two copies will attempt to free the same
memory upon destruction, leading to a double-free error, which is
way more serious than a memory leak.
Initialization semantics
It is generally expected that the constructor of the element type is
called \$n\$ times if \$n\$ elements are pushed into the dynamic
array.  In your code, however, this is not the case, whre the amount
of constructors called is determined by the capacity of the dynamic
array.  Elements are first default initialized, and then copy-assigned
to.
The correct way to solve this problem requires allocating an
uninitialized buffer, and using placement new (or equivalent features)
to construct the elements, which is another can of worms.
Exception safety
Think of what happens when the construction of an element throws an
exception — your code will halt halfway, and there will be a
memory leak.  Resolving this problem would require a manual try
block, or standard library facilities like
std::uninitialized_copy (which essentially do the same under
the hood) if you switched to uninitialized buffers and manual
construction.
Move semantics
All of the elements are copied every time, which is wasteful.  Make
good use of move semantics when appropriate.
Miscellaneous
Used std::size_t instead of int to store sizes and indexes.1
get, size, and print should be const.  Moreover, get should
return a const T&.  In fact, get and set would idiomatically be
replaced by operator[].
Don't throw a const char*.  Use a dedicated exception class like
std::out_of_range instead.
Manual loops like
for (int i = 0; i < m_length; i++) {
    new_arr[i] = m_arr[i];
}

are better replaced with calls to std::copy (or
std::move).
Re-allocating every time insert is called doesn't seem like a good
idea.  A better trade-off might be to append an element and then
std::rotate it to the correct position (assuming rotation
doesn't throw).
Also, print might take an std::ostream& (or perhaps
std::basic_ostream<Char, Traits>&) argument for extra flexibility.

1 As Andreas H. pointed out in the comments, this recommendation is subject to debate, since the use of unsigned arithmetic has its pitfalls.  An alternative is to use std::ptrdiff_t and std::ssize (C++20) instead.  You can write your own version of ssize as shown on the cppreference page if C++20 is not accessible.


Solution for puzzle 3d x 1d = 2d x 2d in Python

Style

Python has a style guide called PEP8. It is definitly worth a read. Among the few things you could do to make your code more pythonic : spacing around operators. Also, you should try to avoid giving your variables the same name as builtins. Furthermore, you can assign all variables in one go if it corresponds to a single logical operation (as in "saving the best result found so far"). Finally, you can remove explicit conversion when printing :

import time
start = time.time()
maxi, gx, gy, gi, gj = 0, 0, 0, 0, 0

for i in range(999, 99, -1):
    for j in range(9, 0, -1):
        mul = i * j

        for x in range(99, 9, -1):
            for y in range(99, 9, -1):
                mul2 = x*y

                if mul == mul2:
                    if mul > maxi:
                        maxi, gx, gy, gi, gj = mul, x, y, i, j

print("i: ", gi)
print("j: ", gj)
print("x: ", gx)
print("y: ", gy)
print("max: ", maxi)
end = time.time()
print(end - start

Algorithm

For each i, j, it only makes sense to check if it can be written under the form _ _ * _ _ if it is bigger than the current best value.

for i in range(999, 99, -1):
    for j in range(9, 0, -1):
        mul = i * j

        if mul > maxi:
            for x in range(99, 9, -1):
                for y in range(99, 9, -1):
                    mul2 = x*y
                    if mul == mul2:
                            maxi, gx, gy, gi, gj = mul, x, y, i, j

This makes your code go roughly 500 times faster.

From this point, it is hard to make things actually faster but let's try.

Once you have mul, to find 2 divisors under of 2 digits, you don't need have two loops : one is enough and then you check if the number actually divides mul and if the result has 2 digits.

    if mul > maxi:
        for x in range(99, 9, -1):
            y, r = divmod(mul, x)
            if r == 0 and 10 <= y < 100:
                axi, gx, gy, gi, gj = mul, x, y, i, j

Once you have it, you can break because it will only find the same solution.

    if mul > maxi:
        for x in range(99, 9, -1):
            y, r = divmod(mul, x)
            if r == 0 and 10 <= y < 100:
                maxi, gx, gy, gi, gj = mul, x, y, i, j
                break

Similarly, you can break out of the j loop when mul <= maxi because mul goes decreasing.

for i in range(999, 99, -1):
    for j in range(9, 0, -1):
        mul = i * j

        if mul <= maxi:
            break
        else:
            for x in range(99, 9, -1):
                y, r = divmod(mul, x)
                if r == 0 and 10 <= y < 100:
                    maxi, gx, gy, gi, gj = mul, x, y, i, j
                    break

Also, in the x loop, it doesn't make sense anymore to do backward.

for i in range(999, 99, -1):
    for j in range(9, 0, -1):
        mul = i * j
        if mul <= maxi:
            break
        else:
            for x in range(10, 100):
                y, r = divmod(mul, x)
                if r == 0 and 10 <= y < 100:
                    maxi, gx, gy, gi, gj = mul, x, y, i, j
                    print(maxi)
                    break

This seems to be roughly 10 000 times faster than it used to be.


Timus Online Judge Problem 1001 - "Reverse Root"

The input stream contains a set of integer numbers \$A_i\$ (\$0 \leq A_i \leq 10^{18}\$).

So you should change

double t;

to

unsigned long long t;

This actually speeds up the program a lot.

To speed up the output, instead of

cout << fixed;
cout << setprecision(4);

for (int i = idx - 1; i >= 0; --i)
    cout << v[i] << endl;

Try

for (int i = idx - 1; i >= 0; --i) {
    printf("%.4f\n", v[i]);
}


Nothing jumps out:

Rather than this:

   if(tmp < 10)
        *p = tmp + '0';
    else
        *p = tmp + 'A' - 10;

I would have used:

   *p = tmp + (tmp < 10) ? '0' : 'A' - 10;

Even though you pass around a pointer to a pointer (for re-alloc I assume). You don't actually do any reallocation. So I would simplify the code and just pass a pointer.

void make_hex_string_easy(unsigned int invokeid, char** xref)
                                                 ^^^^^^   I would just use char*

Note: A lot of common interfaces when you pass a NULL as the destination return how many characters it would have used in the buffer. This leads to a lot of C code that looks like this:

size_t  s = make_hex_string_easy(number, NULL); // assuming you changed your code to return a value.
char*   b = malloc(s+1);
make_hex_string_easy(number, b);

But Since you don't use dynamic buffers I would remove the calloc.

printf("Using sprintf method\n");
for(i = 0; i < sz; ++i) {
    char  test[50] = {0}; // inits to 0
    make_hex_string_easy(testdata[i], test);  // assuming you change to just a pointer
    printf("hex string of %#10x = \t%10s\n", testdata[i], test);
}


Sorting a set of numbers in a file using Java BitSet

Overall your code is very well formatted and readable but I have some complaints at the moment:

Don't declare all methods with throws Exception. Only declare the Exceptions you really need to declare, such as IOException. Declaring throws Exception will force the caller to also catch all RuntimeExceptions, which I say is a big no-no as that could potentially catch important bugs (NPEs for example) in your code. I prefer to let RuntimeExceptions cascade up the hierarchy, without catching them.
Your deriveOutputFile is as far as I can see only called from one place, and consists of only one line. Does it really need to be it's own method? I'd also say that it's name is somewhat ambiguous. deriveOutputFileName would be better.
Your entire class is static. I'm not so sure about this decision. If you'd want to test it in any way you would probably want it non-static, as you then could use a mocking framework to simulate the file input.

Regarding your questions I have some comments:

There's a really good question on StackOverflow about Testing internal implementation or public behaviour
Decoupling the sorting from the file system sounds like a very good idea and would make your code re-usable, so that you could easily use it in another project if needed. By all means, if you really want to then you can abstract things more by making the sorting an interface, and possibly the file system an interface. Remember that there's a risk of over-engineering though. Always remember the rule of YAGNIT.


Graph and Node classes with BFS and DFS functions

Algorithm

Both your BFS and DFS run in time \$\mathcal{O}(EV)\$ due to this:

if nd not in visited and nd not in toVisit:

Since toVisit is a list, finding whether nd not in toVisit will have to iterate over all elements in that list. Since the above if will be iterated around \$\Theta(E)\$ times, and len(toVisit) \$\leq |V|\$, the total work may be as large as \$\mathcal{O}(EV)\$.

What you could do above in order to

if nd not in visited and nd not in toVisit:

in constant time, is to add a set that stores the graph nodes already reached by the search. In order for that to happen, you have to add a couple of special methods to your Node class:

class Node:
    def __init__(self, val):
        self.val = val
        self.edges = []

    # Do this and other represent the same node?
    def __eq__(self, other):
        return self.val == other.val

    # Used for finding the collision chain for this node.
    def __hash__(self):
        return self.val

Note that set() is implemented as a hash table that runs both insertion and query operations in constant time.

Also, I strongly suggest that you do not print to standard output from an algorithm. Instead, arrange an output from the algorithm that may be printed.

Also, taking a look at bfs, there is an improvement opportunity as well: you use a list for representing the search frontier queue. Appending is efficient, yet removing the head node of that "queue" runs in linear time. Instead, use collections.deque(); it allows both pops and pushes in constant time. [1] https://wiki.python.org/moin/TimeComplexity

Naming

Python suggest new_node instead of newNode. Same applies to toVisit.

Misc

The test if self.nodes is None: may be rewritten more succintly:

if not self.nodes:

The above will deal with self.nodes == None and len(self.nodes) == 0.

Summa summarum

All in all, I had this in mind:

from collections import deque

class Node:
    def __init__(self, val):
        self.val = val
        self.edges = []

    def __eq__(self, other):
        return self.val == other.val

    def __hash__(self):
        return self.val

class Graph:
    def __init__(self, nodes=[]):
        self.nodes = nodes

    def add_node(self, val):
        new_node = Node(val)
        self.nodes.append(new_node)

    def add_edge(self, node1, node2):
        node1.edges.append(node2)
        node2.edges.append(node1)

    def bfs(self):
        if not self.nodes:
            return []
        start = self.nodes[0]
        visited, queue, result = set([start]), deque([start]), []
        while queue:
            node = queue.popleft()
            result.append(node)
            for nd in node.edges:
                if nd not in visited:
                    queue.append(nd)
                    visited.add(nd)
        return result

    def dfs(self):
        if not self.nodes:
            return []
        start = self.nodes[0]
        visited, stack, result = set([start]), [start], []
        while stack:
            node = stack.pop()
            result.append(node)
            for nd in node.edges:
                if nd not in visited:
                    stack.append(nd)
                    visited.add(nd)
        return result

graph = Graph()
graph.add_node(5)
graph.add_node(3)
graph.add_node(8)
graph.add_node(1)
graph.add_node(9)
graph.add_node(2)
graph.add_node(10)

#            2
#           /
# 5 - 3 - 8 -  9 - 10
#  \    /
#     1

graph.add_edge(graph.nodes[0], graph.nodes[1])
graph.add_edge(graph.nodes[0], graph.nodes[3])
graph.add_edge(graph.nodes[1], graph.nodes[2])
graph.add_edge(graph.nodes[0], graph.nodes[1])
graph.add_edge(graph.nodes[2], graph.nodes[3])
graph.add_edge(graph.nodes[2], graph.nodes[5])
graph.add_edge(graph.nodes[2], graph.nodes[4])
graph.add_edge(graph.nodes[4], graph.nodes[6])

dfs_result = graph.dfs()
bfs_result = graph.bfs()
print("DFS")
for i in range(len(dfs_result)):
    print(dfs_result[i].val)
print("BFS")
for i in range(len(bfs_result)):
    print(bfs_result[i].val)

Hope that helps.


Multiple things to fix:

variable naming - class names should be in camel-case and start with a capital letter (reference); when there are multiple words in a variable, you should put underscore between them, e.g. in your case procedurename would become procedure_name
missing spaces - there should be spaces around operators, like around the = here:

self.name = param.attrib['name']

incorrect private method naming - when you put double underscores around a method name (this is called "dunder"), you are implying that it is a "magic method" which may confuse future readers of your code (which can also be you); while, I think you meant to create a private method. In other words, naming the method __parse, not __parse__
if(len(mems)==0): can be simplified as if not mems:
bare except clause should be avoided, either replace with handling a more specific error type:

try:
    self.order=member.attrib['order']
except:
    pass

with:

try:
    self.order = member.attrib['order']
except KeyError:
    pass

Or, follow the @LaurentLAPORTE's advice and use the .get() method to set the self.order to None if the "order" attribute does not exist:

self.order = member.attrib.get('order')


Yeah, it seems to cloud up your code a bit. You could write your own LINQ-style extension method similar to the ones below. It uses a couple of C#7 features (tuple types and local methods). The first just recreates the collection with the results associated with each item (to avoid any side-effects of possibly calling the predicate multiple times) and the second will iterate and log/filter as your lambda does.

namespace System.Linq
{
    using System.Collections.Generic;

    public static class Enumerable
    {
        public static IEnumerable<(TSource, bool)> WhereResult<TSource>(
            this IEnumerable<TSource> source,
            Func<TSource, bool> predicate)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            return _();

            IEnumerable<(TSource, bool)> _()
            {
                foreach (TSource current in source)
                {
                    yield return (current, predicate(current));
                }
            }
        }

        public static IEnumerable<(TSource, bool)> LogWhere<TSource>(
            this IEnumerable<(TSource, bool)> source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            return _();

            IEnumerable<(TSource, bool)> _()
            {
                foreach ((TSource, bool) current in source)
                {
                    if (current.Item2)
                    {
                        yield return current;
                    }
                    else
                    {
                        Log(...);
                    }
                }
            }
        }
    }
}

This is just a first thought off the top of my head. Could be improved easily with some AOP instead of the explicit logging call, for instance.


There are two primary ways I can think of to change this:

Iterate over an array

String[] fieldNames = new String[]{ "empName", "empNum", "empSalary" };
for (String field : fieldNames) {
    if (collectValue(field, record) < 0) {
         return false;
    }
}

Boolean short-circuiting

boolean returnFalse = collectValue("empName", record) < 0 || collectValue("empNum", record) < 0 || collectValue("empSalary", record) < 0;
if (returnFalse) {
    return false;
}

I would personally recommend the first version, as the second version creates a long statement and is a bit more difficult to both read and debug.


Simple inheritance with functions in subclasses

As Joseph mentioned, opinion questions is not what CodeReview is about.

I tend to review every OO approach with these 4 questions:

Approach 1

Does instanceof still work ? -> Yes, good
Do you introduce new properties, causing potential naming clashes -> No, good
Can parameters easily be provided to the constructors -> Yes, good
Can I easily have properties in .prototype -> Yes, good

Approach 2

Does instanceof still work ? -> Yes, good
Do you introduce new properties, causing potential naming clashes -> Yes, not so good
Can parameters easily be provided to the constructors -> Yes, good
Can I easily have properties in .prototype -> Yes, good

The second approach uses _super, which is not perfect but definitely acceptable, and the framework was written by John Resig..

In the end, you should use the right tool for the job, and since you provided example code, we can't really tell you which approach is best.


I think this can be improved by using queues as the main construct to convey what is going on.

First, you have a pending queue:

my @pending = (8, 8, 5);

Second, you have an empty queue with the currently active workers:

my @workers;

And this queue has a size limit:

my $max_workers = 2;

This can all be run by a single while loop:

while(@workers < $max_workers) {
    ... add one more worker ...
    ... remove all workers that are done ...
    ... break out of loop is @pending and @workers are both empty
    ... wait for a worker to exit (or sleep) ...
}

When this loop exits, you're all done.


Project Euler - Problem No.4 - Largest palindrome product

Errors

range(start, end) goes from the start value, inclusive, to the end value, exclusive.  So

for i in range(upper_boundary, lower_boundary, -1):

will not include lower_boundary in the values which will be tested, so you will be ignoring products where i would be 10 (two digit case) and 100 (three digit case).

Similarly, for j in range(i, lower_boundary, -1) will ignore products where j would be 10 and 100.

The solution is to use range(..., lower_boundary - 1, -1).

Special Case

Why is n == 1 special cased, to return 9?  Why don’t you trust the algorithm to return the correct value?  Oh, right, 9*1 wouldn’t be tested, because lower_boundary = 1, and got excluded due to the bug above.

Perhaps you should have examined this special case closer.

Optimizations

You compute i*j up to 3 times each loop.  You should compute it once, and store it in a variable, such as prod.

        prod = i * j
        str_prod = str(prod)
        if prod > mul_max and str_prod[::-1] == str_prod:
            mul_max = prod

You are searching in decreasing ranges for the outer and inner loops.  Why?  True: You’ll find the target value faster.  But you still search all product values where j <= i.  Is there any way of determining there won’t be any larger mul_max value, either from the inner loop, or from the outer loop, or both?  For instance, if i*j > mul_max is not true, would it be true for any smaller value of j?

Turning a integer into a string is an \$O(\log n)\$ operation.  Can you skip doing it for every product?

    for j in range(i, lower_boundary - 1, -1):
        prod = i * j

        if prod <= mul_max:
           break

        str_prod = str(prod)
        if str_prod[::-1] == str_prod:
            mul_max = prod

Can something similar be done with the for i in range(...) loop, to speed things up even further?


Aliasing utility class method in extended class

I'm not a fan of the UtilityClass. Here's some examples:

It breaks the single responsibility principle as it is not focused on solving a specific problem.
UtilityClass:trimText() conveys too little context about what it does, and the result of calling the method is unexpected. UtilityClass::trimText() would better suit the problem with signature like UtilityClass:shortenTextTo($text, $length);
UtilityClass::formatNumber() is not specific enough to explain clearly what it does. How does it format the number?

UtilityClass:trimText() seems like a good fit for a static helper. The problem you are trying to solve looks visual, and you should try to convey that. Look at the following:

class Text {
    public static function shortenTo($text, $length) {
        return substr(trim($text), 0, $length);
    }
}

// Html

My awesome blogpost!

<?= Text::shortenTo($text, 100); ?>

Now you have a utility for shortening a text to the wanted length.

Your session class also deals with the wrong problem. A session class would represent a Session (i.e a value object) or handle actual session management, but it wouldn't set permissions. An Authenticator class could use a SessionManager to assign specific permissions TO a session, but Sessions should have no understanding of what permissions are.

Hope that gives you something to work on. Your code is not horrible, but it seems to not focus on solving the right problems in the right places. The point of object-orientation is to represent code in realistic, understandable models, and your code does not do that at the moment. Focus on what a Session represents. What actions should you be able to do with a Session object?


There is no overhead in calling UIImage(named: ...) repeatedly,
because the UIKit framework already caches the image, as documented
in the UIImage(named:) reference:

  This method looks in the system caches for an image object with the specified name and returns the variant of that image that is best suited for the main screen. If a matching image object is not already in the cache, this method locates and loads the image data from disk or from an available asset catalog, and then returns the resulting object.

So keep it simple and assign the image object where needed:

if self.isSecureTextEntry {
    imageView.image = UIImage(named: "eye.png")
} else {
    imageView.image = UIImage(named: "no_eye.png")
}

or shorter:

imageView.image = UIImage(named: isSecureTextEntry ? "eye.png" : "no_eye.png")

Note that self is not necessary to access instance members.

Or use image literals, a feature introduced in Xcode 8.
You can simply type the name of an image resource in the asset catalog. This will be autocompleted to #imageLiteral(resourceName: "<name>"), but displayed as the image itself

in the Xcode source editor.

This is useful to avoid typing errors in the image name, and to visually
check if the right image was chosen. You can even double-click on
the image icon and choose a different one.


Presidential election predictor using matrix-processing

Replacing loops in MATLAB with equivalent matrix operations (a technique commonly referred to as vectorization) often, but not always, leads to improvements in performance. However, this frequently results in code that may be difficult for others to read, so it is advisable to use the profiler to identify bottlenecks and then try vectorizing only those sections of code where performance really matters. You could do something like this (outside the loop):

voteMatrix(regions == 6) = -1

This is equivalent to the first if condition in your loop. Try to do the same to the else condition. (Hint: you'll need to update your voteFromLocation method to handle arrays in the same manner.)

It's been a long time since I last used MATLAB, so my syntax may not be very accurate, but you get the general idea.


Is there a better way to insert an enum into a set without macros?

You can iterate over the enum and insert each one individually.

for ( int i = FIXED_VOLTAGE1; i != FIXED_VOLTAGE4; i++ )
{
    m_modules.insert(CreateAndUseIniFile::static_cast<iniFileValues>(i));
}

Note: This will work with your specific case... don't do this if you have enums with set values that contain gaps between enum values.


Singly Linked List implementation in Python

For the most part it looks good, I haven't tested performance, but nothing stands out as bad. You should probably rewrite remove, so that it takes an index rather than a value. Imagine

list = LinkedList()
list.insert(2)
list.insert(2)
list.remove(2)

Your current code works great as long as there aren't duplicate values, but once there are everything gets kind of messed up.

With regards to pythonicness, the only comment I have is that if(x): is harder to type and harder to parse than if x:.